Esempio n. 1
0
 /**
  * Module initialization stage.
  *
  * @see ModuleConnector::init()
  *
  * @param array $params Initialization parameters
  *
  * @return bool True if resource successfully initialized
  */
 public function init(array $params = array())
 {
     // Subscribe to core template rendering event
     Event::subscribe('core.rendered', [$this, 'renderTemplate']);
     Event::subscribe(Compressor::E_CREATE_RESOURCE_LIST, [$this, 'getResources']);
     // Set default dependency as local file manager
     $this->fileManager = $this->fileManager ?: new LocalFileManager();
     $this->resourceManager = new ResourceManager($this->fileManager);
     ResourceManager::$cacheRoot = $this->cache_path;
     ResourceManager::$webRoot = getcwd();
     ResourceManager::$projectRoot = dirname(ResourceManager::$webRoot) . '/';
     // Get loaded modules
     $moduleList = $this->system->getContainer()->getServices('module');
     // Event for modification of resource list
     Event::fire(self::E_MODULES, [&$moduleList]);
     $appResourcePaths = $this->getAssets($moduleList);
     // Get assets
     $this->resources = $this->resourceManager->manage($appResourcePaths);
     // Fire completion event
     Event::fire(self::E_FINISHED, [&$this->resources]);
     // Get asset URLs
     $this->resourceUrls = array_map([$this, 'getAssetCachedUrl'], $this->resources);
     // Continue parent initialization
     return parent::init($params);
 }
Esempio n. 2
0
 /** @inheritdoc */
 public function __construct(RenderInterface $renderer, QueryInterface $query, Record $entity, \samson\activerecord\field $field)
 {
     $this->name = $field->Description != '' ? $field->Description : $field->Name;
     $this->id .= '_' . $field->Name;
     // Prepare locales array with one default locale by default
     $locales = array(null);
     // If field supports localization - set full locales array
     if ($field->local == 1) {
         $locales = SamsonLocale::$locales;
     }
     /** @var MaterialField $materialField */
     $materialField = null;
     // Iterate defined locales
     if (sizeof(SamsonLocale::$locales)) {
         foreach ($locales as $locale) {
             // Try to find existing MaterialField record
             if (!dbQuery('\\samsoncms\\api\\MaterialField')->MaterialID($entity->id)->FieldID($field->id)->locale($locale)->first($materialField)) {
                 // Create MaterialField record
                 $materialField = new \samsoncms\api\MaterialField(false);
                 $materialField->Active = 1;
                 $materialField->MaterialID = $entity->id;
                 $materialField->FieldID = $field->id;
                 $materialField->locale = $locale;
                 $materialField->save();
             }
             // Add child tab
             $this->subTabs[] = new MaterialFieldLocalized($renderer, $query, $entity, $materialField, $locale);
         }
     }
     // Call parent constructor to define all class fields
     parent::__construct($renderer, $query, $entity);
     Event::fire('samsoncms.material.materialfieldtab.created', array(&$this, $field));
 }
 /**
  * ComposerModuleManager constructor.
  *
  * @param string $path
  * @param string $vendorDir
  */
 public function __construct(string $path, string $vendorDir)
 {
     $this->appPath = $path;
     $this->vendorDir = $vendorDir;
     // TODO Move this somewhere
     Event::fire('core.composer.create', [&$this->composerModules, $this->appPath, ['vendorsList' => ['samsonphp/', 'samsonos/', 'samsoncms/', 'samsonjavascript/'], 'ignoreKey' => 'samson_module_ignore', 'includeKey' => 'samson_module_include']]);
 }
Esempio n. 4
0
 /**
  * Initialize module
  * @param array $params Collection of module parameters
  * @return bool True if module successfully initialized
  */
 public function init(array $params = array())
 {
     if (!$this->loadExternalService($this->fileServiceClassName)) {
         // Signal error
         Event::fire('error', array($this, 'Cannot initialize file system adapter[' . $this->fileServiceClassName . ']'));
     }
     // Call parent initialization
     return parent::init($params);
 }
Esempio n. 5
0
 /** Universal controller action */
 public function __handler()
 {
     // Render menu
     \samsonphp\event\Event::subscribe('template.menu.rendered', array($this, 'subMenuHandler'));
     $html = '';
     // Fire event when application help is rendered
     \samsonphp\event\Event::fire('help.content.rendered', array(&$html, $this));
     // Prepare view
     $this->view('index')->title(t($this->name, true))->set('content', $html);
 }
Esempio n. 6
0
 /** Universal controller action */
 public function __handler($category = null, $subCategory = null, $subSubCategory = null)
 {
     // Render menu and current controller parameters
     \samsonphp\event\Event::subscribe('template.menu.rendered', array($this, 'subMenuHandler'), array($category, $subCategory, $subSubCategory));
     $html = '';
     // Fire event when application help is rendered
     \samsonphp\event\Event::fire('help.content.rendered', array(&$html, $category, $subCategory, $subSubCategory, $this));
     // Prepare view
     $this->view('index')->title(t($this->name, true))->set('content', $html);
 }
Esempio n. 7
0
 /** Test dynamic event callback handler */
 public function testSubscribeDynamic()
 {
     // Subscribe to event
     \samsonphp\event\Event::subscribe('test.subscribe_dynamic', array($this, 'eventDynamicCallback'));
     // Fire event
     $result = null;
     \samsonphp\event\Event::fire('test.subscribe_dynamic', array(&$result));
     // Perform test
     $this->assertEquals(2, $result);
 }
Esempio n. 8
0
 public function init(array $params = array())
 {
     parent::init($params);
     if (isset($this->renderer)) {
         $this->renderer =& m($this->renderer);
     } else {
         $this->renderer =& $this;
     }
     Event::fire('commerce.init.module.commerce.core', array(&$this));
 }
Esempio n. 9
0
 public function activeModuleHandler($module)
 {
     // Define if routed module is related to SamsonCMS
     if ($this->isCMS = $this->ifModuleRelated($module)) {
         // TODO: This should be removed - Reparse url
         url()->parse();
         // Switch template to SamsonCMS
         $this->system->template($this->path() . 'app/view/index.php', true);
         Event::fire(self::EVENT_IS_CMS, array(&$this));
     }
 }
Esempio n. 10
0
 /** E404 controller action */
 function __e404()
 {
     // HTML main #template-container
     $html = '';
     $this->system->active($this);
     Event::fire('template.e404.started', array(&$html));
     Event::fire('template.e404.rendered', array(&$html));
     // Render template e404 into local module
     m('local')->html($this->view('e404')->set($html, 'template-container')->output())->title(t('Страница не найдена', true));
     header("HTTP/1.0 404 Not Found");
 }
Esempio n. 11
0
 /**
  * LESS resource compiler.
  *
  * @param string $resource  Resource full path
  * @param string $extension Resource extension
  * @param string $content   Compiled output resource content
  */
 public function compile($resource, $extension, &$content)
 {
     if (in_array($extension, [ResourceManager::T_CSS, ResourceManager::T_LESS, ResourceManager::T_SASS, ResourceManager::T_SCSS])) {
         $this->currentResource = $resource;
         // Fire event
         Event::fire(self::E_BEFORE_HANDLER, [&$content, $resource]);
         // Rewrite Urls
         $content = preg_replace_callback(self::P_URL, [$this, 'rewriteUrls'], $content);
         // Fire event
         Event::fire(self::E_AFTER_HANDLER, [&$content, $resource]);
     }
 }
Esempio n. 12
0
 /**
  * Module initialization
  */
 public function init(array $params = array())
 {
     // Create default or users Request object
     $this->request = !isset($this->request) || !class_exists($this->request) ? new Request() : new $this->request();
     // If configuration for API Key is not set
     if (!isset($this->apiKey)) {
         // Signal error
         Event::fire('error', array($this, 'Cannot initialize Translate module - Google API Key does not exists'));
     } else {
         // Create default get url
         $this->get = 'https://www.googleapis.com/language/translate/v2?key=' . $this->apiKey;
     }
     // Call parent initialization
     return parent::init($params);
 }
Esempio n. 13
0
 /**
  * @param RenderInterface $renderer
  * @param QueryInterface $query
  * @param Record $entity
  */
 public function __construct(RenderInterface $renderer, QueryInterface $query, Record $entity)
 {
     // Set module renderer for this tab
     $this->renderer = $renderer;
     // Set query object for this tab
     $this->query = $query;
     // Set db entity of this tab
     $this->entity = $entity;
     // If form tabs are not configured
     if (!sizeof($this->tabs)) {
         // Add MainTab to form tabs
         $this->tabs = array(new Entity($renderer, $query, $entity));
     }
     // Fire new event after creating form tabs
     Event::fire('samsoncms.form.created', array(&$this));
 }
Esempio n. 14
0
 public function compress(array $urls, $type, $output)
 {
     $content = '';
     $fileName = '';
     foreach ($urls as $url) {
         if ($this->fileManager->exists($url)) {
             $fileName .= $url . $this->fileManager->lastModified($url);
             $content .= $this->fileManager->read($url);
         }
     }
     $fileName = md5($fileName);
     $fileName = $fileName . '.' . $type;
     Event::fire(Compressor::E_RESOURCE_COMPRESS, array($type, &$content));
     $this->fileManager->write($output . $fileName, $content);
     return $fileName;
 }
Esempio n. 15
0
 /**
  * Load module.
  *
  * @param ModuleInterface $instance Module ancestor for loading
  *
  * @param string|null $alias Module alias
  *
  * @return $this Chaining
  *
  * @throws CannotLoadModule On alias duplication
  */
 public function load($instance, $alias = null)
 {
     // If no alias is passed - use fully qualified class name
     $alias = $alias ?: get_class($instance);
     // Check for duplicating aliases
     if (array_key_exists($alias, $this->modules)) {
         throw new CannotLoadModule($alias . ' - alias already in use');
     }
     // Fire core before module loading
     Event::fire(self::E_BEFORE_LOADED, [&$this, &$instance, &$alias]);
     // Store module instance by alias or class name
     $this->modules[$alias] = $instance;
     // Fire core before module loading
     Event::fire(self::E_AFTER_LOADED, [&$this, &$instance, &$alias]);
     return $this;
 }
Esempio n. 16
0
 /**
  * Generate HTML select element to define additional field type
  * @param int $type Current field selected type
  * @return string HTML select element code
  */
 public static function createSelect($type = 0)
 {
     // Create html view
     $html = '';
     // Define all types of data
     $typeData = array('Текст' => 0, 'Ресурс' => 1, 'Дата' => 3, 'Дата и время' => 10, 'Select' => 4, 'Таблицы' => 5, 'Материал' => 6, 'Число' => 7, 'WYSIWYG' => 8, 'Внешняя картинка' => 13, 'Галерея' => 9);
     // Fire select creation event to give ability other modules to add values
     \samsonphp\event\Event::fire('cms_field.select_create', array(&$typeData));
     // Iterate current types
     foreach ($typeData as $key => $value) {
         // Check selected status
         $selected = $type == $value ? 'selected' : '';
         // Create options of select
         $html .= '<option value="' . $value . '" ' . $selected . '>' . $key . '</option>';
     }
     // Return view
     return '<select name="Type" id="Type">' . $html . '</select>';
 }
Esempio n. 17
0
 /**
  * Initialize module
  * @param array $params Collection of module parameters
  * @return bool True if module successfully initialized
  */
 public function init(array $params = array())
 {
     // If defined file service is not supported
     if (!class_exists($this->fileServiceClassName)) {
         // Signal error
         Event::fire('error', array($this, 'Cannot initialize file system adapter[' . $this->fileServiceClassName . ']'));
     } else {
         /** @var \samson\fs\AbstractFileService Create file service instance */
         $this->fileService = new $this->fileServiceClassName();
         // Set nested file service instance parameters
         foreach ($this->configuration as $key => $value) {
             $this->fileService->{$key} = $value;
         }
         // Initialize file service
         $this->fileService->initialize();
     }
     // Call parent initialization
     return parent::init($params);
 }
Esempio n. 18
0
 /** @inheritdoc */
 public function __construct(RenderInterface $renderer, QueryInterface $query, Record $entity)
 {
     $this->name = t($this->name, true);
     $this->show = false;
     $entity = dbQuery('\\samsoncms\\api\\Material')->cond('MaterialID', $entity->id)->join('structurematerial')->join('structure')->first();
     if (isset($entity['onetomany']) && isset($entity['onetomany']['_structure'])) {
         $structures = $entity['onetomany']['_structure'];
         $nonLocalizedFieldsCount = dbQuery('structurefield')->join('field')->cond('StructureID', array_keys($structures))->cond('field_local', 0)->count();
         $newStructuresId = array();
         // Get all structure which not table
         foreach ($structures as $structure) {
             if ($structure->type == 0) {
                 $newStructuresId[] = $structure->id;
             }
         }
         // If there no structures with localized fields then count of localized fields equal 0
         if (empty($newStructuresId)) {
             $localizedFieldsCount = 0;
         } else {
             $localizedFieldsCount = dbQuery('structurefield')->join('field')->cond('StructureID', $newStructuresId)->cond('field_local', 1)->cond('field_Type', 5, dbRelation::LOWER)->count();
         }
         // If we have not localized fields
         // Don't display the non localized fields
         /*if ($nonLocalizedFieldsCount > 0) {
               // Create default sub tab
               $this->subTabs[] = new FieldLocalized($renderer, $query, $entity, '');
               $this->show = true;
           }*/
         // Iterate available locales if we have localized fields
         if (sizeof(SamsonLocale::$locales) && $localizedFieldsCount > 0) {
             foreach (SamsonLocale::$locales as $locale) {
                 // Create child tab
                 $subTab = new LocaleTab($renderer, $query, $entity, $locale);
                 $this->subTabs[] = $subTab;
             }
             $this->show = true;
         }
     }
     // Call parent constructor to define all class fields
     parent::__construct($renderer, $query, $entity);
     // Trigger special additional field
     Event::fire('samsoncms.material.fieldtab.created', array(&$this));
 }
Esempio n. 19
0
 /**
  * Recursively process asset
  * @param array $dependencies Collection of assets for compilation
  */
 protected function processAsset($dependencies)
 {
     foreach ($dependencies as $source => $nothing) {
         // Read asset content
         $content = $this->fileManager->read($source);
         $extension = pathinfo($source, PATHINFO_EXTENSION);
         // Resource dependant resources
         $innerDependencies = [];
         // Compile content
         $compiled = $content;
         Event::fire(self::E_COMPILE, [$source, &$extension, &$compiled, &$innerDependencies]);
         // Write compiled asset
         $target = $this->getAssetProcessedPath($source);
         $this->fileManager->write($target, $compiled);
         $this->fileManager->touch($target, $this->fileManager->lastModified($source));
         // Go deeper in recursion
         $this->processAsset($innerDependencies);
     }
 }
Esempio n. 20
0
 /**
  * Method prepare core instance removing all unnecessary loaded modules
  * from it, and configuring it.
  * @return string Base64 encoded serialized core object instance
  */
 public function compress()
 {
     $this->logger->log(' -- Compressing core');
     // Switch to production environment
     $this->core->environment($this->environment);
     // Set rendering from string variables mode
     $this->core->render_mode = \samson\core\Core::RENDER_VARIABLE;
     // Unload all modules from core that does not implement interface iModuleCompressable
     foreach ($this->core->module_stack as $id => &$m) {
         // Unload modules that is not compressable
         if (!is_a($m, '\\samson\\core\\iModuleCompressable')) {
             $this->core->unload($id);
             $this->logger->log(' -- [##] -> Unloading module from core', $id);
         } else {
             // Reconfigure module
             Event::fire('core.module.configure', array(&$m, $id));
             $this->logger->log(' -- [##] -> Loading config data', $id);
         }
     }
     // Change system path to relative type
     $this->core->path('');
     // Create serialized object copy
     return base64_encode(serialize($this->core));
 }
Esempio n. 21
0
 /** @inheritdoc */
 public function __construct(RenderInterface $renderer, QueryInterface $query, Record $entity)
 {
     // Get all locales
     $locales = \samson\core\SamsonLocale::get();
     // Set current locale as first value of array
     $localArray = array(locale());
     // Iterate all locales
     foreach ($locales as $local) {
         // Avoid current locale
         if ($local == locale()) {
             continue;
         }
         $localArray[] = $local;
     }
     // Set locales in the new order
     \samson\core\SamsonLocale::$locales = $localArray;
     // TODO This is fix loading SEO module
     // Because seo module used this class, and for checking class_exists function this class have to be exists
     // And we have to call it this but when cms and app will be one single application please remove this line
     new \samsoncms\app\material\form\tab\LocaleTab($renderer, $query, $entity);
     // Fill generic tabs
     $this->tabs = array(new Main($renderer, $query, $entity), new Field($renderer, $query, $entity));
     $this->navigationIDs = dbQuery('structurematerial')->cond('MaterialID', $entity->id)->fields('StructureID');
     // Get all another tabs
     if (sizeof($this->navigationIDs)) {
         $wysiwygFields = dbQuery('field')->cond('Type', 8)->join('structurefield')->cond('structurefield_StructureID', $this->navigationIDs)->exec();
         foreach ($wysiwygFields as $field) {
             $this->tabs[] = new MaterialField($renderer, $query, $entity, $field);
         }
     }
     parent::__construct($renderer, $query, $entity);
     // Fire new event after creating form tabs
     Event::fire('samsoncms.material.form.created', array(&$this, $renderer, $query, $entity));
     // Set old locales
     \samson\core\SamsonLocale::$locales = $locales;
 }
Esempio n. 22
0
 /**
  * Compress web-application
  * @param boolean $debug Disable errors output
  * @param string $php_version PHP version to support
  */
 public function compress($debug = false, $environment = 'prod', $php_version = PHP_VERSION)
 {
     // Set compressed project environment
     $this->environment = $environment;
     elapsed('Started web-application compression[' . $this->environment . ']');
     s()->async(true);
     ini_set('memory_limit', '256M');
     // Check output path
     if (!isset($this->output[0])) {
         return $this->log('Cannot compress web-application from [##] - No output path is specified', $this->input);
     }
     // Define rendering model depending on PHP version
     $php_version = isset($php_version[0]) ? $php_version : PHP_VERSION;
     if (version_compare($php_version, '5.3.0', '<')) {
         $this->view_mode = Core::RENDER_ARRAY;
     }
     // Add url base to path
     $this->output .= url()->base();
     // Creating output project folder
     $result = \samson\core\File::mkdir($this->output);
     if ($result) {
         $this->log('Created output project folder [##]', $this->output);
     } else {
         if ($result == -1) {
             return $this->log('Compression failed! Cannot create output project folder [##]', $this->output);
         }
     }
     // Remove all trailing slashes
     $this->output = realpath($this->output) . '/';
     $this->log('[##]## Compressing web-application[##] from [##] to [##]', $environment, $debug ? '[DEBUG]' : '', $php_version, $this->input, $this->output);
     // Add generic composer auto loader require
     $this->php['__before_all']['composer'] = "\n" . 'if(file_exists("vendor/autoload.php")) require "vendor/autoload.php";';
     // Define global views collection
     $this->php[self::NS_GLOBAL][self::VIEWS] = "\n" . '$GLOBALS["__compressor_files"] = array();';
     // If resourcer is loaded - copy css and js
     // Link
     $rr =& s()->module_stack['resourcer'];
     // Iterate all css and js resources
     $ignoreFolders = array();
     foreach ($this->ignoredFolders as $folder) {
         $ignoreFolders[] = $this->output . $folder;
     }
     // Remove all old javascript and css
     \samson\core\File::clear($this->output, array('js', 'css'), $ignoreFolders);
     $moduleListArray = [];
     //$moduleListArray[Router::I_MAIN_PROJECT_TEMPLATE] = $this->system->module_stack;
     Event::fire(self::E_CREATE_MODULE_LIST, array(&$moduleListArray));
     $resource = new Resource($this->fileManager);
     foreach ($moduleListArray as $template => $moduleList) {
         $resourceUrls = [];
         Event::fire(self::E_CREATE_RESOURCE_LIST, array(&$resourceUrls, $moduleList));
         foreach ($resourceUrls as $type => $urls) {
             $file = $resource->compress($urls, $type, $this->output);
             $this->resourceUrlsList[$template][$type] = [DIRECTORY_SEPARATOR . $file];
         }
     }
     // Iterate core ns resources collection
     foreach (s()->module_stack as $id => &$module) {
         // Work only with compressable modules
         if (is_a($module, ns_classname('CompressInterface', 'samsonframework\\core')) || isset($this->composerParameters['samsonphp_package_compressable']) && ($this->composerParameters['samsonphp_package_compressable'] = 1)) {
             $this->compress_module($module, $module->resourceMap);
         }
         // Change path to local modules
         if (is_a($module, '\\samson\\core\\VirtualModule')) {
             $module->path('');
         }
     }
     /*foreach ($rr->cached['js'] as $jsCachedFile) {
                 // Manage javascript resource
                 $javascriptManager = new resource\JavaScript($this);
                 $javascriptManager->compress(__SAMSON_CWD__ . $jsCachedFile, $this->output . basename($jsCachedFile));
             }
     
             foreach ($rr->cached['css'] as $cssCachedFile) {
                 // Manage CSS resource
                 $cssManager = new resource\CSS($this, $rr);
                 $cssManager->compress(__SAMSON_CWD__ . $cssCachedFile, $this->output . basename($cssCachedFile));
             }*/
     //}
     // Copy main project composer.json
     $composerPath = __SAMSON_CWD__ . 'composer.json';
     if (file_exists($composerPath)) {
         // Read json file
         $composerJSON = (array) json_decode(file_get_contents($composerPath));
         // Remove development dependencies
         unset($composerJSON['require-dev']);
         // Remove autoload section
         unset($composerJSON['autoload']);
         // Remove install/update scripts
         unset($composerJSON['scripts']);
         // Write modified composer.json
         file_put_contents($this->output . 'composer.json', json_encode($composerJSON));
     }
     // Set errors output
     $this->php[self::NS_GLOBAL][self::VIEWS] .= "\n" . '\\samson\\core\\Error::$OUTPUT = ' . (!$debug ? 'false' : 'true') . ';';
     // Create SamsonPHP core compressor
     $core = new \samsonphp\compressor\Core(s(), $environment, $this);
     // Add global base64 serialized core string
     $this->php[self::NS_GLOBAL][self::VIEWS] .= "\n" . '$GLOBALS["__CORE_SNAPSHOT"] = \'' . $core->compress() . '\';';
     // Add all specified requires
     foreach ($this->require as $require) {
         $this->php[self::NS_GLOBAL][self::VIEWS] .= "\n" . 'require("' . $require . '");';
     }
     // Add localization data
     $locale_str = array();
     foreach (\samson\core\SamsonLocale::$locales as $locale) {
         if ($locale != '') {
             $locale_str[] = '\'' . $locale . '\'';
         }
     }
     // Add [setlocales] code
     $this->php[self::NS_GLOBAL][self::VIEWS] .= "\n" . 'setlocales( ' . implode(',', $locale_str) . ');';
     // TODO: add generic handlers to modules to provide compressing logic for each module
     // TODO: add generic constants namespace to put all constants definition there - and put only defined constrat and redeclare them
     // TODO: WTF???? Thi must be local module logic
     // If this is remote web-app - collect local resources
     if (__SAMSON_REMOTE_APP) {
         // Gather all resources
         $path = __SAMSON_CWD__;
         $ls = array();
         s()->resources($path, $ls);
         // If we have any resources
         if (isset($ls['resources'])) {
             $this->copy_path_resources($ls['resources'], __SAMSON_CWD__, '');
         }
     }
     // If default locale is defined
     if (!defined('DEFAULT_LOCALE')) {
         define('DEFAULT_LOCALE', 'ru');
     }
     // Add default system locale to them end of core definition
     $this->php['samson\\core'][self::VIEWS] = "\n" . 'define("DEFAULT_LOCALE", "' . DEFAULT_LOCALE . '");';
     // Pointer to entry script code
     $entryScriptPath = __SAMSON_CWD__ . __SAMSON_PUBLIC_PATH . 'index.php';
     $entryScript =& $this->php[self::NS_GLOBAL][$entryScriptPath];
     // Collect all event system data
     $eventCompressor = new EventCompressor();
     $eventCompressor->collect($entryScript);
     // Remove standard framework entry point from index.php	- just preserve default controller
     if (preg_match('/start\\(\\s*(\'|\\")(?<default>[^\'\\"]+)/i', $entryScript, $matches)) {
         /*
          * Temporary solution to support compressed version, because other way localization does not work,
          * as chain is broken, first time URL object is created and URL is parsed only after start, so
          * CMS::afterCompress does not knows what is current locale and does not inject it to all material
          * queries.
          */
         $this->php[self::NS_GLOBAL][self::VIEWS] .= "\n" . 'url();';
         $this->php[self::NS_GLOBAL][self::VIEWS] .= "\n" . 's()->start(\'' . $matches['default'] . '\');';
     } else {
         e('Default module definition not found - possible errors at compressed version');
     }
     // Clear default entry point
     unset($this->php[self::NS_GLOBAL][$entryScriptPath]);
     // Set global namespace as last
     $global_ns = $this->php[self::NS_GLOBAL];
     unset($this->php[self::NS_GLOBAL]);
     $this->php[self::NS_GLOBAL] = $global_ns;
     // Set view data to the end of global namespace
     $s = $this->php[self::NS_GLOBAL][self::VIEWS];
     unset($this->php[self::NS_GLOBAL][self::VIEWS]);
     $this->php[self::NS_GLOBAL][self::VIEWS] = $s;
     // Load all OOP entities
     $classes = array();
     // Соберем коллекцию загруженных интерфейсов их файлов по пространствам имен
     $this->classes_to_ns_files(get_declared_interfaces(), $classes);
     // Соберем коллекцию загруженных классов их файлов по пространствам имен
     $this->classes_to_ns_files(get_declared_classes(), $classes);
     // Fix OOP entities
     foreach ($this->php as $ns => &$files) {
         // If this namespace has been loaded
         if (isset($classes[$ns])) {
             // Fill namespace entities, make OOP entities correct order
             $files = array_merge($classes[$ns], $files);
         }
     }
     // Соберем весь PHP код в один файл
     $index_php = $this->code_array_to_str($this->php, $this->view_mode == 2);
     // Collect all event system data
     $eventCompressor->collect($index_php);
     // Transform event system in all project code
     if ($eventCompressor->transform($index_php, $index_php)) {
         //trace($eventCompressor->subscriptions, true);
     }
     // Remove url_base parsing and put current url base
     if (preg_match('/define\\(\'__SAMSON_BASE__\',\\s*([^;]+)/i', $index_php, $matches)) {
         $index_php = str_replace($matches[0], 'define(\'__SAMSON_BASE__\',\'' . __SAMSON_BASE__ . '\');', $index_php);
     }
     // Set global constant to specify supported PHP version
     if (preg_match('/define\\s*\\(\'__SAMSON_PHP_OLD[^;]+/', $index_php, $matches)) {
         $index_php = str_replace($matches[0], 'define(\'__SAMSON_PHP_OLD\',\'' . ($this->view_mode == 2) . '\');', $index_php);
     }
     $index_php = $this->removeBlankLines($index_php);
     $index_php = preg_replace('/(declare *\\( *strict_types *= *1 *\\) *;)/i', ' ', $index_php);
     // Запишем пусковой файл
     file_put_contents($this->output . 'index.php', '<?php ' . $index_php . "\n" . '?>');
     // Minify PHP code if no debug is needed
     if (!$debug) {
         file_put_contents($this->output . 'index.php', php_strip_whitespace($this->output . 'index.php'));
     }
     elapsed('Site has been successfully compressed to ' . $this->output);
 }
Esempio n. 23
0
 /**
  * Render file to a buffer.
  *
  * @param string $view Path to file
  * @param array  $data Collection of variables to path to file
  *
  * @return string Rendered file contents
  * @throws ViewPathNotFound
  */
 public function render($view, $data = array())
 {
     // TODO: Make rendering as external system, to split up these 3 rendering options
     // Объявить ассоциативный массив переменных в данном контексте
     if (is_array($data)) {
         extract($data);
     }
     // Начать вывод в буффер
     ob_start();
     // Path to another template view, by default we are using default template folder path,
     // for meeting first condition
     $templateView = $view;
     if (locale() != SamsonLocale::DEF) {
         // Modify standard view path with another template
         $templateView = str_replace(__SAMSON_VIEW_PATH, __SAMSON_VIEW_PATH . locale() . '/', $templateView);
     }
     // Depending on core view rendering model
     switch ($this->render_mode) {
         // Standard algorithm for view rendering
         case self::RENDER_STANDART:
             // Trying to find another template path, by default it's an default template path
             if (file_exists($templateView)) {
                 include $templateView;
             } elseif (file_exists($view)) {
                 // If another template wasn't found - we will use default template path
                 include $view;
             } else {
                 // Error no template view was found
                 throw new ViewPathNotFound($view);
             }
             break;
             // View rendering algorithm from array of view variables
         // View rendering algorithm from array of view variables
         case self::RENDER_VARIABLE:
             // Collection of views
             $views =& $GLOBALS['__compressor_files'];
             // Trying to find another template path, by default it's an default template path
             if (isset($views[$templateView])) {
                 eval(' ?>' . $views[$templateView] . '<?php ');
             } elseif (isset($views[$view])) {
                 // If another template wasn't found - we will use default template path
                 eval(' ?>' . $views[$view] . '<?php ');
             } else {
                 // Error no template view was found
                 throw new ViewPathNotFound($view);
             }
             break;
     }
     // Получим данные из буффера вывода
     $html = ob_get_contents();
     // Очистим буффер
     ob_end_clean();
     // Fire core render event
     Event::fire('core.render', array(&$html, &$data, &$this->active));
     ////elapsed('End rendering '.$__view);
     return $html;
 }
Esempio n. 24
0
 /**
  * Розпарсить URL
  */
 public function parse()
 {
     // Обнулим параметры
     $this->text = NULL;
     $this->parameters = array();
     $this->method = NULL;
     $this->module = NULL;
     $this->last = NULL;
     // Розпарсим URL
     $url = parse_url($_SERVER["REQUEST_URI"]);
     // Получим только путь из URL
     $url = $url['path'];
     // Отрежем путь к текущему веб-приложению из пути и декодируем другие символы
     $url = trim(urldecode(substr($url, strlen(__SAMSON_BASE__))));
     // Установим базовый путь к приложению
     $this->base = __SAMSON_BASE__;
     // Получим массив переданных аргументов маршрута системы из URL
     // Отфильтруем не пустые элементы, не переживая что мы упустим поряд их следования
     // так номера элементов в массиве сохраняются
     $url_args = explode('/', $url);
     // Clear last element if it's empty string
     $lidx = sizeof($url_args) - 1;
     if (!isset($url_args[$lidx][0])) {
         unset($url_args[$lidx]);
     }
     SamsonLocale::parseURL($url_args);
     Event::fire('samson.url.args.created', array(&$this, &$url_args));
     //trace( $url_args, true );
     // Переберем все аргументы и маршрута системы
     foreach ($url_args as $position => $value) {
         // Получим аргумент из URL
         $arg = filter_var($value, FILTER_DEFAULT);
         // Определим тип аргумента
         switch ($position) {
             // 1-й аргумент это всегда имя модуля
             case 0:
                 $this->module = $arg;
                 break;
                 // 2-й аргумент это всегда имя метода модуля
             // 2-й аргумент это всегда имя метода модуля
             case 1:
                 $this->method = $arg;
                 break;
                 // Все остальные аргументы это параметры вызываемого метода
             // Все остальные аргументы это параметры вызываемого метода
             default:
                 // Если в значение аргумента есть запятые - это массив
                 //if( strpos( $arg, ',' ) !== FALSE ) $arg = explode( ',', $arg );
                 // Добавим аргумент как параметр
                 $this->parameters[] = $arg;
         }
     }
     // Сохраним "чистый" текст URL
     $this->text = $url;
     // Получим последний аргумент из URL
     $this->last = isset($position) ? $url_args[$position] : '';
     // If we have only one parameter and it is empty - remove it
     //if( sizeof($this->parameters) == 1 && !isset($this->parameters[0]{1})) unset($this->parameters[0]);
     // Если не создан массив прошлых URL - маршрутов, создадим его
     if (!isset($_SESSION[self::S_PREVIOUS_KEY])) {
         $_SESSION[self::S_PREVIOUS_KEY] = array();
     }
     // Если не создан массив прошлых URL - маршрутов, создадим его
     if (!isset($_SESSION[self::S_BOOKMARK_KEY])) {
         $_SESSION[self::S_BOOKMARK_KEY] = array();
     }
     // Фильтруем аяксовые запросы
     if (isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] != '*/*') {
         // Запишем в сессию объект URL для хранения параметров предыдущего маршрута
         array_unshift($_SESSION[self::S_PREVIOUS_KEY], serialize($this));
         // Если стек разросься обрежим его
         if (sizeof($_SESSION[self::S_PREVIOUS_KEY]) > self::S_PREVIOUS_SIZE) {
             $_SESSION[self::S_PREVIOUS_KEY] = array_slice($_SESSION[self::S_PREVIOUS_KEY], 0, self::S_PREVIOUS_SIZE);
         }
     }
 }
Esempio n. 25
0
 public function createPayment($order, $gate, $amount = null)
 {
     //Get payment
     $payment = new Payment($order, $gate, $amount);
     //Trigger event
     Event::fire('commerce.payment.created', array(&$payment));
     return $payment;
 }
Esempio n. 26
0
 /**
  * Switch active environment
  * @param string $environment Configuration environment identifier
  */
 public function change($environment = Scheme::BASE)
 {
     // Switch to configuration environment
     $this->active =& $this->schemes[$environment];
     // Subscribe active configuration scheme to core module configure event
     Event::subscribe('core.module.configure', array($this, 'configure'));
     // If we have successfully changed configuration scheme
     if (!isset($this->active)) {
         // Signal error
         Event::fire('error', array($this, 'Cannot change configuration scheme to [' . $environment . '] - Configuration scheme does not exists'));
         // Set global scheme as active
         $this->active =& $this->schemes[Scheme::BASE];
     }
 }
Esempio n. 27
0
 /**
  * Module initialization
  * @param array $params
  * @return bool
  */
 public function init(array $params = array())
 {
     // Create default or users Request object
     $this->request = !isset($this->request) ? new Request() : new $this->request();
     // If configuration for API Key is not set
     if (!isset($this->appId) || !isset($this->appSecret)) {
         // Signal error
         Event::fire('error', array($this, 'Cannot initialize Instagram module - API keys does not exists'));
     }
     // Call parent initialization
     return parent::init($params);
 }
Esempio n. 28
0
 /**
  * Compression view code handler.
  *
  * @param string $viewCode Source view code
  *
  * @return string Modified view code
  */
 public function compressionHandler($viewCode)
 {
     // Fire event
     Event::fire(self::EVENT_VIEW_COMPRESSION, array(&$viewCode));
     // Find all paths to intermediate controller
     if (preg_match_all(self::SRC_COMPRESSION_PATTERN, $viewCode, $matches)) {
         for ($i = 0, $size = count($matches['path']); $i < $size; $i++) {
             // Remove function call just leave path related to src(for modules) or www(for local)
             $viewCode = str_replace($matches[0][$i], $matches['path'][$i], $viewCode);
         }
     }
     // Return modified view code
     return $viewCode;
 }
Esempio n. 29
0
 /**    @see ModuleConnector::init() */
 public function init(array $params = array())
 {
     parent::init($params);
     // Создадим имя файла содержащего пути к модулям
     $map_file = md5(implode('', array_keys(s()->module_stack))) . '.map';
     // Если такого файла нет
     if ($this->cache_refresh($map_file)) {
         // Fill in routes collection
         foreach ($this->system->module_stack as $id => $module) {
             self::$routes[$id] = $module->path();
         }
         // Save routes to file
         file_put_contents($map_file, serialize(self::$routes));
     }
     $moduleList = $this->system->module_stack;
     Event::fire(self::EVENT_START_GENERATE_RESOURCES, array(&$moduleList));
     //trace(array_keys($moduleList));die;
     $this->generateResources($moduleList);
     //$this->generateResources($this->system->module_stack);
     // Subscribe to core rendered event
     s()->subscribe('core.rendered', array($this, 'renderer'));
 }
Esempio n. 30
0
 /** Controller for rendering generic locales list */
 public function __list()
 {
     $current = SamsonLocale::current();
     $default = 'ru';
     if (defined('DEFAULT_LOCALE')) {
         $default = DEFAULT_LOCALE;
     }
     $urlText = url()->text;
     $httpHost = $_SERVER['HTTP_HOST'];
     Event::fire('i18n.list.generating', array(&$httpHost, &$urlText));
     // Render all available locales
     $html = '';
     foreach (SamsonLocale::get() as $locale) {
         if ($current != $default) {
             $currentUrlText = substr($urlText, strlen($current) + 1);
         } else {
             $currentUrlText = $urlText;
         }
         if ($locale == $default) {
             $url = 'http://' . $httpHost . __SAMSON_BASE__ . $currentUrlText;
         } else {
             $url = 'http://' . $httpHost . __SAMSON_BASE__ . $locale . '/' . $currentUrlText;
         }
         $localeName = '';
         if ($this->isLocaleLinkText) {
             $localeName = $this->translate($locale, $current);
         }
         $html .= $this->view('list/item')->css(self::CSS_PREFIX)->locale($locale == SamsonLocale::DEF && SamsonLocale::DEF == '' ? 'def' : $locale)->active($locale == $current ? self::CSS_PREFIX . 'active' : '')->url($url)->name($localeName)->output();
     }
     // Set locale list view
     $this->view('list/index')->locale($current)->css(self::CSS_PREFIX)->items($html);
 }