예제 #1
0
 /**
  * Обработка ajax-запроса на удаление приглашения подписаться на приватный блог
  *
  */
 protected function AjaxRemoveBlogInvite()
 {
     //  Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json');
     $sUserId = F::GetRequestStr('idUser', null, 'post');
     $sBlogId = F::GetRequestStr('idBlog', null, 'post');
     //  Если пользователь не авторизирован, возвращаем ошибку
     if (!E::ModuleUser()->IsAuthorization()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return;
     }
     $this->oUserCurrent = E::ModuleUser()->GetUserCurrent();
     //  Проверяем существование блога
     if (!($oBlog = E::ModuleBlog()->GetBlogById($sBlogId))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     $this->oCurrentBlog = $oBlog;
     //  Пользователь существует и активен?
     $oUser = E::ModuleUser()->GetUserById($sUserId);
     if (!$oUser || $oUser->getActivate() != 1) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     //  Проверяем, имеет ли право текущий пользователь добавлять invite в blog
     $oBlogUser = E::ModuleBlog()->GetBlogUserByBlogIdAndUserId($oBlog->getId(), $this->oUserCurrent->getId());
     $bBlogAdministrator = $oBlogUser ? $oBlogUser->IsBlogAdministrator() : false;
     if ($oBlog->getOwnerId() != $this->oUserCurrent->getId() && !$this->oUserCurrent->isAdministrator() && !$this->oUserCurrent->isModerator() && !$bBlogAdministrator) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     $oBlogUser = E::ModuleBlog()->GetBlogUserByBlogIdAndUserId($oBlog->getId(), $oUser->getId());
     if ($oBlogUser->getUserRole() == ModuleBlog::BLOG_USER_ROLE_INVITE) {
         //  Удаляем связь/приглашение
         E::ModuleBlog()->DeleteRelationBlogUser($oBlogUser);
         E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('blog_user_invite_remove_ok', array('login' => $oUser->getLogin())), E::ModuleLang()->Get('attention'));
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
     }
 }
예제 #2
0
 /**
  * Возвращает доступные для создания пользователем типы контента
  *
  * @param ModuleUser_EntityUser $oUser
  *
  * @return ModuleTopic_EntityContentType[]
  */
 public function GetAllowContentTypeByUserId($oUser)
 {
     if ($oUser && ($oUser->isAdministrator() || $oUser->isModerator())) {
         // Для админа и модератора доступны все активные типы контента
         /** @var ModuleTopic_EntityContentType[] $aContentTypes */
         $aContentTypes = E::ModuleTopic()->GetContentTypes(array('content_active' => 1));
         return $aContentTypes;
     }
     // Получим все блоги пользователя
     $aBlogs = E::ModuleBlog()->GetBlogsAllowByUser($oUser, false);
     // Добавим персональный блог пользователю
     if ($oUser) {
         $aBlogs[] = E::ModuleBlog()->GetPersonalBlogByUserId($oUser->getId());
     }
     // Получим типы контента
     /** @var ModuleTopic_EntityContentType[] $aContentTypes */
     $aContentTypes = E::ModuleTopic()->GetContentTypes(array('content_active' => 1));
     $aAllowContentTypes = array();
     /** @var ModuleBlog_EntityBlog $oBlog */
     foreach ($aBlogs as $oBlog) {
         // Пропускаем блог, если в него нельзя добавлять топики
         if (!E::ModuleACL()->CanAddTopic($oUser, $oBlog)) {
             continue;
         }
         if ($aContentTypes) {
             foreach ($aContentTypes as $k => $oContentType) {
                 if ($oBlog->IsContentTypeAllow($oContentType->getContentUrl())) {
                     $aAllowContentTypes[] = $oContentType;
                     // Удалим, что бы повторное не проверять, ведь в каком-то
                     // блоге пользвоателя этот тип контента уже разрешён
                     unset($aContentTypes[$k]);
                 }
             }
         }
     }
     return $aAllowContentTypes;
 }
예제 #3
0
 /**
  * Проверка на ограничение по времени на постинг на стене
  *
  * @param ModuleUser_EntityUser $oUser    Пользователь
  * @param ModuleWall_EntityWall $oWall    Объект сообщения на стене
  *
  * @return bool
  */
 public function CanAddWallTime($oUser, $oWall)
 {
     // * Для администраторов ограничение по времени не действует
     if ($oUser->isAdministrator() || $oUser->isModerator() || Config::Get('acl.create.wall.limit_time') == 0 || $oUser->getRating() >= Config::Get('acl.create.wall.limit_time_rating')) {
         return true;
     }
     if ($oWall->getUserId() == $oWall->getWallUserId()) {
         return true;
     }
     // * Получаем последнее сообщение
     $aWall = E::ModuleWall()->GetWall(array('user_id' => $oWall->getUserId()), array('id' => 'desc'), 1, 1, array());
     // * Если сообщений нет
     if ($aWall['count'] == 0) {
         return true;
     }
     $oWallLast = array_shift($aWall['collection']);
     $sDate = strtotime($oWallLast->getDateAdd());
     if ($sDate && time() - $sDate < Config::Get('acl.create.wall.limit_time')) {
         return false;
     }
     return true;
 }
예제 #4
0
 /**
  * Возвращает список доступных типов для определенного действия
  *
  * @param ModuleUser_EntityUser $oUser
  * @param string                $sAction
  * @param bool                  $bTypeCodesOnly
  *
  * @return array
  */
 public function GetAllowBlogTypes($oUser, $sAction, $bTypeCodesOnly = false)
 {
     $aFilter = array('exclude_type' => in_array($sAction, array('add', 'list')) ? 'personal' : null, 'is_active' => true);
     if ($sAction && !in_array($sAction, array('add', 'list', 'write'))) {
         return array();
     }
     if (!$oUser) {
         // Если пользователь не задан
         if ($sAction == 'add') {
             $aFilter['allow_add'] = true;
         } elseif ($sAction == 'list') {
             $aFilter['allow_list'] = true;
         }
     } elseif ($oUser && !$oUser->IsAdministrator() && !$oUser->isModerator()) {
         // Если пользователь задан и он не админ, то надо учитывать рейтинг
         if ($sAction == 'add') {
             $aFilter['allow_add'] = true;
             $aFilter['min_rate_add'] = $oUser->GetUserRating();
         } elseif ($sAction == 'list') {
             $aFilter['allow_list'] = true;
             $aFilter['min_rate_list'] = $oUser->GetUserRating();
         } elseif ($sAction == 'write') {
             $aFilter['min_rate_write'] = $oUser->GetUserRating();
         }
     }
     $aBlogTypes = $this->GetBlogTypes($aFilter, $bTypeCodesOnly);
     return $aBlogTypes;
 }
예제 #5
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');
     }
 }