1
0
Fork 0
mirror of https://github.com/Oreolek/ifhub.club.git synced 2024-07-02 22:45:02 +03:00
ifhub.club/classes/actions/ActionQuestion.class.php

519 lines
16 KiB
PHP
Raw Normal View History

<?php
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Экшен обработки УРЛа вида /question/ - управление своими топиками(тип: вопрос)
*
* @package actions
* @since 1.0
*/
class ActionQuestion extends Action {
/**
* Главное меню
*
* @var string
*/
protected $sMenuHeadItemSelect='blog';
/**
* Меню
*
* @var string
*/
protected $sMenuItemSelect='topic';
/**
* СубМеню
*
* @var string
*/
protected $sMenuSubItemSelect='question';
/**
* Текущий юзер
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent=null;
/**
* Инициализация
*
*/
public function Init() {
/**
* Проверяем авторизован ли юзер
*/
if (!$this->User_IsAuthorization()) {
2009-04-07 17:59:43 +03:00
$this->Message_AddErrorSingle($this->Lang_Get('not_access'),$this->Lang_Get('error'));
return Router::Action('error');
}
$this->oUserCurrent=$this->User_GetUserCurrent();
$this->SetDefaultEvent('add');
/**
* Устанавливаем title страницы
*/
2009-04-07 17:59:43 +03:00
$this->Viewer_AddHtmlTitle($this->Lang_Get('topic_question_title'));
2011-08-23 17:19:32 +03:00
/**
* Загружаем в шаблон JS текстовки
*/
$this->Lang_AddLangJs(array(
'topic_question_create_answers_error_max','delete'
));
}
/**
* Регистрируем евенты
*
*/
protected function RegisterEvent() {
$this->AddEvent('add','EventAdd');
$this->AddEvent('edit','EventEdit');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Редактирование топика
*
*/
protected function EventEdit() {
/**
* Получаем номер топика из УРЛ и проверяем существует ли он
*/
$sTopicId=$this->GetParam(0);
2009-07-03 23:48:44 +03:00
if (!($oTopic=$this->Topic_GetTopicById($sTopicId))) {
return parent::EventNotFound();
}
/**
* Проверяем тип топика
*/
if ($oTopic->getType()!='question') {
return parent::EventNotFound();
}
/**
2009-07-03 23:48:44 +03:00
* Если права на редактирование
*/
if (!$this->ACL_IsAllowEditTopic($oTopic,$this->oUserCurrent)) {
return parent::EventNotFound();
}
/**
2009-07-03 23:48:44 +03:00
* Вызов хуков
*/
2009-07-03 23:48:44 +03:00
$this->Hook_Run('topic_edit_show',array('oTopic'=>$oTopic));
/**
* Загружаем переменные в шаблон
*/
2009-07-03 23:48:44 +03:00
$this->Viewer_Assign('aBlogsAllow',$this->Blog_GetBlogsAllowByUser($this->oUserCurrent));
$this->Viewer_Assign('bEditDisabled',$oTopic->getQuestionCountVote()==0 ? false : true);
2009-04-07 17:59:43 +03:00
$this->Viewer_AddHtmlTitle($this->Lang_Get('topic_question_title_edit'));
/**
* Устанавливаем шаблон вывода
*/
$this->SetTemplateAction('add');
/**
* Проверяем отправлена ли форма с данными(хотяб одна кнопка)
*/
if (isset($_REQUEST['submit_topic_publish']) or isset($_REQUEST['submit_topic_save'])) {
/**
* Обрабатываем отправку формы
*/
return $this->SubmitEdit($oTopic);
} else {
/**
* Заполняем поля формы для редактирования
* Только перед отправкой формы!
*/
$_REQUEST['topic_title']=$oTopic->getTitle();
$_REQUEST['topic_text']=$oTopic->getTextSource();
$_REQUEST['topic_tags']=$oTopic->getTags();
$_REQUEST['blog_id']=$oTopic->getBlogId();
$_REQUEST['topic_id']=$oTopic->getId();
$_REQUEST['topic_publish_index']=$oTopic->getPublishIndex();
$_REQUEST['topic_forbid_comment']=$oTopic->getForbidComment();
$_REQUEST['answer']=array();
$aAnswers=$oTopic->getQuestionAnswers();
foreach ($aAnswers as $aAnswer) {
$_REQUEST['answer'][]=$aAnswer['text'];
}
}
}
/**
* Добавление топика
*
*/
protected function EventAdd() {
2012-04-09 17:36:41 +03:00
/**
* Вызов хуков
*/
$this->Hook_Run('topic_add_show');
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aBlogsAllow',$this->Blog_GetBlogsAllowByUser($this->oUserCurrent));
$this->Viewer_Assign('bEditDisabled',false);
2009-04-07 17:59:43 +03:00
$this->Viewer_AddHtmlTitle($this->Lang_Get('topic_question_title_create'));
/**
* Обрабатываем отправку формы
*/
return $this->SubmitAdd();
}
/**
* Обработка добавлени топика
*
* @return mixed
*/
protected function SubmitAdd() {
/**
* Проверяем отправлена ли форма с данными(хотяб одна кнопка)
*/
if (!isPost('submit_topic_publish') and !isPost('submit_topic_save')) {
return false;
}
$oTopic=Engine::GetEntity('Topic');
$oTopic->_setValidateScenario('question');
/**
* Заполняем поля для валидации
*/
$oTopic->setBlogId(getRequest('blog_id'));
$oTopic->setTitle(strip_tags(getRequest('topic_title')));
$oTopic->setTextSource(getRequest('topic_text'));
$oTopic->setTags(getRequest('topic_tags'));
$oTopic->setUserId($this->oUserCurrent->getId());
$oTopic->setType('question');
$oTopic->setDateAdd(date("Y-m-d H:i:s"));
$oTopic->setUserIp(func_getIp());
/**
* Проверка корректности полей формы
*/
if (!$this->checkTopicFields($oTopic)) {
return false;
}
/**
* Определяем в какой блог делаем запись
*/
$iBlogId=$oTopic->getBlogId();
if ($iBlogId==0) {
$oBlog=$this->Blog_GetPersonalBlogByUserId($this->oUserCurrent->getId());
} else {
$oBlog=$this->Blog_GetBlogById($iBlogId);
}
/**
* Если блог не определен выдаем предупреждение
*/
if (!$oBlog) {
2009-04-07 17:59:43 +03:00
$this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_unknown'),$this->Lang_Get('error'));
return false;
}
/**
2009-07-03 23:48:44 +03:00
* Проверяем права на постинг в блог
*/
if (!$this->ACL_IsAllowBlog($oBlog,$this->oUserCurrent)) {
2009-07-03 23:48:44 +03:00
$this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_noallow'),$this->Lang_Get('error'));
return false;
}
2010-01-30 21:40:21 +02:00
/**
* Проверяем разрешено ли постить топик по времени
*/
if (isPost('submit_topic_publish') and !$this->ACL_CanPostTopicTime($this->oUserCurrent)) {
2010-01-30 21:40:21 +02:00
$this->Message_AddErrorSingle($this->Lang_Get('topic_time_limit'),$this->Lang_Get('error'));
return;
}
/**
* Теперь можно смело добавлять топик к блогу
*/
$oTopic->setBlogId($oBlog->getId());
$oTopic->setText($this->Text_Parser($oTopic->getTextSource()));
$oTopic->setTextShort($oTopic->getText());
$oTopic->setCutText(null);
/**
* Варианты ответов
*/
$oTopic->clearQuestionAnswer();
foreach (getRequest('answer',array()) as $sAnswer) {
$oTopic->addQuestionAnswer($sAnswer);
}
/**
* Публикуем или сохраняем
*/
if (isset($_REQUEST['submit_topic_publish'])) {
$oTopic->setPublish(1);
$oTopic->setPublishDraft(1);
} else {
$oTopic->setPublish(0);
$oTopic->setPublishDraft(0);
}
/**
* Принудительный вывод на главную
*/
$oTopic->setPublishIndex(0);
if ($this->ACL_IsAllowPublishIndex($this->oUserCurrent)) {
if (getRequest('topic_publish_index')) {
$oTopic->setPublishIndex(1);
}
}
/**
* Запрет на комментарии к топику
*/
$oTopic->setForbidComment(0);
if (getRequest('topic_forbid_comment')) {
$oTopic->setForbidComment(1);
}
2010-08-21 10:33:54 +03:00
/**
* Запускаем выполнение хуков
*/
$this->Hook_Run('topic_add_before', array('oTopic'=>$oTopic,'oBlog'=>$oBlog));
/**
* Добавляем топик
*/
if ($this->Topic_AddTopic($oTopic)) {
2010-08-21 10:33:54 +03:00
$this->Hook_Run('topic_add_after', array('oTopic'=>$oTopic,'oBlog'=>$oBlog));
/**
* Получаем топик, чтоб подцепить связанные данные
*/
2009-07-03 23:48:44 +03:00
$oTopic=$this->Topic_GetTopicById($oTopic->getId());
/**
* Обновляем количество топиков в блоге
*/
$this->Blog_RecalculateCountTopicByBlogId($oTopic->getBlogId());
/**
* Добавляем автора топика в подписчики на новые комментарии к этому топику
*/
$this->Subscribe_AddSubscribeSimple('topic_new_comment',$oTopic->getId(),$this->oUserCurrent->getMail());
//Делаем рассылку спама всем, кто состоит в этом блоге
if ($oTopic->getPublish()==1 and $oBlog->getType()!='personal') {
2009-07-03 23:48:44 +03:00
$this->Topic_SendNotifyTopicNew($oBlog,$oTopic,$this->oUserCurrent);
}
/**
* Добавляем событие в ленту
*/
$this->Stream_write($oTopic->getUserId(), 'add_topic', $oTopic->getId(),$oTopic->getPublish() && $oBlog->getType()!='close');
Router::Location($oTopic->getUrl());
} else {
2009-04-07 17:59:43 +03:00
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
return Router::Action('error');
}
}
/**
* Обработка редактирования топика
*
* @param ModuleTopic_EntityTopic $oTopic
* @return mixed
*/
protected function SubmitEdit($oTopic) {
$oTopic->_setValidateScenario('question');
/**
* Сохраняем старое значение идентификатора блога
*/
$sBlogIdOld = $oTopic->getBlogId();
/**
* Заполняем поля для валидации
*/
$oTopic->setBlogId(getRequest('blog_id'));
if ($oTopic->getQuestionCountVote()==0) {
$oTopic->setTitle(strip_tags(getRequest('topic_title')));
}
$oTopic->setTextSource(getRequest('topic_text'));
$oTopic->setTags(getRequest('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) {
2009-04-07 17:59:43 +03:00
$this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_unknown'),$this->Lang_Get('error'));
return false;
}
/**
2009-07-03 23:48:44 +03:00
* Проверяем права на постинг в блог
*/
if (!$this->ACL_IsAllowBlog($oBlog,$this->oUserCurrent)) {
2009-07-03 23:48:44 +03:00
$this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_noallow'),$this->Lang_Get('error'));
return false;
}
2010-01-30 21:40:21 +02:00
/**
* Проверяем разрешено ли постить топик по времени
*/
if (isPost('submit_topic_publish') and !$oTopic->getPublishDraft() and !$this->ACL_CanPostTopicTime($this->oUserCurrent)) {
2010-01-30 21:40:21 +02:00
$this->Message_AddErrorSingle($this->Lang_Get('topic_time_limit'),$this->Lang_Get('error'));
return;
}
/**
* Теперь можно смело редактировать топик
*/
$oTopic->setBlogId($oBlog->getId());
$oTopic->setText($this->Text_Parser($oTopic->getTextSource()));
$oTopic->setTextShort($oTopic->getText());
/**
* изменяем вопрос/ответы только если еще никто не голосовал
*/
if ($oTopic->getQuestionCountVote()==0) {
$oTopic->clearQuestionAnswer();
foreach (getRequest('answer',array()) as $sAnswer) {
$oTopic->addQuestionAnswer($sAnswer);
}
}
/**
* Публикуем или сохраняем в черновиках
*/
2009-07-03 23:48:44 +03:00
$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"));
2009-07-03 23:48:44 +03:00
$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);
2010-08-21 10:33:54 +03:00
}
$this->Hook_Run('topic_edit_before', array('oTopic'=>$oTopic,'oBlog'=>$oBlog));
/**
* Сохраняем топик
*/
if ($this->Topic_UpdateTopic($oTopic)) {
2010-08-21 10:33:54 +03:00
$this->Hook_Run('topic_edit_after', array('oTopic'=>$oTopic,'oBlog'=>$oBlog,'bSendNotify'=>&$bSendNotify));
2009-07-03 23:48:44 +03:00
/**
* Обновляем данные в комментариях, если топик был перенесен в новый блог
*/
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');
/**
2009-07-03 23:48:44 +03:00
* Рассылаем о новом топике подписчикам блога
*/
if ($bSendNotify) {
$this->Topic_SendNotifyTopicNew($oBlog,$oTopic,$this->oUserCurrent);
}
2008-11-04 23:46:28 +02:00
if (!$oTopic->getPublish() and !$this->oUserCurrent->isAdministrator() and $this->oUserCurrent->getId()!=$oTopic->getUserId()) {
Router::Location($oBlog->getUrlFull());
2008-11-04 23:46:28 +02:00
}
Router::Location($oTopic->getUrl());
} else {
2009-04-07 17:59:43 +03:00
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
return Router::Action('error');
}
}
/**
* Проверка полей формы
*
* @param ModuleTopic_EntityTopic $oTopic
* @return bool
*/
protected function checkTopicFields($oTopic) {
2009-10-20 02:42:23 +03:00
$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) {
if (trim($sAnswer)=='') {
unset($aAnswers[$key]);
continue;
}
if (!func_check($sAnswer,'text',1,100)) {
2009-04-07 17:59:43 +03:00
$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) {
2009-04-07 17:59:43 +03:00
$this->Message_AddError($this->Lang_Get('topic_question_create_answers_error_min'),$this->Lang_Get('error'));
$bOk=false;
}
if (count($aAnswers)>20) {
2009-04-07 17:59:43 +03:00
$this->Message_AddError($this->Lang_Get('topic_question_create_answers_error_max'),$this->Lang_Get('error'));
$bOk=false;
}
}
2010-02-06 14:47:19 +02:00
/**
* Выполнение хуков
*/
2010-02-06 19:47:12 +02:00
$this->Hook_Run('check_question_fields', array('bOk'=>&$bOk));
return $bOk;
}
/**
* При завершении экшена загружаем необходимые переменные
*
*/
public function EventShutdown() {
$this->Viewer_Assign('sMenuHeadItemSelect',$this->sMenuHeadItemSelect);
$this->Viewer_Assign('sMenuItemSelect',$this->sMenuItemSelect);
$this->Viewer_Assign('sMenuSubItemSelect',$this->sMenuSubItemSelect);
}
}
?>