ActionLink
Package | actions |
---|---|
Inheritance | class ActionLink » Action » LsObject |
Since | 1.0 |
Source Code | /classes/actions/ActionLink.class.php |
Экшен обработки УРЛа вида /link/ - управление своими топиками(тип: ссылка)
Protected Properties
Property | Type | Description | Defined By |
---|---|---|---|
aParams | array | Список параметров из URL | Action |
aParamsEventMatch | array | Список совпадений по регулярному выражению для евента | Action |
aRegisterEvent | array | Список зарегистрированных евентов | Action |
oEngine | Engine|null | Объект ядра | Action |
oUserCurrent | ModuleUser_EntityUser|null | Текущий юзер | ActionLink |
sActionTemplate | string|null | Шаблон экшена | Action |
sCurrentAction | null|string | Текущий экшен | Action |
sCurrentEvent | string|null | Текущий евент | Action |
sCurrentEventName | string|null | Имя текущий евента | Action |
sDefaultEvent | string|null | Дефолтный евент | Action |
sMenuHeadItemSelect | string | Главное меню | ActionLink |
sMenuItemSelect | string | Меню | ActionLink |
sMenuSubItemSelect | string | СубМеню | ActionLink |
Public Methods
Method | Description | Defined By |
---|---|---|
EventShutdown() | При завершении экшена загружаем необходимые переменные | ActionLink |
ExecEvent() | Запускает евент на выполнение | Action |
GetActionClass() | Получить каталог с шаблонами экшена(совпадает с именем класса) | Action |
GetCurrentEventName() | Возвращает имя евента | Action |
GetDefaultEvent() | Получает евент по умолчанию | Action |
GetParam() | Получает параметр из URL по его номеру, если его нет то null | Action |
GetParams() | Получает список параметров из УРЛ | Action |
GetTemplate() | Получить шаблон | Action |
Init() | Инициализация | ActionLink |
SetDefaultEvent() | Устанавливает евент по умолчанию | Action |
SetParam() | Установить значение параметра(эмуляция параметра в URL). | Action |
__call() | Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля | Action |
__construct() | Конструктор | Action |
Protected Methods
Method | Description | Defined By |
---|---|---|
AddEvent() | Добавляет евент в экшен | Action |
AddEventPreg() | Добавляет евент в экшен, используя регулярное вырожение для евента и параметров | Action |
EventAdd() | Добавление топика-ссылки | ActionLink |
EventEdit() | Редактирование топика-ссылки | ActionLink |
EventGo() | Переход по ссылке с подсчетом количества переходов | ActionLink |
EventNotFound() | Вызывается в том случаи если не найден евент который запросили через URL | Action |
GetEventMatch() | Возвращает элементы совпадения по регулярному выражению для евента | Action |
GetParamEventMatch() | Возвращает элементы совпадения по регулярному выражению для параметров евента | Action |
RegisterEvent() | Регистрируем евенты | ActionLink |
SetTemplate() | Устанавливает какой шаблон выводить | Action |
SetTemplateAction() | Устанавливает какой шаблон выводить | Action |
SubmitAdd() | Обработка добавлени топика | ActionLink |
SubmitEdit() | Обработка редактирования топика | ActionLink |
checkTopicFields() | Проверка полей формы | ActionLink |
Property Details
oUserCurrent
property
protected ModuleUser_EntityUser|null $oUserCurrent;
Текущий юзер
sMenuHeadItemSelect
property
protected string $sMenuHeadItemSelect;
Главное меню
sMenuItemSelect
property
protected string $sMenuItemSelect;
Меню
sMenuSubItemSelect
property
protected string $sMenuSubItemSelect;
СубМеню
Method Details
EventAdd()
method
protected void EventAdd()
|
Source Code: /classes/actions/ActionLink.class.php#183 (show)
protected function EventAdd() {
/**
* Проверяем авторизован ли юзер
*/
if (!$this->User_IsAuthorization()) {
$this->Message_AddErrorSingle($this->Lang_Get('not_access'),$this->Lang_Get('error'));
return Router::Action('error');
}
/**
* Вызов хуков
*/
$this->Hook_Run('topic_add_show');
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aBlogsAllow',$this->Blog_GetBlogsAllowByUser($this->oUserCurrent));
$this->Viewer_AddHtmlTitle($this->Lang_Get('topic_link_title_create'));
/**
* Обрабатываем отправку формы
*/
return $this->SubmitAdd();
}
Добавление топика-ссылки
EventEdit()
method
protected void EventEdit()
|
Source Code: /classes/actions/ActionLink.class.php#116 (show)
protected function EventEdit() {
/**
* Проверяем авторизован ли юзер
*/
if (!$this->User_IsAuthorization()) {
$this->Message_AddErrorSingle($this->Lang_Get('not_access'),$this->Lang_Get('error'));
return Router::Action('error');
}
/**
* Получаем номер топика из УРЛ и проверяем существует ли он
*/
$sTopicId=$this->GetParam(0);
if (!($oTopic=$this->Topic_GetTopicById($sTopicId))) {
return parent::EventNotFound();
}
/**
* Проверяем тип топика
*/
if ($oTopic->getType()!='link') {
return parent::EventNotFound();
}
/**
* Если права на редактирование
*/
if (!$this->ACL_IsAllowEditTopic($oTopic,$this->oUserCurrent)) {
return parent::EventNotFound();
}
/**
* Вызов хуков
*/
$this->Hook_Run('topic_edit_show',array('oTopic'=>$oTopic));
/**
* Загружаем переменные в шаблон
*/
$this->Viewer_Assign('aBlogsAllow',$this->Blog_GetBlogsAllowByUser($this->oUserCurrent));
$this->Viewer_AddHtmlTitle($this->Lang_Get('topic_link_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_link_url']=$oTopic->getLinkUrl();
$_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();
}
}
Редактирование топика-ссылки
EventGo()
method
protected void EventGo()
|
Source Code: /classes/actions/ActionLink.class.php#88 (show)
protected function EventGo() {
/**
* Получаем номер топика из УРЛ и проверяем существует ли он
*/
$sTopicId=$this->GetParam(0);
if (!($oTopic=$this->Topic_GetTopicById($sTopicId)) or !$oTopic->getPublish()) {
return parent::EventNotFound();
}
/**
* проверяем является ли топик ссылкой
*/
if ($oTopic->getType()!='link') {
return parent::EventNotFound();
}
/**
* увелививаем число переходов по ссылке
*/
$oTopic->setLinkCountJump($oTopic->getLinkCountJump()+1);
$this->Topic_UpdateTopic($oTopic);
/**
* собственно сам переход по ссылке
*/
Router::Location($oTopic->getLinkUrl());
}
Переход по ссылке с подсчетом количества переходов
EventShutdown()
method
public void EventShutdown()
|
Source Code: /classes/actions/ActionLink.class.php#492 (show)
public function EventShutdown() {
$this->Viewer_Assign('sMenuHeadItemSelect',$this->sMenuHeadItemSelect);
$this->Viewer_Assign('sMenuItemSelect',$this->sMenuItemSelect);
$this->Viewer_Assign('sMenuSubItemSelect',$this->sMenuSubItemSelect);
}
При завершении экшена загружаем необходимые переменные
Init()
method
public void Init()
|
Source Code: /classes/actions/ActionLink.class.php#54 (show)
public function Init() {
/**
* Получаем текущего пользователя
*/
$this->oUserCurrent=$this->User_GetUserCurrent();
/**
* Устанавливаем дефолтный евент
*/
$this->SetDefaultEvent('add');
/**
* Устанавливаем title страницы
*/
$this->Viewer_AddHtmlTitle($this->Lang_Get('topic_link_title'));
}
Инициализация
RegisterEvent()
method
protected void RegisterEvent()
|
Source Code: /classes/actions/ActionLink.class.php#72 (show)
protected function RegisterEvent() {
$this->AddEvent('add','EventAdd');
$this->AddEvent('edit','EventEdit');
$this->AddEvent('go','EventGo');
}
Регистрируем евенты
SubmitAdd()
method
protected mixed SubmitAdd()
| ||
{return} | mixed |
Source Code: /classes/actions/ActionLink.class.php#210 (show)
protected function SubmitAdd() {
/**
* Проверяем отправлена ли форма с данными(хотяб одна кнопка)
*/
if (!isPost('submit_topic_publish') and !isPost('submit_topic_save')) {
return false;
}
$oTopic=Engine::GetEntity('Topic');
$oTopic->_setValidateScenario('link');
/**
* Заполняем поля для валидации
*/
$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('link');
$oTopic->setLinkUrl(getRequest('topic_link_url'));
$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) {
$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 !$this->ACL_CanPostTopicTime($this->oUserCurrent)) {
$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);
/**
* Публикуем или сохраняем
*/
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);
}
/**
* Запускаем выполнение хуков
*/
$this->Hook_Run('topic_add_before', array('oTopic'=>$oTopic,'oBlog'=>$oBlog));
/**
* Добавляем топик
*/
if ($this->Topic_AddTopic($oTopic)) {
$this->Hook_Run('topic_add_after', array('oTopic'=>$oTopic,'oBlog'=>$oBlog));
/**
* Получаем топик, чтоб подцепить связанные данные
*/
$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') {
$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 {
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
return Router::Action('error');
}
}
Обработка добавлени топика
SubmitEdit()
method
protected mixed SubmitEdit(ModuleTopic_EntityTopic $oTopic)
| ||
$oTopic | ModuleTopic_EntityTopic | |
{return} | mixed |
Source Code: /classes/actions/ActionLink.class.php#341 (show)
protected function SubmitEdit($oTopic) {
$oTopic->_setValidateScenario('link');
/**
* Сохраняем старое значение идентификатора блога
*/
$sBlogIdOld = $oTopic->getBlogId();
/**
* Заполняем поля для валидации
*/
$oTopic->setBlogId(getRequest('blog_id'));
$oTopic->setTitle(strip_tags(getRequest('topic_title')));
$oTopic->setLinkUrl(getRequest('topic_link_url'));
$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) {
$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());
$oTopic->setText($this->Text_Parser($oTopic->getTextSource()));
$oTopic->setTextShort($oTopic->getText());
/**
* Публикуем или сохраняем в черновиках
*/
$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,$this->oUserCurrent);
}
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');
}
}
Обработка редактирования топика
checkTopicFields()
method
protected bool checkTopicFields(ModuleTopic_EntityTopic $oTopic)
| ||
$oTopic | ModuleTopic_EntityTopic | |
{return} | bool |
Source Code: /classes/actions/ActionLink.class.php#474 (show)
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;
}
Проверка полей формы