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; }
protected function EventStreamCommentSandbox() { $aVars = array(); if ($aComments = E::ModuleComment()->GetCommentsOnline('sandbox', Config::Get('widgets.stream.params.limit'))) { $aVars['aComments'] = $aComments; } $sTextResult = E::ModuleViewer()->FetchWidget('stream_comment.tpl', $aVars); E::ModuleViewer()->AssignAjax('sText', $sTextResult); }
/** * Запуск обработки */ public function Exec() { // * Получаем комментарии if ($aComments = E::ModuleComment()->GetCommentsOnline('topic', Config::Get('widgets.stream.params.limit'))) { $aVars = array('aComments' => $aComments); // * Формируем результат в виде шаблона и возвращаем $sTextResult = $this->Fetch('stream_comment.tpl', $aVars); E::ModuleViewer()->Assign('sStreamComments', $sTextResult); } }
protected function _getLastDateOfTopics() { $sDate = null; $aTopics = E::ModuleTopic()->GetTopicsLast(1); if ($aTopics['collection']) { $oTopic = reset($aTopics['collection']); $sDate = $oTopic->getDateLastMod(); } $aComments = E::ModuleComment()->GetCommentsOnline('topic', 1); if ($aComments) { $oComment = reset($aComments); if ($oComment->getDateEdit() && $oComment->getDateEdit() > $sDate) { $sDate = $oComment->getCommentDateEdit(); } elseif ($oComment->getCommentDate() > $sDate) { $sDate = $oComment->getCommentDate(); } } return $sDate; }
/** * @param int|ModuleComment_EntityComment $xComment * * @return array */ public function getInfo($xComment) { /** @var ModuleComment_EntityComment $oComment */ if (!is_object($xComment)) { $iCommentId = intval($xComment); $sCacheKey = 'api_blog_' . $iCommentId; $oComment = E::ModuleCache()->GetTmp($sCacheKey); if (!$oComment) { $oComment = E::ModuleComment()->GetCommentById($iCommentId); } } else { $oComment = $xComment; $sCacheKey = 'api_blog_' . $oComment->getid(); } if (!$oComment) { return array(); } E::ModuleCache()->SetTmp($oComment, $sCacheKey); return $oComment->getApiData(); }
/** * Поиск комментариев * */ function EventComments() { // * Ищем $aReq = $this->PrepareRequest(); $aRes = $this->PrepareResults($aReq, Config::Get('module.comment.per_page')); if (false === $aRes) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error')); return Router::Action('error'); } // * Если поиск дал результаты if ($this->bIsResults) { // * Получаем топик-объекты по списку идентификаторов $aComments = E::ModuleComment()->GetCommentsAdditionalData(array_keys($this->aSphinxRes['matches'])); // * Конфигурируем парсер $oTextParser = ModuleText::newTextParser('search'); $aErrors = array(); // * Делаем сниппеты /** @var ModuleComment_EntityComment $oComment */ foreach ($aComments as $oComment) { $oComment->setText($oTextParser->parse(E::ModuleSphinx()->GetSnippet(htmlspecialchars($oComment->getText()), 'comments', $aReq['q'], '<span class="searched-item">', '</span>'), $aErrors)); } /** * Отправляем данные в шаблон */ E::ModuleViewer()->Assign('aRes', $aRes); E::ModuleViewer()->Assign('aComments', $aComments); } }
/** * Удаление/восстановление комментария * */ 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); }
/** * Выводит список избранноего юзера * */ protected function EventFavouriteComments() { if (!$this->CheckUserProfile()) { return parent::EventNotFound(); } $this->sMenuSubItemSelect = 'comments'; /** * Передан ли номер страницы */ $iPage = $this->GetParamEventMatch(2, 2) ? $this->GetParamEventMatch(2, 2) : 1; /** * Получаем список избранных комментариев */ $aResult = E::ModuleComment()->GetCommentsFavouriteByUserId($this->oUserProfile->getId(), $iPage, Config::Get('module.comment.per_page')); $aComments = $aResult['collection']; /** * Формируем постраничность */ $aPaging = E::ModuleViewer()->MakePaging($aResult['count'], $iPage, Config::Get('module.comment.per_page'), Config::Get('pagination.pages.count'), $this->oUserProfile->getUserUrl() . 'favourites/comments'); /** * Загружаем переменные в шаблон */ E::ModuleViewer()->Assign('aPaging', $aPaging); E::ModuleViewer()->Assign('aComments', $aComments); E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('user_menu_profile') . ' ' . $this->oUserProfile->getLogin()); E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('user_menu_profile_favourites_comments')); /** * Устанавливаем шаблон вывода */ $this->SetTemplateAction('favourite_comments'); }
/** * Returns stats of user publications and favourites * * @param int|object $xUser * * @return int[] */ public function GetUserProfileStats($xUser) { if (is_object($xUser)) { $iUserId = $xUser->getId(); } else { $iUserId = intval($xUser); } $iCountTopicFavourite = E::ModuleTopic()->GetCountTopicsFavouriteByUserId($iUserId); $iCountCommentFavourite = E::ModuleComment()->GetCountCommentsFavouriteByUserId($iUserId); $iCountTopics = E::ModuleTopic()->GetCountTopicsPersonalByUser($iUserId, 1); $iCountComments = E::ModuleComment()->GetCountCommentsByUserId($iUserId, 'topic'); $iCountWallRecords = E::ModuleWall()->GetCountWall(array('wall_user_id' => $iUserId, 'pid' => null)); $iImageCount = E::ModuleMresource()->GetCountImagesByUserId($iUserId); $iCountUserNotes = $this->GetCountUserNotesByUserId($iUserId); $iCountUserFriends = $this->GetCountUsersFriend($iUserId); $aUserPublicationStats = array('favourite_topics' => $iCountTopicFavourite, 'favourite_comments' => $iCountCommentFavourite, 'count_topics' => $iCountTopics, 'count_comments' => $iCountComments, 'count_usernotes' => $iCountUserNotes, 'count_wallrecords' => $iCountWallRecords, 'count_images' => $iImageCount, 'count_friends' => $iCountUserFriends); $aUserPublicationStats['count_created'] = $aUserPublicationStats['count_topics'] + $aUserPublicationStats['count_comments'] + $aUserPublicationStats['count_images']; if ($iUserId == E::UserId()) { $aUserPublicationStats['count_created'] += $aUserPublicationStats['count_usernotes']; } $aUserPublicationStats['count_favourites'] = $aUserPublicationStats['favourite_topics'] + $aUserPublicationStats['favourite_comments']; return $aUserPublicationStats; }
/** * Получает список комментариев * * @param array $aIds Список ID комментариев * * @return array */ protected function loadRelatedComment($aIds) { return E::ModuleComment()->GetCommentsAdditionalData($aIds); }
/** * Обработка завершения работу экшена */ public function EventShutdown() { if (!$this->oUserCurrent) { return; } $iCountTalkFavourite = E::ModuleTalk()->GetCountTalksFavouriteByUserId($this->oUserCurrent->getId()); E::ModuleViewer()->Assign('iCountTalkFavourite', $iCountTalkFavourite); $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('iCountCreated', $iCountNoteUser + $iCountTopicUser + $iCountCommentUser); E::ModuleViewer()->Assign('iCountFavourite', $iCountCommentFavourite + $iCountTopicFavourite); E::ModuleViewer()->Assign('iCountFriendsUser', E::ModuleUser()->GetCountUsersFriend($this->oUserCurrent->getId())); 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 $iOldBlogId ID старого блога * @param int $iNewBlogId ID нового блога * * @return bool */ public function MoveTopics($iOldBlogId, $iNewBlogId) { if ($bResult = $this->oMapper->MoveTopics($iOldBlogId, $iNewBlogId)) { // перемещаем теги $this->oMapper->MoveTopicsTags($iOldBlogId, $iNewBlogId); // меняем target parent у комментов E::ModuleComment()->MoveTargetParent($iOldBlogId, 'topic', $iNewBlogId); // меняем target parent у комментов в прямом эфире E::ModuleComment()->MoveTargetParentOnline($iOldBlogId, 'topic', $iNewBlogId); return $bResult; } E::ModuleCache()->CleanByTags(array('topic_update', 'blog_update', "blog_update_{$iOldBlogId}", "blog_update_{$iNewBlogId}")); E::ModuleCache()->Delete("blog_{$iOldBlogId}"); E::ModuleCache()->Delete("blog_{$iNewBlogId}"); return false; }
/** * Удаляет комментарий из избранного * * @param ModuleFavourite_EntityFavourite $oFavourite Объект избранного * * @return bool */ public function DeleteFavouriteComment(ModuleFavourite_EntityFavourite $oFavourite) { if ($oFavourite->getTargetType() == 'comment' && ($oComment = E::ModuleComment()->GetCommentById($oFavourite->getTargetId())) && in_array($oComment->getTargetType(), Config::get('module.comment.favourite_target_allow'))) { return E::ModuleFavourite()->DeleteFavourite($oFavourite); } return false; }
/** * Обработка добавление комментария к письму * */ 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()->Parse(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; }
/** * Обрабатывает ссылку на конкретный комментарий, определят к какому топику он относится и перенаправляет на него * Актуально при использовании постраничности комментариев */ protected function EventShowComment() { $iCommentId = $this->sCurrentEvent; // * Проверяем к чему относится комментарий if (!($oComment = E::ModuleComment()->GetCommentById($iCommentId))) { return parent::EventNotFound(); } if ($oComment->getTargetType() != 'topic' || !($oTopic = $oComment->getTarget())) { return parent::EventNotFound(); } // * Определяем необходимую страницу для отображения комментария if (!Config::Get('module.comment.use_nested') || !Config::Get('module.comment.nested_per_page')) { R::Location($oTopic->getUrl() . '#comment' . $oComment->getId()); } $iPage = E::ModuleComment()->GetPageCommentByTargetId($oComment->getTargetId(), $oComment->getTargetType(), $oComment); if ($iPage == 1) { R::Location($oTopic->getUrl() . '#comment' . $oComment->getId()); } else { R::Location($oTopic->getUrl() . "?cmtpage={$iPage}#comment" . $oComment->getId()); } exit; }
/** * Проверяет может ли пользователь создавать комментарии к инбоксу по времени * * @param ModuleUser_EntityUser $oUser Пользователь * * @return bool */ public function CanPostTalkCommentTime(ModuleUser_EntityUser $oUser) { if (!$oUser) { return false; } // * Для администраторов ограничение по времени не действует if ($oUser->isAdministrator() || $oUser->isModerator() || Config::Get('acl.create.talk_comment.limit_time') == 0 || $oUser->getRating() >= Config::Get('acl.create.talk_comment.limit_time_rating')) { return true; } // * Проверяем, если топик опубликованный меньше чем acl.create.topic.limit_time секунд назад $aTalkComments = E::ModuleComment()->GetCommentsByUserId($oUser->getId(), 'talk', 1, 1); // * Если комментариев не было if (!is_array($aTalkComments) || $aTalkComments['count'] == 0) { return true; } // * Достаем последний комментарий $oComment = array_shift($aTalkComments['collection']); $sDate = strtotime($oComment->getDate()); if ($sDate && time() - $sDate < Config::Get('acl.create.talk_comment.limit_time')) { return false; } return true; }
/** * Удаление письма из БД * * @param int $iTalkId ID разговора */ public function DeleteTalk($iTalkId) { $this->oMapper->DeleteTalk($iTalkId); /** * Удаляем комментарии к письму. * При удалении комментариев они удаляются из избранного,прямого эфира и голоса за них */ E::ModuleComment()->DeleteCommentByTargetId($iTalkId, 'talk'); }
/** * @param string $sParam * @param mixed $xValue * @param ModuleUser_EntityUser $oUser * @param array $aParams * * @return bool */ public function CheckRuleActionParam($sParam, $xValue, $oUser, $aParams = array()) { if ($sParam == 'registration_time') { if (time() - strtotime($oUser->getDateRegister()) >= $xValue) { return TRUE; } else { return FALSE; } } if ($sParam == 'rating') { if ($oUser->getRating() >= $xValue) { return TRUE; } else { return FALSE; } } if ($sParam == 'skill') { if ($oUser->getSkill() >= $xValue) { return TRUE; } else { return FALSE; } } if ($sParam == 'count_comment') { if (E::ModuleComment()->GetCountCommentsByUserId($oUser->getId(), 'topic') >= $xValue) { return TRUE; } else { return FALSE; } } if ($sParam == 'count_topic') { if (E::ModuleTopic()->GetCountTopicsPersonalByUser($oUser->getId(), 1) >= $xValue) { return TRUE; } else { return FALSE; } } if ($sParam == 'rating_sum_topic') { if (is_array($xValue) && count($xValue) > 1) { $iRating = $xValue[0]; $iTime = $xValue[1]; } else { $iRating = $xValue; $iTime = 60 * 60 * 24 * 14; } if ($this->GetSumRatingTopic($oUser->getId(), date('Y-m-d H:i:s', time() - $iTime)) >= $iRating) { return TRUE; } else { return FALSE; } } if ($sParam == 'rating_sum_comment') { if (is_array($xValue) && count($xValue) > 1) { $iRating = $xValue[0]; $iTime = $xValue[1]; } else { $iRating = $xValue; $iTime = 60 * 60 * 24 * 7; } if ($this->GetSumRatingComment($oUser->getId(), date('Y-m-d H:i:s', time() - $iTime)) >= $iRating) { return TRUE; } else { return FALSE; } } return FALSE; }
/** * Пересчет счетчика избранных * */ protected function EventRecalculateFavourites() { $this->sMainMenuItem = 'tools'; $this->_setTitle(E::ModuleLang()->Get('action.admin.recalcfavourites_title')); $this->SetTemplateAction('tools/recalcfavourites'); if (F::isPost('recalcfavourites_submit')) { E::ModuleSecurity()->ValidateSendForm(); set_time_limit(0); E::ModuleComment()->RecalculateFavourite(); E::ModuleTopic()->RecalculateFavourite(); E::ModuleCache()->Clean(); E::ModuleMessage()->AddNotice(E::ModuleLang()->Get('action.admin.favourites_recalculated'), E::ModuleLang()->Get('attention')); E::ModuleViewer()->Assign('bActionEnable', false); } else { E::ModuleViewer()->Assign('sMessage', E::ModuleLang()->Get('action.admin.recalcfavourites_message')); E::ModuleViewer()->Assign('bActionEnable', true); } }
/** * Обработка редактирования топика * * @param ModuleTopic_EntityTopic $oTopic * * @return mixed */ protected function SubmitEdit($oTopic) { $oTopic->_setValidateScenario('topic'); // * Сохраняем старое значение идентификатора блога $iBlogIdOld = $oTopic->getBlogId(); // * Заполняем поля для валидации $iBlogId = F::GetRequestStr('blog_id'); // if blog_id is empty then save blog not changed if (is_numeric($iBlogId)) { $oTopic->setBlogId($iBlogId); } // issue 151 (https://github.com/altocms/altocms/issues/151) // Некорректная обработка названия блога // $oTopic->setTitle(strip_tags(F::GetRequestStr('topic_title'))); $oTopic->setTitle(E::ModuleTools()->RemoveAllTags(F::GetRequestStr('topic_title'))); $oTopic->setTextSource(F::GetRequestStr('topic_text')); if ($this->oContentType->isAllow('link')) { $oTopic->setSourceLink(F::GetRequestStr('topic_field_link')); } $oTopic->setTags(F::GetRequestStr('topic_field_tags')); $oTopic->setUserIp(F::GetUserIp()); if ($this->oUserCurrent && ($this->oUserCurrent->isAdministrator() || $this->oUserCurrent->isModerator())) { if (F::GetRequestStr('topic_url') && $oTopic->getTopicUrl() != F::GetRequestStr('topic_url')) { $sTopicUrl = E::ModuleTopic()->CorrectTopicUrl(F::TranslitUrl(F::GetRequestStr('topic_url'))); $oTopic->setTopicUrl($sTopicUrl); } } // * Проверка корректности полей формы if (!$this->checkTopicFields($oTopic)) { return false; } // * Определяем в какой блог делаем запись $nBlogId = $oTopic->getBlogId(); if ($nBlogId == 0) { $oBlog = E::ModuleBlog()->GetPersonalBlogByUserId($oTopic->getUserId()); } else { $oBlog = E::ModuleBlog()->GetBlogById($nBlogId); } // * Если блог не определен выдаем предупреждение if (!$oBlog) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_create_blog_error_unknown'), E::ModuleLang()->Get('error')); return false; } // * Проверяем права на постинг в блог if (!E::ModuleACL()->IsAllowBlog($oBlog, $this->oUserCurrent)) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_create_blog_error_noallow'), E::ModuleLang()->Get('error')); return false; } // * Проверяем разрешено ли постить топик по времени if (isPost('submit_topic_publish') && !$oTopic->getPublishDraft() && !E::ModuleACL()->CanPostTopicTime($this->oUserCurrent)) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_time_limit'), E::ModuleLang()->Get('error')); return; } $oTopic->setBlogId($oBlog->getId()); // * Получаемый и устанавливаем разрезанный текст по тегу <cut> list($sTextShort, $sTextNew, $sTextCut) = E::ModuleText()->Cut($oTopic->getTextSource()); $oTopic->setCutText($sTextCut); $oTopic->setText(E::ModuleText()->Parser($sTextNew)); // Получаем ссылки, полученные при парсинге текста $oTopic->setTextLinks(E::ModuleText()->GetLinks()); $oTopic->setTextShort(E::ModuleText()->Parser($sTextShort)); // * Изменяем вопрос/ответы, только если еще никто не голосовал if ($this->oContentType->isAllow('poll') && F::GetRequestStr('topic_field_question') && F::GetRequest('topic_field_answers', array()) && $oTopic->getQuestionCountVote() == 0) { $oTopic->setQuestionTitle(strip_tags(F::GetRequestStr('topic_field_question'))); $oTopic->clearQuestionAnswer(); $aAnswers = F::GetRequest('topic_field_answers', array()); foreach ($aAnswers as $sAnswer) { $sAnswer = trim((string) $sAnswer); if ($sAnswer) { $oTopic->addQuestionAnswer($sAnswer); } } } $aPhotoSetData = E::ModuleMresource()->GetPhotosetData('photoset', $oTopic->getId()); $oTopic->setPhotosetCount($aPhotoSetData['count']); $oTopic->setPhotosetMainPhotoId($aPhotoSetData['cover']); // * Publish or save as a draft $bSendNotify = false; if (isset($_REQUEST['submit_topic_publish'])) { // If the topic has not been published then sets date of show (publication date) if (!$oTopic->getPublish() && !$oTopic->getDateShow()) { $oTopic->setDateShow(F::Now()); } $oTopic->setPublish(1); if ($oTopic->getPublishDraft() == 0) { $oTopic->setPublishDraft(1); $oTopic->setDateAdd(F::Now()); $bSendNotify = true; } } else { $oTopic->setPublish(0); } // * Принудительный вывод на главную if (E::ModuleACL()->IsAllowPublishIndex($this->oUserCurrent)) { if (F::GetRequest('topic_publish_index')) { $oTopic->setPublishIndex(1); } else { $oTopic->setPublishIndex(0); } } // * Запрет на комментарии к топику $oTopic->setForbidComment(F::GetRequest('topic_forbid_comment', 0)); // Если запрет на индексацию не устанавливался вручную, то задаем, как у блога $oBlogType = $oBlog->GetBlogType(); if ($oBlogType && !$oTopic->getIndexIgnoreLock()) { $oTopic->setTopicIndexIgnore($oBlogType->GetIndexIgnore()); } else { $oTopic->setTopicIndexIgnore(false); } $oTopic->setShowPhotoset(F::GetRequest('topic_show_photoset', 0)); E::ModuleHook()->Run('topic_edit_before', array('oTopic' => $oTopic, 'oBlog' => $oBlog)); // * Сохраняем топик if ($this->_updateTopic($oTopic)) { E::ModuleHook()->Run('topic_edit_after', array('oTopic' => $oTopic, 'oBlog' => $oBlog, 'bSendNotify' => &$bSendNotify)); // * Обновляем данные в комментариях, если топик был перенесен в новый блог if ($iBlogIdOld != $oTopic->getBlogId()) { E::ModuleComment()->UpdateTargetParentByTargetId($oTopic->getBlogId(), 'topic', $oTopic->getId()); E::ModuleComment()->UpdateTargetParentByTargetIdOnline($oTopic->getBlogId(), 'topic', $oTopic->getId()); } // * Обновляем количество топиков в блоге if ($iBlogIdOld != $oTopic->getBlogId()) { E::ModuleBlog()->RecalculateCountTopicByBlogId($iBlogIdOld); } E::ModuleBlog()->RecalculateCountTopicByBlogId($oTopic->getBlogId()); // * Добавляем событие в ленту E::ModuleStream()->Write($oTopic->getUserId(), 'add_topic', $oTopic->getId(), $oTopic->getPublish() && (!$oBlogType || !$oBlog->getBlogType()->IsPrivate())); // * Рассылаем о новом топике подписчикам блога if ($bSendNotify) { E::ModuleTopic()->SendNotifyTopicNew($oBlog, $oTopic, $oTopic->getUser()); } if (!$oTopic->getPublish() && !$this->oUserCurrent->isAdministrator() && !$this->oUserCurrent->isModerator() && $this->oUserCurrent->getId() != $oTopic->getUserId()) { R::Location($oBlog->getUrlFull()); } R::Location($oTopic->getUrl()); } else { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error')); F::SysWarning('System Error'); return R::Action('error'); } }
/** * Поиск комментариев */ public function EventComments() { $this->aReq = $this->_prepareRequest('comments'); $this->OutLog(); if ($this->aReq['regexp']) { $aResult = E::ModuleSearch()->GetCommentsIdByRegexp($this->aReq['regexp'], $this->aReq['iPage'], $this->nItemsPerPage, $this->aReq['params']); if ($aResult['count'] == 0) { $aComments = array(); } else { // * Получаем объекты по списку идентификаторов $aComments = E::ModuleComment()->GetCommentsAdditionalData($aResult['collection']); //подсветка поисковой фразы foreach ($aComments as $oComment) { if ($this->nModeOutList != 'snippet') { $oComment->setText($this->_textHighlite($oComment->getText())); } else { $oComment->setText($this->_makeSnippet($oComment->getText())); } } } } else { $aResult['count'] = 0; $aComments = array(); } // * Логгируем результаты, если требуется if ($this->bLogEnable) { $this->oLogs->RecordAdd('search', array('q' => $this->aReq['q'], 'result' => 'comments:' . $aResult['count'])); $this->oLogs->RecordEnd('search', true); } $aPaging = E::ModuleViewer()->MakePaging($aResult['count'], $this->aReq['iPage'], $this->nItemsPerPage, 4, Config::Get('path.root.url') . '/search/comments', array('q' => $this->aReq['q'])); $this->SetTemplateAction('results'); $aRes = array('aCounts' => array('topics' => null, 'comments' => $aResult['count'])); // * Отправляем данные в шаблон E::ModuleViewer()->AddHtmlTitle($this->aReq['q']); E::ModuleViewer()->Assign('bIsResults', !empty($aResult['count'])); E::ModuleViewer()->Assign('aRes', $aRes); E::ModuleViewer()->Assign('aComments', $aComments); E::ModuleViewer()->Assign('aPaging', $aPaging); }
/** * Updates comment * */ protected function AjaxUpdateComment() { // * Устанавливаем формат Ajax ответа E::ModuleViewer()->SetResponseAjax('json'); // * Пользователь авторизован? if (!$this->oUserCurrent) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error')); return; } if (!E::ModuleSecurity()->ValidateSendForm(false) || $this->GetPost('comment_mode') != 'edit') { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error')); return; } // * Проверяем текст комментария $sNewText = E::ModuleText()->Parse($this->GetPost('comment_text')); $iMin = Config::Val('module.comment.min_length', 2); $iMax = Config::Val('module.comment.max_length', 0); if (!F::CheckVal($sNewText, 'text', $iMin, $iMax)) { if ($iMax) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_text_len', array('min' => $iMin, 'max' => $iMax)), E::ModuleLang()->Get('error')); } else { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_text_min', array('min' => $iMin)), E::ModuleLang()->Get('error')); } return; } // * Получаем комментарий $iCommentId = intval($this->GetPost('comment_id')); /** var ModuleComment_EntityComment $oComment */ if (!$iCommentId || !($oComment = E::ModuleComment()->GetCommentById($iCommentId))) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error')); return; } if (!$oComment->isEditable()) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('comment_cannot_edit'), E::ModuleLang()->Get('error')); return; } if (!$oComment->getEditTime() && !$oComment->isEditable(false)) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('comment_edit_timeout'), E::ModuleLang()->Get('error')); return; } // Если все нормально, то обновляем текст $oComment->setText($sNewText); if (E::ModuleComment()->UpdateComment($oComment)) { $oComment = E::ModuleComment()->GetCommentById($iCommentId); E::ModuleViewer()->AssignAjax('nCommentId', $oComment->getId()); E::ModuleViewer()->AssignAjax('sText', $oComment->getText()); E::ModuleViewer()->AssignAjax('sDateEdit', $oComment->getCommentDateEdit()); E::ModuleViewer()->AssignAjax('sDateEditText', E::ModuleLang()->Get('date_now')); E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('comment_updated')); } else { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error')); } }
/** * Выполняется при завершении работы экшена * */ 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'); }
/** * Проверяет доступность того или иного целевого объекта, переопределяется * плагинами. По умолчанию всё грузить запрещено. * Если всё нормально и пользователю разрешено сюда загружать картинки, * то метод возвращает целевой объект, иначе значение 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; }
/** * Перемещает топики в другой блог * * @param int $nBlogId ID старого блога * @param int $nBlogIdNew ID нового блога * * @return bool */ public function MoveTopics($nBlogId, $nBlogIdNew) { if ($bResult = $this->oMapper->MoveTopics($nBlogId, $nBlogIdNew)) { // перемещаем теги $this->oMapper->MoveTopicsTags($nBlogId, $nBlogIdNew); // меняем target parent у комментов E::ModuleComment()->MoveTargetParent($nBlogId, 'topic', $nBlogIdNew); // меняем target parent у комментов в прямом эфире E::ModuleComment()->MoveTargetParentOnline($nBlogId, 'topic', $nBlogIdNew); return $bResult; } E::ModuleCache()->CleanByTags(array("topic_update", "topic_new_blog_{$nBlogId}", "topic_new_blog_{$nBlogIdNew}")); return false; }
/** * Выполняется при завершении работы экшена */ public function EventShutdown() { if (!$this->oUserProfile) { return; } /** * Загружаем в шаблон необходимые переменные */ $iCountTopicFavourite = E::ModuleTopic()->GetCountTopicsFavouriteByUserId($this->oUserProfile->getId()); $iCountTopicUser = E::ModuleTopic()->GetCountTopicsPersonalByUser($this->oUserProfile->getId(), 1); $iCountCommentUser = E::ModuleComment()->GetCountCommentsByUserId($this->oUserProfile->getId(), 'topic'); $iCountCommentFavourite = E::ModuleComment()->GetCountCommentsFavouriteByUserId($this->oUserProfile->getId()); $iCountNoteUser = E::ModuleUser()->GetCountUserNotesByUserId($this->oUserProfile->getId()); // Получим информацию об изображениях пользовтеля // И посчитаем общее количество картинок /** @var ModuleMresource_EntityMresourceCategory[] $aUserImagesInfo */ $aUserImagesInfo = E::ModuleMresource()->GetAllImageCategoriesByUserId($this->oUserProfile->getId()); $iPhotoCount = E::ModuleMresource()->GetCountImagesByUserId($this->oUserProfile->getId()); E::ModuleViewer()->Assign('oUserProfile', $this->oUserProfile); 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('iCountWallUser', E::ModuleWall()->GetCountWall(array('wall_user_id' => $this->oUserProfile->getId(), 'pid' => null))); E::ModuleViewer()->Assign('oUserImagesInfo', $aUserImagesInfo); E::ModuleViewer()->Assign('iPhotoCount', $iPhotoCount); /** * Общее число публикаций и избранного */ E::ModuleViewer()->Assign('iCountCreated', ($this->oUserCurrent && $this->oUserCurrent->getId() == $this->oUserProfile->getId() ? $iCountNoteUser : 0) + $iCountTopicUser + $iCountCommentUser + $iPhotoCount); E::ModuleViewer()->Assign('iCountFavourite', $iCountCommentFavourite + $iCountTopicFavourite); /** * Заметка текущего пользователя о юзере */ if ($this->oUserCurrent) { E::ModuleViewer()->Assign('oUserNote', $this->oUserProfile->getUserNote()); } E::ModuleViewer()->Assign('iCountFriendsUser', E::ModuleUser()->GetCountUsersFriend($this->oUserProfile->getId())); 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); }