public function initEngine() { if (!$this->oEngine) { $this->oEngine = Engine::getInstance(); $this->oEngine->Init(); } }
function _smarty_include($params) { if (isset($params['smarty_include_tpl_file'])) { $params['smarty_include_tpl_file'] = Engine::getInstance()->Plugin_GetDelegate('template', $params['smarty_include_tpl_file']); } parent::_smarty_include($params); }
/** * Plugin for Smarty * * @param array $aParams * @param Smarty_Internal_Template $oSmartyTemplate * * @return string|null */ function smarty_function_widget_template($aParams, $oSmartyTemplate) { if (!isset($aParams['name'])) { trigger_error('Parameter "name" does not define in {widget ...} function', E_USER_WARNING); return null; } $sWidgetName = $aParams['name']; $aWidgetParams = isset($aParams['params']) ? $aParams['params'] : array(); $oEngine = Engine::getInstance(); // Проверяем делигирование $sTemplate = E::ModulePlugin()->GetDelegate('template', $sWidgetName); if ($sTemplate) { if ($aWidgetParams) { foreach ($aWidgetParams as $sKey => $sVal) { $oSmartyTemplate->assign($sKey, $sVal); } if (!isset($aWidgetParams['params'])) { /* LS-compatible */ $oSmartyTemplate->assign('params', $aWidgetParams); } $oSmartyTemplate->assign('aWidgetParams', $aWidgetParams); } $sResult = $oSmartyTemplate->fetch($sTemplate); } else { $sResult = null; } return $sResult; }
/** * Показывает блоки определенно группы * * @param unknown_type $params * @param unknown_type $smarty * @return unknown */ function smarty_function_show_blocks($aParams, &$oSmarty) { if (!array_key_exists('group', $aParams)) { trigger_error("show_blocks: missing 'group' parameter", E_USER_WARNING); return; } $sGroup = $aParams['group']; $aBlocks = Engine::getInstance()->Viewer_GetBlocks(true); $sResult = ''; if (isset($aBlocks[$sGroup]) and is_array($aBlocks[$sGroup])) { $oSmarty->loadPlugin('smarty_insert_block'); foreach ($aBlocks[$sGroup] as $aBlock) { if ($aBlock['type'] == 'block') { $sResult .= smarty_insert_block(array('block' => $aBlock['name'], 'params' => isset($aBlock['params']) ? $aBlock['params'] : array()), $oSmarty); } elseif ($aBlock['type'] == 'template') { $sResult .= $oSmarty->getSubTemplate($aBlock['name'], $oSmarty->cache_id, $oSmarty->compile_id, null, null, array('params' => isset($aBlock['params']) ? $aBlock['params'] : array()), Smarty::SCOPE_LOCAL); } } } if (!empty($aParams['assign'])) { $oSmarty->assign($aParams['assign'], $sResult); } else { return $sResult; } }
public function ClearComments() { $sql = "SELECT co.comment_id FROM " . Config::Get('db.table.comment_online') . " AS co\n LEFT JOIN " . Config::Get('db.table.topic') . " AS t ON co.target_type='topic' AND co.target_id=t.topic_id\n WHERE t.topic_id IS NULL"; if ($aCommentId = $this->oDb->selectCol($sql)) { Engine::getInstance()->Comment_DeleteCommentOnlineByArrayId($aCommentId, 'topic'); } return true; }
protected function DeclareClass($sClassName) { $aClassElements = $this->ClassNameExplode($sClassName); $sParentClass = ''; $sFileClass = ''; if (isset($aClassElements['Module'])) { $sClassDelegate = Engine::getInstance()->Plugin_GetDelegate('module', $sClassName); if ($sClassDelegate != $sClassName) { $sParentClass = $sClassDelegate; } } if (!$sParentClass) { $sClassNameItem = $sClassName; if (isset($aClassElements['Plugin'])) { // класс внутри плагина $sParentClass = 'Plugin' . ucfirst(strtolower($aClassElements['Plugin'])) . '_'; $n = strpos($sClassName, '_'); if ($n) { $sClassNameItem = substr($sClassName, $n + 1); } // если такой плагин не активирван, то уходим if (!in_array(strtolower($aClassElements['Plugin']), Engine::getInstance()->Plugin_GetActivePlugins())) { return; } } if (preg_match('/^Ls([\\w]+)/', $sClassNameItem, $aMatches)) { $sParentClass .= 'Module' . $aMatches[1]; } elseif (preg_match('/^(\\w+)Entity_([\\w]+)/', $sClassNameItem, $aMatches)) { $sParentClass .= 'Module' . $aMatches[1] . '_Entity' . $aMatches[2]; } elseif (preg_match('/^Mapper_([\\w]+)/', $sClassNameItem, $aMatches)) { $sParentClass .= 'Module' . $aMatches[1] . '_Mapper' . $aMatches[1]; } elseif (isset($aClassElements['Inherits'])) { if (isset($aClassElements['Module'])) { $sParentClass .= 'Inherit_Module' . $aClassElements['Module']; } } elseif (isset($aClassElements['Action'])) { $sParentClass .= 'Action' . $aClassElements['Action']; } elseif (isset($aClassElements['Block'])) { $sParentClass .= 'Block' . $aClassElements['Block']; } elseif (isset($aClassElements['Hook'])) { $sParentClass .= 'Hook' . $aClassElements['Hook']; } elseif (isset($aClassElements['Module'])) { $sParentClass .= $aClassElements['Module']; } elseif (isset($aClassElements['Mapper'])) { $sParentClass .= '_Mapper' . $aClassElements['Mapper']; } } if (!$sFileClass) { $sFileClass = $this->ClassToPath($sClassName); } if ($sFileClass && file_exists($sFileClass)) { include_once $sFileClass; } if (!class_exists($sClassName, false) && $sParentClass && $sParentClass != $sClassName) { $sEvalCode = 'class ' . $sClassName . ' extends ' . $sParentClass . ' {}'; eval($sEvalCode); } }
/** * Загружает в переменную список блоков * * @param unknown_type $params * @param unknown_type $smarty * @return unknown */ function smarty_function_get_blocks($params, &$smarty) { if (!array_key_exists('assign', $params)) { trigger_error("get_blocks: missing 'assign' parameter", E_USER_WARNING); return; } $smarty->assign($params['assign'], Engine::getInstance()->Viewer_GetBlocks()); return ''; }
/** * Плагин для смарти * Подключает обработчик блоков шаблона * * @param array $aParams * @param Smarty $oSmarty * @return string */ function smarty_insert_block($aParams, &$oSmarty) { if (!isset($aParams['block'])) { trigger_error('Not found param "block"', E_USER_WARNING); return; } /** * Устанавливаем шаблон */ $sBlock = ucfirst(basename($aParams['block'])); /** * Проверяем наличие шаблона. Определяем значения параметров работы в зависимости от того, * принадлежит ли блок одному из плагинов, или является пользовательским классом движка */ if (isset($aParams['params']) and isset($aParams['params']['plugin'])) { $sBlockTemplate = Plugin::GetTemplatePath($aParams['params']['plugin']) . '/blocks/block.' . $aParams['block'] . '.tpl'; $sBlock = 'Plugin' . ucfirst($aParams['params']['plugin']) . '_Block' . $sBlock; } else { $sBlockTemplate = 'blocks/block.' . $aParams['block'] . '.tpl'; $sBlock = 'Block' . $sBlock; } $sBlock = Engine::getInstance()->Plugin_GetDelegate('block', $sBlock); /** * параметры */ $aParamsBlock = array(); if (isset($aParams['params'])) { $aParamsBlock = $aParams['params']; } /** * Подключаем необходимый обработчик */ $oBlock = new $sBlock($aParamsBlock); $oBlock->SetTemplate($sBlockTemplate); /** * Запускаем обработчик */ $mResult = $oBlock->Exec(); if (is_string($mResult)) { /** * Если метод возвращает строку - выводим ее вместо рендеринга шаблона */ return $mResult; } else { /** * Получаем шаблон, возможно его переопределили в обработчике блока */ $sBlockTemplate = Engine::getInstance()->Plugin_GetDelegate('template', $oBlock->GetTemplate()); if (!Engine::getInstance()->Viewer_TemplateExists($sBlockTemplate)) { return "<b>Not found template for block: <i>{$sBlockTemplate} ({$sBlock})</i></b>"; } } /** * Возвращаем результат в виде обработанного шаблона блока */ return Engine::getInstance()->Viewer_Fetch($sBlockTemplate); }
/** * Плагин для смарти * Подключает css/js на странице с учетом дублирования (но только в рамках плагина asset) * * @param array $aParams * @param Smarty $oSmarty * @return string */ function smarty_function_asset($aParams, &$oSmarty) { if (empty($aParams['file'])) { trigger_error("Asset: missing 'file' parametr", E_USER_WARNING); return; } if (empty($aParams['type'])) { trigger_error("Asset: missing 'type' parametr", E_USER_WARNING); return; } $sTypeAsset = $aParams['type']; $oEngine = Engine::getInstance(); /** * Проверяем тип */ if (!$oEngine->Asset_CheckAssetType($sTypeAsset)) { trigger_error("Asset: wrong 'type' parametr", E_USER_WARNING); return; } /** * Получаем список текущих подключенных файлов */ $sKeyIncluded = 'smarty_asset_included'; $aIncluded = $oEngine->Cache_GetLife($sKeyIncluded); /** * Проверяем на компонент */ if (preg_match('#^Component@(.+)#i', $aParams['file'], $aMatch)) { $aPath = explode('.', $aMatch[1], 2); $aParams['name'] = 'component.' . $aPath[0] . '.' . $aPath[1]; if ($aParams['file'] = Engine::getInstance()->Component_GetAssetPath($aPath[0], $sTypeAsset, $aPath[1])) { $aParams['file'] = Engine::getInstance()->Fs_GetPathWebFromServer($aParams['file']); } else { return; } } /** * Подготавливаем параметры */ $aParams = $oEngine->Asset_PrepareParams($aParams); $sFileKey = $aParams['name'] ? $aParams['name'] : $aParams['file']; /** * Проверяем на дубли */ if (isset($aIncluded[$sTypeAsset][$sFileKey])) { return; } $aIncluded[$sTypeAsset][$sFileKey] = $aParams; $oEngine->Cache_SetLife($aIncluded, $sKeyIncluded); /** * Формируем HTML */ $oAsset = $oEngine->Asset_CreateObjectType($sTypeAsset); $sHtml = $oAsset->getHeadHtml($aParams['file'], $aParams); return $sHtml; }
/** * Запускает весь процесс :) * */ public function Exec() { $this->ParseUrl(); $this->DefineActionClass(); // Для возможности ДО инициализации модулей определить какой action/event запрошен $this->oEngine = Engine::getInstance(); $this->oEngine->Init(); $this->ExecAction(); $this->Shutdown(false); }
public function doAction() { if (empty($this->segment)) { $this->result['errors'][] = array("code" => -1, "message" => "missing source segment"); } if (empty($this->translation)) { $this->result['errors'][] = array("code" => -2, "message" => "missing target translation"); } if (empty($this->source_lang)) { $this->result['errors'][] = array("code" => -3, "message" => "missing source lang"); } if (empty($this->target_lang)) { $this->result['errors'][] = array("code" => -4, "message" => "missing target lang"); } if (empty($this->time_to_edit)) { $this->result['errors'][] = array("code" => -5, "message" => "missing time to edit"); } if (empty($this->id_segment)) { $this->result['errors'][] = array("code" => -6, "message" => "missing segment id"); } //get Job Infos, we need only a row of jobs ( split ) $job_data = getJobData((int) $this->id_job, $this->password); $pCheck = new AjaxPasswordCheck(); //check for Password correctness if (empty($job_data) || !$pCheck->grantJobAccessByJobData($job_data, $this->password)) { $this->result['errors'][] = array("code" => -10, "message" => "wrong password"); $msg = "\n\n Error \n\n " . var_export(array_merge($this->result, $_POST), true); Log::doLog($msg); Utils::sendErrMailReport($msg); return; } //mt engine to contribute to if ($job_data['id_mt_engine'] <= 1) { return false; } $this->mt = Engine::getInstance($job_data['id_mt_engine']); //array of storicised suggestions for current segment $this->suggestion_json_array = json_decode(getArrayOfSuggestionsJSON($this->id_segment), true); //extra parameters $extra = json_encode(array('id_segment' => $this->id_segment, 'suggestion_json_array' => $this->suggestion_json_array, 'chosen_suggestion_index' => $this->chosen_suggestion_index, 'time_to_edit' => $this->time_to_edit)); //send stuff $config = $this->mt->getConfigStruct(); $config['segment'] = CatUtils::view2rawxliff($this->segment); $config['translation'] = CatUtils::view2rawxliff($this->translation); $config['source'] = $this->source_lang; $config['target'] = $this->target_lang; $config['email'] = INIT::$MYMEMORY_API_KEY; $config['segid'] = $this->id_segment; $config['extra'] = $extra; $config['id_user'] = array("TESTKEY"); $outcome = $this->mt->set($config); if ($outcome->error->code < 0) { $this->result['errors'] = $outcome->error->get_as_array(); } }
public function Statistics() { $oEngine = Engine::getInstance(); $iTimeInit = $oEngine->GetTimeInit(); $iTimeFull = round(microtime(true) - $iTimeInit, 3); $this->Viewer_Assign('iTimeFullPerformance', $iTimeFull); $aStats = $oEngine->getStats(); $aStats['cache']['time'] = round($aStats['cache']['time'], 5); $this->Viewer_Assign('aStatsPerformance', $aStats); $this->Viewer_Assign('bIsShowStatsPerformance', Router::GetIsShowStats()); return $this->Viewer_Fetch('statistics_performance.tpl'); }
public function getPaging() { $iCountItems = $this->getCountPost(); $oForum = $this->getForum(); $iPerPage = $oForum && $oForum->getOptionsValue('posts_per_page') ? $oForum->getOptionsValue('posts_per_page') : Config::Get('plugin.forum.post_per_page'); if (Config::Get('plugin.forum.topic_line_mod')) { $iCountItems--; $iPerPage--; } $oEngine = Engine::getInstance(); $aPaging = $oEngine->Viewer_MakePaging($iCountItems, 1, $iPerPage, Config::Get('pagination.pages.count'), $this->getUrlFull()); return $aPaging; }
public function doAction() { $this->job_info = getJobData($this->id_job, $this->password); /** * For future reminder * * MyMemory (id=1) should not be the only Glossary provider * */ $this->_TMS = Engine::getInstance(1); $this->checkLogin(); try { $config = $this->_TMS->getConfigStruct(); $config['segment'] = $this->segment; $config['translation'] = $this->translation; $config['tnote'] = $this->comment; $config['source'] = $this->job_info['source']; $config['target'] = $this->job_info['target']; $config['email'] = INIT::$MYMEMORY_API_KEY; $config['id_user'] = $this->job_info['id_translator']; $config['isGlossary'] = true; $config['get_mt'] = null; $config['num_result'] = 100; //do not want limit the results from glossary: set as a big number switch ($this->exec) { case 'get': $this->_get($config); break; case 'set': /** * For future reminder * * MyMemory should not be the only Glossary provider * */ if ($this->job_info['id_tms'] == 0) { throw new Exception("Glossary is not available when the TM feature is disabled", -11); } $this->_set($config); break; case 'update': $this->_update($config); break; case 'delete': $this->_delete($config); break; } } catch (Exception $e) { $this->result['errors'][] = array("code" => $e->getCode(), "message" => $e->getMessage()); } }
/** * Плагин для смарти * Запускает хуки из шаблона на выполнение * * @param array $aParams * @param Smarty $oSmarty * @return string */ function smarty_function_hook($aParams, &$oSmarty) { if (empty($aParams['run'])) { trigger_error("Hook: missing 'run' parametr", E_USER_WARNING); return; } $sHookName = 'template_' . strtolower($aParams['run']); unset($aParams['run']); $aResultHook = Engine::getInstance()->Hook_Run($sHookName, $aParams); if (array_key_exists('template_result', $aResultHook)) { return join('', $aResultHook['template_result']); } return ''; }
/** * Возвращает текущего пользователя. Если пользователь "аноним", то создаёт для него объект * с id = 0 и возвращает его. * * @return oUser Результат проверки */ public static function GetUserCurrent() { if (!self::$oUserCurrent) { $oEngine = Engine::getInstance(); list($oModuleUser, $sModuleName, $sMethod) = $oEngine->GetModule('User_IsAuthorization'); //Проверяем является находистя ли пользователь в системе if (!$oModuleUser->IsAuthorization()) { //Создаём анонима self::$oUserCurrent = Engine::GetEntity('User_User', array('user_id' => self::ANONIM_USER_ID, 'user_is_administrator' => false)); } else { self::$oUserCurrent = $oModuleUser->GetUserCurrent(); } } return self::$oUserCurrent; }
public function __construct($sLockFile = null) { $this->oEngine = Engine::getInstance(); /** * Инициализируем ядро */ $this->oEngine->Init(); if (!empty($sLockFile)) { $this->oLockFile = fopen($sLockFile, 'a'); } /** * Инициализируем лог и делает пометку о старте процесса */ $this->oEngine->Logger_SetFileName(Config::Get('sys.logs.cron_file')); $this->Log('Cron process started'); }
/** * Плагин для смарти * Выводит текстовку из языкового файла * * @param array $aParams * @param Smarty $oSmarty * @return string */ function smarty_function_lang($aParams, &$oSmarty) { if (isset($aParams['_default_short'])) { $aParams['name'] = $aParams['_default_short']; } if (empty($aParams['name'])) { trigger_error("Lang: missing 'name' parametr", E_USER_WARNING); return; } $sName = $aParams['name']; $bPlural = isset($aParams['plural']) && $aParams['plural'] ? true : false; /** * Получаем параметры для передачи в текстовку */ $aReplace = array(); if (isset($aParams['params']) and is_array($aParams['params'])) { $aReplace = $aParams['params']; if ($bPlural and isset($aParams['count'])) { $aReplace['count'] = $aParams['count']; } } else { unset($aParams['name']); $aReplace = $aParams; } /** * Получаем текстовку */ $sReturn = Engine::getInstance()->Lang_Get($sName, $aReplace); /** * Если необходимо получить правильную форму множественного числа */ if ($bPlural and isset($aParams['count'])) { if ($aParams['count'] == 0 and isset($aParams['empty'])) { $sReturn = Engine::getInstance()->Lang_Get($aParams['empty']); } else { $sReturn = Engine::getInstance()->Lang_Pluralize((int) $aParams['count'], $sReturn); } } /** * Возвращаем результат */ if (!empty($aParams['assign'])) { $oSmarty->assign($aParams['assign'], $sReturn); } else { return $sReturn; } }
/** * @param string|null $sLockFile Полный путь до лок файла, например <pre>Config::Get('sys.cache.dir').'notify.lock'</pre> */ public function __construct($sLockFile = null) { parent::__construct(); $this->sProcessName = get_class($this); $oEngine = Engine::getInstance(); /** * Инициализируем ядро */ $oEngine->Init(); if (!empty($sLockFile)) { $this->oLockFile = fopen($sLockFile, 'a'); } /** * Инициализируем лог и делает пометку о старте процесса */ $this->Log('Cron process started'); }
/** * Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля * * @param string $sName * @param array $aArgs * @return unknown */ public function __call($sName, $aArgs) { $sType = strtolower(substr($sName, 0, 3)); if (!strpos($sName, '_') and in_array($sType, array('get', 'set'))) { $sKey = strtolower(preg_replace('/([^A-Z])([A-Z])/', "\$1_\$2", substr($sName, 3))); if ($sType == 'get') { if (isset($this->_aData[$sKey])) { return $this->_aData[$sKey]; } return null; } elseif ($sType == 'set' and isset($aArgs[0])) { $this->_aData[$sKey] = $aArgs[0]; } } else { return Engine::getInstance()->_CallModule($sName, $aArgs); } }
static function Init() { if ($aFunc = Config::Get('plugin.aceadminpanel.api')) { self::$aFunc = get_class_methods(get_class()); if (is_array($aFunc)) { self::$aFunc = array_intersect(self::$aFunc, $aFunc); } foreach (self::$aFunc as $key => $val) { self::$aFunc[$key] = strtolower($val); } } else { self::$aFunc = array(); } self::$oEngine = Engine::getInstance(); self::$oDb = self::$oEngine->Database_GetConnect(); self::LoadData(); }
/** * Модификатор declension: склонение существительных * * @param int $count * @param string $forms * @param string $language * @return string */ function smarty_modifier_declension($count, $forms, $language = '') { if (!$language) { $language = Engine::getInstance()->Lang_GetLang(); } $count = abs($count); // Выделяем отдельные словоформы $forms = explode(';', $forms); $fn = 'smarty_modifier_declension_' . $language; if (function_exists($fn)) { // Есть персональная функция для текущего языка return $fn($forms, $count); } else { // Действуем по образу и подобию английского языка return smarty_modifier_declension_english($forms, $count); } }
public static function GetParentInherit($sInheritClass) { $sParentClass = Engine::getInstance()->Plugin_GetParentInherit($sInheritClass); /* if (strpos($sInheritClass, 'Plugin') !== 0 AND strpos($sParentClass, 'Plugin') === 0) { // движок ошибочно выдает имя класса плагина $aInfo = Engine::GetClassInfo($sInheritClass, Engine::CI_CLASSPATH); if (isset($aInfo[Engine::CI_CLASSPATH])) { ACE::FileInclude($aInfo[Engine::CI_CLASSPATH]); return $sInheritClass; } else { return 'LsObject'; } } */ return $sParentClass; }
/** * Create template data object * * Some of the global Smarty settings copied to template scope * It load the required template resources and cacher plugins * * @param string $template_resource template resource string * @param Smarty $smarty Smarty instance * @param Smarty_Internal_Template $_parent back pointer to parent object with variables or null * @param mixed $_cache_id cache id or null * @param mixed $_compile_id compile id or null * @param bool $_caching use caching? * @param int $_cache_lifetime cache life-time in seconds */ public function __construct($template_resource, $smarty, $_parent = null, $_cache_id = null, $_compile_id = null, $_caching = null, $_cache_lifetime = null) { $bSkipDelegate = false; if (preg_match('#^Inherit@(.+)#i', $template_resource, $aMatch)) { /** * Получаем шаблон по цепочке наследования */ $sTpl = trim($aMatch[1]); $sParentTemplate = Engine::getInstance()->Plugin_GetParentInherit($sTpl); if ($sTpl == $sParentTemplate) { /** * Сбрасываем цепочку наследования к начальному состоянию */ Engine::getInstance()->Plugin_ResetInheritPosition($sParentTemplate); /** * В параметре может быть путь до шаблона с ".tpl" в конце, а таже может быть путь до шаблона компонента вида "component.name.template" */ if (!preg_match("#^\\.tpl\$#i", $sTpl)) { $aPath = explode('.', $sTpl); if (count($aPath) == 3 and preg_match('#^([\\w\\_]+\\:)?component$#i', $aPath[0], $aMatch2)) { $sPrefix = ''; if (isset($aMatch2[1])) { $sPrefix = $aMatch2[1]; } $sParentTemplate = Engine::getInstance()->Component_GetTemplatePath($sPrefix . $aPath[1], $aPath[2], false); } } } $template_resource = $sParentTemplate; $bSkipDelegate = true; } /* * Ловим использование extends на файлы компонентов * Синтаксис: {extends '*****@*****.**'} */ if (preg_match('#^Component@(.+)#i', $template_resource, $aMatch)) { $aPath = explode('.', $aMatch[1], 2); $template_resource = Engine::getInstance()->Component_GetTemplatePath($aPath[0], isset($aPath[1]) ? $aPath[1] : null, true); $bSkipDelegate = true; } if (!$bSkipDelegate) { $template_resource = Engine::getInstance()->Plugin_GetDelegate('template', $template_resource); } parent::__construct($template_resource, $smarty, $_parent, $_cache_id, $_compile_id, $_caching, $_cache_lifetime); }
/** * Плагин для смарти * Подключает обработчик блоков шаблона * * @param array $aParams * @param Smarty $oSmarty * @return string */ function smarty_insert_block($aParams, &$oSmarty) { /** * Устанавливаем шаблон */ $sBlock = ucfirst(basename($aParams['block'])); /** * Проверяем наличие шаблона. Определяем значения параметров работы в зависимости от того, * принадлежит ли блок одному из плагинов, или является пользовательским классом движка */ if (isset($aParams['params']) and isset($aParams['params']['plugin'])) { require_once Config::Get('path.root.server') . '/engine/classes/ActionPlugin.class.php'; $sBlockTemplate = Plugin::GetTemplatePath($aParams['params']['plugin']) . '/block.' . $aParams['block'] . '.tpl'; $sBlockClass = Config::Get('path.root.server') . '/plugins/' . $aParams['params']['plugin'] . '/classes/blocks/Block' . $sBlock . '.class.php'; $sCmd = '$oBlock=new Plugin' . ucfirst($aParams['params']['plugin']) . '_Block' . $sBlock . '($aParamsBlock);'; } else { $sBlockTemplate = Engine::getInstance()->Plugin_GetDelegate('template', 'block.' . $aParams['block'] . '.tpl'); $sBlockClass = Config::Get('path.root.server') . '/classes/blocks/Block' . $sBlock . '.class.php'; $sCmd = '$oBlock=new Block' . $sBlock . '($aParamsBlock);'; } if (!isset($aParams['block']) or !$oSmarty->template_exists($sBlockTemplate)) { $oSmarty->trigger_error("Not found template for block: " . $sBlockTemplate); return; } /** * параметры */ $aParamsBlock = array(); if (isset($aParams['params'])) { $aParamsBlock = $aParams['params']; } /** * Подключаем необходимый обработчик */ require_once $sBlockClass; eval($sCmd); /** * Запускаем обработчик */ $oBlock->Exec(); /** * Возвращаем результат в виде обработанного шаблона блока */ return $oSmarty->fetch($sBlockTemplate); }
/** * Плагин для смарти * Запускает блочные хуки из шаблона на выполнение * * @param array $aParams * @param string $sContent * @param Smarty $oSmarty * @param bool $bRepeat * @return string */ function smarty_block_hookb($aParams, $sContent, &$oSmarty, &$bRepeat) { if (empty($aParams['run'])) { trigger_error("Hook: missing 'run' parametr", E_USER_WARNING); return; } if ($sContent) { $sHookName = 'template_block_' . strtolower($aParams['run']); unset($aParams['run']); $aParams['content'] = $sContent; $aResultHook = Engine::getInstance()->Hook_Run($sHookName, $aParams); if (array_key_exists('template_result', $aResultHook)) { echo join('', $aResultHook['template_result']); return; } echo $sContent; } }
/** * Плагин для смарти * Подключает css/js на странице с учетом дублирования (но только в рамках плагина asset) * * @param array $aParams * @param Smarty $oSmarty * @return string */ function smarty_function_asset($aParams, &$oSmarty) { if (empty($aParams['file'])) { trigger_error("Asset: missing 'file' parametr", E_USER_WARNING); return; } if (empty($aParams['type'])) { trigger_error("Asset: missing 'type' parametr", E_USER_WARNING); return; } $sTypeAsset = $aParams['type']; $oEngine = Engine::getInstance(); /** * Проверяем тип */ if (!$oEngine->Asset_CheckAssetType($sTypeAsset)) { trigger_error("Asset: wrong 'type' parametr", E_USER_WARNING); return; } /** * Получаем список текущих подключенных файлов */ $sKeyIncluded = 'smarty_asset_included'; $aIncluded = $oEngine->Cache_GetLife($sKeyIncluded); /** * Подготавливаем параметры */ $aParams = $oEngine->Asset_PrepareParams($aParams); $sFileKey = $aParams['name'] ? $aParams['name'] : $aParams['file']; /** * Проверяем на дубли */ if (isset($aIncluded[$sTypeAsset][$sFileKey])) { return; } $aIncluded[$sTypeAsset][$sFileKey] = $aParams; $oEngine->Cache_SetLife($aIncluded, $sKeyIncluded); /** * Формируем HTML */ $oAsset = $oEngine->Asset_CreateObjectType($sTypeAsset); $sHtml = $oAsset->getHeadHtml($aParams['file'], $aParams); return $sHtml; }
/** * Плагин для смарти * Подключает шаблон компонента * * @param array $aParams * @param Smarty $oSmarty * @return string */ function smarty_function_component($aParams, &$oSmarty) { if (isset($aParams['_default_short'])) { $aParams['component'] = $aParams['_default_short']; } if (empty($aParams['component'])) { trigger_error("Config: missing 'component' parametr", E_USER_WARNING); return; } $sName = $aParams['component']; $sTemplate = null; if (isset($aParams['template'])) { $sTemplate = $aParams['template']; } /** * Получаем параметры компонента */ $aComponentParams = array(); if (isset($aParams['params']) and is_array($aParams['params'])) { $aComponentParams = array_merge($aParams['params'], $aParams); } else { $aComponentParams = $aParams; } unset($aComponentParams['_default_short']); unset($aComponentParams['component']); unset($aComponentParams['template']); unset($aComponentParams['params']); $aComponentParams['params'] = $aComponentParams; /** * Получаем путь до шаблона */ if ($sPathTemplate = Engine::getInstance()->Component_GetTemplatePath($sName, $sTemplate) and Engine::getInstance()->Viewer_TemplateExists($sPathTemplate)) { $sResult = $oSmarty->getSubTemplate($sPathTemplate, $oSmarty->cache_id, $oSmarty->compile_id, null, null, $aComponentParams, Smarty::SCOPE_LOCAL); } else { $sResult = 'Component template not found: ' . $sName . '/' . ($sTemplate ? $sTemplate : $sName) . '.tpl'; } if (!empty($aParams['assign'])) { $oSmarty->assign($aParams['assign'], $sResult); } else { return $sResult; } return ''; }
public function TopicShow($aParams) { $oTopic = $aParams['oTopic']; /** * Если активен плагин "ViewCount", то ничего не делаем */ $aPlugins = Engine::getInstance()->GetPlugins(); if (array_key_exists('viewcount', $aPlugins)) { return; } /** * Если топик просматривает его автор - пропускаем */ $oUserCurrent = $this->User_GetUserCurrent(); if ($oUserCurrent and $oUserCurrent->getId() == $oTopic->getUserId()) { return; } $this->PluginMobiletpl_Main_IncTopicCountRead($oTopic); }
/** * Плагин для смарти * Подключает обработчик блоков шаблона * * @param array $aParams * @param Smarty $oSmarty * @return string */ function smarty_insert_block($aParams, &$oSmarty) { /** * Устанавливаем шаблон */ $sBlock = ucfirst(basename($aParams['block'])); /** * Проверяем наличие шаблона. Определяем значения параметров работы в зависимости от того, * принадлежит ли блок одному из плагинов, или является пользовательским классом движка */ if (isset($aParams['params']) and isset($aParams['params']['plugin'])) { $sBlockTemplate = Plugin::GetTemplatePath($aParams['params']['plugin']) . '/blocks/block.' . $aParams['block'] . '.tpl'; $sBlock = 'Plugin' . ucfirst($aParams['params']['plugin']) . '_Block' . $sBlock; } else { $sBlockTemplate = Engine::getInstance()->Plugin_GetDelegate('template', 'blocks/block.' . $aParams['block'] . '.tpl'); $sBlock = 'Block' . $sBlock; } $sBlock = Engine::getInstance()->Plugin_GetDelegate('block', $sBlock); if (!isset($aParams['block']) or !$oSmarty->templateExists($sBlockTemplate)) { trigger_error("Not found template for block: " . $sBlockTemplate, E_USER_WARNING); return; } /** * параметры */ $aParamsBlock = array(); if (isset($aParams['params'])) { $aParamsBlock = $aParams['params']; } /** * Подключаем необходимый обработчик */ $oBlock = new $sBlock($aParamsBlock); /** * Запускаем обработчик */ $oBlock->Exec(); /** * Возвращаем результат в виде обработанного шаблона блока */ return $oSmarty->fetch($sBlockTemplate); }