Esempio n. 1
0
 /**
  * Инициализация модуля
  *
  */
 public function Init()
 {
     E::ModuleHook()->Run('lang_init_start');
     $this->sDefaultLang = Config::Get('lang.default');
     $this->aLangPaths = F::File_NormPath(Config::Get('lang.paths'));
     // Проверку на языки делаем, только если сайт мультиязычный
     if (Config::Get('lang.multilang')) {
         // Время хранение языка в куках
         $nSavePeriod = F::ToSeconds(Config::Get('lang.save'));
         $sLangKey = is_string(Config::Get('lang.in_get')) ? Config::Get('lang.in_get') : 'lang';
         // Получаем язык, если он был задан в URL
         $this->sCurrentLang = R::GetLang();
         // Проверка куки, если требуется
         if (!$this->sCurrentLang && $nSavePeriod) {
             $sLang = (string) E::ModuleSession()->GetCookie($sLangKey);
             if ($sLang) {
                 $this->sCurrentLang = $sLang;
             }
         }
         if (!$this->sCurrentLang) {
             $this->sCurrentLang = Config::Get('lang.current');
         }
     } else {
         $this->sCurrentLang = Config::Get('lang.current');
     }
     // Проверяем на случай старого обозначения языков
     $this->sDefaultLang = $this->_checkLang($this->sDefaultLang);
     $this->sCurrentLang = $this->_checkLang($this->sCurrentLang);
     if ($this->sCurrentLang && Config::Get('lang.multilang') && $nSavePeriod) {
         // Пишем в куки, если требуется
         E::ModuleSession()->SetCookie($sLangKey, $this->sCurrentLang, $nSavePeriod);
     }
     $this->InitLang();
 }
Esempio n. 2
0
/**
 * Плагин для смарти
 * Запускает хуки из шаблона на выполнение
 *
 * @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;
    }
    $sReturn = '';
    if (strpos($aParams['run'], ',')) {
        $aHooks = F::Array_Str2Array($aParams['run']);
        unset($aParams['run']);
        foreach ($aHooks as $sHook) {
            $aParams['run'] = $sHook;
            $sReturn .= smarty_function_hook($aParams, $oSmarty);
        }
    } else {
        $sHookName = 'template_' . strtolower($aParams['run']);
        unset($aParams['run']);
        $aResultHook = E::ModuleHook()->Run($sHookName, $aParams);
        if (array_key_exists('template_result', $aResultHook)) {
            $sReturn = join('', $aResultHook['template_result']);
        }
        if (!empty($aParams['assign'])) {
            $oSmarty->assign($aParams['assign'], $sReturn);
            $sReturn = '';
        }
    }
    return $sReturn;
}
Esempio n. 3
0
 /**
  * Инициализация модуля
  *
  */
 public function Init()
 {
     E::ModuleHook()->Run('lang_init_start');
     $this->sDefaultLang = Config::Get('lang.default');
     $this->aLangPaths = F::File_NormPath(Config::Get('lang.paths'));
     $this->bDeleteUndefinedVars = Config::Get('module.lang.delete_undefined');
     // Allowed languages
     $aLangsAllow = (array) Config::Get('lang.allow');
     // Проверку на языки делаем, только если сайт мультиязычный
     if (Config::Get('lang.multilang')) {
         // Время хранение языка в куках
         $iSavePeriod = F::ToSeconds(Config::Get('lang.save'));
         $sLangKey = is_string(Config::Get('lang.in_get')) ? Config::Get('lang.in_get') : 'lang';
         // Получаем язык, если он был задан в URL
         $this->sCurrentLang = R::GetLang();
         // Проверка куки, если требуется
         if (!$this->sCurrentLang && $iSavePeriod) {
             $sLang = (string) E::ModuleSession()->GetCookie($sLangKey);
             if ($sLang) {
                 $this->sCurrentLang = $sLang;
             }
         }
         if (!$this->sCurrentLang) {
             $this->sCurrentLang = Config::Get('lang.current');
         }
     } else {
         $this->sCurrentLang = Config::Get('lang.current');
         $iSavePeriod = 0;
         $sLangKey = null;
     }
     // Current language must be in allowed languages
     if (!in_array($this->sCurrentLang, $aLangsAllow)) {
         $this->sCurrentLang = reset($aLangsAllow);
     }
     // Проверяем на случай старого обозначения языков
     $this->sDefaultLang = $this->_checkLang($this->sDefaultLang);
     $this->sCurrentLang = $this->_checkLang($this->sCurrentLang);
     if ($this->sCurrentLang && Config::Get('lang.multilang') && $iSavePeriod) {
         // Пишем в куки, если требуется
         E::ModuleSession()->SetCookie($sLangKey, $this->sCurrentLang, $iSavePeriod);
     }
     $this->InitLang();
 }
 public function EventSandbox()
 {
     // * Меню
     $this->sMenuSubItemSelect = 'sandbox';
     // * Передан ли номер страницы
     $iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
     // * Получаем список топиков
     $aResult = E::ModuleTopic()->GetTopicsNewAll($iPage, Config::Get('module.topic.per_page'));
     $aTopics = $aResult['collection'];
     // * Вызов хуков
     E::ModuleHook()->Run('topics_list_show', array('aTopics' => $aTopics));
     // * Формируем постраничность
     $aPaging = E::ModuleViewer()->MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'), Config::Get('pagination.pages.count'), R::GetPath('index/sandbox'));
     E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('plugin.sandbox.menu_text') . ($iPage > 1 ? ' (' . $iPage . ')' : ''));
     // * Загружаем переменные в шаблон
     E::ModuleViewer()->Assign('aTopics', $aTopics);
     E::ModuleViewer()->Assign('aPaging', $aPaging);
     // * Устанавливаем шаблон вывода
     $this->SetTemplateAction('index');
 }
 /**
  * Список черновиков пользователя
  */
 protected function EventCreatedDrafts()
 {
     if (!$this->CheckUserProfile()) {
         return parent::EventNotFound();
     }
     if (!E::IsAdmin()) {
         return parent::EventNotFound();
     }
     $this->sMenuSubItemSelect = 'draft';
     /**
      * Передан ли номер страницы
      */
     $iPage = $this->GetParamEventMatch(2, 2) ? $this->GetParamEventMatch(2, 2) : 1;
     /**
      * Получаем список топиков
      */
     $aResult = E::ModuleTopic()->GetDraftsPersonalByUser($this->oUserProfile->getId(), $iPage, Config::Get('module.topic.per_page'));
     $aTopics = $aResult['collection'];
     /**
      * Вызов хуков
      */
     E::ModuleHook()->Run('topics_list_show', array('aTopics' => $aTopics));
     /**
      * Формируем постраничность
      */
     $aPaging = E::ModuleViewer()->MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'), Config::Get('pagination.pages.count'), $this->oUserProfile->getUserUrl() . 'created/draft');
     /**
      * Загружаем переменные в шаблон
      */
     E::ModuleViewer()->Assign('aPaging', $aPaging);
     E::ModuleViewer()->Assign('aTopics', $aTopics);
     E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('user_menu_publication') . ' ' . $this->oUserProfile->getLogin());
     E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('user_menu_publication_blog'));
     E::ModuleViewer()->SetHtmlRssAlternate(Router::GetPath('rss') . 'personal_blog/' . $this->oUserProfile->getLogin() . '/', $this->oUserProfile->getLogin());
     /**
      * Устанавливаем шаблон вывода
      */
     $this->SetTemplateAction('created_topics');
 }
Esempio n. 6
0
 /**
  * Отображение топиков
  *
  */
 protected function EventTags()
 {
     // * Gets tag from URL
     $sTag = F::UrlDecode(R::Url('event'), true);
     // * Check page number
     $iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
     // * Gets topics list
     $aResult = E::ModuleTopic()->GetTopicsByTag($sTag, $iPage, Config::Get('module.topic.per_page'));
     $aTopics = $aResult['collection'];
     // * Calls hooks
     E::ModuleHook()->Run('topics_list_show', array('aTopics' => $aTopics));
     // * Makes pages
     $aPaging = E::ModuleViewer()->MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'), Config::Get('pagination.pages.count'), R::GetPath('tag') . htmlspecialchars($sTag));
     // * Loads variables to template
     E::ModuleViewer()->Assign('aPaging', $aPaging);
     E::ModuleViewer()->Assign('aTopics', $aTopics);
     E::ModuleViewer()->Assign('sTag', $sTag);
     E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('tag_title'));
     E::ModuleViewer()->AddHtmlTitle($sTag);
     E::ModuleViewer()->SetHtmlRssAlternate(R::GetPath('rss') . 'tag/' . $sTag . '/', $sTag);
     // * Sets template for display
     $this->SetTemplateAction('index');
 }
 public function EventCreatedSandbox()
 {
     if (!$this->CheckUserProfile()) {
         return parent::EventNotFound();
     }
     $this->sMenuSubItemSelect = 'sandbox';
     // * Передан ли номер страницы
     $iPage = $this->GetParamEventMatch(2, 2) ? $this->GetParamEventMatch(2, 2) : 1;
     // * Получаем список топиков
     $aResult = E::ModuleTopic()->GetTopicsSandboxByUser($this->oUserProfile->getId(), $iPage, Config::Get('module.topic.per_page'));
     $aTopics = $aResult['collection'];
     // * Вызов хуков
     E::ModuleHook()->Run('topics_list_show', array('aTopics' => $aTopics));
     // * Формируем постраничность
     $aPaging = E::ModuleViewer()->MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'), Config::Get('pagination.pages.count'), $this->oUserProfile->getUserUrl() . 'created/sandbox');
     // * Загружаем переменные в шаблон
     E::ModuleViewer()->Assign('aPaging', $aPaging);
     E::ModuleViewer()->Assign('aTopics', $aTopics);
     E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('user_menu_publication') . ' ' . $this->oUserProfile->getLogin());
     E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('plugin.sandbox.menu_text'));
     // * Устанавливаем шаблон вывода
     $this->SetTemplateAction('created_topics');
 }
 /**
  * Вывод всех черновиков
  */
 protected function EventDraft()
 {
     if (!E::IsAdmin()) {
         return parent::EventNotFound();
     }
     E::ModuleViewer()->SetHtmlRssAlternate(Router::GetPath('rss') . 'draft/', Config::Get('view.name'));
     /**
      * Меню
      */
     $this->sMenuSubItemSelect = 'draft';
     /**
      * Передан ли номер страницы
      */
     $iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
     /**
      * Получаем список топиков
      */
     $aResult = E::ModuleTopic()->GetTopicsDraftAll($iPage, Config::Get('module.topic.per_page'));
     $aTopics = $aResult['collection'];
     /**
      * Вызов хуков
      */
     E::ModuleHook()->Run('topics_list_show', array('aTopics' => $aTopics));
     /**
      * Формируем постраничность
      */
     $aPaging = E::ModuleViewer()->MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'), Config::Get('pagination.pages.count'), Router::GetPath('index') . 'draft');
     /**
      * Загружаем переменные в шаблон
      */
     E::ModuleViewer()->Assign('aTopics', $aTopics);
     E::ModuleViewer()->Assign('aPaging', $aPaging);
     /**
      * Устанавливаем шаблон вывода
      */
     $this->SetTemplateAction('index');
 }
Esempio n. 9
0
 public function GetSourceResult()
 {
     return E::ModuleHook()->GetSourceResult();
 }
Esempio n. 10
0
 /**
  * Разбирает текст и анализирует его на наличие сниппетов.
  * Если они найдены, то запускает хуки для их обработки.
  *
  * @version 0.1 Базовый функционал
  * @version 0.2 Добавлены блочный и шаблонный сниппеты
  *
  * @param string $sText
  *
  * @return string
  */
 public function SnippetParser($sText)
 {
     // Массив регулярки для поиска сниппетов
     $aSnippetRegexp = array('~<alto:(\\w+)((?:\\s+\\w+(?:\\s*=\\s*(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>\\s]+))?)*)\\s*>([.\\s\\S\\r\\n]*)</alto:\\1>~Ui', '~<alto:(\\w+)((?:\\s+\\w+(?:\\s*=\\s*(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>\\s]+))?)*)\\s*\\/*>~Ui');
     // Получим массив: сниппетов, их имён и параметров по каждой регклярке
     // Здесь получаем в $aMatches три/четыре массива из которых первым идет массив найденных сниппетов,
     // который позже будет заменён на результат полученный от хука. Вторым массивом идут имена
     // найденных сниппетов, которые будут использоваться для формирвоания имени хука.
     // Третим массивом будут идти параметры сниппетов. Если сниппет блочный, то четвертым параметром
     // будет текст-содержимое блока.
     foreach ($aSnippetRegexp as $sRegExp) {
         if (preg_match_all($sRegExp, $sText, $aMatches)) {
             // Данные для замены сниппетов на полученный код.
             $aReplaceData = array();
             /**
              * @var int $k Порядковый номер найденного сниппета
              * @var string $sSnippetName Имя (идентификатор) сниппета
              */
             foreach ($aMatches[1] as $k => $sSnippetName) {
                 // Получим параметры в виде массива. Вообще-то их может и не быть воовсе,
                 // но мы всё-таки попробуем это сделать...
                 $aParams = array();
                 if (preg_match_all('~([a-zA-Z]+)\\s*=\\s*[\'"]([^\'"]+)[\'"]~Ui', $aMatches[2][$k], $aMatchesParams)) {
                     foreach ($aMatchesParams[1] as $pk => $sParamName) {
                         $aParams[$sParamName] = @$aMatchesParams[2][$pk];
                     }
                 }
                 // Добавим в параметры текст, который был в топике, вдруг какой-нибудь сниппет
                 // захочет с ним поработать.
                 $aParams['target_text'] = $sText;
                 // Если это блочный сниппет, то добавим в параметры еще и текст блока
                 $aParams['snippet_text'] = isset($aMatches[3][$k]) ? $aMatches[3][$k] : '';
                 // Добавим в параметры имя сниппета
                 $aParams['snippet_name'] = $sSnippetName;
                 // Попытаемся получить результат от обработчика
                 // Может сниппет уже был в обработке, тогда просто возьмем его из кэша
                 $sCacheKey = $sSnippetName . md5(serialize($aParams));
                 if (FALSE === ($sResult = E::ModuleCache()->GetTmp($sCacheKey))) {
                     // Определим тип сниппета, может быть шаблонным, а может и исполняемым
                     // по умолчанию сниппет ссчитаем исполняемым. Если шаблонный, то его
                     // обрабатывает предопределенный хук snippet_template_type
                     $sHookName = 'snippet_' . $sSnippetName;
                     $sHookName = E::ModuleHook()->IsEnabled($sHookName) ? 'snippet_' . $sSnippetName : 'snippet_template_type';
                     // Установим хук
                     E::ModuleHook()->Run($sHookName, array('params' => &$aParams, 'result' => &$sResult));
                     // Запишем результат обработки в кэш
                     E::ModuleCache()->SetTmp($sResult, $sCacheKey);
                 }
                 $aReplaceData[$k] = is_string($sResult) ? $sResult : '';
             }
             // Произведем замену. Если обработчиков не было, то сниппеты
             // будут заменены на пустую строку.
             $sText = str_replace(array_values($aMatches[0]), array_values($aReplaceData), $sText);
         }
     }
     return $sText;
 }
Esempio n. 11
0
 /**
  * Initialization of render before Fetch() or Display()
  */
 protected function _initRender()
 {
     E::ModuleHook()->Run('render_init_start', array('bLocal' => $this->bLocal));
     // If skin not initialized (or it was changed) then init one
     if ($this->sViewSkin != $this->GetConfigSkin()) {
         $this->_initSkin($this->bLocal);
     } else {
         // Level could be changed after skin initialization
         Config::SetLevel(Config::LEVEL_SKIN);
     }
     // init templator if not yet
     $this->_initTemplator();
     // Loads localized texts
     $this->Assign('aLang', E::ModuleLang()->GetLangMsg());
     $this->Assign('oLang', E::ModuleLang()->Dictionary());
     if (!$this->bLocal && !$this->GetResponseAjax()) {
         // Initialization of assets (JS-, CSS-files)
         $this->InitAssetFiles();
     }
     E::ModuleHook()->Run('render_init_done', array('bLocal' => $this->bLocal));
 }
Esempio n. 12
0
 /**
  * Проверка полей формы
  *
  * @param $oTopic
  *
  * @return bool
  */
 protected function checkTopicFields($oTopic)
 {
     E::ModuleSecurity()->ValidateSendForm();
     $bOk = true;
     /**
      * Валидируем топик
      */
     if (!$oTopic->_Validate()) {
         E::ModuleMessage()->AddError($oTopic->_getValidateError(), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     /**
      * Выполнение хуков
      */
     E::ModuleHook()->Run('check_topic_fields', array('bOk' => &$bOk));
     return $bOk;
 }
Esempio n. 13
0
 /**
  * Загружаем картинку
  */
 public function EventMultiUpload()
 {
     // Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json', FALSE);
     E::ModuleSecurity()->ValidateSendForm();
     // Проверяем, загружен ли файл
     if (!($aUploadedFile = $this->GetUploadedFile('uploader-upload-image'))) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('error_upload_image'), E::ModuleLang()->Get('error'));
         return false;
     }
     $sTarget = F::GetRequest('target', FALSE);
     $sTargetId = F::GetRequest('target_id', FALSE);
     $oTarget = E::ModuleUploader()->CheckAccessAndGetTarget($sTarget, $sTargetId);
     $bTmp = F::GetRequest('tmp', FALSE);
     $bTmp = $bTmp == 'true' ? true : false;
     // Проверяем, целевой объект и права на его редактирование
     if (!$oTarget) {
         // Здесь два варианта, либо редактировать нельзя, либо можно, но топика еще нет
         if ($oTarget === TRUE) {
             // Будем делать временную картинку
         } else {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('not_access'), E::ModuleLang()->Get('error'));
             return false;
         }
     }
     // Ошибок пока нет
     $sError = '';
     // Сделаем временный файд
     $sTmpFile = E::ModuleUploader()->UploadLocal($aUploadedFile);
     // Вызовем хук перед началом загрузки картинки
     E::ModuleHook()->Run('uploader_upload_before', array('oTarget' => $oTarget, 'sTmpFile' => $sTmpFile, 'sTarget' => $sTarget));
     // Если все ок, и по миме проходит, то
     if ($sTmpFile && E::ModuleImg()->MimeType($sTmpFile)) {
         // Проверим, проходит ли по количеству
         if (!E::ModuleUploader()->GetAllowedCount($sTarget = F::GetRequest('target', FALSE), $sTargetId = F::GetRequest('target_id', FALSE))) {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('uploader_photoset_error_count_photos', array('MAX' => Config::Get('module.topic.photoset.count_photos_max'))), E::ModuleLang()->Get('error'));
             return FALSE;
         }
         // Определим, существует ли объект или он будет создан позже
         if (!($sTmpKey = E::ModuleSession()->GetCookie(ModuleUploader::COOKIE_TARGET_TMP)) && $sTargetId == '0' && $bTmp) {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('error_upload_image'), E::ModuleLang()->Get('error'));
             return FALSE;
         }
         // Пересохраним файл из кэша
         // Сохраняем фото во временный файл
         $oImg = E::ModuleImg()->Read($sTmpFile);
         $sExtension = strtolower(pathinfo($sTmpFile, PATHINFO_EXTENSION));
         if (!($sTmpFile = $oImg->Save(F::File_UploadUniqname($sExtension)))) {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('error_upload_image'), E::ModuleLang()->Get('error'));
             return FALSE;
         }
         // Окончательная запись файла только через модуль Uploader
         if ($oStoredFile = E::ModuleUploader()->StoreImage($sTmpFile, $sTarget, $sTargetId, null, true)) {
             /** @var ModuleMresource_EntityMresource $oResource */
             //$oResource = $this->AddUploadedFileRelationInfo($oStoredFile, $sTarget, $sTargetId, TRUE);
             $oResource = E::ModuleMresource()->GetMresourcesByUuid($oStoredFile->getUuid());
             $sFile = $oStoredFile->GetUrl();
             if ($oResource) {
                 $oResource->setType(ModuleMresource::TYPE_PHOTO);
                 E::ModuleMresource()->UpdateType($oResource);
             }
             $sFilePreview = $sFile;
             if ($sSize = F::GetRequest('crop_size', FALSE)) {
                 $sFilePreview = E::ModuleUploader()->ResizeTargetImage($sFile, $sSize);
             }
             // Запускаем хук на действия после загрузки картинки
             E::ModuleHook()->Run('uploader_upload_image_after', array('sFile' => $sFile, 'sFilePreview' => $sFilePreview, 'sTargetId' => $sTargetId, 'sTarget' => $sTarget, 'oTarget' => $oTarget));
             E::ModuleViewer()->AssignAjax('file', $sFilePreview);
             E::ModuleViewer()->AssignAjax('id', $oResource->getMresourceId());
             // Чистим
             E::ModuleImg()->Delete($sTmpFile);
             return TRUE;
         }
     } else {
         // Ошибки загрузки картинки
         $sError = E::ModuleUploader()->GetErrorMsg();
         if (!$sError) {
             $sError = E::ModuleLang()->Get('error_upload_image');
         }
     }
     // Выведем ошибки пользователю
     E::ModuleMessage()->AddError($sError, E::ModuleLang()->Get('error'));
     // Удалим ранее загруженый файл
     F::File_Delete($sTmpFile);
 }
Esempio n. 14
0
 /**
  * hook:hook_name
  * text:just_a_text
  * func:func_name
  * conf:some.config.key
  * 
  * @param mixed $xExpression
  * @param array $aParams
  *
  * @return mixed
  */
 public static function evaluate($xExpression, $aParams = array())
 {
     if (is_bool($xExpression)) {
         return $xExpression;
     } elseif (is_numeric($xExpression)) {
         return (int) $xExpression;
     } elseif (is_object($xExpression)) {
         return $xExpression();
     } elseif (is_string($xExpression) && strpos($xExpression, ':')) {
         list($sType, $sName) = explode(':', $xExpression, 2);
         if ($sType === 'hook') {
             return E::ModuleHook()->Run($sName, $aParams, false);
         } elseif ($sType === 'text') {
             return $sName;
         } elseif ($sType === 'func') {
             return call_user_func($sName, $aParams);
         } elseif ($sType === 'call') {
             return call_user_func($sName, $aParams);
         } elseif ($sType === 'conf') {
             return C::Get($sName);
         }
     }
     return $xExpression;
 }
Esempio n. 15
0
 /**
  * Обработка дополнительных полей топика
  *
  * @param ModuleTopic_EntityTopic $oTopic
  * @param string $sType
  *
  * @return bool
  */
 public function processTopicFields($oTopic, $sType = 'add')
 {
     /** @var ModuleTopic_EntityContentValues $aValues */
     $aValues = array();
     if ($sType == 'update') {
         // * Получаем существующие значения
         if ($aData = $this->GetTopicValuesByArrayId(array($oTopic->getId()))) {
             $aValues = $aData[$oTopic->getId()];
         }
         // * Чистим существующие значения
         E::ModuleTopic()->DeleteTopicValuesByTopicId($oTopic->getId());
     }
     if ($oType = E::ModuleTopic()->GetContentTypeByUrl($oTopic->getType())) {
         //получаем поля для данного типа
         if ($aFields = $oType->getFields()) {
             foreach ($aFields as $oField) {
                 $sData = null;
                 if (isset($_REQUEST['fields'][$oField->getFieldId()]) || isset($_FILES['fields_' . $oField->getFieldId()]) || $oField->getFieldType() == 'single-image-uploader') {
                     //текстовые поля
                     if (in_array($oField->getFieldType(), array('input', 'textarea', 'select'))) {
                         $sData = E::ModuleText()->Parser($_REQUEST['fields'][$oField->getFieldId()]);
                     }
                     //поле ссылки
                     if ($oField->getFieldType() == 'link') {
                         $sData = $_REQUEST['fields'][$oField->getFieldId()];
                     }
                     //поле даты
                     if ($oField->getFieldType() == 'date') {
                         if (isset($_REQUEST['fields'][$oField->getFieldId()])) {
                             if (F::CheckVal($_REQUEST['fields'][$oField->getFieldId()], 'text', 6, 10) && substr_count($_REQUEST['fields'][$oField->getFieldId()], '.') == 2) {
                                 list($d, $m, $y) = explode('.', $_REQUEST['fields'][$oField->getFieldId()]);
                                 if (@checkdate($m, $d, $y)) {
                                     $sData = $_REQUEST['fields'][$oField->getFieldId()];
                                 }
                             }
                         }
                     }
                     //поле с файлом
                     if ($oField->getFieldType() == 'file') {
                         //если указано удаление файла
                         if (F::GetRequest('topic_delete_file_' . $oField->getFieldId())) {
                             if ($oTopic->getFieldFile($oField->getFieldId())) {
                                 @unlink(Config::Get('path.root.dir') . $oTopic->getFieldFile($oField->getFieldId())->getFileUrl());
                                 //$oTopic->setValueField($oField->getFieldId(),'');
                                 $sData = null;
                             }
                         } else {
                             //если удаление файла не указано, уже ранее залит файл^ и нового файла не загружалось
                             if ($sType == 'update' && isset($aValues[$oField->getFieldId()])) {
                                 $sData = $aValues[$oField->getFieldId()]->getValueSource();
                             }
                         }
                         if (isset($_FILES['fields_' . $oField->getFieldId()]) && is_uploaded_file($_FILES['fields_' . $oField->getFieldId()]['tmp_name'])) {
                             $iMaxFileSize = F::MemSize2Int(Config::Get('module.uploader.files.default.file_maxsize'));
                             $aFileExtensions = Config::Get('module.uploader.files.default.file_extensions');
                             if (!$iMaxFileSize || filesize($_FILES['fields_' . $oField->getFieldId()]['tmp_name']) <= $iMaxFileSize) {
                                 $aPathInfo = pathinfo($_FILES['fields_' . $oField->getFieldId()]['name']);
                                 if (!$aFileExtensions || in_array(strtolower($aPathInfo['extension']), $aFileExtensions)) {
                                     $sFileTmp = $_FILES['fields_' . $oField->getFieldId()]['tmp_name'];
                                     $sDirSave = Config::Get('path.uploads.root') . '/files/' . E::ModuleUser()->GetUserCurrent()->getId() . '/' . F::RandomStr(16);
                                     mkdir(Config::Get('path.root.dir') . $sDirSave, 0777, true);
                                     if (is_dir(Config::Get('path.root.dir') . $sDirSave)) {
                                         $sFile = $sDirSave . '/' . F::RandomStr(10) . '.' . strtolower($aPathInfo['extension']);
                                         $sFileFullPath = Config::Get('path.root.dir') . $sFile;
                                         if (copy($sFileTmp, $sFileFullPath)) {
                                             //удаляем старый файл
                                             if ($oTopic->getFieldFile($oField->getFieldId())) {
                                                 $sOldFile = Config::Get('path.root.dir') . $oTopic->getFieldFile($oField->getFieldId())->getFileUrl();
                                                 F::File_Delete($sOldFile);
                                             }
                                             $aFileObj = array();
                                             $aFileObj['file_hash'] = F::RandomStr(32);
                                             $aFileObj['file_name'] = E::ModuleText()->Parser($_FILES['fields_' . $oField->getFieldId()]['name']);
                                             $aFileObj['file_url'] = $sFile;
                                             $aFileObj['file_size'] = $_FILES['fields_' . $oField->getFieldId()]['size'];
                                             $aFileObj['file_extension'] = $aPathInfo['extension'];
                                             $aFileObj['file_downloads'] = 0;
                                             $sData = serialize($aFileObj);
                                             F::File_Delete($sFileTmp);
                                         }
                                     }
                                 } else {
                                     $sTypes = implode(', ', $aFileExtensions);
                                     E::ModuleMessage()->AddError(E::ModuleLang()->Get('topic_field_file_upload_err_type', array('types' => $sTypes)), null, true);
                                 }
                             } else {
                                 E::ModuleMessage()->AddError(E::ModuleLang()->Get('topic_field_file_upload_err_size', array('size' => $iMaxFileSize)), null, true);
                             }
                             F::File_Delete($_FILES['fields_' . $oField->getFieldId()]['tmp_name']);
                         }
                     }
                     // Поле с изображением
                     if ($oField->getFieldType() == 'single-image-uploader') {
                         $sTargetType = $oField->getFieldType() . '-' . $oField->getFieldId();
                         $iTargetId = $oTopic->getId();
                         // 1. Удалить значение target_tmp
                         // Нужно затереть временный ключ в ресурсах, что бы в дальнейшем картнка не
                         // воспринималась как временная.
                         if ($sTargetTmp = E::ModuleSession()->GetCookie(ModuleUploader::COOKIE_TARGET_TMP)) {
                             // 2. Удалить куку.
                             // Если прозошло сохранение вновь созданного топика, то нужно
                             // удалить куку временной картинки. Если же сохранялся уже существующий топик,
                             // то удаление куки ни на что влиять не будет.
                             E::ModuleSession()->DelCookie(ModuleUploader::COOKIE_TARGET_TMP);
                             // 3. Переместить фото
                             $sNewPath = E::ModuleUploader()->GetUserImageDir(E::UserId(), true, false);
                             $aMresourceRel = E::ModuleMresource()->GetMresourcesRelByTargetAndUser($sTargetType, 0, E::UserId());
                             if ($aMresourceRel) {
                                 $oResource = array_shift($aMresourceRel);
                                 $sOldPath = $oResource->GetFile();
                                 $oStoredFile = E::ModuleUploader()->Store($sOldPath, $sNewPath);
                                 /** @var ModuleMresource_EntityMresource $oResource */
                                 $oResource = E::ModuleMresource()->GetMresourcesByUuid($oStoredFile->getUuid());
                                 if ($oResource) {
                                     $oResource->setUrl(E::ModuleMresource()->NormalizeUrl(E::ModuleUploader()->GetTargetUrl($sTargetType, $iTargetId)));
                                     $oResource->setType($sTargetType);
                                     $oResource->setUserId(E::UserId());
                                     // 4. В свойство поля записать адрес картинки
                                     $sData = $oResource->getMresourceId();
                                     $oResource = array($oResource);
                                     E::ModuleMresource()->UnlinkFile($sTargetType, 0, $oTopic->getUserId());
                                     E::ModuleMresource()->AddTargetRel($oResource, $sTargetType, $iTargetId);
                                 }
                             }
                         } else {
                             // Топик редактируется, просто обновим поле
                             $aMresourceRel = E::ModuleMresource()->GetMresourcesRelByTargetAndUser($sTargetType, $iTargetId, E::UserId());
                             if ($aMresourceRel) {
                                 $oResource = array_shift($aMresourceRel);
                                 $sData = $oResource->getMresourceId();
                             } else {
                                 $sData = false;
                                 //                                    $this->DeleteField($oField);
                             }
                         }
                     }
                     E::ModuleHook()->Run('content_field_proccess', array('sData' => &$sData, 'oField' => $oField, 'oTopic' => $oTopic, 'aValues' => $aValues, 'sType' => &$sType));
                     //Добавляем поле к топику.
                     if ($sData) {
                         /** @var ModuleTopic_EntityContentValues $oValue */
                         $oValue = E::GetEntity('Topic_ContentValues');
                         $oValue->setTargetId($oTopic->getId());
                         $oValue->setTargetType('topic');
                         $oValue->setFieldId($oField->getFieldId());
                         $oValue->setFieldType($oField->getFieldType());
                         $oValue->setValue($sData);
                         $oValue->setValueSource(in_array($oField->getFieldType(), array('file', 'single-image-uploader')) ? $sData : $_REQUEST['fields'][$oField->getFieldId()]);
                         $this->AddTopicValue($oValue);
                     }
                 }
             }
         }
     }
     return true;
 }
Esempio n. 16
0
 /**
  * Запускает на выполнение экшен
  * Может запускаться рекурсивно если в одном экшене стоит переадресация на другой
  *
  */
 public function ExecAction()
 {
     $this->DefineActionClass();
     // Hook before action
     E::ModuleHook()->Run('action_before');
     $sActionClass = $this->DefineActionClass();
     // * Определяем наличие делегата экшена
     if ($aChain = E::ModulePlugin()->GetDelegationChain('action', $sActionClass)) {
         if (!empty($aChain)) {
             $sActionClass = $aChain[0];
         }
     }
     static::$sActionClass = $sActionClass;
     if (!class_exists($sActionClass)) {
         throw new Exception('Cannot load class "' . $sActionClass . '"');
     }
     $this->oAction = new $sActionClass(static::$sAction);
     // * Инициализируем экшен
     $sInitResult = $this->oAction->Init();
     if ($sInitResult === 'next') {
         $this->ExecAction();
     } else {
         // Если инициализация экшена прошла успешно,
         // то запускаем запрошенный ивент на исполнение.
         if ($sInitResult !== false) {
             $xEventResult = $this->oAction->ExecEvent();
             static::$sActionEventName = $this->oAction->GetCurrentEventName();
             $this->oAction->EventShutdown();
             if ($xEventResult === 'next') {
                 $this->ExecAction();
             }
         }
     }
     // Hook after action
     E::ModuleHook()->Run('action_after');
 }
Esempio n. 17
0
 /**
  * Запускает евент на выполнение
  * Если текущий евент не определен то  запускается тот которые определен по умолчанию (default event)
  *
  * @return mixed
  */
 public function ExecEvent()
 {
     if ($this->GetDefaultEvent() == 'index' && method_exists($this, 'EventIndex')) {
         $this->AddEvent('index', 'EventIndex');
     }
     $this->sCurrentEvent = R::GetActionEvent();
     if ($this->sCurrentEvent == null) {
         $this->sCurrentEvent = $this->GetDefaultEvent();
         R::SetActionEvent($this->sCurrentEvent);
     }
     $this->aCurrentEventHandler = $this->_getEventHandler();
     if ($this->aCurrentEventHandler !== false) {
         $this->sCurrentEventName = $this->aCurrentEventHandler['name'];
         if ($this->Access(R::GetActionEvent())) {
             $sMethod = $this->aCurrentEventHandler['method'];
             $sHook = 'action_event_' . strtolower($this->sCurrentAction);
             E::ModuleHook()->Run($sHook . '_before', array('event' => $this->sCurrentEvent, 'params' => $this->GetParams()));
             $xResult = $this->{$sMethod}();
             E::ModuleHook()->Run($sHook . '_after', array('event' => $this->sCurrentEvent, 'params' => $this->GetParams()));
             return $xResult;
         } else {
             return $this->AccessDenied(R::GetActionEvent());
             //return null;
         }
     }
     return $this->EventNotFound();
 }
Esempio n. 18
0
 /**
  * Обработка Ajax регистрации
  */
 protected function EventAjaxRegistration()
 {
     // * Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json');
     E::ModuleSecurity()->ValidateSendForm();
     // * Создаем объект пользователя и устанавливаем сценарий валидации
     /** @var ModuleUser_EntityUser $oUser */
     $oUser = E::GetEntity('ModuleUser_EntityUser');
     $oUser->_setValidateScenario('registration');
     // * Заполняем поля (данные)
     $oUser->setLogin($this->GetPost('login'));
     $oUser->setMail($this->GetPost('mail'));
     $oUser->setPassword($this->GetPost('password'));
     $oUser->setPasswordConfirm($this->GetPost('password_confirm'));
     $oUser->setCaptcha($this->GetPost('captcha'));
     $oUser->setDateRegister(F::Now());
     $oUser->setIpRegister(F::GetUserIp());
     // * Если используется активация, то генерим код активации
     if (Config::Get('general.reg.activation')) {
         $oUser->setActivate(0);
         $oUser->setActivationKey(F::RandomStr());
     } else {
         $oUser->setActivate(1);
         $oUser->setActivationKey(null);
     }
     E::ModuleHook()->Run('registration_validate_before', array('oUser' => $oUser));
     // * Запускаем валидацию
     if ($oUser->_Validate()) {
         // Сбросим капчу // issue#342.
         E::ModuleSession()->Drop(E::ModuleCaptcha()->GetKeyName());
         E::ModuleHook()->Run('registration_validate_after', array('oUser' => $oUser));
         $oUser->setPassword($oUser->getPassword(), true);
         if ($this->_addUser($oUser)) {
             E::ModuleHook()->Run('registration_after', array('oUser' => $oUser));
             // * Подписываем пользователя на дефолтные события в ленте активности
             E::ModuleStream()->SwitchUserEventDefaultTypes($oUser->getId());
             // * Если юзер зарегистрировался по приглашению то обновляем инвайт
             if (Config::Get('general.reg.invite') && ($oInvite = E::ModuleUser()->GetInviteByCode($this->GetInviteRegister()))) {
                 $oInvite->setUserToId($oUser->getId());
                 $oInvite->setDateUsed(F::Now());
                 $oInvite->setUsed(1);
                 E::ModuleUser()->UpdateInvite($oInvite);
             }
             // * Если стоит регистрация с активацией то проводим её
             if (Config::Get('general.reg.activation')) {
                 // * Отправляем на мыло письмо о подтверждении регистрации
                 E::ModuleNotify()->SendRegistrationActivate($oUser, F::GetRequestStr('password'));
                 E::ModuleViewer()->AssignAjax('sUrlRedirect', R::GetPath('registration') . 'confirm/');
             } else {
                 E::ModuleNotify()->SendRegistration($oUser, F::GetRequestStr('password'));
                 $oUser = E::ModuleUser()->GetUserById($oUser->getId());
                 // * Сразу авторизуем
                 E::ModuleUser()->Authorization($oUser, false);
                 $this->DropInviteRegister();
                 // * Определяем URL для редиректа после авторизации
                 $sUrl = Config::Get('module.user.redirect_after_registration');
                 if (F::GetRequestStr('return-path')) {
                     $sUrl = F::GetRequestStr('return-path');
                 }
                 E::ModuleViewer()->AssignAjax('sUrlRedirect', $sUrl ? $sUrl : Config::Get('path.root.url'));
                 E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('registration_ok'));
             }
         } else {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'));
             return;
         }
     } else {
         // * Получаем ошибки
         E::ModuleViewer()->AssignAjax('aErrors', $oUser->_getValidateErrors());
     }
 }
Esempio n. 19
0
 /**
  * Удаление/восстановление комментария
  *
  */
 protected function EventCommentDelete()
 {
     // * Комментарий существует?
     $idComment = F::GetRequestStr('idComment', null, 'post');
     if (!($oComment = E::ModuleComment()->GetCommentById($idComment))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     // * Есть права на удаление комментария?
     if (!$oComment->isDeletable()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('not_access'), E::ModuleLang()->Get('error'));
         return;
     }
     // * Устанавливаем пометку о том, что комментарий удален
     $oComment->setDelete(($oComment->getDelete() + 1) % 2);
     E::ModuleHook()->Run('comment_delete_before', array('oComment' => $oComment));
     if (!E::ModuleComment()->UpdateCommentStatus($oComment)) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     E::ModuleHook()->Run('comment_delete_after', array('oComment' => $oComment));
     // * Формируем текст ответа
     if ($bState = (bool) $oComment->getDelete()) {
         $sMsg = E::ModuleLang()->Get('comment_delete_ok');
         $sTextToggle = E::ModuleLang()->Get('comment_repair');
     } else {
         $sMsg = E::ModuleLang()->Get('comment_repair_ok');
         $sTextToggle = E::ModuleLang()->Get('comment_delete');
     }
     // * Обновление события в ленте активности
     E::ModuleStream()->Write($oComment->getUserId(), 'add_comment', $oComment->getId(), !$oComment->getDelete());
     // * Показываем сообщение и передаем переменные в ajax ответ
     E::ModuleMessage()->AddNoticeSingle($sMsg, E::ModuleLang()->Get('attention'));
     E::ModuleViewer()->AssignAjax('bState', $bState);
     E::ModuleViewer()->AssignAjax('sTextToggle', $sTextToggle);
 }
Esempio n. 20
0
 /**
  * Удаление блога
  *
  */
 protected function EventDeleteBlog()
 {
     E::ModuleSecurity()->ValidateSendForm();
     // * Проверяем передан ли в УРЛе номер блога
     $nBlogId = intval($this->GetParam(0));
     if (!$nBlogId || !($oBlog = E::ModuleBlog()->GetBlogById($nBlogId))) {
         return parent::EventNotFound();
     }
     $this->oCurrentBlog = $oBlog;
     // * Проверям авторизован ли пользователь
     if (!E::ModuleUser()->IsAuthorization()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('not_access'), E::ModuleLang()->Get('error'));
         return R::Action('error');
     }
     // * проверяем есть ли право на удаление блога
     if (!($nAccess = E::ModuleACL()->IsAllowDeleteBlog($oBlog, $this->oUserCurrent))) {
         return parent::EventNotFound();
     }
     $aTopics = E::ModuleTopic()->GetTopicsByBlogId($nBlogId);
     switch ($nAccess) {
         case ModuleACL::CAN_DELETE_BLOG_EMPTY_ONLY:
             if (is_array($aTopics) && count($aTopics)) {
                 E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('blog_admin_delete_not_empty'), E::ModuleLang()->Get('error'), true);
                 R::Location($oBlog->getUrlFull());
             }
             break;
         case ModuleACL::CAN_DELETE_BLOG_WITH_TOPICS:
             /*
              * Если указан идентификатор блога для перемещения,
              * то делаем попытку переместить топики.
              *
              * (-1) - выбран пункт меню "удалить топики".
              */
             $nNewBlogId = intval(F::GetRequestStr('topic_move_to'));
             if ($nNewBlogId > 0 && is_array($aTopics) && count($aTopics)) {
                 if (!($oBlogNew = E::ModuleBlog()->GetBlogById($nNewBlogId))) {
                     E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('blog_admin_delete_move_error'), E::ModuleLang()->Get('error'), true);
                     R::Location($oBlog->getUrlFull());
                 }
                 // * Если выбранный блог является персональным, возвращаем ошибку
                 if ($oBlogNew->getType() == 'personal') {
                     E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('blog_admin_delete_move_personal'), E::ModuleLang()->Get('error'), true);
                     R::Location($oBlog->getUrlFull());
                 }
                 // * Перемещаем топики
                 E::ModuleTopic()->MoveTopics($nBlogId, $nNewBlogId);
             }
             break;
         default:
             return parent::EventNotFound();
     }
     // * Удаляяем блог и перенаправляем пользователя к списку блогов
     E::ModuleHook()->Run('blog_delete_before', array('sBlogId' => $nBlogId));
     if ($this->_deleteBlog($oBlog)) {
         E::ModuleHook()->Run('blog_delete_after', array('sBlogId' => $nBlogId));
         E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('blog_admin_delete_success'), E::ModuleLang()->Get('attention'), true);
         R::Location(R::GetPath('blogs'));
     } else {
         R::Location($oBlog->getUrlFull());
     }
 }
Esempio n. 21
0
 /**
  * @param string $sTagName
  * @param array  $aTagAttributes
  * @param string $sСontent
  *
  * @return string
  */
 public function CallbackTagSnippet($sTagName, $aTagAttributes, $sСontent)
 {
     if (isset($aTagAttributes['data-alto-tag-name'])) {
         $sSnippetName = $aTagAttributes['data-alto-tag-name'];
     } elseif (isset($aTagAttributes['name'])) {
         $sSnippetName = $aTagAttributes['name'];
     } else {
         // Нет имени сниппета, оставляем, как есть
         return $this->_buildTag($sTagName, $aTagAttributes, $sСontent);
     }
     // Имя сниппета есть, обрабатываем его
     $sCacheKey = serialize(array($sTagName, $aTagAttributes, $sСontent));
     // Может сниппет уже был в обработке, тогда просто возьмем его из кэша
     $sResult = E::ModuleCache()->GetTmp($sCacheKey);
     // Если результата в кеше нет, то обрабатываем
     if (FALSE === $sResult) {
         $aParams = array();
         if (!empty($aTagAttributes['data-alto-tag-attr'])) {
             $aTagAttr = explode(';', $aTagAttributes['data-alto-tag-attr']);
             foreach ($aTagAttr as $sAttr) {
                 if ($sAttr) {
                     list($sAttrName, $sAttrValue) = explode(':', $sAttr);
                     $aParams[$sAttrName] = $sAttrValue;
                 }
             }
         }
         // Добавим в параметры текст, который был в топике, вдруг какой-нибудь сниппет
         // захочет с ним поработать.
         //$aSnippetParams['target_text'] = $sText;
         // Добавим контент сниппета
         $aParams['snippet_text'] = $sСontent;
         // Добавим в параметры имя сниппета
         $aParams['snippet_name'] = $sSnippetName;
         // Попытаемся получить результат от обработчика
         // Определим тип сниппета, может быть шаблонным, а может и исполняемым
         // по умолчанию сниппет ссчитаем исполняемым. Если шаблонный, то его
         // обрабатывает предопределенный хук snippet_template_type
         $sHookName = 'snippet_' . $sSnippetName;
         $sHookName = E::ModuleHook()->IsEnabled($sHookName) ? 'snippet_' . $sSnippetName : 'snippet_template_type';
         // Вызовем хук
         E::ModuleHook()->Run($sHookName, array('params' => &$aParams, 'result' => &$sResult));
         if ($sHookName === 'snippet_template_type' && $sResult === false) {
             // Шаблонный хук не отработал, оставлям тег, как есть
             $sResult = $this->_buildTag($sTagName, $aTagAttributes, $sСontent);
         }
         // Запишем результат обработки в кэш
         E::ModuleCache()->SetTmp($sResult, $sCacheKey);
     }
     return $sResult;
 }
Esempio n. 22
0
 /**
  * Проверяет массив правил. В качестве правил может быть задана колбэк-функция
  * или указан метод владельца сущности, который должен быть реализован заранее
  *
  * @param $aRules
  * @param bool $bConcatenateResult
  * @param bool $sOwnerClassName
  * @return bool
  */
 public function checkCustomRules($aRules, $bConcatenateResult = FALSE, $sOwnerClassName = FALSE)
 {
     // Ключ кэша
     $sCacheKey = md5(serialize($aRules) . (string) $bConcatenateResult . (string) $sOwnerClassName);
     if (!(FALSE === ($data = E::ModuleCache()->GetTmp($sCacheKey)))) {
         return $data;
     }
     // Правило жёстко задано - вернем его
     if (is_bool($aRules)) {
         return $aRules;
     }
     // Правило жёстко задано - вернем его
     if (is_string($aRules)) {
         return $aRules;
     }
     /** @var callable[]|[][] $aActiveRule Правило вычисления активности */
     // Нет правила, кнопка вообще не активна будет
     if (!$aRules) {
         return FALSE;
     }
     // Правило задается методаом меню
     if (!is_array($aRules)) {
         return FALSE;
     }
     if (!$sOwnerClassName) {
         $aOwnerClassName = E::getInstance()->GetClassInfo($this, Engine::CI_MODULE);
         $sOwnerClassName = reset($aOwnerClassName);
     }
     // Все проверки пройдены, запускаем вычисление активности
     $bResult = FALSE;
     foreach ($aRules as $sMethodName => $xRule) {
         if (is_bool($xRule)) {
             if ($bConcatenateResult) {
                 $bResult .= $xRule;
             } else {
                 $bResult = $bResult || $xRule;
             }
             if ($bResult && !$bConcatenateResult) {
                 break;
             }
             continue;
         }
         if (is_string($xRule) && $bConcatenateResult) {
             if (strpos($xRule, 'hook:') === 0) {
                 $bResult .= E::ModuleHook()->Run(substr($xRule, 5));
             } elseif (strpos($xRule, 'text:') === 0) {
                 $bResult .= substr($xRule, 5);
             } elseif (strpos($xRule, 'func:') === 0) {
                 $bResult .= call_user_func(substr($xRule, 5));
             } else {
                 $bResult .= $xRule;
             }
             continue;
         }
         // Передан колбэк
         if (is_callable($xRule)) {
             $bResult = $bResult || $xRule();
             if ($bResult && !$bConcatenateResult) {
                 break;
             }
             continue;
         }
         /**
          * Передан вызов функции, например
          * $xRule = array('compare_action' => array('index'))
          */
         $sTmpMethodName = FALSE;
         $aTmpMethodParams = FALSE;
         // Метод передан строкой
         if (is_int($sMethodName) && is_string($xRule)) {
             $sTmpMethodName = $xRule;
             $aTmpMethodParams = array();
         }
         // Метод передан массивом
         if (is_string($sMethodName) && is_array($xRule)) {
             $sTmpMethodName = $sMethodName;
             $aTmpMethodParams = $xRule;
         }
         // Вызовем метод
         if ($sTmpMethodName && $aTmpMethodParams !== FALSE) {
             if (strpos($sTmpMethodName, 'hook:') === 0) {
                 $xCallResult = E::ModuleHook()->Run(substr($sTmpMethodName, 5), $aTmpMethodParams, false);
             } elseif (strpos($sTmpMethodName, 'text:') === 0) {
                 $xCallResult = substr($sTmpMethodName, 5);
             } elseif (strpos($sTmpMethodName, 'func:') === 0) {
                 $xCallResult = call_user_func_array(substr($sTmpMethodName, 5), $aTmpMethodParams);
             } else {
                 $sTmpMethodName = $sOwnerClassName . '_' . F::StrCamelize($sTmpMethodName);
                 $xCallResult = call_user_func_array(array($this, $sTmpMethodName), $aTmpMethodParams);
             }
             if ($bConcatenateResult) {
                 if (!empty($xCallResult) && (is_string($xCallResult) || is_numeric($xCallResult))) {
                     $bResult .= $xCallResult;
                 }
             } else {
                 $bResult = $bResult || $xCallResult;
             }
             if ($bResult && !$bConcatenateResult) {
                 break;
             }
             continue;
         }
     }
     // Закэшируем результат
     E::ModuleCache()->SetTmp($bResult, $sCacheKey);
     return $bResult;
 }
Esempio n. 23
0
 /**
  * @param string $sType
  * @param string $sName
  * @param string $sContent
  * @param int    $iTimestamp
  * @param object $oSmarty
  *
  * @return string|void
  */
 public function SmartyDefaultTemplateHandler($sType, $sName, &$sContent, &$iTimestamp, $oSmarty)
 {
     $sSkin = $this->GetConfigSkin();
     $sResult = parent::SmartyDefaultTemplateHandler($sType, $sName, $sContent, $iTimestamp, $oSmarty);
     if (!$sResult) {
         if ($sType == 'file') {
             if (in_array($sName, $this->aTemplatesAutocreate)) {
                 $sResult = $this->_autocreateOldTemplate($sName);
                 if ($sResult) {
                     $this->_setTemplatePath($sSkin, $sName, $sResult);
                 }
                 return $sResult;
             }
             if (strpos($sName, 'widgets/widget.') === 0) {
                 $sFile = Config::Get('path.smarty.template') . str_replace('widgets/widget.', 'blocks/block.', $sName);
                 if (F::File_Exists($sFile)) {
                     if ($sFile) {
                         $this->_setTemplatePath($sSkin, $sName, $sFile);
                     }
                     return $sFile;
                 }
             } elseif ($sName == 'actions/ActionContent/add.tpl' || $sName == 'actions/content/action.content.add.tpl' || $sName == 'actions/content/action.content.edit.tpl') {
                 $sResult = Config::Get('path.smarty.template') . '/actions/ActionContent/add.tpl';
                 if (!is_file($sResult)) {
                     $sResult = Config::Get('path.smarty.template') . '/actions/ActionTopic/add.tpl';
                 }
                 if (!in_array(Config::Get('view.skin'), $this->aAdaptedSkins)) {
                     E::ModuleHook()->AddExecFunction('template_form_add_topic_topic_end', array($this, 'TemplateFormAddTopic'));
                 }
                 $oContentType = $oSmarty->getTemplateVars('oContentType');
                 $oType = $oSmarty->getTemplateVars('oType');
                 if (!$oType && $oContentType) {
                     $oSmarty->assign('oType', $oContentType);
                 }
             } elseif (strpos($sName, 'forms/view_field') === 0 || strpos($sName, 'forms/form_field') === 0) {
                 $sResult = Plugin::GetTemplateDir('PluginLs') . $sName;
             } elseif ($sName == 'actions/page/action.page.show.tpl') {
                 if ($this->TemplateExists('actions/page/action.page.page.tpl')) {
                     $sResult = F::File_Exists('actions/page/action.page.page.tpl', $this->oSmarty->getTemplateDir());
                 }
                 if (!$sResult && $this->TemplateExists('actions/ActionPage/page.tpl')) {
                     $sResult = F::File_Exists('actions/ActionPage/page.tpl', $this->oSmarty->getTemplateDir());
                 } else {
                     $sResult = parent::SmartyDefaultTemplateHandler($sType, 'actions/ActionPage/page.tpl', $sContent, $iTimestamp, $oSmarty);
                 }
             }
             if (!$sResult && isset($this->aTemplatesLsMap[$sName])) {
                 $sLsTemplate = $this->aTemplatesLsMap[$sName];
                 $sResult = $this->TemplateExists($sLsTemplate);
                 if ($sResult) {
                     $sResult = F::File_Exists($sLsTemplate, $this->oSmarty->getTemplateDir());
                 } else {
                     $sResult = parent::SmartyDefaultTemplateHandler($sType, $sLsTemplate, $sContent, $iTimestamp, $oSmarty);
                 }
             }
             if (!$sResult) {
                 if (preg_match('~^(tpls/)?actions/([^/]+)/action\\.(\\w+)\\.(.+)$~', $sName, $aMatches)) {
                     $sLsTemplate = 'actions/Action' . ucfirst($aMatches[2]) . '/' . $aMatches[4];
                     if ($this->TemplateExists($sLsTemplate, false)) {
                         $sResult = F::File_Exists($sLsTemplate, $this->oSmarty->getTemplateDir());
                     } else {
                         $sResult = $this->SmartyDefaultTemplateHandler($sType, $sLsTemplate, $sContent, $iTimestamp, $oSmarty);
                     }
                 } elseif (preg_match('~^topic_(\\w+)\\.tpl$~', $sName)) {
                     $sLsTemplate = 'topic_topic.tpl';
                     if ($this->TemplateExists($sLsTemplate, false)) {
                         $sResult = F::File_Exists($sLsTemplate, $this->oSmarty->getTemplateDir());
                     } else {
                         $sResult = $this->SmartyDefaultTemplateHandler($sType, $sLsTemplate, $sContent, $iTimestamp, $oSmarty);
                     }
                 } elseif ($nPos = strpos($sName, '/emails/ru/email.')) {
                     if (strpos(substr($sName, $nPos + 17), '/')) {
                         $sLsTemplate = str_replace('/emails/ru/email.', '/notify/russian/', $sName);
                     } else {
                         $sLsTemplate = str_replace('/emails/ru/email.', '/notify/russian/notify.', $sName);
                     }
                     if (F::File_Exists($sLsTemplate)) {
                         $sResult = $sLsTemplate;
                     } else {
                         $sResult = $this->SmartyDefaultTemplateHandler($sType, $sLsTemplate, $sContent, $iTimestamp, $oSmarty);
                     }
                 } elseif ($nPos = strpos($sName, '/notify/ru/email.notify.')) {
                     $sLsTemplate = str_replace('/notify/ru/email.notify.', '/notify/russian/notify.', $sName);
                     if (F::File_Exists($sLsTemplate)) {
                         $sResult = $sLsTemplate;
                     } else {
                         $sResult = $this->SmartyDefaultTemplateHandler($sType, $sLsTemplate, $sContent, $iTimestamp, $oSmarty);
                     }
                 } elseif ($nPos = strpos($sName, '/notify/ru/email.shop/')) {
                     $sLsTemplate = str_replace('/notify/ru/email.shop/', '/notify/russian/shop/', $sName);
                     if (F::File_Exists($sLsTemplate)) {
                         $sResult = $sLsTemplate;
                     } else {
                         $sResult = $this->SmartyDefaultTemplateHandler($sType, $sLsTemplate, $sContent, $iTimestamp, $oSmarty);
                     }
                 } elseif ($nPos = strpos($sName, '/email.')) {
                     $sLsTemplate = substr($sName, 0, $nPos) . '/notify.' . substr($sName, $nPos + 7);
                     if (F::File_Exists($sLsTemplate)) {
                         $sResult = $sLsTemplate;
                     } else {
                         $sResult = $this->SmartyDefaultTemplateHandler($sType, $sLsTemplate, $sContent, $iTimestamp, $oSmarty);
                     }
                 } elseif (preg_match('#^menus\\/menu\\.((content)?\\-)?([\\w\\-\\.]+)\\.tpl$#i', $sName, $aMatches)) {
                     if (!$aMatches[2]) {
                         $sLsTemplate = 'menu.' . $aMatches[3] . '.tpl';
                     } else {
                         $sLsTemplate = 'menu.' . $aMatches[3] . '.content.tpl';
                     }
                     if ($this->TemplateExists($sLsTemplate, false)) {
                         $sResult = F::File_Exists($sLsTemplate, $this->oSmarty->getTemplateDir());
                     } else {
                         $sResult = $this->SmartyDefaultTemplateHandler($sType, $sLsTemplate, $sContent, $iTimestamp, $oSmarty);
                     }
                 }
             }
             if (!$sResult && ($sNewTemplate = array_search($sName, $this->aTemplatesLsMap))) {
                 $sResult = $this->TemplateExists($sNewTemplate);
                 if ($sResult) {
                     $sResult = F::File_Exists($sNewTemplate, $this->oSmarty->getTemplateDir());
                 } else {
                     $sResult = parent::SmartyDefaultTemplateHandler($sType, $sNewTemplate, $sContent, $iTimestamp, $oSmarty);
                 }
             }
         }
     }
     if ($sResult) {
         $this->_setTemplatePath($sSkin, $sName, $sResult);
     }
     return $sResult;
 }
Esempio n. 24
0
 /**
  * @return null|string
  */
 protected function RssPersonalBlog()
 {
     $sUserLogin = $this->GetParam(0);
     $aParams = $this->GetParams();
     array_shift($aParams);
     if ($iMaxItems = intval(C::Get('module.topic.max_rss_count'))) {
         C::Set('module.topic.per_page', $iMaxItems);
     }
     $oUser = E::ModuleUser()->GetUserByLogin($sUserLogin);
     if ($oUser && ($oBlog = E::ModuleBlog()->GetPersonalBlogByUserId($oUser->getId()))) {
         E::ModuleHook()->AddHandler('action_after', array($this, 'ShowRssBlog'));
         return R::Action('blog', $oBlog->getId(), $aParams);
     } else {
         $this->_displayEmptyRss();
     }
     return null;
 }
Esempio n. 25
0
 /**
  * Выполняется при завершении работы экшена
  *
  */
 public function EventShutdown()
 {
     $iCountTopicFavourite = E::ModuleTopic()->GetCountTopicsFavouriteByUserId($this->oUserCurrent->getId());
     $iCountTopicUser = E::ModuleTopic()->GetCountTopicsPersonalByUser($this->oUserCurrent->getId(), 1);
     $iCountCommentUser = E::ModuleComment()->GetCountCommentsByUserId($this->oUserCurrent->getId(), 'topic');
     $iCountCommentFavourite = E::ModuleComment()->GetCountCommentsFavouriteByUserId($this->oUserCurrent->getId());
     $iCountNoteUser = E::ModuleUser()->GetCountUserNotesByUserId($this->oUserCurrent->getId());
     E::ModuleViewer()->Assign('oUserProfile', $this->oUserCurrent);
     E::ModuleViewer()->Assign('iCountWallUser', E::ModuleWall()->GetCountWall(array('wall_user_id' => $this->oUserCurrent->getId(), 'pid' => null)));
     // * Общее число публикация и избранного
     E::ModuleViewer()->Assign('iCountTopicUser', $iCountTopicUser);
     E::ModuleViewer()->Assign('iCountCommentUser', $iCountCommentUser);
     E::ModuleViewer()->Assign('iCountTopicFavourite', $iCountTopicFavourite);
     E::ModuleViewer()->Assign('iCountCommentFavourite', $iCountCommentFavourite);
     E::ModuleViewer()->Assign('iCountNoteUser', $iCountNoteUser);
     E::ModuleViewer()->Assign('iCountCreated', $iCountNoteUser + $iCountTopicUser + $iCountCommentUser);
     E::ModuleViewer()->Assign('iCountFavourite', $iCountCommentFavourite + $iCountTopicFavourite);
     E::ModuleViewer()->Assign('iCountFriendsUser', E::ModuleUser()->GetCountUsersFriend($this->oUserCurrent->getId()));
     // * Загружаем в шаблон необходимые переменные
     E::ModuleViewer()->Assign('sMenuItemSelect', $this->sMenuItemSelect);
     E::ModuleViewer()->Assign('sMenuSubItemSelect', $this->sMenuSubItemSelect);
     E::ModuleHook()->Run('action_shutdown_settings');
 }
Esempio n. 26
0
 /**
  * Обработка добавление комментария к письму
  *
  */
 protected function SubmitComment()
 {
     // * Проверям авторизован ли пользователь
     if (!E::ModuleUser()->IsAuthorization()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Проверяем разговор
     if (!($oTalk = E::ModuleTalk()->GetTalkById(F::GetRequestStr('cmt_target_id')))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return false;
     }
     if (!($oTalkUser = E::ModuleTalk()->GetTalkUser($oTalk->getId(), $this->oUserCurrent->getId()))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Проверяем разрешено ли отправлять инбокс по времени
     if (!E::ModuleACL()->CanPostTalkCommentTime($this->oUserCurrent)) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('talk_time_limit'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Проверяем текст комментария
     $sText = E::ModuleText()->Parser(F::GetRequestStr('comment_text'));
     $iMin = intval(Config::Get('module.talk.min_length'));
     $iMax = intval(Config::Get('module.talk.max_length'));
     if (!F::CheckVal($sText, 'text', $iMin, $iMax)) {
         if ($iMax) {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('talk_create_text_error_len', array('min' => $iMin, 'max' => $iMax)), E::ModuleLang()->Get('error'));
         } else {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('talk_create_text_error_min', array('min' => $iMin)), E::ModuleLang()->Get('error'));
         }
         return false;
     }
     // * Проверям на какой коммент отвечаем
     $sParentId = (int) F::GetRequest('reply');
     if (!F::CheckVal($sParentId, 'id')) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return false;
     }
     $oCommentParent = null;
     if ($sParentId != 0) {
         // * Проверяем существует ли комментарий на который отвечаем
         if (!($oCommentParent = E::ModuleComment()->GetCommentById($sParentId))) {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
             return false;
         }
         // * Проверяем из одного топика ли новый коммент и тот на который отвечаем
         if ($oCommentParent->getTargetId() != $oTalk->getId()) {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
             return false;
         }
     } else {
         // * Корневой комментарий
         $sParentId = null;
     }
     // * Проверка на дублирующий коммент
     if (E::ModuleComment()->GetCommentUnique($oTalk->getId(), 'talk', $this->oUserCurrent->getId(), $sParentId, md5($sText))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_spam'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Создаём комментарий
     /** @var ModuleComment_EntityComment $oCommentNew */
     $oCommentNew = E::GetEntity('Comment');
     $oCommentNew->setTargetId($oTalk->getId());
     $oCommentNew->setTargetType('talk');
     $oCommentNew->setUserId($this->oUserCurrent->getId());
     $oCommentNew->setText($sText);
     $oCommentNew->setDate(F::Now());
     $oCommentNew->setUserIp(F::GetUserIp());
     $oCommentNew->setPid($sParentId);
     $oCommentNew->setTextHash(md5($sText));
     $oCommentNew->setPublish(1);
     // * Добавляем коммент
     E::ModuleHook()->Run('talk_comment_add_before', array('oCommentNew' => $oCommentNew, 'oCommentParent' => $oCommentParent, 'oTalk' => $oTalk));
     if (E::ModuleComment()->AddComment($oCommentNew)) {
         E::ModuleHook()->Run('talk_comment_add_after', array('oCommentNew' => $oCommentNew, 'oCommentParent' => $oCommentParent, 'oTalk' => $oTalk));
         E::ModuleViewer()->AssignAjax('sCommentId', $oCommentNew->getId());
         $oTalk->setDateLast(F::Now());
         $oTalk->setUserIdLast($oCommentNew->getUserId());
         $oTalk->setCommentIdLast($oCommentNew->getId());
         $oTalk->setCountComment($oTalk->getCountComment() + 1);
         E::ModuleTalk()->UpdateTalk($oTalk);
         // * Отсылаем уведомления всем адресатам
         $aUsersTalk = E::ModuleTalk()->GetUsersTalk($oTalk->getId(), ModuleTalk::TALK_USER_ACTIVE);
         foreach ($aUsersTalk as $oUserTalk) {
             if ($oUserTalk->getId() != $oCommentNew->getUserId()) {
                 E::ModuleNotify()->SendTalkCommentNew($oUserTalk, $this->oUserCurrent, $oTalk, $oCommentNew);
             }
         }
         // * Увеличиваем число новых комментов
         E::ModuleTalk()->IncreaseCountCommentNew($oTalk->getId(), $oCommentNew->getUserId());
         return true;
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
     }
     return false;
 }
Esempio n. 27
0
 /**
  * Initialization of render before Fetch() or Display()
  *
  * @param bool $bForce
  */
 protected function _initRender($bForce = false)
 {
     if ($this->bInitRender && !$bForce) {
         return;
     }
     $nTimer = microtime(true);
     E::ModuleHook()->Run('render_init_start', array('bLocal' => $this->bLocal));
     // If skin not initialized (or it was changed) then init one
     if ($this->sViewSkin != $this->GetConfigSkin()) {
         $this->_initSkin();
     } else {
         // Level could be changed after skin initialization
         Config::SetLevel(Config::LEVEL_SKIN_CUSTOM);
     }
     // init templator if not yet
     $this->_initTemplator();
     // Loads localized texts
     $aLang = E::ModuleLang()->GetLangMsg();
     // Old skin compatibility
     $aLang['registration_password_notice'] = E::ModuleLang()->Get('registration_password_notice', array('min' => C::Val('module.security.password_len', 3)));
     $this->Assign('aLang', $aLang);
     //$this->Assign('oLang', E::ModuleLang()->Dictionary());
     if (!$this->bLocal && !$this->GetResponseAjax()) {
         // Initialization of assets (JS-, CSS-files)
         $this->InitAssetFiles();
     }
     $oSkin = E::ModuleSkin()->GetSkin($this->sViewSkin);
     if (!$oSkin || !$oSkin->GetCompatible() || $oSkin->SkinCompatible('1.1', '<')) {
         // Для старых скинов загружаем объект доступа к конфигурации
         $this->Assign('oConfig', Config::getInstance());
     }
     E::ModuleHook()->Run('render_init_done', array('bLocal' => $this->bLocal));
     $this->bInitRender = true;
     self::$_preprocessTime += microtime(true) - $nTimer;
 }
Esempio n. 28
0
 public function EventAjaxUserAdd()
 {
     E::ModuleViewer()->SetResponseAjax('json');
     if ($this->IsPost()) {
         Config::Set('module.user.captcha_use_registration', false);
         $oUser = E::GetEntity('ModuleUser_EntityUser');
         $oUser->_setValidateScenario('registration');
         // * Заполняем поля (данные)
         $oUser->setLogin($this->GetPost('user_login'));
         $oUser->setMail($this->GetPost('user_mail'));
         $oUser->setPassword($this->GetPost('user_password'));
         $oUser->setPasswordConfirm($this->GetPost('user_password'));
         $oUser->setDateRegister(F::Now());
         $oUser->setIpRegister('');
         $oUser->setActivate(1);
         if ($oUser->_Validate()) {
             E::ModuleHook()->Run('registration_validate_after', array('oUser' => $oUser));
             $oUser->setPassword($oUser->getPassword(), true);
             if (E::ModuleUser()->Add($oUser)) {
                 E::ModuleHook()->Run('registration_after', array('oUser' => $oUser));
                 // Подписываем пользователя на дефолтные события в ленте активности
                 E::ModuleStream()->SwitchUserEventDefaultTypes($oUser->getId());
                 if ($this->IsPost('user_setadmin')) {
                     E::ModuleAdmin()->SetAdministrator($oUser->GetId());
                 }
             }
             E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('registration_ok'));
         } else {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('error'));
             E::ModuleViewer()->AssignAjax('aErrors', $oUser->_getValidateErrors());
         }
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'));
     }
 }
Esempio n. 29
0
 /**
  * Вывод интересных на главную
  *
  */
 protected function EventIndex()
 {
     E::ModuleViewer()->SetHtmlRssAlternate(R::GetPath('rss') . 'index/', Config::Get('view.name'));
     /**
      * Меню
      */
     $this->sTopicFilter = $this->sMenuSubItemSelect = 'good';
     /**
      * Передан ли номер страницы
      */
     $iPage = $this->GetEventMatch(2) ? $this->GetEventMatch(2) : 1;
     /**
      * Устанавливаем основной URL для поисковиков
      */
     if ($iPage == 1) {
         E::ModuleViewer()->SetHtmlCanonical(trim(Config::Get('path.root.url'), '/') . '/');
     }
     /**
      * Получаем список топиков
      */
     $aResult = E::ModuleTopic()->GetTopicsGood($iPage, Config::Get('module.topic.per_page'));
     $aTopics = $aResult['collection'];
     /**
      * Вызов хуков
      */
     E::ModuleHook()->Run('topics_list_show', array('aTopics' => $aTopics));
     /**
      * Формируем постраничность
      */
     $aPaging = E::ModuleViewer()->MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'), Config::Get('pagination.pages.count'), R::GetPath('index'));
     /**
      * Загружаем переменные в шаблон
      */
     E::ModuleViewer()->Assign('aTopics', $aTopics);
     E::ModuleViewer()->Assign('aPaging', $aPaging);
     /**
      * Устанавливаем шаблон вывода
      */
     $this->SetTemplateAction('index');
 }
Esempio n. 30
0
 /**
  * Запускает на выполнение экшен
  * Может запускаться рекурсивно если в одном экшене стоит переадресация на другой
  *
  */
 public function ExecAction()
 {
     $this->DefineActionClass();
     // Hook before action
     E::ModuleHook()->Run('action_before');
     $sActionClass = $this->DefineActionClass();
     // * Определяем наличие делегата экшена
     if ($aChain = E::ModulePlugin()->GetDelegationChain('action', $sActionClass)) {
         if (!empty($aChain)) {
             $sActionClass = $aChain[0];
         }
     }
     static::$sActionClass = $sActionClass;
     if (!class_exists($sActionClass)) {
         throw new Exception('Cannot load class "' . $sActionClass . '"');
     }
     $this->oAction = new $sActionClass(static::$sAction);
     // * Инициализируем экшен
     $sInitResult = $this->oAction->Init();
     if ($sInitResult === 'next') {
         $this->ExecAction();
     } else {
         // Если инициализация экшена прошла успешно и метод провеки доступа вернул
         // положительный результат то запускаем запрошенный ивент на исполнение.
         if ($sInitResult !== false && $this->oAction->Access(self::GetActionEvent()) !== false) {
             $res = $this->oAction->ExecEvent();
             static::$sActionEventName = $this->oAction->GetCurrentEventName();
             $this->oAction->EventShutdown();
             if ($res === 'next') {
                 $this->ExecAction();
             }
         } else {
             if (!F::AjaxRequest()) {
                 static::$sAction = $this->aConfigRoute['config']['action_not_found'];
                 static::$sActionEvent = '404';
                 $this->ExecAction();
             }
         }
     }
     // Hook after action
     E::ModuleHook()->Run('action_after');
 }