Example #1
0
 /**
  * Module initialization.
  *
  * @param array $params Initialization parameters collection
  * @return bool Initialization result
  */
 public function init(array $params = array())
 {
     //[PHPCOMPRESSOR(remove,start)]
     // Create SamsonPHP routing table from loaded modules
     $rg = new GenericRouteGenerator($this->system->module_stack);
     // Generate web-application routes
     $routes = $rg->generate();
     $routes->add($this->findGenericDefaultAction());
     // Create cache marker
     $this->cacheFile = $routes->hash() . '.php';
     // If we need to refresh cache
     if ($this->cache_refresh($this->cacheFile)) {
         $generator = new Structure($routes, new \samsonphp\generator\Generator());
         // Generate routing logic function
         $routerLogic = $generator->generate();
         // Store router logic in cache
         file_put_contents($this->cacheFile, '<?php ' . "\n" . $routerLogic);
     }
     require $this->cacheFile;
     //[PHPCOMPRESSOR(remove,end)]
     // This should be change to receive path as a parameter on initialization
     $pathParts = explode(Route::DELIMITER, $_SERVER['REQUEST_URI']);
     SamsonLocale::parseURL($pathParts);
     $this->requestURI = implode(Route::DELIMITER, $pathParts);
     // Subscribe to samsonphp\core routing event
     \samsonphp\event\Event::subscribe('core.routing', array($this, 'router'));
     // Continue initialization
     return parent::init($params);
 }
Example #2
0
 public function init(array $params = array())
 {
     // Create top parent container
     $this->workspace = new Container($this);
     // Create main UI menu
     $menu = new Menu($this, $this->workspace);
     $menu->set('class', 'main-menu');
     // Create home item
     $homeItem = new MenuItem($menu);
     $homeItem->set('title', 'Home')->set('class', 'btn-home')->set('content', '<a href="/"><i class="sprite sprite-header_home" href="/"></i></a>');
     // Create site item
     $siteItem = new MenuItem($menu);
     $siteItem->set('title', t('Перейти на веб-сайт', true))->set('class', 'btn-site')->set('content', '<a href="/"><i class="sprite sprite-header_site" href="/"></i></a>');
     // Fire event that ui menu left container has been created
     Event::fire('cms_ui.mainmenu_leftcreated', array(&$menu, &$this));
     // Create exit item
     $exitItem = new MenuItem($menu);
     $exitItem->set('title', t('Выйти', true))->set('class', 'btn-icon-right btn-logout')->set('content', '<a href="signin/logout"><i class="sprite sprite-header_logout" href="/"></i></a>');
     // Create settings item
     $settingsItem = new MenuItem($menu);
     $settingsItem->set('title', t('Выйти', true))->set('class', 'btn-icon-right btn-settings')->set('content', '<a href="settings"><i class="sprite sprite-header_settings" href="/"></i></a>');
     // Create i18n menu
     $i18nMenu = new Menu($this, $menu);
     $i18nMenu->set('title', t('Выберите язык', true))->set('class', 'i18n-list');
     // Iterate all supported locales
     foreach (\samson\core\SamsonLocale::get() as $locale) {
         $localeItem = new MenuItem($i18nMenu);
         $url = $locale == DEFAULT_LOCALE ? '' : '/' . $locale;
         $localeItem->set('class', 'i18n_item-' . $locale . ' ' . ($locale == \samson\core\SamsonLocale::current() ? 'i18n-active' : ''))->set('content', '<a href="' . $url . '">' . $locale . '</a>');
     }
     // Fire event that ui menu container has been created
     Event::fire('cms_ui.mainmenu_created', array(&$menu, &$this));
     // Create main UI menu
     $subMenu = new Menu($this, $menu);
     $subMenu->set('class', 'sub-menu');
     // Fire event that ui sub-menu container has been created
     Event::fire('cms_ui.submenu_created', array(&$subMenu, &$this));
     // Create main-content panel
     $mainPanel = new Container($this, $this->workspace);
     $mainPanel->set('class', 'mainPanel ' . (sizeof($subMenu->children()) ? 'with-sub-menu' : ''));
     /*// Create form with tabs
             $form = new Form($this, $mainPanel);
     
             // Create form tab view
             $tabs = new TabView($form);
     
             // Add tab
             $tab = new Tab($tabs);
             $tab->header->set('content', '<span>Описание</span>');
     
             // Create localized tabs
             foreach (\samson\core\SamsonLocale::get() as $locale) {
                 (new Tab($tab))->header->set('content', '<span>'.$locale.'</span>');
             }*/
     // Fire event that ui workspace container has been created
     Event::fire('cms_ui.workspace_created', array(&$this->workspace, &$this));
     return parent::init($params);
 }
Example #3
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;
 }
Example #4
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);
         }
     }
 }
Example #5
0
 /**
  * Handle core main template rendered event to
  * add SEO needed localization metatags to HTML markup
  * @param string $html Rendered HTML template from core
  * @param array $parameters Collection of data passed to current view
  * @param Module $module Pointer to active core module
  */
 public function templateRenderer(&$html)
 {
     $html = str_ireplace('</head>', $this->renderMetaTags(SamsonLocale::current(), SamsonLocale::$defaultLocale, url()->text) . '</head>', $html);
     $html = str_ireplace('<html>', '<html lang="' . SamsonLocale::current() . '">', $html);
 }
Example #6
0
 /**
  * Module initialization.
  *
  * @param array $params Initialization parameters collection
  * @return bool Initialization result
  */
 public function init(array $params = array())
 {
     //[PHPCOMPRESSOR(remove,start)]
     // Create SamsonPHP routing table from loaded modules
     $rg = new GenericRouteGenerator($this->system->module_stack);
     // Generate web-application routes
     $routes = $rg->generate();
     $routes->add($this->findGenericDefaultAction());
     // Create cache marker
     $this->cacheFile = $routes->hash() . '.php';
     // If we need to refresh cache
     if ($this->cache_refresh($this->cacheFile)) {
         $generator = new Structure($routes, new \samsonphp\generator\Generator());
         // Generate routing logic function
         $routerLogic = $generator->generate();
         // Store router logic in cache
         file_put_contents($this->cacheFile, '<?php ' . "\n" . $routerLogic);
     }
     require $this->cacheFile;
     //[PHPCOMPRESSOR(remove,end)]
     // Set locale resolver mode
     SamsonLocale::$leaveDefaultLocale = $this->browserLocaleRedirect;
     // This should be change to receive path as a parameter on initialization
     $pathParts = array_values(array_filter(explode(Route::DELIMITER, $_SERVER['REQUEST_URI'])));
     // Parse URL and store locale found bug
     $localeFound = SamsonLocale::parseURL($pathParts, $this->browserLocaleRedirect);
     // Gather URL path parts with removed locale placeholder
     $this->requestURI = implode(Route::DELIMITER, $pathParts);
     // Get localization data
     $current = SamsonLocale::current();
     $default = SamsonLocale::$defaultLocale;
     // Browser agent language detection logic
     if ($this->browserLocaleRedirect && !$localeFound) {
         // Redirect to browser language
         $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
         // Is browser language supported by application
         $langSupport = in_array($lang, SamsonLocale::get(), true);
         /**
          * If browser language header is supported by our web-application and we are already not on that locale
          * and current locale is not default.
          */
         if ($current === $default && $current !== $lang && $langSupport) {
             header('Location: http://' . $_SERVER['HTTP_HOST'] . '/' . $lang . '/' . $this->requestURI);
             exit;
         } elseif (!$langSupport || $lang === $current) {
             SamsonLocale::$leaveDefaultLocale = false;
         }
     }
     // Subscribe to samsonphp\core routing event
     \samsonphp\event\Event::subscribe('core.routing', array($this, 'router'));
     // Continue initialization
     return parent::init($params);
 }
Example #7
0
 public function parseUrl(&$urlObj, &$urlArgs)
 {
     if ($this->isCMS) {
         if (in_array($urlArgs[0], SamsonLocale::get(), true)) {
             unset($urlArgs[1]);
             $urlArgs = array_values($urlArgs);
         } else {
             array_shift($urlArgs);
         }
     }
 }
Example #8
0
/**
 * Build URL relative to current web-application, method accepts any number of arguments,
 * every argument starting from 2-nd firstly considered as module view parameter, if no such
 * parameters is found - its used as string.
 *
 * If current locale differs from default locale, current locale prepended to the beginning of URL
 *
 * @see URL::build()
 *
 * @return string Builded URL
 */
function url_build()
{
    // Get cached URL builder for speedup
    static $_v;
    $_v = isset($_v) ? $_v : url();
    // Get passed arguments
    $args = func_get_args();
    // If we have current locale set
    if (\samson\core\SamsonLocale::$leaveDefaultLocale && \samson\core\SamsonLocale::current() != \samson\core\SamsonLocale::DEF) {
        // Add locale as first url parameter
        array_unshift($args, \samson\core\SamsonLocale::current());
    }
    // Call URL builder with parameters
    return call_user_func_array(array($_v, 'build'), $args);
}