public function Init() { if ($result = parent::Init()) { return $result; } $this->SetDefaultEvent('info'); $this->InitParams(); $this->aConfig = array_merge($this->aConfig, HelperPlugin::GetConfig()); $this->oUserCurrent = $this->PluginAceadminpanel_Admin_GetUserCurrent(); if (!$this->User_IsAuthorization() || !$this->oUserCurrent->isAdministrator()) { return $this->EventDenied(); } $this->oUserCurrent = $this->User_GetUserCurrent(); $this->Viewer_Assign('ROUTE_PAGE_ADMIN', ROUTE_PAGE_ADMIN); $this->Viewer_Assign('sModuleVersion', $this->PluginAceadminpanel_Admin_getVersion(true)); if (Config::Get('plugin.avalogs.admin_file') && Config::Get('plugin.avalogs.admin_enable')) { if (!$this->oLogs) { $this->oLogs = $this->Adminlogs_GetLogs(); } $this->oLogs->SetLogOptions('admin', array('file' => Config::Get('plugin.avalogs.admin_file'))); $this->aLogsMsg[] = 'user=>' . $this->oUserCurrent->GetLogin() . ', ip=>' . $_SERVER["REMOTE_ADDR"] . ', action=>' . Router::GetAction() . ', event=>' . Router::GetActionEvent() . ', path=>' . Router::GetPathWebCurrent(); } if (isset($_SERVER['HTTP_REFERER'])) { $this->sPageRef = $_SERVER['HTTP_REFERER']; } $this->PluginSetTemplate(Router::GetActionEvent()); $this->sMenuItemSelect = Router::GetActionEvent(); $this->sMenuSubItemSelect = Router::GetParam(0); $this->aPluginInfo = array('version' => HelperPlugin::GetConfig('version')); $this->PluginAppendStyle('admin.css'); $this->PluginAppendScript('admin.js'); }
public function Init() { $this->sCurrentEvent = Router::GetActionEvent(); if ($result = parent::Init()) { return $result; } if ($this->User_IsAuthorization()) { $this->oUserCurrent = $this->PluginAceadminpanel_Admin_GetUserCurrent(); } if (!$this->oUserCurrent or !$this->oUserCurrent->isAdministrator()) { return $this->EventDenied(); } if (!$this->oUserCurrent) { $this->oUserCurrent = $this->User_GetUserCurrent(); } $this->Viewer_Assign('ROUTE_PAGE_ADMIN', ROUTE_PAGE_ADMIN); $this->Viewer_Assign('sModuleVersion', $this->PluginAceadminpanel_Admin_getVersion(true)); $this->_InitParams(); $this->aConfig = array_merge($this->aConfig, HelperPlugin::GetConfig()); if (Config::Get('plugin.avalogs.admin_file') and Config::Get('plugin.avalogs.admin_enable')) { if (!$this->oLogs) { $this->oLogs = $this->Adminlogs_GetLogs(); } $this->oLogs->SetLogOptions('admin', array('file' => Config::Get('plugin.avalogs.admin_file'))); $this->aLogsMsg[] = 'user=>' . $this->oUserCurrent->GetLogin() . ', ip=>' . $_SERVER["REMOTE_ADDR"] . ', action=>' . Router::GetAction() . ', event=>' . Router::GetActionEvent() . ', path=>' . Router::GetPathWebCurrent(); } $this->sPageRef = ACE::Backward('url'); if (ACE::Backward('action') == Router::GetAction()) { $this->sFormAction = $this->sPageRef; } //$this->_PluginSetTemplate(Router::GetActionEvent()); $this->sMenuItemSelect = Router::GetActionEvent(); $this->sMenuSubItemSelect = Router::GetParam(0); $sVerion = HelperPlugin::GetConfig('version'); if (!$sVerion) { $sVerion = ACEADMINPANEL_VERSION . '.' . ACEADMINPANEL_VERSION_BUILD; } if (preg_match('|[a-z\\-]+|i', $sVerion, $m)) { $sVerion = str_replace($m[0], '', $sVerion) . $m[0]; } $this->aPluginInfo = array('version' => $sVerion); $sHtmlTitle = $this->Lang_Get('adm_title') . ' v.' . $this->PluginAceadminpanel_Admin_getVersion(); //$this->Viewer_AddTemplateDir(HelperPlugin::GetTemplatePath(), true); $this->Viewer_AddHtmlTitle($sHtmlTitle); $this->Viewer_Assign('sAdminTitle', 'aceAdminPanel v.' . $this->PluginAceadminpanel_Admin_getVersion()); }
/** * Строит массив для подключения css и js, * преобразовывает их в строку для HTML * * @return bool */ protected function BuildHeadFiles() { $sPath = Router::GetPathWebCurrent(); /** * По умолчанию имеем дефаултовые настройки */ $aResult = $this->aFilesDefault; $this->aFileRules = Config::Get('head.rules'); foreach ((array) $this->aFileRules as $sName => $aRule) { if (!$aRule['path']) { continue; } foreach ((array) $aRule['path'] as $sRulePath) { $sPattern = "~" . str_replace(array('/', '*'), array('\\/', '\\w+'), $sRulePath) . "~"; if (preg_match($sPattern, $sPath)) { /** * Преобразование JS */ if (isset($aRule['js']['empty']) && $aRule['js']['empty']) { $aResult['js'] = array(); } if (isset($aRule['js']['exclude']) && is_array($aRule['js']['exclude'])) { $aResult['js'] = array_diff($aResult['js'], $aRule['js']['exclude']); } if (isset($aRule['js']['include']) && is_array($aRule['js']['include'])) { $aResult['js'] = array_merge($aResult['js'], $aRule['js']['include']); } /** * Преобразование CSS */ if (isset($aRule['css']['empty']) && $aRule['css']['empty']) { $aResult['css'] = array(); } if (isset($aRule['css']['exclude']) && is_array($aRule['css']['exclude'])) { $aResult['css'] = array_diff($aResult['css'], $aRule['css']['exclude']); } if (isset($aRule['css']['include']) && is_array($aRule['css']['include'])) { $aResult['css'] = array_merge($aResult['css'], $aRule['css']['include']); } /** * Продолжаем поиск */ if (isset($aRule['stop'])) { break 2; } } } } /** * Добавляем скрипты и css из массивов */ $aResult['js'] = array_values(array_merge((array) $this->aJsInclude['prepend'], (array) $aResult['js'], (array) $this->aJsInclude['append'])); $aResult['css'] = array_values(array_merge((array) $this->aCssInclude['prepend'], (array) $aResult['css'], (array) $this->aCssInclude['append'])); /** * Получаем список блоков */ $aBlocks['js'] = array_unique(array_map(create_function('$sJs', 'return isset($sJs["block"]) ? $sJs["block"] : null;'), $this->aFilesParams['js'])); $aBlocks['css'] = array_unique(array_map(create_function('$sCss', 'return isset($sCss["block"]) ? $sCss["block"] : null;'), $this->aFilesParams['css'])); /** * Сливаем файлы в один, используя блочное разделение */ $aHeadFiles = array('js' => array(), 'css' => array()); foreach (array('js', 'css') as $sType) { /** * Отдельно выделяем файлы, для которых указано отображение, * привязанное к браузеру (ex. IE6, IE7) */ $aFilesHack = array_filter($this->aFilesParams[$sType], create_function('$aParams', 'return array_key_exists("browser",(array)$aParams);')); $aFilesHack = array_intersect(array_keys($aFilesHack), $aResult[$sType]); /** * Исключаем эти файлы из основной выдачи */ $aResult[$sType] = array_diff($aResult[$sType], $aFilesHack); /** * Аналогично выделяем файлы, которые не нужно объединять со всеми * TODO: объединить в один цикл с $aFilesHack */ $aFilesNoMerge = array_filter($this->aFilesParams[$sType], create_function('$aParams', 'return array_key_exists("merge",(array)$aParams) and !$aParams["merge"];')); $aFilesNoMerge = array_intersect(array_keys($aFilesNoMerge), $aResult[$sType]); $aResult[$sType] = array_diff($aResult[$sType], $aFilesNoMerge); /** * Добавляем файлы поблочно */ if ($aBlocks[$sType] && count($aBlocks[$sType])) { foreach ($aBlocks[$sType] as $sBlock) { if (!$sBlock) { continue; } /** * Выбираем все файлы, входящие в данный блок */ $aFiles = array_filter($this->aFilesParams[$sType], create_function('$aParams', 'return (isset($aParams)&&($aParams["block"]=="' . $sBlock . '"));')); $aFiles = array_intersect(array_keys($aFiles), $aResult[$sType]); if ($aFiles && count($aFiles)) { $aHeadFiles[$sType][] = $this->Compress($aFiles, $sType); /** * Удаляем эти файлы из */ $aResult[$sType] = array_diff($aResult[$sType], $aFiles); } } } /** * Обрабатываем "последние" оставшиеся */ if (Config::Get("compress.{$sType}.merge")) { $aHeadFiles[$sType][] = $this->Compress($aResult[$sType], $sType); } else { $aHeadFiles[$sType] = array_map(array($this, 'GetWebPath'), array_merge($aHeadFiles[$sType], $aResult[$sType])); } /** * Добавляем файлы хаков */ if (is_array($aFilesHack) && count($aFilesHack)) { $aHeadFiles[$sType] = array_merge($aHeadFiles[$sType], $aFilesHack); } if (is_array($aFilesNoMerge) && count($aFilesNoMerge)) { $aHeadFiles[$sType] = array_merge($aHeadFiles[$sType], $aFilesNoMerge); } } /** * Получаем HTML код */ $aHtmlHeadFiles = $this->BuildHtmlHeadFiles($aHeadFiles); $this->SetHtmlHeadFiles($aHtmlHeadFiles); return true; }
/** * Анализируем правила и наборы массивов * получаем окончательные списки блоков */ protected function BuildBlocks() { $sAction = strtolower(Router::GetAction()); $sEvent = strtolower(Router::GetActionEvent()); $sEventName = strtolower(Router::GetActionEventName()); foreach ($this->aBlockRules as $sName => $aRule) { $bUse = false; /** * Если в правиле не указан список блоков, нам такое не нужно */ if (!array_key_exists('blocks', $aRule)) { continue; } /** * Если не задан action для исполнения и нет ни одного шаблона path, * или текущий не входит в перечисленные в правиле * то выбираем следующее правило */ if (!array_key_exists('action', $aRule) && !array_key_exists('path', $aRule)) { continue; } if (isset($aRule['action'])) { if (in_array($sAction, (array) $aRule['action'])) { $bUse = true; } if (array_key_exists($sAction, (array) $aRule['action'])) { /** * Если задан список event`ов и текущий в него не входит, * переходи к следующему действию. */ foreach ((array) $aRule['action'][$sAction] as $sEventPreg) { if (substr($sEventPreg, 0, 1) == '/') { /** * Это регулярное выражение */ if (preg_match($sEventPreg, $sEvent)) { $bUse = true; break; } } elseif (substr($sEventPreg, 0, 1) == '{') { /** * Это имя event'a (именованный евент, если его нет, то совпадает с именем метода евента в экшене) */ if (trim($sEventPreg, '{}') == $sEventName) { $bUse = true; break; } } else { /** * Это название event`a */ if ($sEvent == $sEventPreg) { $bUse = true; break; } } } } } /** * Если не найдено совпадение по паре Action/Event, * переходим к поиску по regexp путей. */ if (!$bUse && isset($aRule['path'])) { $sPath = rtrim(Router::GetPathWebCurrent(), "/"); /** * Проверяем последовательно каждый regexp */ foreach ((array) $aRule['path'] as $sRulePath) { $sPattern = "~" . str_replace(array('/', '*'), array('\\/', '[\\w\\-]+'), $sRulePath) . "~"; if (preg_match($sPattern, $sPath)) { $bUse = true; break 1; } } } if ($bUse) { /** * Если задан режим очистки блоков, сначала чистим старые блоки */ if (isset($aRule['clear'])) { switch (true) { /** * Если установлен в true, значит очищаем все */ case $aRule['clear'] === true: $this->ClearBlocksAll(); break; case is_string($aRule['clear']): $this->ClearBlocks($aRule['clear']); break; case is_array($aRule['clear']): foreach ($aRule['clear'] as $sGroup) { $this->ClearBlocks($sGroup); } break; } } /** * Добавляем все блоки, указанные в параметре blocks */ foreach ($aRule['blocks'] as $sGroup => $aBlocks) { foreach ((array) $aBlocks as $sName => $aParams) { /** * Если название блока указывается в параметрах */ if (is_int($sName)) { if (is_array($aParams)) { $sName = $aParams['block']; } } /** * Если $aParams не являются массивом, значит передано только имя блока */ if (!is_array($aParams)) { $this->AddBlock($sGroup, $aParams); } else { $this->AddBlock($sGroup, $sName, isset($aParams['params']) ? $aParams['params'] : array(), isset($aParams['priority']) ? $aParams['priority'] : 5); } } } } } }
/** * Возвращает список дефолтных параметров * * @return array */ protected function getDefaultProperties() { if (file_exists(Config::Get('path.smarty.template') . DIRECTORY_SEPARATOR . 'og-default.png')) { $sImage = Config::Get('path.skin.web') . '/og-default.png'; } else { $sImage = Config::Get('path.framework.web') . '/frontend/common/images/ls-logo.png'; } return array('og:title' => $this->Viewer_GetHtmlTitle(), 'og:type' => 'website', 'og:image' => Router::GetFixPathWeb($sImage), 'og:url' => Router::GetPathWebCurrent(), 'og:site_name' => Config::Get('view.name')); }
/** * Установка языка интерфейса * * @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'))); }
/** * Загружает виджеты, указанные в правилах * * @return mixed */ protected function _loadWidgetsList() { $aResult = parent::_loadWidgetsList(); // добавляем LS-блоки по старым правилам, если они есть $aBlockRules = Config::Get('block'); if ($aBlockRules) { $sAction = strtolower(Router::GetAction()); $sEvent = strtolower(Router::GetActionEvent()); $sEventName = strtolower(Router::GetActionEventName()); foreach ($aBlockRules as $aRule) { $bUse = false; // * Если в правиле не указан список блоков, нам такое не нужно if (!array_key_exists('blocks', $aRule)) { continue; } /* * Если не задан action для исполнения и нет ни одного шаблона path, * или текущий не входит в перечисленные в правиле * то выбираем следующее правило */ if (!array_key_exists('action', $aRule) && !array_key_exists('path', $aRule)) { continue; } if (isset($aRule['action'])) { if (in_array($sAction, (array) $aRule['action'])) { $bUse = true; } if (array_key_exists($sAction, (array) $aRule['action'])) { /** * Если задан список event`ов и текущий в него не входит, * переходи к следующему действию. */ foreach ((array) $aRule['action'][$sAction] as $sEventPreg) { if (substr($sEventPreg, 0, 1) == '/') { // * Это регулярное выражение if (preg_match($sEventPreg, $sEvent)) { $bUse = true; break; } } elseif (substr($sEventPreg, 0, 1) == '{') { // * Это имя event'a (именованный евент, если его нет, то совпадает с именем метода евента в экшене) if (trim($sEventPreg, '{}') == $sEventName) { $bUse = true; break; } } else { // * Это название event`a if ($sEvent == $sEventPreg) { $bUse = true; break; } } } } } // * Если не найдено совпадение по паре Action/Event, то переходим к поиску по regexp путей. if (!$bUse && isset($aRule['path'])) { $sPath = rtrim(Router::GetPathWebCurrent(), "/"); // * Проверяем последовательно каждый regexp foreach ((array) $aRule['path'] as $sRulePath) { $sPattern = "~" . str_replace(array('/', '*'), array('\\/', '[\\w\\-]+'), $sRulePath) . "~"; if (preg_match($sPattern, $sPath)) { $bUse = true; break 1; } } } if ($bUse) { // * Если задан режим очистки блоков, сначала чистим старые блоки if (isset($aRule['clear'])) { switch (true) { // * Если установлен в true, значит очищаем все case $aRule['clear'] === true: //$this->ClearBlocksAll(); $aResult = array(); break; case is_string($aRule['clear']): //$this->ClearBlocks($aRule['clear']); foreach ($aResult as $sId => $oWidget) { if ($oWidget->GetGroup() == $aRule['clear']) { unset($aResult[$sId]); } } break; case is_array($aRule['clear']): /* foreach ($aRule['clear'] as $sGroup) { $this->ClearBlocks($sGroup); } */ foreach ($aResult as $sId => $oWidget) { if (in_array($oWidget->GetGroup(), $aRule['clear'])) { unset($aResult[$sId]); } } break; } } // * Добавляем все блоки, указанные в параметре blocks foreach ($aRule['blocks'] as $sGroup => $aBlocks) { foreach ((array) $aBlocks as $sName => $aParams) { // * Если название блока указывается в параметрах if (is_int($sName)) { if (is_array($aParams)) { $sName = $aParams['block']; } } // * Если $aParams не являются массивом, значит передано только имя блока if (!is_array($aParams)) { $sName = $aParams; $aParams = array(); $nPriority = isset($aParams['priority']) ? $aParams['priority'] : 5; } else { $nPriority = isset($aParams['priority']) ? $aParams['priority'] : 5; $aParams = isset($aParams['params']) ? $aParams['params'] : array(); } $aWidgetData = array('name' => $sName, 'group' => $sGroup, 'priority' => $nPriority, 'params' => $aParams); $oWidget = $this->MakeWidget($aWidgetData); $aResult[$oWidget->getId()] = $oWidget; } } } } } return $aResult; }
/** * Протоколирование запросов */ public function OutLog($aVars = null) { if (!$this->bLogEnable) { return; } if (defined('MYSEARCH_LOGS_FILE') && MYSEARCH_LOGS_FILE) { $sLogFile = MYSEARCH_LOGS_FILE; } else { $sLogFile = 'mysearch.log'; } if (!$this->oUser) { if ($sUserId = $this->Session_Get('user_id')) { $this->oUser = $this->User_GetUserById($sUserId); } } if (!$this->oUser) { $sUserLogin = '******'; } else { $sUserLogin = $this->oUser->GetLogin(); } if (!$this->oLogs) { $this->oLogs = $this->Adminlogs_GetLogs(); } $path = Router::GetPathWebCurrent(); if (strpos($path, DIR_WEB_ROOT) === 0) { $path = mb_substr($path, DIR_WEB_ROOT); } $uri = $_SERVER["REQUEST_URI"]; if (strpos($uri, DIR_WEB_ROOT) === 0) { $uri = mb_substr($uri, DIR_WEB_ROOT); } $sStrLog = 'user=>"' . $sUserLogin . '" ip=>"' . $_SERVER["REMOTE_ADDR"] . '"' . "\n" . str_repeat(' ', 22) . 'path=>' . $path . '"' . "\n" . str_repeat(' ', 22) . 'uri=>' . $uri . '"'; if (is_array($aVars) && sizeof($aVars)) { foreach ($aVars as $key => $val) { $sStrLog .= "\n" . str_repeat(' ', 22) . $key . '=>"' . $val . '"'; } } $this->oLogs->SetLogOptions('mysearch', array('file' => $sLogFile, 'trace' => false)); $this->oLogs->RecordAdd('mysearch', $sStrLog); }