/** * Инициализация модуля * */ public function Init($bLocal = false) { $this->Hook_Run('viewer_init_start', compact('bLocal')); /** * Load template config */ if (!$bLocal) { if (file_exists($sFile = Config::Get('path.smarty.template') . '/settings/config/config.php')) { Config::LoadFromFile($sFile, false); } } /** * Разделитель заголовков страниц */ $this->SetHtmlTitleSeparation(Config::Get('view.title_separator')); /** * Заголовок HTML страницы */ $this->AddHtmlTitle(Config::Get('view.name')); /** * SEO ключевые слова страницы */ $this->sHtmlKeywords = Config::Get('view.keywords'); /** * SEO описание страницы */ $this->sHtmlDescription = Config::Get('view.description'); /** * Создаём объект Smarty и устанавливаем необходимые параметры */ $this->oSmarty = $this->CreateSmartyObject(); $this->oSmarty->error_reporting = error_reporting() & ~E_NOTICE; // подавляем NOTICE ошибки - в этом вся прелесть смарти ) $this->oSmarty->setTemplateDir(array_merge((array) Config::Get('path.smarty.template'), array(Config::Get('path.application.plugins.server') . '/'))); $this->oSmarty->compile_check = Config::Get('smarty.compile_check'); $this->oSmarty->force_compile = Config::Get('smarty.force_compile'); /** * Для каждого скина устанавливаем свою директорию компиляции шаблонов */ $sCompilePath = Config::Get('path.smarty.compiled') . '/' . Config::Get('view.skin'); if (!is_dir($sCompilePath)) { @mkdir($sCompilePath, 0777, true); } $this->oSmarty->setCompileDir($sCompilePath); $sCachePath = Config::Get('path.smarty.cache'); if (!is_dir($sCachePath)) { @mkdir($sCachePath, 0777, true); } $this->oSmarty->setCacheDir($sCachePath); $this->oSmarty->addPluginsDir(array(Config::Get('path.smarty.plug'), 'plugins')); $this->oSmarty->default_template_handler_func = array($this, 'SmartyDefaultTemplateHandler'); }
/** * Инициализация модуля * */ public function Init($bLocal = false) { $this->Hook_Run('viewer_init_start', compact('bLocal')); /** * Load template config */ if (!$bLocal) { if (file_exists(Config::Get('path.smarty.template') . '/settings/config/config.php')) { Config::LoadFromFile(Config::Get('path.smarty.template') . '/settings/config/config.php', false); } } /** * Заголовок HTML страницы */ $this->sHtmlTitle = Config::Get('view.name'); /** * SEO ключевые слова страницы */ $this->sHtmlKeywords = Config::Get('view.keywords'); /** * SEO описание страницы */ $this->sHtmlDescription = Config::Get('view.description'); /** * Создаём объект Smarty и устанавливаем необходиму параметры */ $this->oSmarty = new lsSmarty(); $this->oSmarty->error_reporting = E_ALL ^ E_NOTICE; // подавляем NOTICE ошибки - в этом вся прелесть смарти ) $this->oSmarty->template_dir = (array) Config::Get('path.smarty.template'); $this->oSmarty->template_dir[] = Config::Get('path.root.server') . '/plugins/'; /** * Для каждого скина устанавливаем свою директорию компиляции шаблонов */ $sCompilePath = Config::Get('path.smarty.compiled') . '/' . Config::Get('view.skin'); if (!is_dir($sCompilePath)) { @mkdir($sCompilePath); } $this->oSmarty->compile_dir = $sCompilePath; $this->oSmarty->cache_dir = Config::Get('path.smarty.cache'); $this->oSmarty->plugins_dir = array_merge(array(Config::Get('path.smarty.plug'), 'plugins'), $this->oSmarty->plugins_dir); /** * Получаем настройки блоков из конфигов */ $this->InitBlockParams(); /** * Добавляем блоки по предзагруженным правилам из конфигов */ $this->BuildBlocks(); /** * Получаем настройки JS, CSS файлов */ $this->InitFileParams(); $this->sCacheDir = Config::Get('path.smarty.cache'); }
/** * @param array $aConfig */ public static function Init($aConfig) { // Регистрация автозагрузчика классов spl_autoload_register('Loader::Autoload'); Config::Load($aConfig); $sConfigDir = Config::Get('path.dir.config'); // Load main config Config::LoadFromFile($sConfigDir . '/config.php', false); // Load additional config files if defined $aConfigLoad = F::Str2Array(Config::Get('config_load')); if ($aConfigLoad) { self::_loadConfigSections($sConfigDir, $aConfigLoad); } // Includes all *.php files from {path.root.engine}/include/ $sIncludeDir = Config::Get('path.dir.engine') . '/include/'; self::_includeAllFiles($sIncludeDir); // Load main config level (modules, local & plugins) self::_loadConfigFiles($sConfigDir, Config::LEVEL_MAIN); // Define app config dir $sAppConfigDir = Config::Get('path.dir.app') . '/config/'; // Ups config level Config::ResetLevel(Config::LEVEL_APP); // Load application config level (modules, local & plugins) self::_loadConfigFiles($sAppConfigDir, Config::LEVEL_APP); // Load additional config files (the set could be changed in this point) $aConfigLoad = F::Str2Array(Config::Get('config_load')); if ($aConfigLoad) { self::_loadConfigSections($sAppConfigDir, $aConfigLoad, Config::LEVEL_APP); } // Load include files of plugins self::_loadIncludeFiles(Config::LEVEL_MAIN); self::_loadIncludeFiles(Config::LEVEL_APP); self::_checkRequiredDirs(); $aSeekDirClasses = array(Config::Get('path.dir.app'), Config::Get('path.dir.common'), Config::Get('path.dir.engine')); Config::Set('path.root.seek', $aSeekDirClasses); if (is_null(Config::Get('path.root.subdir'))) { if (isset($_SERVER['DOCUMENT_ROOT'])) { $sPathSubdir = '/' . F::File_LocalPath(ALTO_DIR, $_SERVER['DOCUMENT_ROOT']); } elseif ($iOffset = Config::Get('path.offset_request_url')) { $aParts = array_slice(explode('/', F::File_NormPath(ALTO_DIR)), -$iOffset); $sPathSubdir = '/' . implode('/', $aParts); } else { $sPathSubdir = ''; } Config::Set('path.root.subdir', $sPathSubdir); } // Подгружаем конфиг из файлового кеша, если он есть Config::ResetLevel(Config::LEVEL_CUSTOM); $aConfig = Config::ReadCustomConfig(null, true); if ($aConfig) { Config::Load($aConfig, false, null, null, 'custom'); } // Задаем локаль по умолчанию F::IncludeLib('UserLocale/UserLocale.class.php'); // Устанавливаем признак того, является ли сайт многоязычным $aLangsAllow = (array) Config::Get('lang.allow'); if (sizeof($aLangsAllow) > 1) { UserLocale::initLocales($aLangsAllow); Config::Set('lang.multilang', true); } else { Config::Set('lang.multilang', false); } UserLocale::setLocale(Config::Get('lang.current'), array('local' => Config::Get('i18n.locale'), 'timezone' => Config::Get('i18n.timezone'))); Config::Set('i18n', UserLocale::getLocale()); F::IncludeFile(Config::Get('path.dir.engine') . '/classes/core/Engine.class.php'); }
$aConfig = (include $sPath); if (!empty($aConfig) && is_array($aConfig)) { // Если конфиг этого плагина пуст, то загружаем массив целиком $sKey = "plugin.{$sPlugin}"; if (!Config::isExist($sKey)) { Config::Set($sKey, $aConfig); } else { // Если уже существую привязанные к плагину ключи, // то сливаем старые и новое значения ассоциативно Config::Set($sKey, func_array_merge_assoc(Config::Get($sKey), $aConfig)); } } } } /** * Подключаем include-файлы */ $aIncludeFiles = glob($sPluginsDir . '/' . $sPlugin . '/include/*.php'); if ($aIncludeFiles and count($aIncludeFiles)) { foreach ($aIncludeFiles as $sPath) { require_once $sPath; } } } } /** * Загружает конфиг текущего шаблона */ if (file_exists(Config::Get('path.smarty.template') . '/settings/config/config.php')) { Config::LoadFromFile(Config::Get('path.smarty.template') . '/settings/config/config.php', false); }
Config::Set($sKey, func_array_merge_assoc(Config::Get($sKey), $aConfig)); } } } } } closedir($hDirConfig); } /** * Подгружаем файлы локального и продакшн-конфига */ if (file_exists(Config::Get('path.root.server') . '/config/config.local.php')) { Config::LoadFromFile(Config::Get('path.root.server') . '/config/config.local.php', false); } if (file_exists(Config::Get('path.root.server') . '/config/config.stable.php')) { Config::LoadFromFile(Config::Get('path.root.server') . '/config/config.stable.php', false); } /** * Загружает конфиги плагинов вида /plugins/[plugin_name]/config/*.php * и include-файлы /plugins/[plugin_name]/include/*.php */ $sPluginsDir = Config::Get('path.root.server') . '/plugins'; $sPluginsListFile = $sPluginsDir . '/' . Config::Get('sys.plugins.activation_file'); if ($aPluginsList = @file($sPluginsListFile)) { $aPluginsList = array_map('trim', $aPluginsList); foreach ($aPluginsList as $sPlugin) { $aConfigFiles = glob($sPluginsDir . '/' . $sPlugin . '/config/*.php'); if ($aConfigFiles and count($aConfigFiles) > 0) { foreach ($aConfigFiles as $sPath) { $aConfig = $fGetConfig($sPath); if (!empty($aConfig) && is_array($aConfig)) {
while (false !== ($sFileInclude = readdir($hDirInclude))) { $sFileIncludePathFull = $sDirInclude . $sFileInclude; if ($sFileInclude != '.' and $sFileInclude != '..' and is_file($sFileIncludePathFull)) { $aPathInfo = pathinfo($sFileIncludePathFull); if (isset($aPathInfo['extension']) and strtolower($aPathInfo['extension']) == 'php') { require_once $sDirInclude . $sFileInclude; } } } closedir($hDirInclude); } /** * Подгружаем конфиг окружения */ if (file_exists(Config::Get('path.application.server') . "/config/config.{$sEnvironmentCurrent}.php")) { Config::LoadFromFile(Config::Get('path.application.server') . "/config/config.{$sEnvironmentCurrent}.php", false); } /** * Загружает конфиги плагинов вида /plugins/[plugin_name]/config/*.php * и include-файлы /plugins/[plugin_name]/include/*.php */ $sPluginsDir = Config::Get('path.application.plugins.server'); $sPluginsListFile = $sPluginsDir . '/' . Config::Get('sys.plugins.activation_file'); if ($aPluginsList = @file($sPluginsListFile)) { $aPluginsList = array_map('trim', $aPluginsList); foreach ($aPluginsList as $sPlugin) { $aConfigFiles = glob($sPluginsDir . '/' . $sPlugin . '/config/*.php'); if ($aConfigFiles and count($aConfigFiles) > 0) { foreach ($aConfigFiles as $sPath) { $aConfig = $fGetConfig($sPath); if (!empty($aConfig) && is_array($aConfig)) {
/** * Установка языка интерфейса * * @return void */ public function SetLang() { if (!$this->User_IsInit()) { $this->User_Init(); } if ($this->PluginL10n_L10n_GetLangFromUrl()) { // берем язык интерфейса с урла Config::Set('lang.current', $this->PluginL10n_L10n_GetLangFromUrl()); } elseif ($this->User_IsAuthorization()) { // если в урле пусто - // для авторизированных пользователей проверяем какой язык интерфейса // выбран по умолчанию и устанавливаем его в качестве текущего $oUser = $this->User_GetUserCurrent(); Config::Set('lang.current', $oUser->getUserLang()); } elseif (isset($_SERVER['REMOTE_ADDR']) && Config::Get('plugin.l10n.use_geoip')) { // для остальных язык будет передаваться по GeoIP require_once Plugin::GetPath(__CLASS__) . 'classes/lib/external/GeoIp/Wrapper.php'; $gi = new GeoIp_Wrapper(); // 2х значный код страны - он же код языка $country = $gi->getCountryCodeByAddr($_SERVER['REMOTE_ADDR']); $ruSpeaks = Config::Get('plugin.l10n.ru.countries'); // @todo refact if ($country == 'ua') { Config::Set('lang.current', $this->PluginL10n_L10n_GetLangByAlias('uk')); setlocale(LC_ALL, "uk_UA.UTF-8"); } else { Config::Set('lang.current', $this->PluginL10n_L10n_GetLangByAlias('ru')); setlocale(LC_ALL, "ru_RU.UTF-8"); date_default_timezone_set('Europe/Moscow'); // See http://php.net/manual/en/timezones.php } // if (in_array($country, $ruSpeaks)) { // Config::Set('lang.current', $this->PluginL10n_L10n_GetLangByAlias('ru')); // // setlocale(LC_ALL, "ru_RU.UTF-8"); // date_default_timezone_set('Europe/Moscow'); // See http://php.net/manual/en/timezones.php // } else { // Config::Set('lang.current', $this->PluginL10n_L10n_GetLangByAlias('en')); // // setlocale(LC_ALL, "en_EN.UTF-8"); // } } else { Config::Set('lang.current', Config::Get('lang.default')); } $sLang = $this->PluginL10n_L10n_GetAliasByLang(Config::Get('lang.current')); $sWebPath = Router::GetPathWebCurrent(); /** * Проверяем, включено ли принудительно проставление языка в урле, не является ли это CLI или Аяксом */ if (Config::Get('plugin.l10n.lang_in_url') && $sWebPath && !$this->isAjax()) { /** * Проверям, был ли язык в урле, и не главная ли это страница */ if (!Router::getLang() && rtrim($sWebPath, '/') != Config::Get('path.root.web')) { $sWebPath = str_replace(Config::Get('path.root.web'), Config::Get('path.root.web') . '/' . $sLang, $sWebPath); Router::Location($sWebPath); } $this->PluginL10n_L10n_SetLangForUrl($sLang); } $sConfigFile = Config::Get('path.root.server') . '/config/plugins/l10n/config.' . $sLang . '.php'; if (file_exists($sConfigFile)) { Config::LoadFromFile($sConfigFile); } $this->UpdateBlockRoutes(); $this->Viewer_Assign('sLangCurrent', $this->PluginL10n_L10n_GetAliasByLang(Config::Get('lang.current'))); }
/** * Чтение пользовательской конфигурации плагинов * * @param null|string|array $aPlugins - имя плагина или массив имен, если не задано, то все активные плагины * @param bool $bForce - подгружать, даже если подгрузка запрещена в конфиге * @param bool $bPluginOnly - подгружать только кофиг плагина */ static function LoadCustomPluginsConfig($aPlugins = null, $bForce = false, $bPluginOnly = false) { if (self::_getVal('custom_config.enable') or $bForce) { if ($sCustomConfigPath = self::_getCustomConfigPath() and is_dir($sCustomConfigPath)) { // Подгрузка общего файла конфигурации, если он есть if (!$bPluginOnly and is_file($sCustomConfigPath . '/config.php')) { Config::LoadFromFile($sCustomConfigPath . '/config.php', false); } if (self::_getVal('custom_config.plugins')) { if (is_null($aPlugins)) { $aPlugins = self::_getActivePlugins(); } elseif (!is_array($aPlugins)) { $aPlugins = array($aPlugins); } // Подгрузка файлов конфигурации для каждого плагина foreach ($aPlugins as $sPlugin) { // сначала проверяем файл config.<plugin>.php if (is_file($sFile = $sCustomConfigPath . '/config.' . $sPlugin . '.php')) { self::LoadPluginConfig($sPlugin, $sFile); } // проверяем файлы <plugin>/config.php if (is_dir($sPath = $sCustomConfigPath . '/' . $sPlugin)) { if (is_file($sFile = $sPath . '/config.php')) { self::LoadPluginConfig($sPlugin, $sFile); } } } } } } }
/** * Конструктор * * @param Engine $oEngine Объект ядра * @param string $sAction Название экшена */ public function __construct($oEngine, $sAction = null) { if (func_num_args() == 1 && is_string($oEngine)) { // Передан только экшен $this->oEngine = E::getInstance(); $sAction = $oEngine; } else { // LS-compatible $this->oEngine = $oEngine; } //Engine::getInstance(); $this->sCurrentAction = $sAction; $this->aParams = R::GetParams(); $this->RegisterEvent(); // load action's config if exists Config::ResetLevel(Config::LEVEL_ACTION); if ($sFile = F::File_Exists('/config/actions/' . $sAction . '.php', Config::Get('path.root.seek'))) { // Дополняем текущий конфиг конфигом экшена Config::LoadFromFile($sFile, false, Config::LEVEL_ACTION); } }