예제 #1
0
 /**
  * Расчет рейтинга и силы при гоосовании за топик
  *
  * @param ModuleUser_EntityUser $oUser	Объект пользователя, который голосует
  * @param ModuleTopic_EntityTopic $oTopic	Объект топика
  * @param int $iValue
  * @return int
  */
 public function VoteTopic(ModuleUser_EntityUser $oUser, ModuleTopic_EntityTopic $oTopic, $iValue)
 {
     $oTopic->setRating($oTopic->getRating() + $iValue);
     $skill = $oUser->getSkill();
     $oUserTopic = $this->User_GetUserById($oTopic->getUserId());
     $iSkillNew = $oUserTopic->getSkill() + $iValue;
     $oUserTopic->setSkill($iSkillNew);
     $this->User_Update($oUserTopic);
     return $iValue;
 }
예제 #2
0
    protected function updateTopicFixedStatus(ModuleTopic_EntityTopic $oTopic)
    {
        $sql = 'UPDATE ' . Config::Get('db.table.topic') . ' 
			SET 
				topic_fixed = ?
			WHERE
				topic_id = ?d';
        if ($this->oDb->query($sql, $oTopic->getFixedStatus(), $oTopic->getId()) !== null) {
            return true;
        }
        return false;
    }
예제 #3
0
    protected function updateTopicadditionalfields(ModuleTopic_EntityTopic $oTopic)
    {
        $sql = 'UPDATE ' . Config::Get('db.table.topic') . ' 
			SET 
				now_listening = ? ,
				current_place = ? ,
				mood = ?
			WHERE
				topic_id = ?d';
        if ($this->oDb->query($sql, $oTopic->getNowListening(), $oTopic->getCurrentPlace(), $oTopic->getMood(), $oTopic->getId()) !== null) {
            return true;
        }
        return false;
    }
예제 #4
0
 /**
  * Расчет рейтинга и силы при гоосовании за топик
  *
  * @param ModuleUser_EntityUser $oUser Объект пользователя, который голосует
  * @param ModuleTopic_EntityTopic $oTopic Объект топика
  * @param int $iValue
  * @return int
  */
 public function VoteTopic(ModuleUser_EntityUser $oUser, ModuleTopic_EntityTopic $oTopic, $iValue)
 {
     /**
      * Устанавливаем рейтинг топика
      */
     $oTopic->setRating($oTopic->getRating() + $iValue);
     /**
      * Меняем рейтинг автора топика
      */
     $fDeltaUser = ($iValue < 0 ? -1 : 1) * Config::Get('module.rating.topic_multiplier');
     $oUserTopic = $this->User_GetUserById($oTopic->getUserId());
     $oUserTopic->setRating($oUserTopic->getRating() + $fDeltaUser);
     $this->User_Update($oUserTopic);
     return $iValue;
 }
예제 #5
0
 /**
  * Расчет рейтинга и силы при гоосовании за топик
  *
  * @param ModuleUser_EntityUser $oUser Объект пользователя, который голосует
  * @param ModuleTopic_EntityTopic $oTopic Объект топика
  * @param int $iValue
  *
  * @return int
  */
 public function VoteTopic($oUser, $oTopic, $iValue)
 {
     if (!C::Get('plugin.simplerating.topic.vote')) {
         return 0;
     }
     if (!C::Get('plugin.simplerating.topic.dislike') && $iValue < 0) {
         return 0;
     }
     /**
      * Устанавливаем рейтинг топика
      */
     if (C::Get('plugin.simplerating.topic.add')) {
         $oTopic->setRating((double) $oTopic->getRating() + $iValue * (double) C::Get('plugin.simplerating.topic.add'));
     }
     /**
      * Устанавливаем рейтинг автора
      */
     if (C::Get('plugin.simplerating.topic.user_add')) {
         $oUserTopic = $this->User_GetUserById($oTopic->getUserId());
         $oUserTopic->setRating((double) $oUserTopic->getRating() + $iValue * (double) C::Get('plugin.simplerating.topic.user_add'));
         $this->User_Update($oUserTopic);
     }
     /**
      * Убавляем рейтинг голосующего, если нужно
      */
     if (C::Get('plugin.simplerating.topic.user_remove')) {
         $oUser->setRating((double) $oUser->getRating() + (double) C::Get('plugin.simplerating.topic.user_remove'));
         $this->User_Update($oUser);
     }
     return (double) C::Get('plugin.simplerating.topic.add');
 }
예제 #6
0
 /**
  * Расчет рейтинга и силы при гоосовании за топик
  *
  * @param ModuleUser_EntityUser $oUser Объект пользователя, который голосует
  * @param ModuleTopic_EntityTopic $oTopic Объект топика
  * @param int $iValue
  * @return int
  */
 public function VoteTopic(ModuleUser_EntityUser $oUser, ModuleTopic_EntityTopic $oTopic, $iValue)
 {
     $skill = $oUser->getSkill();
     /**
      * Устанавливаем рейтинг топика
      */
     $iDeltaRating = $iValue;
     if ($skill >= 100 and $skill < 250) {
         $iDeltaRating = $iValue * 2;
     } elseif ($skill >= 250 and $skill < 400) {
         $iDeltaRating = $iValue * 3;
     } elseif ($skill >= 400) {
         $iDeltaRating = $iValue * 4;
     }
     $oTopic->setRating($oTopic->getRating() + $iDeltaRating);
     /**
      * Начисляем силу и рейтинг автору топика, используя логарифмическое распределение
      */
     $iMinSize = 0.1;
     $iMaxSize = 8;
     $iSizeRange = $iMaxSize - $iMinSize;
     $iMinCount = log(0 + 1);
     $iMaxCount = log(500 + 1);
     $iCountRange = $iMaxCount - $iMinCount;
     if ($iCountRange == 0) {
         $iCountRange = 1;
     }
     if ($skill > 50 and $skill < 200) {
         $skill_new = $skill / 70;
     } elseif ($skill >= 200) {
         $skill_new = $skill / 10;
     } else {
         $skill_new = $skill / 100;
     }
     $iDelta = $iMinSize + (log($skill_new + 1) - $iMinCount) * ($iSizeRange / $iCountRange);
     /**
      * Сохраняем силу и рейтинг
      */
     $oUserTopic = $this->User_GetUserById($oTopic->getUserId());
     $iSkillNew = $oUserTopic->getSkill() + $iValue * $iDelta;
     $iSkillNew = $iSkillNew < 0 ? 0 : $iSkillNew;
     $oUserTopic->setSkill($iSkillNew);
     $oUserTopic->setRating($oUserTopic->getRating() + $iValue * $iDelta / 2.73);
     $this->User_Update($oUserTopic);
     return $iDeltaRating;
 }
예제 #7
0
 /**
  * Возвращает похожие записи для объекта топика (по тегам)
  *
  * @param ModuleTopic_EntityTopic $oTopic
  *
  * @return array
  */
 public function getSimilarTopicsForTopic(ModuleTopic_EntityTopic $oTopic)
 {
     if ($oTopic == null) {
         return array();
     }
     //        Вытаскиваем переменные с файлов Config
     //        Максимальное количество топиков, которое выводится в блоке - iCountTopics
     //        По какому параметру сортировать записи - sOrderBy
     //        Как сортировать топики в выдаче
     $iCountTopics = Config::Get('plugin.similar.max_topics_count');
     $sOrderBy = Config::Get('plugin.similar.topics_order_by');
     $iOrderByDirection = Config::Get('plugin.similar.topics_order_by_direction');
     $sLang = null;
     if (in_array('l10n', $this->Plugin_GetActivePlugins())) {
         $sLang = $this->PluginL10n_L10n_GetLangForQuery();
     }
     // Генерируем ключ для кеша
     $key = "simular_topics_by_tags_for_" . $oTopic->getId() . ($sLang ? "_{$sLang}" : "") . "_{$iCountTopics}_{$sOrderBy}_{$iOrderByDirection}";
     if (!($aTopicIds = $this->Cache_Get($key))) {
         $aTopicIds = $this->oMapper->getTopicIdForTags($oTopic->getTagsArray(), $iCountTopics + 1, $sOrderBy, $iOrderByDirection, $sLang);
         unset($aTopicIds[array_search($oTopic->getId(), $aTopicIds)]);
         // Кешируем массив топиков на один час
         $this->Cache_Set($aTopicIds, $key, array('topic_update'), 60 * 10);
     }
     // Пытаемся вытянуть массив топиков из кеша
     // Массив id'шек топиков похожих на текущий
     // Достаем топики вместе с дополнительной информацией (автор, блог и т.д.)
     $aTopics = $this->Topic_GetTopicsAdditionalData($aTopicIds, array('user' => array(), 'blog' => array('owner' => array())));
     // Удаляем топики из недоступных для пользователя блогов
     $oUser = $this->User_GetUserCurrent();
     $aInaccessibleBlogIds = $this->Blog_GetInaccessibleBlogsByUser($oUser);
     foreach ($aTopics as $oTopic) {
         if (in_array($oTopic->getBlogId(), $aInaccessibleBlogIds)) {
             unset($aTopics[$oTopic->getTopicId()]);
         }
     }
     return $aTopics;
 }
예제 #8
0
 /**
  * Проверка полей формы
  *
  * @param ModuleTopic_EntityTopic $oTopic
  * @return bool
  */
 protected function checkTopicFields($oTopic)
 {
     $this->Security_ValidateSendForm();
     $bOk = true;
     if (!$oTopic->_Validate()) {
         $this->Message_AddError($oTopic->_getValidateError(), $this->Lang_Get('error'));
         $bOk = false;
     }
     /**
      * Выполнение хуков
      */
     $this->Hook_Run('check_link_fields', array('bOk' => &$bOk));
     return $bOk;
 }
예제 #9
0
 /**
  * Присоединение фотографий к фотосету топика
  *
  * @param ModuleTopic_EntityTopic $oTopic
  * @param string                  $sTargetTmp
  *
  * @return bool
  */
 public function attachTmpPhotoToTopic($oTopic, $sTargetTmp)
 {
     if ($sTargetTmp) {
         $sql = "\n                UPDATE ?_topic_photo\n                SET topic_id=?d, target_tmp=NULL\n                WHERE target_tmp=?\n            ";
         return $this->oDb->query($sql, $oTopic->getId(), $sTargetTmp) !== false;
     }
     return true;
 }
예제 #10
0
 /**
  * Show topic
  *
  * @return string|null
  */
 protected function EventShowTopic()
 {
     $this->sMenuHeadItemSelect = 'index';
     $sBlogUrl = '';
     $sTopicUrlMask = R::GetTopicUrlMask();
     if ($this->oCurrentTopic) {
         $this->oCurrentBlog = $this->oCurrentTopic->getBlog();
         if ($this->oCurrentBlog) {
             $sBlogUrl = $this->oCurrentBlog->getUrl();
         }
         $this->sMenuItemSelect = 'blog';
     } else {
         if ($this->GetParamEventMatch(0, 1)) {
             // из коллективного блога
             $sBlogUrl = $this->sCurrentEvent;
             $iTopicId = $this->GetParamEventMatch(0, 1);
             $this->sMenuItemSelect = 'blog';
         } else {
             // из персонального блога
             $iTopicId = $this->GetEventMatch(1);
             $this->sMenuItemSelect = 'log';
         }
         // * Проверяем есть ли такой топик
         if (!$iTopicId || !($this->oCurrentTopic = E::ModuleTopic()->GetTopicById($iTopicId))) {
             return parent::EventNotFound();
         }
     }
     if (!$this->oCurrentTopic->getBlog()) {
         // Этого быть не должно, но если вдруг, то надо отработать
         return parent::EventNotFound();
     }
     $this->sMenuSubItemSelect = '';
     // Trusted user is admin or owner of topic
     if ($this->oUserCurrent && ($this->oUserCurrent->isAdministrator() || $this->oUserCurrent->isModerator() || $this->oUserCurrent->getId() == $this->oCurrentTopic->getUserId())) {
         $bTrustedUser = true;
     } else {
         $bTrustedUser = false;
     }
     if (!$bTrustedUser) {
         // Topic with future date
         if ($this->oCurrentTopic->getDate() > date('Y-m-d H:i:s')) {
             return parent::EventNotFound();
         }
         // * Проверяем права на просмотр топика-черновика
         if (!$this->oCurrentTopic->getPublish()) {
             if (!Config::Get('module.topic.draft_link')) {
                 return parent::EventNotFound();
             } else {
                 // Если режим просмотра по прямой ссылке включен, то проверяем параметры
                 $bOk = false;
                 if ($sDraftCode = F::GetRequestStr('draft', null, 'get')) {
                     if (strpos($sDraftCode, ':')) {
                         list($nUser, $sHash) = explode(':', $sDraftCode);
                         if ($this->oCurrentTopic->GetUserId() == $nUser && $this->oCurrentTopic->getTextHash() == $sHash) {
                             $bOk = true;
                         }
                     }
                 }
                 if (!$bOk) {
                     return parent::EventNotFound();
                 }
             }
         }
     }
     // Если номер топика правильный, но URL блога неверный, то корректируем его и перенаправляем на нужный адрес
     if ($sBlogUrl !== '' && $this->oCurrentTopic->getBlog()->getUrl() !== $sBlogUrl) {
         R::Location($this->oCurrentTopic->getUrl());
     }
     // Если запросили топик с определенной маской, не указаным названием блога,
     // но ссылка на топик и ЧПУ url разные, и это не запрос RSS
     // то перенаправляем на страницу для вывода топика (во избежание дублирования контента по разным URL)
     if ($sTopicUrlMask && $sBlogUrl == '' && $this->oCurrentTopic->getUrl() != R::GetPathWebCurrent() . (substr($this->oCurrentTopic->getUrl(), -1) === '/' ? '/' : '') && substr(R::RealUrl(true), 0, 4) !== 'rss/') {
         R::Location($this->oCurrentTopic->getUrl());
     }
     // Checks rights to show content from the blog
     if (!$this->oCurrentTopic->getBlog()->CanReadBy($this->oUserCurrent)) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('acl_cannot_show_content'), E::ModuleLang()->Get('not_access'));
         return R::Action('error');
     }
     // Обрабатываем добавление коммента
     if (isset($_REQUEST['submit_comment'])) {
         $this->SubmitComment();
     }
     // Достаём комменты к топику
     if (!Config::Get('module.comment.nested_page_reverse') && Config::Get('module.comment.use_nested') && Config::Get('module.comment.nested_per_page')) {
         $iPageDef = ceil(E::ModuleComment()->GetCountCommentsRootByTargetId($this->oCurrentTopic->getId(), 'topic') / Config::Get('module.comment.nested_per_page'));
     } else {
         $iPageDef = 1;
     }
     $iPage = intval(F::GetRequest('cmtpage', 0));
     if ($iPage < 1) {
         $iPage = $iPageDef;
     }
     $aReturn = E::ModuleComment()->GetCommentsByTargetId($this->oCurrentTopic, 'topic', $iPage, Config::Get('module.comment.nested_per_page'));
     $iMaxIdComment = $aReturn['iMaxIdComment'];
     /** @var ModuleComment_EntityComment[] $aComments */
     $aComments = $aReturn['comments'];
     if ($aComments && $iMaxIdComment && isset($aComments[$iMaxIdComment])) {
         $sLastCommentDate = $aComments[$iMaxIdComment]->getDate();
     } else {
         $sLastCommentDate = null;
     }
     // Если используется постраничность для комментариев - формируем ее
     if (Config::Get('module.comment.use_nested') && Config::Get('module.comment.nested_per_page')) {
         $aPaging = E::ModuleViewer()->MakePaging($aReturn['count'], $iPage, Config::Get('module.comment.nested_per_page'), Config::Get('pagination.pages.count'), '');
         if (!Config::Get('module.comment.nested_page_reverse') && $aPaging) {
             // переворачиваем страницы в обратном порядке
             $aPaging['aPagesLeft'] = array_reverse($aPaging['aPagesLeft']);
             $aPaging['aPagesRight'] = array_reverse($aPaging['aPagesRight']);
         }
         E::ModuleViewer()->Assign('aPagingCmt', $aPaging);
     }
     //      issue 253 {@link https://github.com/altocms/altocms/issues/253}
     //      Запрещаем оставлять комментарии к топику-черновику
     //      if ($this->oUserCurrent) {
     if ($this->oUserCurrent && (int) $this->oCurrentTopic->getPublish()) {
         $bAllowToComment = E::ModuleBlog()->GetBlogsAllowTo('comment', $this->oUserCurrent, $this->oCurrentTopic->getBlog()->GetId(), true);
     } else {
         $bAllowToComment = false;
     }
     // Отмечаем прочтение топика
     if ($this->oUserCurrent) {
         $oTopicRead = E::ModuleTopic()->GetTopicRead($this->oCurrentTopic->getId(), $this->oUserCurrent->getid());
         if (!$oTopicRead) {
             /** @var ModuleTopic_EntityTopicRead $oTopicRead */
             $oTopicRead = E::GetEntity('Topic_TopicRead');
             $oTopicRead->setTopicId($this->oCurrentTopic->getId());
             $oTopicRead->setUserId($this->oUserCurrent->getId());
             $oTopicRead->setCommentCountLast($this->oCurrentTopic->getCountComment());
             $oTopicRead->setCommentIdLast($iMaxIdComment);
             $oTopicRead->setDateRead(F::Now());
             E::ModuleTopic()->AddTopicRead($oTopicRead);
         } else {
             if ($oTopicRead->getCommentCountLast() != $this->oCurrentTopic->getCountComment() || $oTopicRead->getCommentIdLast() != $iMaxIdComment || !is_null($sLastCommentDate) && $oTopicRead->getDateRead() <= $sLastCommentDate) {
                 $oTopicRead->setCommentCountLast($this->oCurrentTopic->getCountComment());
                 $oTopicRead->setCommentIdLast($iMaxIdComment);
                 $oTopicRead->setDateRead(F::Now());
                 E::ModuleTopic()->UpdateTopicRead($oTopicRead);
             }
         }
     }
     // Выставляем SEO данные
     $sTextSeo = strip_tags($this->oCurrentTopic->getText());
     E::ModuleViewer()->SetHtmlDescription(F::CutText($sTextSeo, Config::Get('view.html.description_max_words')));
     E::ModuleViewer()->SetHtmlKeywords($this->oCurrentTopic->getTags());
     E::ModuleViewer()->SetHtmlCanonical($this->oCurrentTopic->getUrl());
     // Вызов хуков
     E::ModuleHook()->Run('topic_show', array('oTopic' => $this->oCurrentTopic));
     // Загружаем переменные в шаблон
     E::ModuleViewer()->Assign('oTopic', $this->oCurrentTopic);
     E::ModuleViewer()->Assign('aComments', $aComments);
     E::ModuleViewer()->Assign('iMaxIdComment', $iMaxIdComment);
     E::ModuleViewer()->Assign('bAllowToComment', $bAllowToComment);
     // Устанавливаем title страницы
     E::ModuleViewer()->AddHtmlTitle($this->oCurrentTopic->getBlog()->getTitle());
     E::ModuleViewer()->AddHtmlTitle($this->oCurrentTopic->getTitle());
     E::ModuleViewer()->SetHtmlRssAlternate(R::GetPath('rss') . 'comments/' . $this->oCurrentTopic->getId() . '/', $this->oCurrentTopic->getTitle());
     // Устанавливаем шаблон вывода
     $this->SetTemplateAction('topic');
     // Additional tags for <head>
     $aHeadTags = $this->_getHeadTags($this->oCurrentTopic);
     if ($aHeadTags) {
         E::ModuleViewer()->SetHtmlHeadTags($aHeadTags);
     }
     return null;
 }
 /**
  * Проверка полей формы
  *
  * @param ModuleTopic_EntityTopic $oTopic
  * @return bool
  */
 protected function checkTopicFields($oTopic)
 {
     $this->Security_ValidateSendForm();
     $bOk = true;
     if (!$oTopic->_Validate()) {
         $this->Message_AddError($oTopic->_getValidateError(), $this->Lang_Get('error'));
         $bOk = false;
     }
     /**
      * проверяем заполнение ответов только если еще никто не голосовал
      */
     if ($oTopic->getQuestionCountVote() == 0) {
         /**
          * Проверяем варианты ответов
          */
         $aAnswers = getRequest('answer', array());
         foreach ($aAnswers as $key => $sAnswer) {
             $sAnswer = (string) $sAnswer;
             if (trim($sAnswer) == '') {
                 unset($aAnswers[$key]);
                 continue;
             }
             if (!func_check($sAnswer, 'text', 1, 100)) {
                 $this->Message_AddError($this->Lang_Get('topic_question_create_answers_error'), $this->Lang_Get('error'));
                 $bOk = false;
                 break;
             }
         }
         $_REQUEST['answer'] = $aAnswers;
         /**
          * Ограничения на количество вариантов
          */
         if (count($aAnswers) < 2) {
             $this->Message_AddError($this->Lang_Get('topic_question_create_answers_error_min'), $this->Lang_Get('error'));
             $bOk = false;
         }
         if (count($aAnswers) > 20) {
             $this->Message_AddError($this->Lang_Get('topic_question_create_answers_error_max'), $this->Lang_Get('error'));
             $bOk = false;
         }
     }
     /**
      * Выполнение хуков
      */
     $this->Hook_Run('check_question_fields', array('bOk' => &$bOk));
     return $bOk;
 }
예제 #12
0
 /**
  * Формирует и возвращает полный ЧПУ URL для топика
  *
  * @param ModuleTopic_EntityTopic $oTopic
  * @param bool $bAbsolute При false вернет относительный УРЛ
  * @return string
  */
 public function BuildUrlForTopic($oTopic, $bAbsolute = true)
 {
     $sUrlMask = Config::Get('module.topic.url');
     $iDateCreate = strtotime($oTopic->getDatePublish());
     $aReplace = array('%year%' => date("Y", $iDateCreate), '%month%' => date("m", $iDateCreate), '%day%' => date("d", $iDateCreate), '%hour%' => date("H", $iDateCreate), '%minute%' => date("i", $iDateCreate), '%second%' => date("s", $iDateCreate), '%login%' => '', '%blog%' => '', '%id%' => $oTopic->getId(), '%title%' => $oTopic->getSlug(), '%type%' => $oTopic->getType());
     /**
      * Получаем связанные данные только если в этом есть необходимость
      */
     if (strpos($sUrlMask, '%blog%') !== false) {
         if (!($oBlog = $oTopic->GetBlog())) {
             $oBlog = $this->Blog_GetBlogById($oTopic->getBlogId());
         }
         if ($oBlog) {
             if ($oBlog->getType() == 'personal') {
                 $sUrlMask = str_replace('%blog%', '%login%', $sUrlMask);
             } else {
                 $aReplace['%blog%'] = $oBlog->getUrl();
             }
         }
     }
     if (strpos($sUrlMask, '%login%') !== false) {
         if (!($oUser = $oTopic->GetUser())) {
             $oUser = $this->User_GetUserById($oTopic->getUserId());
         }
         if ($oUser) {
             $aReplace['%login%'] = $oUser->getLogin();
         }
     }
     $sUrl = strtr($sUrlMask, $aReplace);
     return $bAbsolute ? Router::GetPathRootWeb() . '/' . $sUrl : $sUrl;
 }
예제 #13
0
 /**
  * Расчет рейтинга и силы при гоосовании за топик
  *
  * @param ModuleUser_EntityUser   $oUser     Объект пользователя, который голосует
  * @param ModuleTopic_EntityTopic $oTopic    Объект топика
  * @param int                     $iValue
  *
  * @return int
  */
 public function VoteTopic($oUser, $oTopic, $iValue)
 {
     $iDeltaRating = 0;
     $skill = $oUser->getSkill();
     if (C::Get('plugin.rating.topic.vote') && (C::Get('plugin.rating.topic.dislike') || !C::Get('plugin.rating.topic.dislike') && $iValue > 0)) {
         /**
          * Устанавливаем рейтинг топика
          */
         $iDeltaRating = $iValue * C::Get('plugin.rating.rating.topic_k1');
         //1
         if ($skill >= C::Get('plugin.rating.rating.topic_border_1') and $skill < C::Get('plugin.rating.rating.topic_border_2')) {
             // 100-250
             $iDeltaRating = $iValue * C::Get('plugin.rating.rating.topic_k2');
             //2
         } elseif ($skill >= C::Get('plugin.rating.rating.topic_border_2') and $skill < C::Get('plugin.rating.rating.topic_border_3')) {
             //250-400
             $iDeltaRating = $iValue * C::Get('plugin.rating.rating.topic_k3');
             //3
         } elseif ($skill >= C::Get('plugin.rating.rating.topic_border_3')) {
             //400
             $iDeltaRating = $iValue * C::Get('plugin.rating.rating.topic_k4');
             //4
         }
         $oTopic->setRating($oTopic->getRating() + $iDeltaRating);
     }
     if (C::Get('plugin.rating.rating.vote') && (C::Get('plugin.rating.topic.dislike') || !C::Get('plugin.rating.topic.dislike') && $iValue > 0)) {
         /**
          * Начисляем силу и рейтинг автору топика, используя логарифмическое распределение
          */
         $iMinSize = C::Get('plugin.rating.topic.min_change');
         //0.1;
         $iMaxSize = C::Get('plugin.rating.topic.max_change');
         //8;
         $iSizeRange = $iMaxSize - $iMinSize;
         $iMinCount = log(0 + 1);
         $iMaxCount = log(C::Get('plugin.rating.topic.max_rating') + 1);
         $iCountRange = $iMaxCount - $iMinCount;
         if ($iCountRange == 0) {
             $iCountRange = 1;
         }
         if ($skill > C::Get('plugin.rating.topic.left_border') and $skill < C::Get('plugin.rating.topic.right_border')) {
             //200
             $skill_new = $skill / C::Get('plugin.rating.topic.mid_divider');
             //70;
         } elseif ($skill >= C::Get('plugin.rating.topic.right_border')) {
             //200
             $skill_new = $skill / C::Get('plugin.rating.topic.right_divider');
             //10;
         } else {
             $skill_new = $skill / C::Get('plugin.rating.topic.left_divider');
             //100;
         }
         $iDelta = $iMinSize + (log($skill_new + 1) - $iMinCount) * ($iSizeRange / $iCountRange);
         /**
          * Сохраняем силу и рейтинг
          */
         $oUserTopic = $this->User_GetUserById($oTopic->getUserId());
         $iSkillNew = $oUserTopic->getSkill() + $iValue * $iDelta;
         $iSkillNew = $iSkillNew < 0 ? 0 : $iSkillNew;
         $oUserTopic->setSkill($iSkillNew);
         $oUserTopic->setRating($oUserTopic->getRating() + $iValue * $iDelta / C::Get('plugin.rating.topic.auth_coef'));
         //2.73
         $this->User_Update($oUserTopic);
     }
     if ($skill > C::Get('plugin.rating.topic.left_border') and $skill < C::Get('plugin.rating.topic.right_border')) {
         //200
         $skill_new = $skill / C::Get('plugin.rating.topic.mid_divider');
         //70;
     } elseif ($skill >= C::Get('plugin.rating.topic.right_border')) {
         //200
         $skill_new = $skill / C::Get('plugin.rating.topic.right_divider');
         //10;
     } else {
         $skill_new = $skill / C::Get('plugin.rating.topic.left_divider');
         //100;
     }
     $iDelta = $iMinSize + (log($skill_new + 1) - $iMinCount) * ($iSizeRange / $iCountRange);
     /**
      * Сохраняем силу и рейтинг
      */
     $oUserTopic = $this->User_GetUserById($oTopic->getUserId());
     $iSkillNew = $oUserTopic->getSkill() + $iValue * $iDelta;
     $iSkillNew = $iSkillNew < 0 ? 0 : $iSkillNew;
     $oUserTopic->setSkill($iSkillNew);
     $oUserTopic->setRating($oUserTopic->getRating() + $iValue * $iDelta / C::Get('plugin.rating.topic.auth_coef'));
     //2.73
     $this->User_Update($oUserTopic);
     return $iDeltaRating;
 }
예제 #14
0
 /**
  * Проверяет можно или нет пользователю удалять данный топик
  *
  * @param ModuleTopic_EntityTopic $oTopic	Топик
  * @param ModuleUser_EntityUser $oUser	Пользователь
  * @return bool
  */
 public function IsAllowDeleteTopic($oTopic, $oUser)
 {
     /**
      * Разрешаем если это админ сайта или автор топика
      */
     if ($oTopic->getUserId() == $oUser->getId() or $oUser->isAdministrator()) {
         return true;
     }
     /**
      * Если автор(смотритель) блога
      */
     if ($oTopic->getBlog()->getOwnerId() == $oUser->getId()) {
         return true;
     }
     /**
      * Если модер или админ блога
      */
     if ($this->User_GetUserCurrent() and $this->User_GetUserCurrent()->getId() == $oUser->getId()) {
         /**
          * Для авторизованного пользователя данный код будет работать быстрее
          */
         if ($oTopic->getBlog()->getUserIsAdministrator() or $oTopic->getBlog()->getUserIsModerator()) {
             return true;
         }
     } else {
         $oBlogUser = $this->Blog_GetBlogUserByBlogIdAndUserId($oTopic->getBlogId(), $oUser->getId());
         if ($oBlogUser and ($oBlogUser->getIsModerator() or $oBlogUser->getIsAdministrator())) {
             return true;
         }
     }
     return false;
 }
 /**
  * Обновляет контент топика
  *
  * @param ModuleTopic_EntityTopic $oTopic Объект топика
  * @return bool
  */
 public function UpdateTopicContent(ModuleTopic_EntityTopic $oTopic)
 {
     $sql = "UPDATE " . Config::Get('db.table.topic_content') . "\n      SET\n        topic_text= ?,\n        topic_text_short= ?,\n        topic_text_source= ?,\n        topic_extra= ?\n      WHERE\n        topic_id = ?d\n    ";
     if ($this->oDb->query($sql, $oTopic->getText(), $oTopic->getTextShort(), $oTopic->getTextSource(), $oTopic->getExtra(), $oTopic->getId())) {
         return true;
     }
     return false;
 }
예제 #16
0
 /**
  * Проверяет можно или нет пользователю удалять данный топик
  *
  * @param ModuleTopic_EntityTopic $oTopic Топик
  * @param ModuleUser_EntityUser $oUser Пользователь
  * @return bool
  */
 public function IsAllowDeleteTopic($oTopic, $oUser)
 {
     $that = $this;
     // fix for PHP < 5.4
     return $this->Rbac_IsAllowUser($oUser, 'remove_topic', array('callback' => function ($oUser, $aParams) use($that, $oTopic) {
         if (!$oUser) {
             return false;
         }
         /**
          * Разрешаем если это админ сайта или автор топика
          */
         if ($oTopic->getUserId() == $oUser->getId() or $oUser->isAdministrator()) {
             return true;
         }
         /**
          * Если автор(смотритель) блога
          */
         if ($oTopic->getBlog()->getOwnerId() == $oUser->getId()) {
             return true;
         }
         /**
          * Если модер или админ блога
          */
         if ($that->User_GetUserCurrent() and $that->User_GetUserCurrent()->getId() == $oUser->getId()) {
             /**
              * Для авторизованного пользователя данный код будет работать быстрее
              */
             if ($oTopic->getBlog()->getUserIsAdministrator() or $oTopic->getBlog()->getUserIsModerator()) {
                 return true;
             }
         } else {
             $oBlogUser = $that->Blog_GetBlogUserByBlogIdAndUserId($oTopic->getBlogId(), $oUser->getId());
             if ($oBlogUser and ($oBlogUser->getIsModerator() or $oBlogUser->getIsAdministrator())) {
                 return true;
             }
         }
         return false;
     }));
 }
예제 #17
0
 /**
  * Проверяет можно или нет пользователю удалять данный топик
  *
  * @param ModuleTopic_EntityTopic $oTopic    Топик
  * @param ModuleUser_EntityUser   $oUser     Пользователь
  *
  * @return bool
  */
 public function IsAllowDeleteTopic($oTopic, $oUser)
 {
     if (!$oTopic || !$oUser) {
         return false;
     }
     // * Разрешаем если это админ сайта или автор топика
     if ($oTopic->getUserId() == $oUser->getId() || $oUser->isAdministrator() || $oUser->isModerator()) {
         return true;
     }
     // * Если владелец блога
     if ($oTopic->getBlog()->getOwnerId() == $oUser->getId()) {
         return true;
     }
     // Проверяем права
     return $this->CheckBlogDeleteContent($oTopic->getBlog(), $oUser);
 }
예제 #18
0
 /**
  * Проверка на соответсвие коментария родительскому коментарию
  *
  * @param ModuleTopic_EntityTopic $oTopic
  * @param string $sText
  * @param ModuleComment_EntityComment $oCommentParent
  *
  * @return bool result
  */
 protected function CheckParentComment($oTopic, $sText, $oCommentParent)
 {
     $sParentId = 0;
     if ($oCommentParent) {
         $sParentId = $oCommentParent->GetCommentId();
     }
     $bOk = true;
     /**
      * Проверям на какой коммент отвечаем
      */
     if (!func_check($sParentId, 'id')) {
         $this->Message_AddErrorSingle($this->Lang_Get('common.error.system.base'), $this->Lang_Get('common.error.error'));
         $bOk = false;
     }
     if ($sParentId) {
         /**
          * Проверяем существует ли комментарий на который отвечаем
          */
         if (!$oCommentParent) {
             $this->Message_AddErrorSingle($this->Lang_Get('common.error.system.base'), $this->Lang_Get('common.error.error'));
             $bOk = false;
         }
         /**
          * Проверяем из одного топика ли новый коммент и тот на который отвечаем
          */
         if ($oCommentParent->getTargetId() != $oTopic->getId()) {
             $this->Message_AddErrorSingle($this->Lang_Get('common.error.system.base'), $this->Lang_Get('common.error.error'));
             $bOk = false;
         }
     } else {
         $sParentId = null;
     }
     /**
      * Проверка на дублирующий коммент
      */
     if ($this->Comment_GetCommentUnique($oTopic->getId(), 'topic', $this->oUserCurrent->getId(), $sParentId, md5($sText))) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic.comments.notices.spam'), $this->Lang_Get('common.error.error'));
         $bOk = false;
     }
     $this->Hook_Run('comment_check_parent', array('oTopic' => $oTopic, 'sText' => $sText, 'oCommentParent' => $oCommentParent, 'bOk' => &$bOk));
     return $bOk;
 }
예제 #19
0
 /**
  * Обновляет контент топика
  *
  * @param ModuleTopic_EntityTopic $oTopic Объект топика
  * @return bool
  */
 public function UpdateTopicContent(ModuleTopic_EntityTopic $oTopic)
 {
     $sql = "UPDATE " . Config::Get('db.table.topic_content') . "\n\t\t\tSET \t\t\t\t\n\t\t\t\ttopic_text= ?,\n\t\t\t\ttopic_text_short= ?,\n\t\t\t\ttopic_text_source= ?,\n\t\t\t\ttopic_extra= ?\n\t\t\tWHERE\n\t\t\t\ttopic_id = ?d\n\t\t";
     $res = $this->oDb->query($sql, $oTopic->getText(), $oTopic->getTextShort(), $oTopic->getTextSource(), $oTopic->getExtra(), $oTopic->getId());
     return $this->IsSuccessful($res);
 }
예제 #20
0
 /**
  * Обработка редактирования топика
  *
  * @param ModuleTopic_EntityTopic $oTopic
  * @return mixed
  */
 protected function SubmitEdit($oTopic)
 {
     $oTopic->_setValidateScenario('topic');
     /**
      * Сохраняем старое значение идентификатора блога
      */
     $sBlogIdOld = $oTopic->getBlogId();
     /**
      * Заполняем поля для валидации
      */
     $oTopic->setBlogId(getRequestStr('blog_id'));
     $oTopic->setTitle(strip_tags(getRequestStr('topic_title')));
     $oTopic->setTextSource(getRequestStr('topic_text'));
     $oTopic->setTags(getRequestStr('topic_tags'));
     $oTopic->setUserIp(func_getIp());
     /**
      * Проверка корректности полей формы
      */
     if (!$this->checkTopicFields($oTopic)) {
         return false;
     }
     /**
      * Определяем в какой блог делаем запись
      */
     $iBlogId = $oTopic->getBlogId();
     if ($iBlogId == 0) {
         $oBlog = $this->Blog_GetPersonalBlogByUserId($oTopic->getUserId());
     } else {
         $oBlog = $this->Blog_GetBlogById($iBlogId);
     }
     /**
      * Если блог не определен выдаем предупреждение
      */
     if (!$oBlog) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_unknown'), $this->Lang_Get('error'));
         return false;
     }
     /**
      * Проверяем права на постинг в блог
      */
     if (!$this->ACL_IsAllowBlog($oBlog, $this->oUserCurrent)) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_noallow'), $this->Lang_Get('error'));
         return false;
     }
     /**
      * Проверяем разрешено ли постить топик по времени
      */
     if (isPost('submit_topic_publish') and !$oTopic->getPublishDraft() and !$this->ACL_CanPostTopicTime($this->oUserCurrent)) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic_time_limit'), $this->Lang_Get('error'));
         return;
     }
     $oTopic->setBlogId($oBlog->getId());
     /**
      * Получаемый и устанавливаем разрезанный текст по тегу <cut>
      */
     list($sTextShort, $sTextNew, $sTextCut) = $this->Text_Cut($oTopic->getTextSource());
     $oTopic->setCutText($sTextCut);
     $oTopic->setText($this->Text_Parser($sTextNew));
     $oTopic->setTextShort($this->Text_Parser($sTextShort));
     /**
      * Публикуем или сохраняем в черновиках
      */
     $bSendNotify = false;
     if (isset($_REQUEST['submit_topic_publish'])) {
         $oTopic->setPublish(1);
         if ($oTopic->getPublishDraft() == 0) {
             $oTopic->setPublishDraft(1);
             $oTopic->setDateAdd(date("Y-m-d H:i:s"));
             $bSendNotify = true;
         }
     } else {
         $oTopic->setPublish(0);
     }
     /**
      * Принудительный вывод на главную
      */
     if ($this->ACL_IsAllowPublishIndex($this->oUserCurrent)) {
         if (getRequest('topic_publish_index')) {
             $oTopic->setPublishIndex(1);
         } else {
             $oTopic->setPublishIndex(0);
         }
     }
     /**
      * Запрет на комментарии к топику
      */
     $oTopic->setForbidComment(0);
     if (getRequest('topic_forbid_comment')) {
         $oTopic->setForbidComment(1);
     }
     $this->Hook_Run('topic_edit_before', array('oTopic' => $oTopic, 'oBlog' => $oBlog));
     /**
      * Сохраняем топик
      */
     if ($this->Topic_UpdateTopic($oTopic)) {
         $this->Hook_Run('topic_edit_after', array('oTopic' => $oTopic, 'oBlog' => $oBlog, 'bSendNotify' => &$bSendNotify));
         /**
          * Обновляем данные в комментариях, если топик был перенесен в новый блог
          */
         if ($sBlogIdOld != $oTopic->getBlogId()) {
             $this->Comment_UpdateTargetParentByTargetId($oTopic->getBlogId(), 'topic', $oTopic->getId());
             $this->Comment_UpdateTargetParentByTargetIdOnline($oTopic->getBlogId(), 'topic', $oTopic->getId());
         }
         /**
          * Обновляем количество топиков в блоге
          */
         if ($sBlogIdOld != $oTopic->getBlogId()) {
             $this->Blog_RecalculateCountTopicByBlogId($sBlogIdOld);
         }
         $this->Blog_RecalculateCountTopicByBlogId($oTopic->getBlogId());
         /**
          * Добавляем событие в ленту
          */
         $this->Stream_write($oTopic->getUserId(), 'add_topic', $oTopic->getId(), $oTopic->getPublish() && $oBlog->getType() != 'close');
         /**
          * Рассылаем о новом топике подписчикам блога
          */
         if ($bSendNotify) {
             $this->Topic_SendNotifyTopicNew($oBlog, $oTopic, $oTopic->getUser());
         }
         if (!$oTopic->getPublish() and !$this->oUserCurrent->isAdministrator() and $this->oUserCurrent->getId() != $oTopic->getUserId()) {
             Router::Location($oBlog->getUrlFull());
         }
         Router::Location($oTopic->getUrl());
     } else {
         $this->Message_AddErrorSingle($this->Lang_Get('system_error'));
         return Router::Action('error');
     }
 }
예제 #21
0
 /**
  * Обновляет топик
  *
  * @param ModuleTopic_EntityTopic $oTopic	Объект топика
  * @return bool
  */
 public function UpdateTopic(ModuleTopic_EntityTopic $oTopic)
 {
     /**
      * Получаем топик ДО изменения
      */
     $oTopicOld = $this->GetTopicById($oTopic->getId());
     $oTopic->setDateEdit(date("Y-m-d H:i:s"));
     if ($this->oMapperTopic->UpdateTopic($oTopic)) {
         /**
          * Если топик изменил видимость(publish) или локацию (BlogId) или список тегов
          */
         if ($oTopic->getPublish() != $oTopicOld->getPublish() || $oTopic->getBlogId() != $oTopicOld->getBlogId() || $oTopic->getTags() != $oTopicOld->getTags()) {
             /**
              * Обновляем теги
              */
             $this->DeleteTopicTagsByTopicId($oTopic->getId());
             if ($oTopic->getPublish() and $oTopic->getTags()) {
                 $aTags = explode(',', $oTopic->getTags());
                 foreach ($aTags as $sTag) {
                     $oTag = Engine::GetEntity('Topic_TopicTag');
                     $oTag->setTopicId($oTopic->getId());
                     $oTag->setUserId($oTopic->getUserId());
                     $oTag->setBlogId($oTopic->getBlogId());
                     $oTag->setText($sTag);
                     $this->AddTopicTag($oTag);
                 }
             }
         }
         if ($oTopic->getPublish() != $oTopicOld->getPublish()) {
             /**
              * Обновляем избранное
              */
             $this->SetFavouriteTopicPublish($oTopic->getId(), $oTopic->getPublish());
             /**
              * Удаляем комментарий топика из прямого эфира
              */
             if ($oTopic->getPublish() == 0) {
                 $this->Comment_DeleteCommentOnlineByTargetId($oTopic->getId(), 'topic');
             }
             /**
              * Изменяем видимость комментов
              */
             $this->Comment_SetCommentsPublish($oTopic->getId(), 'topic', $oTopic->getPublish());
         }
         //чистим зависимые кеши
         $this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('topic_update', "topic_update_user_{$oTopic->getUserId()}"));
         $this->Cache_Delete("topic_{$oTopic->getId()}");
         return true;
     }
     return false;
 }
예제 #22
0
 /**
  * Обработка редактирования топика
  *
  * @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');
     }
 }
예제 #23
0
 /**
  * @param ModuleTopic_EntityTopic $oTopic
  * @param null $sTargetTmp
  * @return bool
  */
 public function AttachTmpPhotoToTopic($oTopic, $sTargetTmp = null)
 {
     if (is_null($sTargetTmp)) {
         $sTargetTmp = E::ModuleSession()->GetCookie(ModuleUploader::COOKIE_TARGET_TMP);
     }
     E::ModuleMresource()->ResetTmpRelById($sTargetTmp, $oTopic->getId());
     return $this->oMapper->attachTmpPhotoToTopic($oTopic, $sTargetTmp);
 }
예제 #24
0
    protected function updateAccessLevel(ModuleTopic_EntityTopic $oTopic)
    {
        $sql = 'UPDATE ' . Config::Get('db.table.topic') . ' 
			SET 
				access_level = ?d
			WHERE
				topic_id = ?d
		';
        if ($this->oDb->query($sql, $oTopic->getAccessLevel(), $oTopic->getId()) !== null) {
            return true;
        }
        return false;
    }