ActionTalk

Package application.actions
Inheritance class ActionTalk » Action » LsObject
Since 1.0
Source Code /application/classes/actions/ActionTalk.class.php
Экшен обработки личной почты (сообщения /talk/)

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
_aBehaviors Список поведений в виде готовых объектов, формируется автоматически LsObject
aBehaviors array Список поведений LsObject
aParams array Список параметров из URL Action
aParamsEventMatch array Список совпадений по регулярному выражению для евента Action
aRegisterEvent array Список зарегистрированных евентов Action
aRegisterEventExternal array Список евентов, которые нужно обрабатывать внешним обработчиком Action
aUsersId array Массив ID юзеров адресатов ActionTalk
oUserCurrent ModuleUser_EntityUser|null Текущий юзер ActionTalk
sActionTemplate string|null Шаблон экшена Action
sCurrentAction null|string Текущий экшен Action
sCurrentEvent string|null Текущий евент Action
sCurrentEventName string|null Имя текущий евента Action
sDefaultEvent string|null Дефолтный евент Action
sMenuSubItemSelect string Подменю ActionTalk

Public Methods

Hide inherited methods

MethodDescriptionDefined By
ActionCall() Позволяет запускать не публичные методы экшена через объект Action
ActionCallExists() Проверяет метод экшена на существование Action
ActionGet() Возвращает свойство объекта экшена Action
ActionSet() Устанавливает свойство объекта экшена Action
AddBehaviorHook() Добавляет хук поведения LsObject
AjaxAddTalkUser() Добавление нового участника разговора (ajax) ActionTalk
AjaxAddToBlacklist() Добавление нового пользователя(-лей) в блек лист (ajax) ActionTalk
AjaxDeleteFromBlacklist() Удаление пользователя из блек листа (ajax) ActionTalk
AjaxDeleteTalkUser() Удаление участника разговора (ajax) ActionTalk
AjaxNewMessages() Возвращает количество новых сообщений ActionTalk
AttachBehavior() Присоединяет поведение к объекту LsObject
DetachBehavior() Отсоединяет поведение от объекта LsObject
EventShutdown() Обработка завершения работу экшена ActionTalk
ExecEvent() Запускает евент на выполнение Action
GetActionClass() Получить каталог с шаблонами экшена(совпадает с именем класса) Action
GetBehavior() Возвращает объект поведения по его имени LsObject
GetBehaviors() Возвращает все объекты поведения LsObject
GetCurrentEventName() Возвращает имя евента Action
GetDefaultEvent() Получает евент по умолчанию Action
GetParam() Получает параметр из URL по его номеру, если его нет то null Action
GetParams() Получает список параметров из УРЛ Action
GetTemplate() Получить шаблон Action
Init() Инициализация ActionTalk
RemoveBehaviorHook() Удаляет хук поведения LsObject
RunBehaviorHook() Запускает хук поведения на выполнение LsObject
SetDefaultEvent() Устанавливает евент по умолчанию Action
SetParam() Установить значение параметра(эмуляция параметра в URL). Action
__call() Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля LsObject
__clone() При клонировании сбрасываем поведения LsObject
__construct() Конструктор Action
__get() Обработка доступа к объекты поведения LsObject

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
AddEvent() Добавляет евент в экшен Action
AddEventPreg() Добавляет евент в экшен, используя регулярное выражение для евента и параметров Action
AjaxAddComment() Обработка добавление комментария к письму через ajax ActionTalk
AjaxResponseComment() Получение новых комментариев ActionTalk
BuildFilter() Формирует из REQUEST массива фильтр для отбора писем ActionTalk
EventAdd() Страница создания письма ActionTalk
EventBlacklist() Отображение списка блэк-листа ActionTalk
EventDelete() Удаление письма ActionTalk
EventErrorDebug() Выводит отладочную информацию в стандартном сообщении Action
EventFavourites() Отображение списка избранных писем ActionTalk
EventInbox() Отображение списка сообщений ActionTalk
EventNotFound() Вызывается в том случаи если не найден евент который запросили через URL Action
EventRead() Чтение письма ActionTalk
GetEventMatch() Возвращает элементы совпадения по регулярному выражению для евента Action
GetParamEventMatch() Возвращает элементы совпадения по регулярному выражению для параметров евента Action
PrepareBehaviors() Инициализация поведений LsObject
RegisterEvent() Регистрация евентов ActionTalk
RegisterEventExternal() Регистрируем внешние обработчики для евентов Action
SetTemplate() Устанавливает какой шаблон выводить Action
SetTemplateAction() Устанавливает какой шаблон выводить Action
SubmitComment() Обработка добавление комментария к письму ActionTalk
checkTalkFields() Проверка полей при создании письма ActionTalk

Property Details

aUsersId property
protected array $aUsersId;

Массив ID юзеров адресатов

oUserCurrent property
protected ModuleUser_EntityUser|null $oUserCurrent;

Текущий юзер

sMenuSubItemSelect property
protected string $sMenuSubItemSelect;

Подменю

Method Details

AjaxAddComment() method
protected void AjaxAddComment()
Source Code: /application/classes/actions/ActionTalk.class.php#632 (show)
protected function AjaxAddComment()
{
    
/**
     * Устанавливаем формат Ajax ответа
     */
    
$this->Viewer_SetResponseAjax('json');
    
$this->SubmitComment();
}

Обработка добавление комментария к письму через ajax

AjaxAddTalkUser() method
public void AjaxAddTalkUser()
Source Code: /application/classes/actions/ActionTalk.class.php#1016 (show)
public function AjaxAddTalkUser()
{
    
/**
     * Устанавливаем формат Ajax ответа
     */
    
$this->Viewer_SetResponseAjax('json');
    
$aUsers getRequest('aUserList'null'post');
    
$idTalk getRequestStr('iTargetId'null'post');
    
/**
     * Валидация
     */
    
if (!is_array($aUsers)) {
        return 
$this->EventErrorDebug();
    }
    
/**
     * Если пользователь не авторизирован, возвращаем ошибку
     */
    
if (!$this->User_IsAuthorization()) {
        
$this->Message_AddErrorSingle(
            
$this->Lang_Get('need_authorization'),
            
$this->Lang_Get('error')
        );
        return;
    }
    
/**
     * Если разговор не найден, или пользователь не является его автором (или админом), возвращаем ошибку
     */
    
if ((!$oTalk $this->Talk_GetTalkById($idTalk))
        || ((
$oTalk->getUserId() != $this->oUserCurrent->getId()) && !$this->oUserCurrent->isAdministrator())
    ) {
        
$this->Message_AddErrorSingle(
            
$this->Lang_Get('talk.notices.not_found'),
            
$this->Lang_Get('error')
        );
        return;
    }
    
/**
     * Получаем список всех участников разговора
     */
    
$aTalkUsers $oTalk->getTalkUsers();
    
/**
     * Получаем список пользователей, которые не принимают письма
     */
    
$aUserInBlacklist $this->Talk_GetBlacklistByTargetId($this->oUserCurrent->getId());
    
/**
     * Ограничения на максимальное число участников разговора
     */
    
if (count($aTalkUsers) >= Config::Get('module.talk.max_users') and !$this->oUserCurrent->isAdministrator()) {
        
$this->Message_AddError($this->Lang_Get('talk.add.notices.users_error_many'), $this->Lang_Get('error'));
        return;
    }
    
/**
     * Обрабатываем добавление по каждому переданному логину пользователя
     */
    
foreach ($aUsers as $sUser) {
        
$sUser trim($sUser);
        if (
$sUser == '') {
            continue;
        }
        
/**
         * Попытка добавить себя
         */
        
if (strtolower($sUser) == strtolower($this->oUserCurrent->getLogin())) {
            
$aResult[] = array(
                
'bStateError' => true,
                
'sMsgTitle'   => $this->Lang_Get('error'),
                
'sMsg'        => $this->Lang_Get('user_list_add.notices.error_self')
            );
            continue;
        }
        if ((
$oUser $this->User_GetUserByLogin($sUser))
            && (
$oUser->getActivate() == 1)
        ) {
            if (!
in_array($oUser->getId(), $aUserInBlacklist)) {
                if (
array_key_exists($oUser->getId(), $aTalkUsers)) {
                    switch (
$aTalkUsers[$oUser->getId()]->getUserActive()) {
                        
/**
                         * Если пользователь ранее был удален админом разговора, то добавляем его снова
                         */
                        
case ModuleTalk::TALK_USER_DELETE_BY_AUTHOR:
                            if (
                            
$this->Talk_AddTalkUser(
                                
Engine::GetEntity('Talk_TalkUser',
                                    array(
                                        
'talk_id'          => $idTalk,
                                        
'user_id'          => $oUser->getId(),
                                        
'date_last'        => null,
                                        
'talk_user_active' => ModuleTalk::TALK_USER_ACTIVE
                                    
)
                                )
                            )
                            ) {
                                
$this->Notify_SendTalkNew($oUser$this->oUserCurrent$oTalk);

                                
$oViewer $this->Viewer_GetLocalViewer();
                                
$oViewer->Assign('oUser'$oUser);
                                
$oViewer->Assign('bUserListSmallShowActions'true);

                                
$aResult[] = array(
                                    
'bStateError'   => false,
                                    
'sMsgTitle'     => $this->Lang_Get('attention'),
                                    
'sMsg'          => $this->Lang_Get('user_list_add.notices.success_add',
                                        array(
'login'htmlspecialchars($sUser))),
                                    
'iUserId'       => $oUser->getId(),
                                    
'sUserLogin'    => $oUser->getLogin(),
                                    
'sUserLink'     => $oUser->getUserWebPath(),
                                    
'sUserWebPath'  => $oUser->getUserWebPath(),
                                    
'sUserAvatar48' => $oUser->getProfileAvatarPath(48),
                                    
'sHtml'         => $oViewer->Fetch("components/talk/talk-users-item.tpl")
                                );
                                
$bState true;
                            } else {
                                
$aResult[] = array(
                                    
'bStateError' => true,
                                    
'sMsgTitle'   => $this->Lang_Get('error'),
                                    
'sMsg'        => $this->Lang_Get('system_error')
                                );
                            }
                            break;
                        
/**
                         * Если пользователь является активным участником разговора, возвращаем ошибку
                         */
                        
case ModuleTalk::TALK_USER_ACTIVE:
                            
$aResult[] = array(
                                
'bStateError' => true,
                                
'sMsgTitle'   => $this->Lang_Get('error'),
                                
'sMsg'        => $this->Lang_Get('user_list_add.notices.error_already_added',
                                    array(
'login' => htmlspecialchars($sUser)))
                            );
                            break;
                        
/**
                         * Если пользователь удалил себя из разговора самостоятельно, то блокируем повторное добавление
                         */
                        
case ModuleTalk::TALK_USER_DELETE_BY_SELF:
                            
$aResult[] = array(
                                
'bStateError' => true,
                                
'sMsgTitle'   => $this->Lang_Get('error'),
                                
'sMsg'        => $this->Lang_Get('talk.users.notices.deleted',
                                    array(
'login' => htmlspecialchars($sUser)))
                            );
                            break;

                        default:
                            
$aResult[] = array(
                                
'bStateError' => true,
                                
'sMsgTitle'   => $this->Lang_Get('error'),
                                
'sMsg'        => $this->Lang_Get('system_error')
                            );
                    }
                } elseif (
                
$this->Talk_AddTalkUser(
                    
Engine::GetEntity('Talk_TalkUser',
                        array(
                            
'talk_id'          => $idTalk,
                            
'user_id'          => $oUser->getId(),
                            
'date_last'        => null,
                            
'talk_user_active' => ModuleTalk::TALK_USER_ACTIVE
                        
)
                    )
                )
                ) {
                    
$this->Notify_SendTalkNew($oUser$this->oUserCurrent$oTalk);

                    
$oViewer $this->Viewer_GetLocalViewer();
                    
$oViewer->Assign('oUser'$oUser);
                    
$oViewer->Assign('bUserListSmallShowActions'true);

                    
$aResult[] = array(
                        
'bStateError' => false,
                        
'sMsgTitle'   => $this->Lang_Get('attention'),
                        
'sMsg'        => $this->Lang_Get('user_list_add.notices.success_add',
                            array(
'login'htmlspecialchars($sUser))),
                        
'iUserId'     => $oUser->getId(),
                        
'sHtml'       => $oViewer->Fetch("components/talk/talk-users-item.tpl")
                    );
                    
$bState true;
                } else {
                    
$aResult[] = array(
                        
'bStateError' => true,
                        
'sMsgTitle'   => $this->Lang_Get('error'),
                        
'sMsg'        => $this->Lang_Get('system_error')
                    );
                }
            } else {
                
/**
                 * Добавляем пользователь не принимает сообщения
                 */
                
$aResult[] = array(
                    
'bStateError' => true,
                    
'sMsgTitle'   => $this->Lang_Get('error'),
                    
'sMsg'        => $this->Lang_Get('talk.blacklist.notices.blocked',
                        array(
'login' => htmlspecialchars($sUser)))
                );
            }
        } else {
            
/**
             * Пользователь не найден в базе данных или не активен
             */
            
$aResult[] = array(
                
'bStateError' => true,
                
'sMsgTitle'   => $this->Lang_Get('error'),
                
'sMsg'        => $this->Lang_Get('user.notices.not_found',
                    array(
'login' => htmlspecialchars($sUser)))
            );
        }
    }
    
/**
     * Передаем во вьевер массив результатов обработки по каждому пользователю
     */
    
$this->Viewer_AssignAjax('aUserList'$aResult);
}

Добавление нового участника разговора (ajax)

AjaxAddToBlacklist() method
public void AjaxAddToBlacklist()
Source Code: /application/classes/actions/ActionTalk.class.php#766 (show)
public function AjaxAddToBlacklist()
{
    
/**
     * Устанавливаем формат Ajax ответа
     */
    
$this->Viewer_SetResponseAjax('json');
    
$aUsers getRequest('aUserList'null'post');

    
/**
     * Валидация
     */
    
if (!is_array($aUsers)) {
        return 
$this->EventErrorDebug();
    }
    
/**
     * Если пользователь не авторизирован, возвращаем ошибку
     */
    
if (!$this->User_IsAuthorization()) {
        
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'), $this->Lang_Get('error'));
        return;
    }
    
/**
     * Получаем блекслист пользователя
     */
    
$aUserBlacklist $this->Talk_GetBlacklistByUserId($this->oUserCurrent->getId());

    
$aResult = array();
    
/**
     * Обрабатываем добавление по каждому из переданных логинов
     */
    
foreach ($aUsers as $sUser) {
        
$sUser trim($sUser);
        if (
$sUser == '') {
            continue;
        }
        
/**
         * Если пользователь пытается добавить в блеклист самого себя,
         * возвращаем ошибку
         */
        
if (strtolower($sUser) == strtolower($this->oUserCurrent->getLogin())) {
            
$aResult[] = array(
                
'bStateError' => true,
                
'sMsgTitle'   => $this->Lang_Get('error'),
                
'sMsg'        => $this->Lang_Get('user_list_add.notices.error_self')
            );
            continue;
        }
        
/**
         * Если пользователь не найден или неактивен, возвращаем ошибку
         */
        
if ($oUser $this->User_GetUserByLogin($sUser) and $oUser->getActivate() == 1) {
            if (!isset(
$aUserBlacklist[$oUser->getId()])) {
                if (
$this->Talk_AddUserToBlackList($oUser->getId(), $this->oUserCurrent->getId())) {
                    
$oViewer $this->Viewer_GetLocalViewer();
                    
$oViewer->Assign('oUser'$oUser);
                    
$oViewer->Assign('bUserListSmallShowActions'true);

                    
$aResult[] = array(
                        
'bStateError'   => false,
                        
'sMsgTitle'     => $this->Lang_Get('attention'),
                        
'sMsg'          => $this->Lang_Get('common.success.add',
                            array(
'login' => htmlspecialchars($sUser))),
                        
'sUserId'       => $oUser->getId(),
                        
'sUserLogin'    => htmlspecialchars($sUser),
                        
'sUserWebPath'  => $oUser->getUserWebPath(),
                        
'sUserAvatar48' => $oUser->getProfileAvatarPath(48),
                        
'sHtml'         => $oViewer->Fetch("components/user_list_small/user_list_small_item.tpl")
                    );
                } else {
                    
$aResult[] = array(
                        
'bStateError' => true,
                        
'sMsgTitle'   => $this->Lang_Get('error'),
                        
'sMsg'        => $this->Lang_Get('system_error'),
                        
'sUserLogin'  => htmlspecialchars($sUser)
                    );
                }
            } else {
                
/**
                 * Попытка добавить уже существующего в блеклисте пользователя, возвращаем ошибку
                 */
                
$aResult[] = array(
                    
'bStateError' => true,
                    
'sMsgTitle'   => $this->Lang_Get('error'),
                    
'sMsg'        => $this->Lang_Get('user_list_add.notices.error_already_added',
                        array(
'login' => htmlspecialchars($sUser))),
                    
'sUserLogin'  => htmlspecialchars($sUser)
                );
                continue;
            }
        } else {
            
$aResult[] = array(
                
'bStateError' => true,
                
'sMsgTitle'   => $this->Lang_Get('error'),
                
'sMsg'        => $this->Lang_Get('user.notices.not_found',
                    array(
'login' => htmlspecialchars($sUser))),
                
'sUserLogin'  => htmlspecialchars($sUser)
            );
        }
    }
    
/**
     * Передаем во вьевер массив с результатами обработки по каждому пользователю
     */
    
$this->Viewer_AssignAjax('aUserList'$aResult);
}

Добавление нового пользователя(-лей) в блек лист (ajax)

AjaxDeleteFromBlacklist() method
public void AjaxDeleteFromBlacklist()
Source Code: /application/classes/actions/ActionTalk.class.php#875 (show)
public function AjaxDeleteFromBlacklist()
{
    
/**
     * Устанавливаем формат Ajax ответа
     */
    
$this->Viewer_SetResponseAjax('json');
    
$iUserId getRequestStr('iUserId'null'post');
    
/**
     * Если пользователь не авторизирован, возвращаем ошибку
     */
    
if (!$this->User_IsAuthorization()) {
        
$this->Message_AddErrorSingle(
            
$this->Lang_Get('need_authorization'),
            
$this->Lang_Get('error')
        );
        return;
    }
    
/**
     * Если пользователь не существуем, возращаем ошибку
     */
    
if (!$oUserTarget $this->User_GetUserById($iUserId)) {
        
$this->Message_AddErrorSingle(
            
$this->Lang_Get('user.notices.not_found_by_id', array('id' => htmlspecialchars($iUserId))),
            
$this->Lang_Get('error')
        );
        return;
    }
    
/**
     * Получаем блеклист пользователя
     */
    
$aBlacklist $this->Talk_GetBlacklistByUserId($this->oUserCurrent->getId());
    
/**
     * Если указанный пользователь не найден в блекслисте, возвращаем ошибку
     */
    
if (!isset($aBlacklist[$oUserTarget->getId()])) {
        
$this->Message_AddErrorSingle(
            
$this->Lang_Get(
                
'talk.blacklist.notices.user_not_found',
                array(
'login' => $oUserTarget->getLogin())
            ),
            
$this->Lang_Get('error')
        );
        return;
    }
    
/**
     * Производим удаление пользователя из блекслиста
     */
    
if (!$this->Talk_DeleteUserFromBlacklist($iUserId$this->oUserCurrent->getId())) {
        return 
$this->EventErrorDebug();
    }
    
$this->Message_AddNoticeSingle(
        
$this->Lang_Get(
            
'common.success.remove',
            array(
'login' => $oUserTarget->getLogin())
        ),
        
$this->Lang_Get('attention')
    );
}

Удаление пользователя из блек листа (ajax)

AjaxDeleteTalkUser() method
public void AjaxDeleteTalkUser()
Source Code: /application/classes/actions/ActionTalk.class.php#938 (show)
public function AjaxDeleteTalkUser()
{
    
/**
     * Устанавливаем формат Ajax ответа
     */
    
$this->Viewer_SetResponseAjax('json');
    
$iUserId getRequestStr('iUserId'null'post');
    
$iTalkId getRequestStr('iTargetId'null'post');
    
/**
     * Если пользователь не авторизирован, возвращаем ошибку
     */
    
if (!$this->User_IsAuthorization()) {
        
$this->Message_AddErrorSingle(
            
$this->Lang_Get('need_authorization'),
            
$this->Lang_Get('error')
        );
        return;
    }
    
/**
     * Если удаляемый участник не существует в базе данных, возвращаем ошибку
     */
    
if (!$oUserTarget $this->User_GetUserById($iUserId)) {
        
$this->Message_AddErrorSingle(
            
$this->Lang_Get('user.notices.not_found_by_id', array('id' => htmlspecialchars($iUserId))),
            
$this->Lang_Get('error')
        );
        return;
    }
    
/**
     * Если разговор не найден, или пользователь не является его автором (либо админом), возвращаем ошибку
     */
    
if ((!$oTalk $this->Talk_GetTalkById($iTalkId))
        || ((
$oTalk->getUserId() != $this->oUserCurrent->getId()) && !$this->oUserCurrent->isAdministrator())
    ) {
        
$this->Message_AddErrorSingle(
            
$this->Lang_Get('talk.notices.not_found'),
            
$this->Lang_Get('error')
        );
        return;
    }
    
/**
     * Получаем список всех участников разговора
     */
    
$aTalkUsers $oTalk->getTalkUsers();
    
/**
     * Если пользователь не является участником разговора или удалил себя самостоятельно  возвращаем ошибку
     */
    
if (!isset($aTalkUsers[$iUserId])
        || 
$aTalkUsers[$iUserId]->getUserActive() == ModuleTalk::TALK_USER_DELETE_BY_SELF
    
) {
        
$this->Message_AddErrorSingle(
            
$this->Lang_Get(
                
'talk.users.notices.user_not_found',
                array(
'login' => $oUserTarget->getLogin())
            ),
            
$this->Lang_Get('error')
        );
        return;
    }
    
/**
     * Удаляем пользователя из разговора,  если удаление прошло неудачно - возвращаем системную ошибку
     */
    
if (!$this->Talk_DeleteTalkUserByArray($iTalkId$iUserIdModuleTalk::TALK_USER_DELETE_BY_AUTHOR)) {
        return 
$this->EventErrorDebug();
    }
    
$this->Message_AddNoticeSingle(
        
$this->Lang_Get(
            
'common.success.remove',
            array(
'login' => $oUserTarget->getLogin())
        ),
        
$this->Lang_Get('attention')
    );
}

Удаление участника разговора (ajax)

AjaxNewMessages() method
public void AjaxNewMessages()
Source Code: /application/classes/actions/ActionTalk.class.php#1231 (show)
public function AjaxNewMessages()
{
    
/**
     * Устанавливаем формат Ajax ответа
     */
    
$this->Viewer_SetResponseAjax('json');

    if (!
$this->oUserCurrent) {
        
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'), $this->Lang_Get('error'));
        return;
    }
    
$iCountTalkNew $this->Talk_GetCountTalkNew($this->oUserCurrent->getId());
    
$this->Viewer_AssignAjax('iCountTalkNew'$iCountTalkNew);
}

Возвращает количество новых сообщений

AjaxResponseComment() method
protected void AjaxResponseComment()
Source Code: /application/classes/actions/ActionTalk.class.php#572 (show)
protected function AjaxResponseComment()
{
    
/**
     * Устанавливаем формат Ajax ответа
     */
    
$this->Viewer_SetResponseAjax('json');
    
$idCommentLast getRequestStr('idCommentLast');
    
/**
     * Проверям авторизован ли пользователь
     */
    
if (!$this->User_IsAuthorization()) {
        
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'), $this->Lang_Get('error'));
        return;
    }
    
/**
     * Проверяем разговор
     */
    
if (!($oTalk $this->Talk_GetTalkById(getRequestStr('idTarget')))) {
        return 
$this->EventErrorDebug();
    }
    
/**
     * Доступен?
     */
    
if (!($oTalkUser $this->Talk_GetTalkUser($oTalk->getId(), $this->oUserCurrent->getId()))) {
        return 
$this->EventErrorDebug();
    }
    
/**
     * Получаем комментарии
     */
    
$aReturn $this->Comment_GetCommentsNewByTargetId($oTalk->getId(), 'talk'$idCommentLast);
    
$iMaxIdComment $aReturn['iMaxIdComment'];
    
/**
     * Отмечаем дату прочтения письма
     */
    
$oTalkUser->setDateLast(date("Y-m-d H:i:s"));
    if (
$iMaxIdComment != 0) {
        
$oTalkUser->setCommentIdLast($iMaxIdComment);
    }
    
$oTalkUser->setCommentCountNew(0);
    
$this->Talk_UpdateTalkUser($oTalkUser);

    
$aComments = array();
    
$aCmts $aReturn['comments'];
    if (
$aCmts and is_array($aCmts)) {
        foreach (
$aCmts as $aCmt) {
            
$aComments[] = array(
                
'html'     => $aCmt['html'],
                
'idParent' => $aCmt['obj']->getPid(),
                
'id'       => $aCmt['obj']->getId(),
            );
        }
    }
    
$this->Viewer_AssignAjax('aComments'$aComments);
    
$this->Viewer_AssignAjax('iMaxIdComment'$iMaxIdComment);
}

Получение новых комментариев

BuildFilter() method
protected array BuildFilter()
{return} array
Source Code: /application/classes/actions/ActionTalk.class.php#222 (show)
protected function BuildFilter()
{
    
/**
     * Текущий пользователь
     */
    
$aFilter = array(
        
'user_id' => $this->oUserCurrent->getId(),
    );
    
/**
     * Дата старта поиска
     */
    
if ($start getRequestStr('start')) {
        if (
func_check($start'text'610) && substr_count($start'.') == 2) {
            list(
$d$m$y) = explode('.'$start);
            if (@
checkdate($m$d$y)) {
                
$aFilter['date_min'] = "{$y}-{$m}-{$d}";
            } else {
                
$this->Message_AddError(
                    
$this->Lang_Get('talk.search.notices.error_date_format'),
                    
$this->Lang_Get('talk.search.notices.error')
                );
                unset(
$_REQUEST['start']);
            }
        } else {
            
$this->Message_AddError(
                
$this->Lang_Get('talk.search.notices.error_date_format'),
                
$this->Lang_Get('talk.search.notices.error')
            );
            unset(
$_REQUEST['start']);
        }
    }
    
/**
     * Дата окончания поиска
     */
    
if ($end getRequestStr('end')) {
        if (
func_check($end'text'610) && substr_count($end'.') == 2) {
            list(
$d$m$y) = explode('.'$end);
            if (@
checkdate($m$d$y)) {
                
$aFilter['date_max'] = "{$y}-{$m}-{$d} 23:59:59";
            } else {
                
$this->Message_AddError(
                    
$this->Lang_Get('talk.search.notices.error_date_format'),
                    
$this->Lang_Get('talk.search.notices.error')
                );
                unset(
$_REQUEST['end']);
            }
        } else {
            
$this->Message_AddError(
                
$this->Lang_Get('talk.search.notices.error_date_format'),
                
$this->Lang_Get('talk.search.notices.error')
            );
            unset(
$_REQUEST['end']);
        }
    }
    
/**
     * Ключевые слова в теме сообщения
     */
    
if ($sKeyRequest getRequest('keyword') and is_string($sKeyRequest)) {
        
$sKeyRequest urldecode($sKeyRequest);
        
preg_match_all('~(\S+)~u'$sKeyRequest$aWords);

        if (
is_array($aWords[1]) && isset($aWords[1]) && count($aWords[1])) {
            
$aFilter['keyword'] = '%' implode('%'$aWords[1]) . '%';
        } else {
            unset(
$_REQUEST['keyword']);
        }
    }
    
/**
     * Ключевые слова в тексте сообщения
     */
    
if ($sKeyRequest getRequest('keyword_text') and is_string($sKeyRequest)) {
        
$sKeyRequest urldecode($sKeyRequest);
        
preg_match_all('~(\S+)~u'$sKeyRequest$aWords);

        if (
is_array($aWords[1]) && isset($aWords[1]) && count($aWords[1])) {
            
$aFilter['text_like'] = '%' implode('%'$aWords[1]) . '%';
        } else {
            unset(
$_REQUEST['keyword_text']);
        }
    }
    
/**
     * Отправитель
     */
    
if ($sender getRequest('sender') and is_string($sender)) {
        
$aFilter['user_login'] = urldecode($sender);
    }
    
/**
     * Отправитель
     */
    
if ($sReceiver urldecode(getRequestStr('receiver')) and $oUserReceiver $this->User_GetUserByLogin($sReceiver)) {
        
$aFilter['receiver_user_id'] = $oUserReceiver->getId();
    }
    
/**
     * Искать только в избранных письмах
     */
    
if (getRequest('favourite')) {
        
$aTalkIdResult $this->Favourite_GetFavouritesByUserId($this->oUserCurrent->getId(), 'talk'1,
            
500); // ограничиваем
        
$aFilter['id'] = $aTalkIdResult['collection'];
        
$_REQUEST['favourite'] = 1;
    } else {
        unset(
$_REQUEST['favourite']);
    }
    return 
$aFilter;
}

Формирует из REQUEST массива фильтр для отбора писем

EventAdd() method
protected void EventAdd()
Source Code: /application/classes/actions/ActionTalk.class.php#374 (show)
protected function EventAdd()
{
    
$this->sMenuSubItemSelect 'add';
    
$this->Viewer_AddHtmlTitle($this->Lang_Get('talk.nav.add'));
    
/**
     * Получаем список друзей
     */
    
$aUsersFriend $this->User_GetUsersFriend($this->oUserCurrent->getId());
    if (
$aUsersFriend['collection']) {
        
$this->Viewer_Assign('aUsersFriend'$aUsersFriend['collection']);
    }
    
/**
     * Проверяем отправлена ли форма с данными
     */
    
if (!isPost('submit_talk_add')) {
        return 
false;
    }
    
/**
     * Проверяем разрешено ли отправлять личное сообщение
     */
    
if (!$this->ACL_CanAddTalk($this->oUserCurrent)) {
        
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
        return 
Router::Action('error');
    }
    
/**
     * Проверка корректности полей формы
     */
    
if (!$this->checkTalkFields()) {
        return 
false;
    }
    
/**
     * Отправляем письмо
     */
    
if ($oTalk $this->Talk_SendTalk($this->Text_Parser(strip_tags(getRequestStr('talk_title'))),
        
$this->Text_Parser(getRequestStr('talk_text')), $this->oUserCurrent$this->aUsersId)
    ) {
        
/**
         * Фиксируем ID у media файлов
         */
        
$this->Media_ReplaceTargetTmpById('talk'$oTalk->getId());
        
Router::Location(Router::GetPath('talk') . 'read/' $oTalk->getId() . '/');
    } else {
        
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
        return 
Router::Action('error');
    }
}

Страница создания письма

EventBlacklist() method
protected void EventBlacklist()
Source Code: /application/classes/actions/ActionTalk.class.php#331 (show)
protected function EventBlacklist()
{
    
$this->sMenuSubItemSelect 'blacklist';
    
$aUsersBlacklist $this->Talk_GetBlacklistByUserId($this->oUserCurrent->getId());
    
$this->Viewer_Assign('aUsersBlacklist'$aUsersBlacklist);
}

Отображение списка блэк-листа

EventDelete() method
protected void EventDelete()
Source Code: /application/classes/actions/ActionTalk.class.php#107 (show)
protected function EventDelete()
{
    
$this->Security_ValidateSendForm();
    
/**
     * Получаем номер сообщения из УРЛ и проверяем существует ли оно
     */
    
$sTalkId $this->GetParam(0);
    if (!(
$oTalk $this->Talk_GetTalkById($sTalkId))) {
        return 
parent::EventNotFound();
    }
    
/**
     * Пользователь входит в переписку?
     */
    
if (!($oTalkUser $this->Talk_GetTalkUser($oTalk->getId(), $this->oUserCurrent->getId()))) {
        return 
parent::EventNotFound();
    }
    
/**
     * Обработка удаления сообщения
     */
    
$this->Talk_DeleteTalkUserByArray($sTalkId$this->oUserCurrent->getId());
    
Router::Location(Router::GetPath('talk'));
}

Удаление письма

EventFavourites() method
protected void EventFavourites()
Source Code: /application/classes/actions/ActionTalk.class.php#341 (show)
protected function EventFavourites()
{
    
$this->sMenuSubItemSelect 'favourites';
    
/**
     * Передан ли номер страницы
     */
    
$iPage preg_match("/^page([1-9]\d{0,5})$/i"$this->getParam(0), $aMatch) ? $aMatch[1] : 1;
    
/**
     * Получаем список писем
     */
    
$aResult $this->Talk_GetTalksFavouriteByUserId(
        
$this->oUserCurrent->getId(),
        
$iPageConfig::Get('module.talk.per_page')
    );
    
$aTalks $aResult['collection'];
    
/**
     * Формируем постраничность
     */
    
$aPaging $this->Viewer_MakePaging(
        
$aResult['count'], $iPageConfig::Get('module.talk.per_page'), Config::Get('pagination.pages.count'),
        
Router::GetPath('talk') . $this->sCurrentEvent
    
);
    
/**
     * Загружаем переменные в шаблон
     */
    
$this->Viewer_Assign('aPaging'$aPaging);
    
$this->Viewer_Assign('aTalks'$aTalks);
    
$this->Viewer_AddHtmlTitle($this->Lang_Get('talk.nav.favourites'));
}

Отображение списка избранных писем

EventInbox() method
protected void EventInbox()
Source Code: /application/classes/actions/ActionTalk.class.php#133 (show)
protected function EventInbox()
{
    
/**
     * Обработка удаления сообщений
     */
    
if (getRequestStr('form_action') == 'remove') {
        
$this->Security_ValidateSendForm();

        
$aTalksIdDel getRequest('talk_select');
        if (
is_array($aTalksIdDel)) {
            
$this->Talk_DeleteTalkUserByArray(array_keys($aTalksIdDel), $this->oUserCurrent->getId());
        }
    }
    
/**
     * Обработка отметки о прочтении
     */
    
if (getRequestStr('form_action') == 'mark_as_read') {
        
$this->Security_ValidateSendForm();

        
$aTalksIdDel getRequest('talk_select');
        if (
is_array($aTalksIdDel)) {
            
$this->Talk_MarkReadTalkUserByArray(array_keys($aTalksIdDel), $this->oUserCurrent->getId());
        }
    }
    
$this->sMenuSubItemSelect 'inbox';
    
/**
     * Количество сообщений на страницу
     */
    
$iPerPage Config::Get('module.talk.per_page');
    
/**
     * Формируем фильтр для поиска сообщений
     */
    
$aFilter $this->BuildFilter();
    
/**
     * Если только новые, то добавляем условие в фильтр
     */
    
if ($this->GetParam(0) == 'new') {
        
$this->sMenuSubItemSelect 'new';
        
$aFilter['only_new'] = true;
        
$iPerPage 50// новых отображаем только последние 50 писем, без постраничности
    
}
    
/**
     * Передан ли номер страницы
     */
    
$iPage preg_match("/^page([1-9]\d{0,5})$/i"$this->getParam(0), $aMatch) ? $aMatch[1] : 1;
    
/**
     * Получаем список писем
     */
    
$aResult $this->Talk_GetTalksByFilter(
        
$aFilter$iPage$iPerPage
    
);

    
$aTalks $aResult['collection'];
    
/**
     * Формируем постраничность
     */
    
$aPaging $this->Viewer_MakePaging(
        
$aResult['count'], $iPage$iPerPageConfig::Get('pagination.pages.count'),
        
Router::GetPath('talk') . $this->sCurrentEvent,
        
array_intersect_key(
            
$_REQUEST,
            
array_fill_keys(
                array(
'start''end''keyword''sender''keyword_text''favourite'),
                
''
            
)
        )
    );
    
/**
     * Показываем сообщение, если происходит поиск по фильтру
     */
    
if (getRequest('submit_talk_filter')) {
        
$this->Message_AddNotice(
            (
$aResult['count'])
                ? 
$this->Lang_Get('talk.search.notices.result_count', array('count' => $aResult['count']))
                : 
$this->Lang_Get('talk.search.notices.result_empty')
        );
    }
    
/**
     * Загружаем переменные в шаблон
     */
    
$this->Viewer_Assign('aPaging'$aPaging);
    
$this->Viewer_Assign('aTalks'$aTalks);
}

Отображение списка сообщений

EventRead() method
protected void EventRead()
Source Code: /application/classes/actions/ActionTalk.class.php#424 (show)
protected function EventRead()
{
    
$this->sMenuSubItemSelect 'read';
    
/**
     * Получаем номер сообщения из УРЛ и проверяем существует ли оно
     */
    
$sTalkId $this->GetParam(0);
    if (!(
$oTalk $this->Talk_GetTalkById($sTalkId))) {
        return 
parent::EventNotFound();
    }
    
/**
     * Пользователь есть в переписке?
     */
    
if (!($oTalkUser $this->Talk_GetTalkUser($oTalk->getId(), $this->oUserCurrent->getId()))) {
        return 
parent::EventNotFound();
    }
    
/**
     * Пользователь активен в переписке?
     */
    
if ($oTalkUser->getUserActive() != ModuleTalk::TALK_USER_ACTIVE) {
        return 
parent::EventNotFound();
    }
    
/**
     * Достаём комменты к сообщению
     */
    
$aReturn $this->Comment_GetCommentsByTargetId($oTalk->getId(), 'talk');
    
$iMaxIdComment $aReturn['iMaxIdComment'];
    
$aComments $aReturn['comments'];
    
/**
     * Помечаем дату последнего просмотра
     */
    
$oTalkUser->setDateLast(date("Y-m-d H:i:s"));
    
$oTalkUser->setCommentIdLast($iMaxIdComment);
    
$oTalkUser->setCommentCountNew(0);
    
$this->Talk_UpdateTalkUser($oTalkUser);

    
$this->Viewer_AddHtmlTitle($oTalk->getTitle());
    
$this->Viewer_Assign('oTalk'$oTalk);
    
$this->Viewer_Assign('aComments'$aComments);
    
$this->Viewer_Assign('iMaxIdComment'$iMaxIdComment);
    
/**
     * Подсчитываем нужно ли отображать комментарии.
     * Комментарии не отображаются, если у вестки только один читатель
     * и ранее созданных комментариев нет.
     */
    
if (count($aComments) == 0) {
        
$iActiveSpeakers 0;
        foreach ((array)
$oTalk->getTalkUsers() as $oTalkUser) {
            if ((
$oTalkUser->getUserId() != $this->oUserCurrent->getId())
                && 
$oTalkUser->getUserActive() == ModuleTalk::TALK_USER_ACTIVE
            
) {
                
$iActiveSpeakers++;
                break;
            }
        }
        if (
$iActiveSpeakers == 0) {
            
$this->Viewer_Assign('bNoComments'true);
        }
    }

    
$this->SetTemplateAction('talk');
}

Чтение письма

EventShutdown() method
public void EventShutdown()
Source Code: /application/classes/actions/ActionTalk.class.php#1249 (show)
public function EventShutdown()
{
    if (!
$this->oUserCurrent) {
        return;
    }
    
$iCountTalkFavourite $this->Talk_GetCountTalksFavouriteByUserId($this->oUserCurrent->getId());
    
$this->Viewer_Assign('iCountTalkFavourite'$iCountTalkFavourite);

    
$iCountTopicFavourite $this->Topic_GetCountTopicsFavouriteByUserId($this->oUserCurrent->getId());
    
$iCountTopicUser $this->Topic_GetCountTopicsPersonalByUser($this->oUserCurrent->getId(), 1);
    
$iCountCommentUser $this->Comment_GetCountCommentsByUserId($this->oUserCurrent->getId(), 'topic');
    
$iCountCommentFavourite $this->Comment_GetCountCommentsFavouriteByUserId($this->oUserCurrent->getId());
    
$iCountNoteUser $this->User_GetCountUserNotesByUserId($this->oUserCurrent->getId());

    
$this->Viewer_Assign('oUserProfile'$this->oUserCurrent);
    
$this->Viewer_Assign('iCountWallUser',
        
$this->Wall_GetCountWall(array('wall_user_id' => $this->oUserCurrent->getId(), 'pid' => null)));
    
/**
     * Общее число публикация и избранного
     */
    
$this->Viewer_Assign('iCountCreated'$iCountNoteUser $iCountTopicUser $iCountCommentUser);
    
$this->Viewer_Assign('iCountFavourite'$iCountCommentFavourite $iCountTopicFavourite);
    
$this->Viewer_Assign('iCountFriendsUser'$this->User_GetCountUsersFriend($this->oUserCurrent->getId()));

    
$this->Viewer_Assign('sMenuSubItemSelect'$this->sMenuSubItemSelect);
    
/**
     * Передаем во вьевер константы состояний участников разговора
     */
    
$this->Viewer_Assign('TALK_USER_ACTIVE'ModuleTalk::TALK_USER_ACTIVE);
    
$this->Viewer_Assign('TALK_USER_DELETE_BY_SELF'ModuleTalk::TALK_USER_DELETE_BY_SELF);
    
$this->Viewer_Assign('TALK_USER_DELETE_BY_AUTHOR'ModuleTalk::TALK_USER_DELETE_BY_AUTHOR);
}

Обработка завершения работу экшена

Init() method
public void Init()
Source Code: /application/classes/actions/ActionTalk.class.php#53 (show)
public function Init()
{
    
/**
     * Проверяем авторизован ли юзер
     */
    
if (!$this->User_IsAuthorization()) {
        
$this->Message_AddErrorSingle($this->Lang_Get('not_access'));
        return 
Router::Action('error');
    }
    
/**
     * Получаем текущего юзера
     */
    
$this->oUserCurrent $this->User_GetUserCurrent();
    
$this->SetDefaultEvent('inbox');
    
$this->Viewer_AddHtmlTitle($this->Lang_Get('talk.nav.inbox'));

    
/**
     * Загружаем в шаблон JS текстовки
     */
    
$this->Lang_AddLangJs(array(
        
'delete'
    
));
}

Инициализация

RegisterEvent() method
protected void RegisterEvent()
Source Code: /application/classes/actions/ActionTalk.class.php#80 (show)
protected function RegisterEvent()
{
    
$this->AddEvent('inbox''EventInbox');
    
$this->AddEvent('add''EventAdd');
    
$this->AddEvent('read''EventRead');
    
$this->AddEvent('delete''EventDelete');
    
$this->AddEvent('favourites''EventFavourites');
    
$this->AddEvent('blacklist''EventBlacklist');

    
$this->AddEvent('ajaxaddcomment''AjaxAddComment');
    
$this->AddEvent('ajaxresponsecomment''AjaxResponseComment');
    
$this->AddEvent('ajaxaddtoblacklist''AjaxAddToBlacklist');
    
$this->AddEvent('ajaxdeletefromblacklist''AjaxDeleteFromBlacklist');
    
$this->AddEvent('ajaxdeletetalkuser''AjaxDeleteTalkUser');
    
$this->AddEvent('ajaxaddtalkuser''AjaxAddTalkUser');
    
$this->AddEvent('ajaxnewmessages''AjaxNewMessages');
}

Регистрация евентов

SubmitComment() method
protected void SubmitComment()
Source Code: /application/classes/actions/ActionTalk.class.php#645 (show)
protected function SubmitComment()
{
    
/**
     * Проверям авторизован ли пользователь
     */
    
if (!$this->User_IsAuthorization()) {
        
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'), $this->Lang_Get('error'));
        return;
    }
    
/**
     * Проверяем разговор
     */
    
if (!($oTalk $this->Talk_GetTalkById(getRequestStr('cmt_target_id')))) {
        return 
$this->EventErrorDebug();
    }
    if (!(
$oTalkUser $this->Talk_GetTalkUser($oTalk->getId(), $this->oUserCurrent->getId()))) {
        return 
$this->EventErrorDebug();
    }
    
/**
     * Проверяем разрешено ли постить комменты
     */
    
if (!$this->ACL_CanPostTalkComment($this->oUserCurrent)) {
        
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
        return;
    }
    
/**
     * Проверяем текст комментария
     */
    
$sText getRequestStr('comment_text');
    if (!
func_check($sText'text'23000)) {
        
$this->Message_AddErrorSingle($this->Lang_Get('talk.message.notices.error_text'), $this->Lang_Get('error'));
        return;
    }
    
/**
     * Проверям на какой коммент отвечаем
     */
    
$sParentId = (int)getRequest('reply');
    if (!
func_check($sParentId'id')) {
        return 
$this->EventErrorDebug();
    }
    
$oCommentParent null;
    if (
$sParentId != 0) {
        
/**
         * Проверяем существует ли комментарий на который отвечаем
         */
        
if (!($oCommentParent $this->Comment_GetCommentById($sParentId))) {
            return 
$this->EventErrorDebug();
        }
        
/**
         * Проверяем из одного топика ли новый коммент и тот на который отвечаем
         */
        
if ($oCommentParent->getTargetId() != $oTalk->getId()) {
            return 
$this->EventErrorDebug();
        }
    } else {
        
/**
         * Корневой комментарий
         */
        
$sParentId null;
    }
    
/**
     * Проверка на дублирующий коммент
     */
    
if ($this->Comment_GetCommentUnique($oTalk->getId(), 'talk'$this->oUserCurrent->getId(), $sParentId,
        
md5($sText))
    ) {
        
$this->Message_AddErrorSingle($this->Lang_Get('topic.comments.notices.spam'), $this->Lang_Get('error'));
        return;
    }
    
/**
     * Создаём коммент
     */
    
$oCommentNew Engine::GetEntity('Comment');
    
$oCommentNew->setTargetId($oTalk->getId());
    
$oCommentNew->setTargetType('talk');
    
$oCommentNew->setUserId($this->oUserCurrent->getId());
    
$oCommentNew->setText($this->Text_Parser($sText));
    
$oCommentNew->setTextSource($sText);
    
$oCommentNew->setDate(date("Y-m-d H:i:s"));
    
$oCommentNew->setUserIp(func_getIp());
    
$oCommentNew->setPid($sParentId);
    
$oCommentNew->setTextHash(md5($sText));
    
$oCommentNew->setPublish(1);
    
/**
     * Добавляем коммент
     */
    
$this->Hook_Run('talk_comment_add_before',
        array(
'oCommentNew' => $oCommentNew'oCommentParent' => $oCommentParent'oTalk' => $oTalk));
    if (
$this->Comment_AddComment($oCommentNew)) {
        
$this->Hook_Run('talk_comment_add_after',
            array(
'oCommentNew' => $oCommentNew'oCommentParent' => $oCommentParent'oTalk' => $oTalk));

        
$this->Viewer_AssignAjax('sCommentId'$oCommentNew->getId());
        
$oTalk->setDateLast(date("Y-m-d H:i:s"));
        
$oTalk->setUserIdLast($oCommentNew->getUserId());
        
$oTalk->setCommentIdLast($oCommentNew->getId());
        
$oTalk->setCountComment($oTalk->getCountComment() + 1);
        
$this->Talk_UpdateTalk($oTalk);
        
/**
         * Отсылаем уведомления всем адресатам
         */
        
$aUsersTalk $this->Talk_GetUsersTalk($oTalk->getId(), ModuleTalk::TALK_USER_ACTIVE);

        foreach (
$aUsersTalk as $oUserTalk) {
            if (
$oUserTalk->getId() != $oCommentNew->getUserId()) {
                
$this->Notify_SendTalkCommentNew($oUserTalk$this->oUserCurrent$oTalk$oCommentNew);
            }
        }
        
/**
         * Увеличиваем число новых комментов
         */
        
$this->Talk_increaseCountCommentNew($oTalk->getId(), $oCommentNew->getUserId());
    } else {
        return 
$this->EventErrorDebug();
    }
}

Обработка добавление комментария к письму

checkTalkFields() method
protected bool checkTalkFields()
{return} bool
Source Code: /application/classes/actions/ActionTalk.class.php#492 (show)
protected function checkTalkFields()
{
    
$this->Security_ValidateSendForm();

    
$bOk true;
    
/**
     * Проверяем есть ли заголовок
     */
    
if (!func_check(getRequestStr('talk_title'), 'text'2200)) {
        
$this->Message_AddError($this->Lang_Get('talk.add.notices.title_error'), $this->Lang_Get('error'));
        
$bOk false;
    }
    
/**
     * Проверяем есть ли содержание топика
     */
    
if (!func_check(getRequestStr('talk_text'), 'text'23000)) {
        
$this->Message_AddError($this->Lang_Get('talk.add.notices.text_error'), $this->Lang_Get('error'));
        
$bOk false;
    }
    
/**
     * Проверяем адресатов
     */
    
$sUsers getRequest('talk_users');
    
$aUsers explode(',', (string)$sUsers);
    
$aUsersNew = array();
    
$aUserInBlacklist $this->Talk_GetBlacklistByTargetId($this->oUserCurrent->getId());

    
$this->aUsersId = array();
    foreach (
$aUsers as $sUser) {
        
$sUser trim($sUser);
        if (
$sUser == '' or strtolower($sUser) == strtolower($this->oUserCurrent->getLogin())) {
            continue;
        }
        if (
$oUser $this->User_GetUserByLogin($sUser) and $oUser->getActivate() == 1) {
            
// Проверяем, попал ли отправиль в блек лист
            
if (!in_array($oUser->getId(), $aUserInBlacklist)) {
                
$this->aUsersId[] = $oUser->getId();
            } else {
                
$this->Message_AddError(
                    
str_replace(
                        
'login',
                        
$oUser->getLogin(),
                        
$this->Lang_Get('talk.blacklist.notices.blocked',
                            array(
'login' => htmlspecialchars($oUser->getLogin())))
                    ),
                    
$this->Lang_Get('error')
                );
                
$bOk false;
                continue;
            }
        } else {
            
$this->Message_AddError($this->Lang_Get('talk.add.notices.users_error_not_found') . ' «' htmlspecialchars($sUser) . '»',
                
$this->Lang_Get('error'));
            
$bOk false;
        }
        
$aUsersNew[] = $sUser;
    }
    if (!
count($aUsersNew)) {
        
$this->Message_AddError($this->Lang_Get('talk.add.notices.users_error'), $this->Lang_Get('error'));
        
$_REQUEST['talk_users'] = '';
        
$bOk false;
    } else {
        if (
count($aUsersNew) > Config::Get('module.talk.max_users') and !$this->oUserCurrent->isAdministrator()) {
            
$this->Message_AddError($this->Lang_Get('talk.add.notices.users_error_many'), $this->Lang_Get('error'));
            
$bOk false;
        }
        
$_REQUEST['talk_users'] = join(','$aUsersNew);
    }
    
/**
     * Выполнение хуков
     */
    
$this->Hook_Run('check_talk_fields', array('bOk' => &$bOk));

    return 
$bOk;
}

Проверка полей при создании письма