public function getComments($iTopicId, $iPageNum, $iPageSize) { $sCacheKey = 'api_topic_' . $iTopicId; $oTopic = E::ModuleCache()->GetTmp($sCacheKey); if (!$oTopic) { $oTopic = E::ModuleTopic()->GetTopicById($iTopicId); } if (!$oTopic || !($oBlog = $oTopic->getBlog())) { return array(); } $oBlogType = $oBlog->GetBlogType(); if ($oBlogType) { $bCloseBlog = !$oBlog->CanReadBy(E::User()); } else { // if blog type not defined then it' open blog $bCloseBlog = false; } if ($bCloseBlog) { return array(); } $aComments = E::ModuleComment()->GetCommentsByTargetId($oTopic, 'topic', $iPageNum, $iPageSize); $aResult = array('total' => $oTopic->getCountComment(), 'list' => array()); foreach ($aComments['comments'] as $oComment) { $aResult['list'][] = $oComment->getApiData(); } return $aResult; }
/** * @param int $iBlogId * @param int $iPageNum * @param int $iPageSize * * @return array */ public function getPosts($iBlogId, $iPageNum, $iPageSize) { $sCacheKey = 'api_blog_' . $iBlogId; $oBlog = E::ModuleCache()->GetTmp($sCacheKey); if (!$oBlog) { $oBlog = E::ModuleBlog()->GetBlogById($iBlogId); } $oBlogType = $oBlog->GetBlogType(); if ($oBlogType) { $bCloseBlog = !$oBlog->CanReadBy(E::User()); } else { // if blog type not defined then it' open blog $bCloseBlog = false; } if ($bCloseBlog) { return array(); } $aTopics = E::ModuleTopic()->GetTopicsByBlog($oBlog, $iPageNum, $iPageSize, 'newall', null); $aResult = array('total' => $aTopics['count'], 'list' => array()); /** @var PluginAltoApi_ModuleApiPosts_EntityPost $oTopic */ foreach ($aTopics['collection'] as $oTopic) { $aResult['list'][] = $oTopic->getApiData(); } return $aResult; }
public function Init() { E::ModuleViewer()->SetResponseAjax('json'); if (!E::IsAdmin()) { Router::Location('error/404/'); } $this->oUserCurrent = E::User(); }
public function getLink() { $oUser = $this->getProp('user'); if (!$oUser) { $oUser = E::User(); } if ($oUser) { return $oUser->getProfileUrl() . 'favourites/topics/tag/' . F::UrlEncode($this->getText()) . '/'; } }
/** * Adds new topic * * @param $oTopic * * @return bool|ModuleTopic_EntityTopic */ protected function _addTopic($oTopic) { if (!E::IsAdminOrModerator()) { $xUserRatingOut = C::Val('plugin.sandbox.user_rating_out', false); if ($xUserRatingOut === false || E::User()->getUserRating() < $xUserRatingOut) { $oTopic->setTopicStatus(TOPIC_STATUS_SANDBOX); } } return parent::_addTopic($oTopic); }
/** * Компилирует тему * * @param array $aParams Передаваемые параметры * @return bool */ public function CompileTheme($aParams, $bDownload = FALSE) { if (!E::User()) { return FALSE; } $sCompiledStyle = E::ModuleLess()->CompileFile(array(C::Get('path.skins.dir') . 'experience-simple/themes/custom/less/theme.less' => C::Get('path.root.web')), __DIR__ . '/../../../cache/', C::Get('path.skins.dir') . 'experience-simple/themes/custom/css/theme.custom.css.map', $aParams, $bDownload); if ($sCompiledStyle) { if (!$bDownload || E::IsAdmin()) { F::File_PutContents(C::Get('path.skins.dir') . 'experience-simple/themes/custom/css/theme.custom.css', $sCompiledStyle); } else { $sPath = C::Get('plugin.estheme.path_for_download') . E::UserId() . '/theme.custom.css'; F::File_PutContents($sPath, $sCompiledStyle); } } }
/** * Добавление записи на стену */ public function EventWallAdd() { // * Устанавливаем формат Ajax ответа E::ModuleViewer()->SetResponseAjax('json'); // * Пользователь авторизован? if (!E::IsUser()) { return parent::EventNotFound(); } $xResult = E::Module('PluginMagicrules\\Rule')->CheckRuleAction('create_wall', E::User()); if ($xResult === true) { return parent::EventWallAdd(); } else { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('plugin.magicrules.check_rule_action_error'), E::ModuleLang()->Get('attention')); return Router::Action('error'); } }
public function EventEsTheme() { if (!E::User() || !C::Get('plugin.estheme.use_client')) { return R::Action('error'); } $aProcessData = $this->PluginEstheme_Estheme_GetProcessData(); if (getRequest('submit_estheme')) { $sCSSDownloadPath = F::File_Dir2Url(C::Get('plugin.estheme.path_for_download') . E::UserId() . '/theme.custom.css'); $aCompiledData = $this->_processConfig($aProcessData, TRUE); $this->PluginEstheme_Estheme_CompileTheme($aCompiledData, TRUE); } else { $sCSSDownloadPath = FALSE; $this->_processConfig($aProcessData, FALSE); } E::ModuleViewer()->Assign('sCSSDownloadPath', $sCSSDownloadPath); }
public function CodeHook() { // Если пользоватль авторизован и у него не заполнено поле о себе, то if (E::IsUser() && trim(E::User()->getProfileAbout()) == '') { // Получим меню пользователя /** @var ModuleMenu_EntityMenu $oMenu */ $oMenu = E::ModuleMenu()->GetMenu('user'); // Проверим, может в этой теме меню не объектное if ($oMenu && !$oMenu->GetItemById('plugin_menutest_my_menu')) { // Создадим элемент меню $oMenuItem = E::ModuleMenu()->CreateMenuItem('plugin_menutest_my_menu', array('text' => '{{plugin.menutest.empty_about}}', 'link' => E::User()->getProfileUrl() . 'settings/', 'display' => array('not_event' => array('settings')), 'options' => array('class' => 'btn right create'))); // Добавим в меню $oMenu->AddItem('first', $oMenuItem); // Сохраним E::ModuleMenu()->SaveMenu($oMenu); } } }
/** * @return string|void */ protected function EventVoteUser() { // * Пользователь авторизован? if (!E::IsUser()) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error')); return; } $xResult = E::Module('PluginMagicrules\\Rule')->CheckRuleAction('vote_user', E::User(), array('vote_value' => (int) $this->getPost('value'))); if (true === $xResult) { return parent::EventVoteUser(); } else { if (is_string($xResult)) { E::ModuleMessage()->AddErrorSingle($xResult, E::ModuleLang()->Get('attention')); return Router::Action('error'); } else { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('plugin.magicrules.check_rule_action_error'), E::ModuleLang()->Get('attention')); return Router::Action('error'); } } }
/** * Метод, который вызывается после создания меню */ public function CodeHook() { // Получим результат выполнения метода-источника хука /** @var ModuleMenu_EntityMenu $oMenu */ $oMenu = $this->GetSourceResult(); // Убеждаемся, что было создано нужное нам меню - меню пользователя if ($oMenu && $oMenu->getId() == 'user') { // Если пользователь авторизован и у него не заполнено поле о себе, то if (E::IsUser() && trim(E::User()->getProfileAbout()) == '') { // Проверим, есть ли в меню нужный элемент if (!$oMenu->GetItemById('plugin.menutest.my_menu')) { // Создадим элемент меню $oMenuItem = E::ModuleMenu()->CreateMenuItem('plugin.menutest.my_menu', array('text' => '{{plugin.menutest.empty_about}}', 'link' => E::User()->getProfileUrl() . 'settings/', 'display' => array('not_event' => array('settings')), 'options' => array('class' => 'btn right create'))); // Добавим в меню $oMenu->AddItem($oMenuItem, 'first'); // Сохраним E::ModuleMenu()->SaveMenu($oMenu); } } } }
/** * Удаление картинки */ public function EventRemoveImage() { // * Устанавливаем формат Ajax ответа E::ModuleViewer()->SetResponseAjax('json'); // Проверяем, целевой объект и права на его редактирование if (!($oTarget = E::ModuleUploader()->CheckAccessAndGetTarget($sTargetType = F::GetRequest('target', FALSE), $sTargetId = F::GetRequest('target_id', FALSE)))) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('not_access'), E::ModuleLang()->Get('error')); return; } $bResult = E::ModuleHook()->Run('uploader_remove_image_before', array('sTargetId' => $sTargetId, 'sTarget' => $sTargetType, 'oTarget' => $oTarget)); if ($bResult !== false) { // * Удаляем картинку E::ModuleUploader()->DeleteImage($sTargetType, $sTargetId, E::User()); // Запускаем хук на действия после удаления картинки E::ModuleHook()->Run('uploader_remove_image_after', array('sTargetId' => $sTargetId, 'sTarget' => $sTargetType, 'oTarget' => $oTarget)); } // * Возвращает сообщение E::ModuleViewer()->AssignAjax('sTitleUpload', E::ModuleLang()->Get('uploader_upload_success')); }
/** * Загрузка страницы картинок */ protected function EventImageManagerLoadImages() { E::ModuleSecurity()->ValidateSendForm(); // Менеджер изображений может запускаться в том числе и из админки // Если передано название скина админки, то используем его, если же // нет, то ту тему, которая установлена для сайта if (($sAdminTheme = F::GetRequest('admin')) && E::IsAdmin()) { C::Set('view.skin', $sAdminTheme); } // Получим идентификатор пользователя, изображения которого нужно загрузить $iUserId = (int) F::GetRequest('profile', FALSE); if ($iUserId && E::ModuleUser()->GetUserById($iUserId)) { C::Set('menu.data.profile_images.uid', $iUserId); } else { // Только пользователь может смотреть своё дерево изображений if (!E::IsUser()) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error')); return; } $iUserId = E::UserId(); } $sCategory = F::GetRequestStr('category', FALSE); $iPage = intval(F::GetRequestStr('page', '1')); $sTopicId = F::GetRequestStr('topic_id', FALSE); $sTargetType = F::GetRequestStr('target'); if (!$sCategory) { return; } $aTplVariables = array('sTargetType' => $sTargetType, 'sTargetId' => $sTopicId); // Страница загрузки картинки с компьютера if ($sCategory == 'insert-from-pc') { $sImages = E::ModuleViewer()->Fetch('modals/insert_img/inject.pc.tpl', $aTplVariables); E::ModuleViewer()->AssignAjax('images', $sImages); return; } // Страница загрузки из интернета if ($sCategory == 'insert-from-link') { $sImages = E::ModuleViewer()->Fetch('modals/insert_img/inject.link.tpl', $aTplVariables); E::ModuleViewer()->AssignAjax('images', $sImages); return; } $sTemplateName = 'inject.images.tpl'; $aResources = array('collection' => array()); $iPagesCount = 0; if ($sCategory == 'user') { //ок // * Аватар и фото пользователя $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('target_type' => array('profile_avatar', 'profile_photo'), 'user_id' => $iUserId), $iPage, Config::Get('module.topic.images_per_page')); $sTemplateName = 'inject.images.user.tpl'; $iPagesCount = 0; } elseif ($sCategory == '_topic') { // * Конкретный топик $oTopic = E::ModuleTopic()->GetTopicById($sTopicId); if ($oTopic && ($oTopic->isPublished() || $oTopic->getUserId() == E::UserId()) && E::ModuleACL()->IsAllowShowBlog($oTopic->getBlog(), E::User())) { $aResourcesId = E::ModuleMresource()->GetCurrentTopicResourcesId($iUserId, $sTopicId); if ($aResourcesId) { $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'mresource_id' => $aResourcesId), $iPage, Config::Get('module.topic.images_per_page')); $aResources['count'] = count($aResourcesId); $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.images_per_page')); $aTplVariables['oTopic'] = $oTopic; } } $sTemplateName = 'inject.images.tpl'; } elseif ($sCategory == 'talk') { // * Письмо /** @var ModuleTalk_EntityTalk $oTopic */ $oTopic = E::ModuleTalk()->GetTalkById($sTopicId); if ($oTopic && E::ModuleTalk()->GetTalkUser($sTopicId, $iUserId)) { $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'target_type' => 'talk', 'target_id' => $sTopicId), $iPage, Config::Get('module.topic.images_per_page')); $aResources['count'] = E::ModuleMresource()->GetMresourcesCountByTargetIdAndUserId('talk', $sTopicId, $iUserId); $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.images_per_page')); $aTplVariables['oTopic'] = $oTopic; } $sTemplateName = 'inject.images.tpl'; } elseif ($sCategory == 'comments') { // * Комментарии $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'target_type' => array('talk_comment', 'topic_comment')), $iPage, Config::Get('module.topic.images_per_page')); $aResources['count'] = E::ModuleMresource()->GetMresourcesCountByTargetAndUserId(array('talk_comment', 'topic_comment'), $iUserId); $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.images_per_page')); $sTemplateName = 'inject.images.tpl'; } elseif ($sCategory == 'current') { //ок // * Картинки текущего топика (текст, фотосет, одиночные картинки) $aResourcesId = E::ModuleMresource()->GetCurrentTopicResourcesId($iUserId, $sTopicId); if ($aResourcesId) { $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'mresource_id' => $aResourcesId), $iPage, Config::Get('module.topic.images_per_page')); $aResources['count'] = count($aResourcesId); $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.images_per_page')); } $sTemplateName = 'inject.images.tpl'; } elseif ($sCategory == 'blog_avatar') { // ок // * Аватары созданных блогов $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('target_type' => 'blog_avatar', 'user_id' => $iUserId), $iPage, Config::Get('module.topic.group_images_per_page')); $aResources['count'] = E::ModuleMresource()->GetMresourcesCountByTargetAndUserId('blog_avatar', $iUserId); // Получим блоги $aBlogsId = array(); foreach ($aResources['collection'] as $oResource) { $aBlogsId[] = $oResource->getTargetId(); } if ($aBlogsId) { $aBlogs = E::ModuleBlog()->GetBlogsAdditionalData($aBlogsId); $aTplVariables['aBlogs'] = $aBlogs; } $sTemplateName = 'inject.images.blog.tpl'; $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.group_images_per_page')); } elseif ($sCategory == 'topics') { // ок // * Страница топиков $aTopicsData = E::ModuleMresource()->GetTopicsPage($iUserId, $iPage, Config::Get('module.topic.group_images_per_page')); $aTplVariables['aTopics'] = $aTopicsData['collection']; $sTemplateName = 'inject.images.topic.tpl'; $iPagesCount = ceil($aTopicsData['count'] / Config::Get('module.topic.group_images_per_page')); $aResources = array('collection' => array()); } elseif (in_array($sCategory, E::ModuleTopic()->GetTopicTypes())) { // ок // * Страница топиков $aTopicsData = E::ModuleMresource()->GetTopicsPageByType($iUserId, $sCategory, $iPage, Config::Get('module.topic.group_images_per_page')); $aTplVariables['aTopics'] = $aTopicsData['collection']; $sTemplateName = 'inject.images.topic.tpl'; $iPagesCount = ceil($aTopicsData['count'] / Config::Get('module.topic.group_images_per_page')); $aResources = array('collection' => array()); } elseif ($sCategory == 'talks') { // ок // * Страница писем $aTalksData = E::ModuleMresource()->GetTalksPage($iUserId, $iPage, Config::Get('module.topic.group_images_per_page')); $aTplVariables['aTalks'] = $aTalksData['collection']; $sTemplateName = 'inject.images.talk.tpl'; $iPagesCount = ceil($aTalksData['count'] / Config::Get('module.topic.group_images_per_page')); $aResources = array('collection' => array()); } else { // * Прочие изображения $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('target_type' => $sCategory, 'user_id' => $iUserId), $iPage, Config::Get('module.topic.images_per_page')); $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.images_per_page')); } $aTplVariables['aResources'] = $aResources['collection']; $sPath = F::GetRequest('profile', FALSE) ? 'actions/profile/created_photos/' : 'modals/insert_img/'; $sImages = E::ModuleViewer()->GetLocalViewer()->Fetch($sPath . $sTemplateName, $aTplVariables); E::ModuleViewer()->AssignAjax('images', $sImages); E::ModuleViewer()->AssignAjax('category', $sCategory); E::ModuleViewer()->AssignAjax('page', $iPage); E::ModuleViewer()->AssignAjax('pages', $iPagesCount); }
/** * Проверяет доступность того или иного целевого объекта, переопределяется * плагинами. По умолчанию всё грузить запрещено. * Если всё нормально и пользователю разрешено сюда загружать картинки, * то метод возвращает целевой объект, иначе значение FALSE. * * @param string $sTarget * @param int $iTargetId * * @return bool */ public function CheckAccessAndGetTarget($sTarget, $iTargetId = null) { // Проверяем право пользователя на прикрепление картинок к топику if (mb_strpos($sTarget, 'single-image-uploader') === 0 || $sTarget == 'photoset') { // Проверям, авторизован ли пользователь if (!E::IsUser()) { return FALSE; } // Топик редактируется if ($oTopic = E::ModuleTopic()->GetTopicById($iTargetId)) { if (!E::ModuleACL()->IsAllowEditTopic($oTopic, E::User())) { return FALSE; } return $oTopic; } return TRUE; } // Загружать аватарки можно только в свой профиль if ($sTarget == 'profile_avatar') { if ($iTargetId && E::IsUser() && $iTargetId == E::UserId()) { return E::User(); } return FALSE; } // Загружать аватарки можно только в свой профиль if ($sTarget == 'profile_photo') { if ($iTargetId && E::IsUser() && $iTargetId == E::UserId()) { return E::User(); } return FALSE; } if ($sTarget == 'blog_avatar') { /** @var ModuleBlog_EntityBlog $oBlog */ $oBlog = E::ModuleBlog()->GetBlogById($iTargetId); if (!E::IsUser()) { return false; } if (!$oBlog) { // Блог еще не создан return E::ModuleACL()->CanCreateBlog(E::User()) || E::IsAdminOrModerator(); } if ($oBlog && (E::ModuleACL()->CheckBlogEditBlog($oBlog, E::User()) || E::IsAdminOrModerator())) { return $oBlog; } return ''; } if ($sTarget == 'topic') { if (!E::IsUser()) { return false; } /** @var ModuleTopic_EntityTopic $oTopic */ $oTopic = E::ModuleTopic()->GetTopicById($iTargetId); if (!$oTopic) { // Топик еще не создан return TRUE; } if ($oTopic && (E::ModuleACL()->IsAllowEditTopic($oTopic, E::User()) || E::IsAdminOrModerator())) { return $oTopic; } return ''; } if ($sTarget == 'topic_comment') { if (!E::IsUser()) { return false; } /** @var ModuleComment_EntityComment $oComment */ $oComment = E::ModuleComment()->GetCommentById($iTargetId); if (!$oComment) { // Комментарий еще не создан return TRUE; } if ($oComment && (E::ModuleACL()->CanPostComment(E::User(), $oComment->getTarget()) && E::ModuleAcl()->CanPostCommentTime(E::User()) || E::IsAdminOrModerator())) { return $oComment; } return ''; } if ($sTarget == 'talk_comment') { if (!E::IsUser()) { return false; } /** @var ModuleComment_EntityComment $oComment */ $oComment = E::ModuleComment()->GetCommentById($iTargetId); if (!$oComment) { // Комментарий еще не создан return TRUE; } if ($oComment && (E::ModuleAcl()->CanPostTalkCommentTime(E::User()) || E::IsAdminOrModerator())) { return $oComment; } return ''; } if ($sTarget == 'talk') { if (!E::IsUser()) { return false; } /** @var ModuleComment_EntityComment $oTalk */ $oTalk = E::ModuleTalk()->GetTalkById($iTargetId); if (!$oTalk) { // Комментарий еще не создан return TRUE; } if ($oTalk && (E::ModuleAcl()->CanSendTalkTime(E::User()) || E::IsAdminOrModerator())) { return $oTalk; } return ''; } return FALSE; }
/** * Return filter for blog list by name and params * * @param string $sFilterName * @param array $aParams * * @return array */ public function GetNamedFilter($sFilterName, $aParams = array()) { $aFilter = $this->GetBlogsFilter(); $aFilter['include_type'] = $this->GetAllowBlogTypes(E::User(), 'list', true); switch ($sFilterName) { case 'top': $aFilter['order'] = array('blog_rating' => 'desc'); break; default: break; } if (!empty($aParams['exclude_type'])) { $aFilter['exclude_type'] = $aParams['exclude_type']; } if (!empty($aParams['owner_id'])) { $aFilter['user_owner_id'] = $aParams['owner_id']; } return $aFilter; }
/** * Возвращает html-код фотосета * * @param $aData * @return bool */ public function SnippetPhotoset($aData) { // Попытаемся определить откуда вызывается сниппет фотосета // поскольку нужно точно определить целевой объект и его ид // Редактируется топик. // Получим его ид. и по нему поднимем необходимый фотосет $aAdminMatches = array(); if (preg_match('~content\\/edit\\/(\\d+)\\/~', R::GetControllerPath(), $aMatches) || preg_match('~admin\\/content-pages\\/edit\\/(\\d+)\\/~', R::GetControllerPath(), $aAdminMatches)) { // Найдем топик, из которого будем брать фотосет $iTopicId = (int) isset($aData['params']['topic']) ? $aData['params']['topic'] : ($aAdminMatches ? FALSE : $aMatches[1]); // Странно, но топик не нашли - завернём сниппет if (!($oTopic = E::ModuleTopic()->GetTopicById($iTopicId))) { return FALSE; } // Проверим, можно ли пользователю читать этот топик, а то вдруг // он запросил картинки из топика закрытого блога - а так нельзя if (!E::ModuleACL()->IsAllowShowBlog($oTopic->getBlog(), E::User())) { return FALSE; } // Попытаемся найти фотосет /** @var ModuleMresource_EntityMresource[] $aPhotos */ if (!(($aPhotos = E::ModuleMresource()->GetMresourcesRelByTarget('photoset', $oTopic->getId())) && is_array($aPhotos) && count($aPhotos) > 0)) { return FALSE; } // Фотосет нашли, теперь из него нужно выбрать только те фото, // которые выбрал пользователь в параметрах from и to $iFrom = isset($aData['params']['from']) ? $aData['params']['from'] : 0; $iFrom = (int) str_replace(array('last', 'first'), array(count($aPhotos), 0), $iFrom); // Пользователи считают картинки с первой, а не с нулевой if ($iFrom) { $iFrom -= 1; } // Если указана длина, то правый предел игнорируем if ($iCount = (int) isset($aData['params']['count']) ? $aData['params']['count'] : FALSE) { $iTo = $iFrom + $iCount - 1; } else { $iTo = isset($aData['params']['to']) ? $aData['params']['to'] : count($aPhotos); $iTo = (int) str_replace(array('last', 'first'), array(count($aPhotos), 0), $iTo); if ($iTo) { $iTo -= 1; } } // Пользователь ошибочно указал диапазон. выдумывать ничего не будем, // просто не выведем фотосет if ($iTo - $iFrom < 0) { return FALSE; } // Сбросим ключи набора фото, так лучше считать диапазон $aPhotos = array_values($aPhotos); foreach ($aPhotos as $k => $v) { if ($k < $iFrom || $k > $iTo) { unset($aPhotos[$k]); } } if (!$aPhotos) { return FALSE; } $sPosition = $iTopicId = (int) isset($aData['params']['position']) ? $aData['params']['position'] : 'center'; if (!in_array($sPosition, array('left', 'right'))) { $sPosition = 'center'; } // Получим html-код сниппета $aVars = array('oTopic' => $oTopic, 'aPhotos' => $aPhotos, 'sPosition' => $sPosition, 'sPhotosetHash' => md5(serialize($aData['params']))); $aData['result'] = trim(E::ModuleViewer()->Fetch('tpls/snippets/snippet.photoset.tpl', $aVars)); return $aData['result']; } return FALSE; }
/** * Сколько секунд осталось до конца редактирования * * @param bool $bFormat * * @return int */ public function getEditTime($bFormat = false) { if (Config::Get('module.comment.edit.enable') && ($oUser = E::User()) && $oUser->getId() == $this->getUserId()) { $sDateTime = F::DateTimeAdd($this->GetCommentDate(), Config::Get('module.comment.edit.enable')); $sNow = date('Y-m-d H:i:s'); if ($sNow < $sDateTime) { $nRest = F::DateDiffSeconds($sNow, $sDateTime); if (!$bFormat) { return $nRest; } if ($nRest < 60) { return sprintf('%2d sec', $nRest); } $nS = $nRest % 60; $nM = ($nRest - $nS) / 60; if ($nM < 60) { return sprintf('%2d:%02d', $nM, $nS); } $nRest = $nM; $nM = $nRest % 60; $nH = ($nRest - $nM) / 60; if ($nH < 24) { return sprintf('%2d:%02d:%02d', $nH, $nM, $nS); } $nRest = $nH; $nH = $nRest % 24; $nD = ($nRest - $nH) / 24; return sprintf('%3d, %2d:%02d:%02d', $nD, $nH, $nM, $nS); } } return 0; }
/** * Выполняется при завершении работы экшена * */ public function EventShutdown() { $iUserId = E::UserId(); // Get stats of various user publications topics, comments, images, etc. and stats of favourites $aProfileStats = E::ModuleUser()->GetUserProfileStats($iUserId); // Получим информацию об изображениях пользователя /** @var ModuleMresource_EntityMresourceCategory[] $aUserImagesInfo */ $aUserImagesInfo = E::ModuleMresource()->GetAllImageCategoriesByUserId($iUserId); E::ModuleViewer()->Assign('oUserProfile', E::User()); E::ModuleViewer()->Assign('aProfileStats', $aProfileStats); E::ModuleViewer()->Assign('aUserImagesInfo', $aUserImagesInfo); // Old style skin compatibility E::ModuleViewer()->Assign('iCountTopicUser', $aProfileStats['count_topics']); E::ModuleViewer()->Assign('iCountCommentUser', $aProfileStats['count_comments']); E::ModuleViewer()->Assign('iCountTopicFavourite', $aProfileStats['favourite_topics']); E::ModuleViewer()->Assign('iCountCommentFavourite', $aProfileStats['favourite_comments']); E::ModuleViewer()->Assign('iCountNoteUser', $aProfileStats['count_usernotes']); E::ModuleViewer()->Assign('iCountWallUser', $aProfileStats['count_wallrecords']); E::ModuleViewer()->Assign('iPhotoCount', $aProfileStats['count_images']); E::ModuleViewer()->Assign('iCountCreated', $aProfileStats['count_created']); E::ModuleViewer()->Assign('iCountFavourite', $aProfileStats['count_favourites']); E::ModuleViewer()->Assign('iCountFriendsUser', $aProfileStats['count_friends']); // * Загружаем в шаблон необходимые переменные E::ModuleViewer()->Assign('sMenuItemSelect', $this->sMenuItemSelect); E::ModuleViewer()->Assign('sMenuSubItemSelect', $this->sMenuSubItemSelect); E::ModuleHook()->Run('action_shutdown_settings'); }
/** * Возвращает текущего авторизованного пользователя * @see ModuleUser::GetUserCurrent * * @return ModuleUser_EntityUser */ public static function CurUsr() { return E::User(); }
/** * Вызывается по строке "count_track" * @param string $sIcon * @return bool */ public function CountTrack($sIcon = '') { if (!E::IsUser()) { return ''; } $sKeyString = 'menu_count_track_' . E::User()->getId() . '_' . $sIcon; if (FALSE === ($xData = E::ModuleCache()->GetTmp($sKeyString))) { $sCount = E::ModuleUserfeed()->GetCountTrackNew(E::User()->getId()); $xData = $sIcon . ($sCount ? '+' . $sCount : '0'); E::ModuleCache()->SetTmp($xData, $sKeyString); } return $xData; }
/** * Shutdown and output result */ public function EventShutdown() { parent::EventShutdown(); if ($this->bRestApi) { if (E::IsUser()) { $this->aResponseData['auth_token'] = E::User()->getAuthToken(); } E::ModuleViewer()->AssignAjax('error', $this->iResponseError); E::ModuleViewer()->AssignAjax('message', $this->sResponseMessage); E::ModuleViewer()->AssignAjax('data', $this->aResponseData); E::ModuleViewer()->SetResponseHeader('Content-type', 'application/json; charset=utf-8'); $sOutput = E::ModuleViewer()->getAjaxVars(); E::ModuleViewer()->Flush($sOutput); } }
* Главное меню сайта * Настройки берутся из главного конфига меню common/config/menu.php */ /** * Вход и регистрация */ $config['menu']['data']['login'] = array('list' => array('login' => array('options' => array('link_class' => 'js-modal-auth-login')), 'registration' => array('options' => array('class' => 'hidden-sm', 'link_class' => 'js-modal-auth-registration')))); if (E::IsUser()) { /** * Меню пользователя */ $config['menu']['data']['user'] = array('list' => array('talk' => array('text' => array('<span class="glyphicon glyphicon-envelope"></span> +', 'new_talk' => array()), 'options' => array('link_class' => 'new-messages')), 'userbar' => array('text' => array('user_name' => array(), '<b class="caret"></b>'), 'options' => array('class' => 'dropdown nav-userbar', 'link_class' => 'dropdown-toggle username', 'image_url' => array('user_avatar_url' => array('32')), 'image_title' => array('user_name'), 'image_class' => 'avatar', 'link_data' => array('toggle' => 'dropdown', 'target' => '#'))))); /** * Подменю пользователя */ $config['menu']['data']['userbar'] = array('class' => 'dropdown-menu', 'list' => array('user' => array('link' => E::User()->getProfileUrl()), 'talk' => array('text' => array('{{user_privat_messages}}', '<span class="new-messages">', 'new_talk_string' => array(), '</span>'), 'options' => array('link_id' => 'new_messages', 'link_title' => array('new_talk' => array()))), 'wall' => array('link' => E::User()->getProfileUrl() . 'wall/'), 'publication' => array('link' => E::User()->getProfileUrl() . 'created/topics/'), 'favourites' => array('link' => E::User()->getProfileUrl() . 'favourites/topics/'), 'userbar_item' => '', 'logout' => array('link' => Router::GetPath('login') . 'exit/?security_key=' . E::Security_GetSecurityKey()))); } /** * Меню топиков */ $config['menu']['data']['topics'] = array('list' => array('good' => array('options' => array('class' => 'bordered')), 'new' => array('text' => array('{{blog_menu_all_new}} + ', 'new_topics_count' => array()), 'options' => array('class' => 'bordered', 'link_title' => '{{blog_menu_top_period_24h}}')), 'newall' => array('options' => array('class' => 'bordered', 'link_title' => '{{blog_menu_top_period_24h}}')), 'feed' => array('options' => array('class' => 'bordered')), 'empty' => array('text' => false, 'options' => array('class' => 'divider')), 'discussed' => array('text' => array('{{blog_menu_all_discussed}}', '<b class="caret"></b>'), 'submenu' => 'discussed', 'options' => array('class' => 'dropdown', 'link_class' => 'dropdown-toggle', 'link_data' => array('toggle' => 'dropdown'))))); if (C::Get('rating.enabled')) { $config['menu']['data']['topics']['list']['top'] = array('text' => array('{{blog_menu_all_top}}', '<b class="caret"></b>'), 'submenu' => 'top', 'options' => array('class' => 'dropdown', 'link_class' => 'dropdown-toggle', 'link_data' => array('toggle' => 'dropdown'))); } /** * Подменю обсуждаемых */ $config['menu']['data']['discussed'] = array('class' => 'dropdown-menu'); if (C::Get('rating.enabled')) { /** * Подменю топовых
/** * Выполняется при завершении работы экшена */ public function EventShutdown() { if (!$this->oUserProfile) { return; } $iProfileUserId = $this->oUserProfile->getId(); // Get stats of various user publications topics, comments, images, etc. and stats of favourites $aProfileStats = E::ModuleUser()->GetUserProfileStats($iProfileUserId); // Получим информацию об изображениях пользователя /** @var ModuleMresource_EntityMresourceCategory[] $aUserImagesInfo */ //$aUserImagesInfo = E::ModuleMresource()->GetAllImageCategoriesByUserId($iProfileUserId); // * Загружаем в шаблон необходимые переменные E::ModuleViewer()->Assign('oUserProfile', $this->oUserProfile); E::ModuleViewer()->Assign('aProfileStats', $aProfileStats); // unused //E::ModuleViewer()->Assign('aUserImagesInfo', $aUserImagesInfo); // * Заметка текущего пользователя о юзере if (E::User()) { E::ModuleViewer()->Assign('oUserNote', $this->oUserProfile->getUserNote()); } E::ModuleViewer()->Assign('sMenuSubItemSelect', $this->sMenuSubItemSelect); E::ModuleViewer()->Assign('sMenuHeadItemSelect', $this->sMenuHeadItemSelect); E::ModuleViewer()->Assign('USER_FRIEND_NULL', ModuleUser::USER_FRIEND_NULL); E::ModuleViewer()->Assign('USER_FRIEND_OFFER', ModuleUser::USER_FRIEND_OFFER); E::ModuleViewer()->Assign('USER_FRIEND_ACCEPT', ModuleUser::USER_FRIEND_ACCEPT); E::ModuleViewer()->Assign('USER_FRIEND_REJECT', ModuleUser::USER_FRIEND_REJECT); E::ModuleViewer()->Assign('USER_FRIEND_DELETE', ModuleUser::USER_FRIEND_DELETE); // Old style skin compatibility E::ModuleViewer()->Assign('iCountTopicUser', $aProfileStats['count_topics']); E::ModuleViewer()->Assign('iCountCommentUser', $aProfileStats['count_comments']); E::ModuleViewer()->Assign('iCountTopicFavourite', $aProfileStats['favourite_topics']); E::ModuleViewer()->Assign('iCountCommentFavourite', $aProfileStats['favourite_comments']); E::ModuleViewer()->Assign('iCountNoteUser', $aProfileStats['count_usernotes']); E::ModuleViewer()->Assign('iCountWallUser', $aProfileStats['count_wallrecords']); E::ModuleViewer()->Assign('iPhotoCount', $aProfileStats['count_images']); E::ModuleViewer()->Assign('iCountCreated', $aProfileStats['count_created']); E::ModuleViewer()->Assign('iCountFavourite', $aProfileStats['count_favourites']); E::ModuleViewer()->Assign('iCountFriendsUser', $aProfileStats['count_friends']); }
/** * Обработка завершения работу экшена */ public function EventShutdown() { if (!E::User()) { return; } $iCountTalkFavourite = E::ModuleTalk()->GetCountTalksFavouriteByUserId($this->oUserCurrent->getId()); E::ModuleViewer()->Assign('iCountTalkFavourite', $iCountTalkFavourite); $iUserId = E::UserId(); // Get stats of various user publications topics, comments, images, etc. and stats of favourites $aProfileStats = E::ModuleUser()->GetUserProfileStats($iUserId); // Получим информацию об изображениях пользователя /** @var ModuleMresource_EntityMresourceCategory[] $aUserImagesInfo */ $aUserImagesInfo = E::ModuleMresource()->GetAllImageCategoriesByUserId($iUserId); E::ModuleViewer()->Assign('oUserProfile', E::User()); E::ModuleViewer()->Assign('aProfileStats', $aProfileStats); E::ModuleViewer()->Assign('aUserImagesInfo', $aUserImagesInfo); // Old style skin compatibility E::ModuleViewer()->Assign('iCountTopicUser', $aProfileStats['count_topics']); E::ModuleViewer()->Assign('iCountCommentUser', $aProfileStats['count_comments']); E::ModuleViewer()->Assign('iCountTopicFavourite', $aProfileStats['favourite_topics']); E::ModuleViewer()->Assign('iCountCommentFavourite', $aProfileStats['favourite_comments']); E::ModuleViewer()->Assign('iCountNoteUser', $aProfileStats['count_usernotes']); E::ModuleViewer()->Assign('iCountWallUser', $aProfileStats['count_wallrecords']); E::ModuleViewer()->Assign('iPhotoCount', $aProfileStats['count_images']); E::ModuleViewer()->Assign('iCountCreated', $aProfileStats['count_created']); E::ModuleViewer()->Assign('iCountFavourite', $aProfileStats['count_favourites']); E::ModuleViewer()->Assign('iCountFriendsUser', $aProfileStats['count_friends']); E::ModuleViewer()->Assign('sMenuSubItemSelect', $this->sMenuSubItemSelect); E::ModuleViewer()->Assign('sMenuSubItemSelect', $this->sMenuSubItemSelect); // * Передаем константы состояний участников разговора E::ModuleViewer()->Assign('TALK_USER_ACTIVE', ModuleTalk::TALK_USER_ACTIVE); E::ModuleViewer()->Assign('TALK_USER_DELETE_BY_SELF', ModuleTalk::TALK_USER_DELETE_BY_SELF); E::ModuleViewer()->Assign('TALK_USER_DELETE_BY_AUTHOR', ModuleTalk::TALK_USER_DELETE_BY_AUTHOR); }
/** * Получает топики пользователя с картинками * * @param int $iUserId * @param string $sType * @param int $iPage * @param int $iPerPage * * @return array */ public function GetTopicsPageByType($iUserId, $sType, $iPage, $iPerPage) { $iCount = 0; $aFilter = array('user_id' => $iUserId, 'mresource_type' => ModuleMresource::TYPE_IMAGE | ModuleMresource::TYPE_PHOTO | ModuleMresource::TYPE_PHOTO_PRIMARY, 'target_type' => array('photoset', 'topic')); if (E::IsUser() && E::User() !== $iUserId) { // Если текущий юзер не совпадает с запрашиваемым, то получаем список доступных блогов $aFilter['blogs_id'] = E::ModuleBlog()->GetAccessibleBlogsByUser(E::User()); // И топики должны быть опубликованы $aFilter['topic_publish'] = 1; } if (!E::IsUser()) { // Если юзер не авторизован, то считаем все доступные для индексации топики $aFilter['topic_index_ignore'] = 0; } $aFilter['topic_type'] = $sType; $aTopicInfo = $this->oMapper->GetTopicInfo($aFilter, $iCount, $iPage, $iPerPage); if ($aTopicInfo) { $aFilter = array('topic_id' => array_keys($aTopicInfo), 'topic_type' => $sType); // Результат в формате array('collection'=>..., 'count'=>...) $aResult = E::ModuleTopic()->GetTopicsByFilter($aFilter, 1, count($aTopicInfo)); if ($aResult) { /** @var ModuleTopic_EntityTopic $oTopic */ foreach ($aResult['collection'] as $sTopicId => $oTopic) { $oTopic->setImagesCount($aTopicInfo[$sTopicId]); $aResult['collection'][$sTopicId] = $oTopic; } $aResult['count'] = $iCount; // total number of topics with images } return $aResult; } return array('collection' => array(), 'count' => 0); }
/** * Получить новые комменты для владельца * * @param int $nTargetId ID владельца коммента * @param string $sTargetType Тип владельца комментария * @param int $nIdCommentLast ID последнего прочитанного комментария * * @return array('comments'=>array,'iMaxIdComment'=>int) */ public function GetCommentsNewByTargetId($nTargetId, $sTargetType, $nIdCommentLast) { $sCacheKey = "comment_target_{$nTargetId}_{$sTargetType}_{$nIdCommentLast}"; if (false === ($aCommentsId = E::ModuleCache()->Get($sCacheKey))) { $aCommentsId = $this->oMapper->GetCommentsIdNewByTargetId($nTargetId, $sTargetType, $nIdCommentLast); E::ModuleCache()->Set($aCommentsId, $sCacheKey, array("comment_new_{$sTargetType}_{$nTargetId}"), 'P1D'); } $aComments = array(); if (count($aCommentsId)) { $aComments = $this->GetCommentsAdditionalData($aCommentsId); } if (!$aComments) { return array('comments' => array(), 'iMaxIdComment' => $nIdCommentLast); } $iMaxIdComment = max($aCommentsId); $aVars = array('oUserCurrent' => E::ModuleUser()->GetUserCurrent(), 'bOneComment' => true); if ($sTargetType != 'topic') { $aVars['bNoCommentFavourites'] = true; } $aCommentsHtml = array(); $bAllowToComment = false; if ($sTargetType == 'talk') { $bAllowToComment = TRUE; } elseif ($oUserCurrent = E::User()) { $oComment = reset($aComments); if ($oComment->getTarget() && $oComment->getTarget()->getBlog()) { $iBlogId = $oComment->getTarget()->getBlog()->GetId(); $bAllowToComment = E::ModuleBlog()->GetBlogsAllowTo('comment', $oUserCurrent, $iBlogId, TRUE); } } $aVars['bAllowToComment'] = $bAllowToComment; foreach ($aComments as $oComment) { $aVars['oComment'] = $oComment; $sText = E::ModuleViewer()->Fetch($this->GetTemplateCommentByTarget($nTargetId, $sTargetType), $aVars); $aCommentsHtml[] = array('html' => $sText, 'obj' => $oComment); } return array('comments' => $aCommentsHtml, 'iMaxIdComment' => $iMaxIdComment); }
$config['data']['user'] = array('list' => array('userbar' => array('text' => array('user_name' => array(), 'count_messages' => array($sTemplate = '<span class="badge badge-danger badge-mail-counter">+{{count_messages}}</span>'), ' <span class="caret"></span>'), 'options' => array('class' => 'dropdown', 'link_class' => 'dropdown-toggle user-button', 'image_url' => array('user_avatar_url' => array('32x32crop')), 'image_title' => array('user_name'), 'image_class' => 'user', 'link_data' => array('toggle' => 'dropdown', 'role' => 'button', 'target' => '#'), 'data' => array('hidden-class' => 'btn'))), 'talk' => FALSE)); /** * Меню пользователя + experience */ $config['data']['toolbar_user'] = array('init' => array('fill' => array('list' => array('*'))), 'description' => '{{menu_user_description}}', 'list' => array('userbar' => array('text' => array('user_name' => array(), 'count_messages' => array('<span class="badge badge-danger badge-mail-counter">+{{count_messages}}</span>')), 'link' => E::User()->getProfileUrl(), 'options' => array('image_url' => array('user_avatar_url' => array('32x32crop')))))); /** * Подменю пользователя + experience */ $config['data']['toolbar_userbar'] = array('init' => array('fill' => array('list' => array('*'))), 'description' => '{{menu_toolbar_userbar_description}}', 'class' => 'dropdown-menu dropdown-user-menu animated fadeIn', 'list' => array('user' => array('text' => '<span><i class="fa fa-user"></i></span><span>{{user_menu_profile}}</span>', 'link' => E::User()->getProfileUrl(), 'options' => array('class' => 'fixed-item')), 'favourites' => array('text' => '<span><i class="fa fa-star"></i></span><span>{{user_menu_profile_favourites}}</span>', 'link' => E::User()->getProfileUrl() . 'favourites/topics/', 'options' => array('class' => 'fixed-item')), 'talk' => array('text' => array('<span><i class="fa fa-envelope"></i></span><span>{{user_privat_messages}}</span>', ' <span class="new-messages">', 'new_talk_string' => array(), '</span>'), 'link' => Router::GetPath('talk'), 'options' => array('link_id' => 'new_messages', 'class' => 'fixed-item')), 'settings' => array('text' => '<span><i class="fa fa-cog"></i></span><span>{{user_settings}}</span>', 'link' => '___path.root.url___/settings/', 'options' => array('class' => 'fixed-item')), 'toolbar_userbar_item' => '', 'logout' => array('text' => '<span><i class="fa fa-sign-out"></i></span><span>{{exit}}</span>', 'link' => Router::GetPath('login') . 'exit/?security_key=' . E::Security_GetSecurityKey(), 'options' => array('class' => 'fixed-item')))); /** * Подменю пользователя + experience */ $config['data']['userbar'] = array('class' => 'dropdown-menu dropdown-user-menu animated fadeIn', 'list' => array('pre' => array('text' => FALSE, 'link' => FALSE, 'options' => array('class' => 'user_activity_items'), 'submenu' => 'userinfo'), 'user' => array('text' => '<i class="fa fa-user"></i> {{user_menu_profile}}', 'link' => E::User()->getProfileUrl()), 'create' => array('text' => '<i class="fa fa-pencil"></i> {{block_create}}', 'link' => '#', 'options' => array('data' => array('toggle' => 'modal', 'target' => '#modal-write'))), 'talk' => array('text' => array('<i class="fa fa-envelope-o"></i> {{user_privat_messages}}', ' <span class="new-messages">', 'new_talk_string' => array(), '</span>'), 'link' => Router::GetPath('talk'), 'options' => array('link_id' => 'new_messages')), 'wall' => array('text' => '<i class="fa fa-bars"></i> {{user_menu_profile_wall}}', 'link' => E::User()->getProfileUrl() . 'wall/'), 'publication' => array('text' => '<i class="fa fa-file-o"></i> {{user_menu_publication}}', 'link' => E::User()->getProfileUrl() . 'created/topics/'), 'favourites' => array('text' => '<i class="fa fa-star-o"></i> {{user_menu_profile_favourites}}', 'link' => E::User()->getProfileUrl() . 'favourites/topics/'), 'settings' => array('text' => '<i class="fa fa-cogs"></i> {{user_settings}}', 'link' => '___path.root.url___/settings/'), 'userbar_item' => '', 'logout' => array('text' => '<i class="fa fa-sign-out"></i> {{exit}}', 'link' => Router::GetPath('login') . 'exit/?security_key=' . E::Security_GetSecurityKey()))); } if (E::IsUser()) { $config['data']['userinfo'] = array('init' => array('fill' => array('list' => array('*'))), 'description' => 'Индикаторы пользователя', 'list' => array('user_rating' => array('text' => array('user_rating' => array('<i class="fa fa-bar-chart-o"></i>', 'negative')), 'link' => E::User()->getProfileUrl(), 'options' => array('class' => 'menu-item-user-rating')), 'user_comments' => array('text' => array('count_track' => array('<i class="fa fa-bullhorn"></i>')), 'link' => Router::GetPath('feed') . 'track/', 'options' => array('class' => 'menu-item-user-comments')), 'user_mails' => array('text' => array('new_talk_string' => array('<i class="fa fa-envelope-o"></i>')), 'link' => Router::GetPath('talk'), 'options' => array('class' => 'menu-item-user-talks')))); } /** * Меню топиков */ C::Set('menu.data.topics.discussed.text', array('{{blog_menu_all_discussed}}', ' <i class="caret"></i>')); $config['data']['topics'] = array('class' => 'menu-topics', 'list' => array('good' => array('active' => array('topic_kind' => array('good')), 'options' => array('class' => 'menu-topics-good')), 'new' => array('text' => array('{{blog_menu_all_new}}', 'new_topics_count' => array('red')), 'options' => array('class' => 'menu-topics-new', 'link_title' => '{{blog_menu_top_period_24h}}')), 'newall' => array('options' => array('class' => 'menu-topics-all', 'link_title' => '{{blog_menu_top_period_24h}}')), 'feed' => array('options' => array('class' => 'menu-topics-feed role-guest-hide')), 'discussed' => array('text' => array('{{blog_menu_all_discussed}}', ' <i class="caret"></i>'), 'submenu' => 'discussed', 'options' => array('class' => 'dropdown menu-topics-discussed', 'link_data' => array('toggle' => 'dropdown'))))); if (C::Get('rating.enabled')) { $config['data']['topics']['list']['top'] = array('text' => array('{{blog_menu_all_top}}', ' <i class="caret"></i>'), 'submenu' => 'top', 'options' => array('class' => 'dropdown menu-topics-top', 'link_data' => array('toggle' => 'dropdown'))); } /** * Подменю обсуждаемых */ $config['data']['discussed'] = array('class' => 'dropdown-menu dropdown-content-menu animated fadeIn'); if (C::Get('rating.enabled')) { /**
/** * Отображение списка блогов */ protected function EventShowBlogs() { // * По какому полю сортировать $sOrder = F::GetRequestStr('order', 'blog_rating'); // * В каком направлении сортировать $sOrderWay = F::GetRequestStr('order_way', 'desc'); // * Фильтр поиска блогов $aFilter = array('include_type' => E::ModuleBlog()->GetAllowBlogTypes(E::User(), 'list', true)); if ($sOrder == 'blog_title') { $aFilter['order'] = array('blog_title' => $sOrderWay); } else { $aFilter['order'] = array($sOrder => $sOrderWay, 'blog_title' => 'asc'); } // * Передан ли номер страницы $iPage = preg_match('/^\\d+$/i', $this->GetEventMatch(2)) ? $this->GetEventMatch(2) : 1; // * Получаем список блогов $aResult = E::ModuleBlog()->GetBlogsByFilter($aFilter, $iPage, Config::Get('module.blog.per_page')); $aBlogs = $aResult['collection']; // * Формируем постраничность $aPaging = E::ModuleViewer()->MakePaging($aResult['count'], $iPage, Config::Get('module.blog.per_page'), Config::Get('pagination.pages.count'), R::GetPath('blogs'), array('order' => $sOrder, 'order_way' => $sOrderWay)); // * Загружаем переменные в шаблон E::ModuleViewer()->Assign('aPaging', $aPaging); E::ModuleViewer()->Assign('aBlogs', $aBlogs); E::ModuleViewer()->Assign('sBlogOrder', htmlspecialchars($sOrder)); E::ModuleViewer()->Assign('sBlogOrderWay', htmlspecialchars($sOrderWay)); E::ModuleViewer()->Assign('sBlogOrderWayNext', $sOrderWay == 'desc' ? 'asc' : 'desc'); E::ModuleViewer()->Assign('sShow', 'collective'); E::ModuleViewer()->Assign('sBlogsRootPage', R::GetPath('blogs')); // * Устанавливаем title страницы E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('blog_menu_all_list')); // * Устанавливаем шаблон вывода $this->SetTemplateAction('index'); }
/** * Return filter for topic list by name and params * * @param string $sFilterName * @param array $aParams * * @return array */ public function GetNamedFilter($sFilterName, $aParams = array()) { $aFilter = $this->GetTopicsFilter(); switch ($sFilterName) { case 'good': // Filter for good topics $aFilter['topic_rating'] = array('value' => empty($aParams['rating']) ? 0 : intval($aParams['rating']), 'type' => 'top', 'publish_index' => 1); break; case 'bad': // Filter for good topics $aFilter['topic_rating'] = array('value' => empty($aParams['rating']) ? 0 : intval($aParams['rating']), 'type' => 'down', 'publish_index' => 1); break; case 'new': // Filter for new topics $sDate = date('Y-m-d H:00:00', time() - Config::Get('module.topic.new_time')); $aFilter['topic_new'] = $sDate; break; case 'new_all': // Filter for ALL new topics // Nothing others break; case 'discussed': // if (!empty($aParams['period'])) { if (is_numeric($aParams['period'])) { // количество последних секунд $sPeriod = date('Y-m-d H:00:00', time() - intval($aParams['period'])); } else { $sPeriod = $aParams['period']; } $aFilter['topic_date_more'] = $sPeriod; } if (!isset($aFilter['order'])) { $aFilter['order'] = array(); } $aFilter['order'][] = 't.topic_count_comment DESC'; $aFilter['order'][] = 't.topic_date_show DESC'; $aFilter['order'][] = 't.topic_id DESC'; break; case 'top': if (!empty($aParams['period'])) { if (is_numeric($aParams['period'])) { // количество последних секунд $sPeriod = date('Y-m-d H:00:00', time() - intval($aParams['period'])); } else { $sPeriod = $aParams['period']; } $aFilter['topic_date_more'] = $sPeriod; } if (!isset($aFilter['order'])) { $aFilter['order'] = array(); } $aFilter['order'][] = 't.topic_rating DESC'; $aFilter['order'][] = 't.topic_date_show DESC'; $aFilter['order'][] = 't.topic_id DESC'; break; default: // Nothing others } if (!empty($aParams['blog_id'])) { $aFilter['blog_id'] = intval($aParams['blog_id']); } else { $aFilter['blog_type'] = empty($aParams['personal']) ? E::ModuleBlog()->GetOpenBlogTypes() : 'personal'; // If a user is authorized then adds blogs on which it is subscribed if (E::IsUser() && !empty($aParams['accessible']) && empty($aParams['personal'])) { $aOpenBlogs = E::ModuleBlog()->GetAccessibleBlogsByUser(E::User()); if (count($aOpenBlogs)) { $aFilter['blog_type']['*'] = $aOpenBlogs; } } } if (isset($aParams['personal']) && $aParams['personal'] === false && $aFilter['blog_type'] && is_array($aFilter['blog_type'])) { if (false !== ($iKey = array_search('personal', $aFilter['blog_type']))) { unset($aFilter['blog_type'][$iKey]); } } if (!empty($aParams['topic_type'])) { $aFilter['topic_type'] = $aParams['topic_type']; } if (!empty($aParams['user_id'])) { $aFilter['user_id'] = $aParams['user_id']; } if (isset($aParams['topic_published'])) { $aFilter['topic_publish'] = $aParams['topic_published'] ? 1 : 0; } return $aFilter; }
/** * Returns IDs of similar topics by tags * * @param array $aTags * @param array $aExcludeTopics * @param null $iLimit * * @return array */ public function GetSimilarTopicsIdByTags($aTags, $aExcludeTopics = array(), $iLimit = null) { $iUserId = E::UserId(); $aFilter = array('exclude_blogs' => E::ModuleBlog()->GetInaccessibleBlogsByUser(E::User())); if ($aExcludeTopics) { $aFilter['exclude_topics'] = is_array($aExcludeTopics) ? $aExcludeTopics : array(intval($aExcludeTopics)); } if ($iLimit) { $aFilter['limit'] = $iLimit; } $sCacheKey = 'similar_topics_id_' . $iUserId . '_' . serialize($aFilter); if (false === ($aTopicsId = E::ModuleCache()->Get($sCacheKey))) { $aTopicsId = $this->oMapper->GetTopicsIdByTags($aTags, $aFilter); E::ModuleCache()->Set($aTopicsId, $sCacheKey, array('content_new', 'content_update', 'blog_new', 'blog_update'), 'P1D'); } return $aTopicsId; }