/**
  * Показ топиков
  *
  */
 protected function EventTopics()
 {
     $sPeriod = 1;
     // по дефолту 1 день
     if (in_array(getRequestStr('period'), array(1, 7, 30, 'all'))) {
         $sPeriod = getRequestStr('period');
     }
     $sShowType = $this->sCurrentEvent;
     if (!in_array($sShowType, array('discussed', 'top'))) {
         $sPeriod = 'all';
     }
     /**
      * Меню
      */
     $this->sMenuSubItemSelect = $sShowType == 'newall' ? 'new' : $sShowType;
     /**
      * Передан ли номер страницы
      */
     $iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
     if ($iPage == 1 and !getRequest('period')) {
         $this->Viewer_SetHtmlCanonical(Router::GetPath('personal_blog') . $sShowType . '/');
     }
     /**
      * Получаем список топиков
      */
     $aResult = $this->Topic_GetTopicsPersonal($iPage, Config::Get('module.topic.per_page'), $sShowType, $sPeriod == 'all' ? null : $sPeriod * 60 * 60 * 24);
     /**
      * Если нет топиков за 1 день, то показываем за неделю (7)
      */
     if (in_array($sShowType, array('discussed', 'top')) and !$aResult['count'] and $iPage == 1 and !getRequest('period')) {
         $sPeriod = 7;
         $aResult = $this->Topic_GetTopicsPersonal($iPage, Config::Get('module.topic.per_page'), $sShowType, $sPeriod == 'all' ? null : $sPeriod * 60 * 60 * 24);
     }
     $aTopics = $aResult['collection'];
     /**
      * Вызов хуков
      */
     $this->Hook_Run('topics_list_show', array('aTopics' => $aTopics));
     /**
      * Формируем постраничность
      */
     $aPaging = $this->Viewer_MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'), Config::Get('pagination.pages.count'), Router::GetPath('personal_blog') . $sShowType, in_array($sShowType, array('discussed', 'top')) ? array('period' => $sPeriod) : array());
     /**
      * Вызов хуков
      */
     $this->Hook_Run('personal_show', array('sShowType' => $sShowType));
     /**
      * Загружаем переменные в шаблон
      */
     $this->Viewer_Assign('aTopics', $aTopics);
     $this->Viewer_Assign('aPaging', $aPaging);
     if (in_array($sShowType, array('discussed', 'top'))) {
         $this->Viewer_Assign('sPeriodSelectCurrent', $sPeriod);
         $this->Viewer_Assign('sPeriodSelectRoot', Router::GetPath('personal_blog') . $sShowType . '/');
     }
     /**
      * Устанавливаем шаблон вывода
      */
     $this->SetTemplateAction('index');
 }
 protected function EventSubscriptionAjaxSetSubscription()
 {
     $this->Viewer_SetResponseAjax('json');
     require_once Config::Get('path.root.engine') . '/lib/external/XXTEA/encrypt.php';
     if (!($sSubscriptionMail = getRequestStr('subscription_mail'))) {
         $this->Message_AddErrorSingle($this->Lang_Get('plugin.subscription.subscription_mail_error_empty'), $this->Lang_Get('error'));
         return;
     }
     $oSubscription = Engine::GetEntity('PluginSubscription_ModuleSubscription_EntitySubscription');
     $oSubscription->_setValidateScenario('subscription_mail');
     $oSubscription->setMail($sSubscriptionMail);
     $oSubscription->_Validate();
     if ($oSubscription->_hasValidateErrors()) {
         $this->Message_AddErrorSingle($oSubscription->_getValidateError());
         return false;
     }
     if ($oSubscription = $this->PluginSubscription_Subscription_GetSubscriptionByMail($sSubscriptionMail)) {
         if ($oSubscription->getUnsubscribeHash()) {
             $sUnsubscribeCode = $oSubscription->getUnsubscribeHash();
             $sUnsubscribeCode .= base64_encode(xxtea_encrypt($oSubscription->getMail(), $oSubscription->getUnsubscribeHash()));
             $sUnsubscribeCode = str_replace(array('/', '+'), array('{', '}'), $sUnsubscribeCode);
             $this->Notify_Send($oSubscription->getMail(), 'notify.subscription_unsubscription.tpl', $this->Lang_Get('plugin.subscription.subscription_mail_message_subject'), array('sUnsubscribeCode' => $sUnsubscribeCode), 'subscription');
             $this->Viewer_AssignAjax('sText', $this->Lang_Get('plugin.subscription.subscription_block_subscription_submit_unsubscrib_ok'));
         } else {
             if ($oSubscription->getSubscribeDate()) {
                 $this->Viewer_AssignAjax('sText', $this->Lang_Get('plugin.subscription.subscription_mail_error_used'));
             } else {
                 $sSubscribeCode = $oSubscription->getSubscribeHash();
                 $sSubscribeCode .= base64_encode(xxtea_encrypt($oSubscription->getMail(), $oSubscription->getSubscribeHash()));
                 $sSubscribeCode = str_replace(array('/', '+'), array('{', '}'), $sSubscribeCode);
                 $this->Notify_Send($oSubscription->getMail(), 'notify.subscription_subscription.tpl', $this->Lang_Get('plugin.subscription.subscription_mail_message_subject'), array('sSubscribeCode' => $sSubscribeCode), 'subscription');
                 $this->Viewer_AssignAjax('sText', $this->Lang_Get('plugin.subscription.subscription_block_subscription_submit_repeatedly_ok'));
             }
         }
     } else {
         $oSubscription = Engine::GetEntity('PluginSubscription_ModuleSubscription_EntitySubscription');
         $oSubscription->setMail($sSubscriptionMail);
         $oSubscription->setSubscribeHash(func_generator());
         if ($this->PluginSubscription_Subscription_AddSubscription($oSubscription)) {
             $sSubscribeCode = $oSubscription->getSubscribeHash();
             $sSubscribeCode .= base64_encode(xxtea_encrypt($oSubscription->getMail(), $oSubscription->getSubscribeHash()));
             $sSubscribeCode = str_replace(array('/', '+'), array('{', '}'), $sSubscribeCode);
             $this->Notify_Send($oSubscription->getMail(), 'notify.subscription_subscription.tpl', $this->Lang_Get('plugin.subscription.subscription_mail_message_subject'), array('sSubscribeCode' => $sSubscribeCode), 'subscription');
             $this->Viewer_AssignAjax('sText', $this->Lang_Get('plugin.subscription.subscription_block_subscription_submit_ok'));
         } else {
             $this->Viewer_AssignAjax('sText', $this->Lang_Get('system_error'));
         }
     }
     return true;
 }
 /**
  * Добавление точки на карту
  */
 protected function AjaxAddPoint()
 {
     $this->Viewer_SetResponseAjax('json');
     $iCity = getRequestStr('uid');
     $iUid = getRequestStr('uid');
     $iLat = getRequestStr('lat');
     $iLon = getRequestStr('lon');
     $oUser = $this->PluginCoverage_Abills_GetUserByUid($iUid);
     $iVlan = $oUser->getVlan();
     $oUser = Engine::GetEntity('PluginCoverage_Coverage_Users');
     $oUser->setLat($iLat);
     $oUser->setLon($iLon);
     $oUser->setUid($iUid);
     $oUser->setVlanId($iVlan);
     $oUser->save();
     //print_r($oUser);
     //die();
     $this->Viewer_AssignAjax('1', '');
     $this->Viewer_AssignAjax('2', $iLat);
     $this->Viewer_AssignAjax('3', $iLon);
 }
 /**
  * Проверка полей формы создания поста
  */
 private function checkPostFields($oPost)
 {
     $this->Security_ValidateSendForm();
     $bOk = true;
     /**
      * Валидация данных
      */
     if (!$oPost->_Validate()) {
         $this->Message_AddError($oPost->_getValidateError(), $this->Lang_Get('error'));
         $bOk = false;
     }
     if (!$this->User_IsAuthorization()) {
         if (!$this->Validate_Validate('captcha', getRequestStr('guest_captcha'))) {
             $this->Message_AddError($this->Validate_GetErrorLast(), $this->Lang_Get('error'));
             $bOk = false;
         }
     }
     /**
      * Проверка вложений
      */
     $iCountFiles = 0;
     if (!$oPost->getId()) {
         if (isset($_COOKIE['ls_fattach_target_tmp'])) {
             $iCountFiles = $this->PluginForum_Forum_GetCountFilesByTargetTmp($_COOKIE['ls_fattach_target_tmp']);
         } else {
             $this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
             $bOk = false;
         }
     } else {
         $iCountFiles = count($oPost->getFiles());
     }
     if ($iCountFiles > Config::Get('plugin.forum.attach.count_max')) {
         $this->Message_AddError($this->Lang_Get('plugin.forum.attach_error_too_much_files', array('MAX' => Config::Get('plugin.forum.attach.count_max'))), $this->Lang_Get('error'));
         $bOk = false;
     }
     /**
      * Выполнение хуков
      */
     $this->Hook_Run('forum_check_post_fields', array('bOk' => &$bOk));
     return $bOk;
 }
 /**
  * Показывает модальное окно с кропом аватара
  */
 protected function EventAjaxModalCropAvatar()
 {
     $this->Viewer_SetResponseAjax('json');
     $oViewer = $this->Viewer_GetLocalViewer();
     $oViewer->Assign('image', getRequestStr('path'), true);
     $oViewer->Assign('originalWidth', (int) getRequest('original_width'), true);
     $oViewer->Assign('originalHeight', (int) getRequest('original_height'), true);
     $oViewer->Assign('width', (int) getRequest('width'), true);
     $oViewer->Assign('height', (int) getRequest('height'), true);
     $this->Viewer_AssignAjax('sText', $oViewer->Fetch("component@blog.modal.crop-avatar"));
 }
 /**
  * Добавление нового участника разговора (ajax)
  *
  */
 public function AjaxAddTalkUser()
 {
     /**
      * Устанавливаем формат Ajax ответа
      */
     $this->Viewer_SetResponseAjax('json');
     $aUsers = getRequest('users', null, 'post');
     $idTalk = getRequestStr('target_id', null, 'post');
     /**
      * Валидация
      */
     if (!is_array($aUsers)) {
         return $this->EventErrorDebug();
     }
     /**
      * Если пользователь не авторизирован, возвращаем ошибку
      */
     if (!$this->User_IsAuthorization()) {
         $this->Message_AddErrorSingle($this->Lang_Get('common.error.need_authorization'), $this->Lang_Get('common.error.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('common.error.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('common.error.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('common.error.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->Talk_SendNotifyTalkNew($oUser, $this->oUserCurrent, $oTalk);
                                 $oViewer = $this->Viewer_GetLocalViewer();
                                 $oViewer->Assign('user', $oUser, true);
                                 $oViewer->Assign('showActions', true, true);
                                 $aResult[] = array('bStateError' => false, 'sMsgTitle' => $this->Lang_Get('common.attention'), 'sMsg' => $this->Lang_Get('user_list_add.notices.success_add', array('login', htmlspecialchars($sUser))), 'user_id' => $oUser->getId(), 'user_login' => $oUser->getLogin(), 'html' => $oViewer->Fetch("component@talk.participants-item"));
                                 $bState = true;
                             } else {
                                 $aResult[] = array('bStateError' => true, 'sMsgTitle' => $this->Lang_Get('common.error.error'), 'sMsg' => $this->Lang_Get('common.error.system.base'));
                             }
                             break;
                             /**
                              * Если пользователь является активным участником разговора, возвращаем ошибку
                              */
                         /**
                          * Если пользователь является активным участником разговора, возвращаем ошибку
                          */
                         case ModuleTalk::TALK_USER_ACTIVE:
                             $aResult[] = array('bStateError' => true, 'sMsgTitle' => $this->Lang_Get('common.error.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('common.error.error'), 'sMsg' => $this->Lang_Get('talk.users.notices.deleted', array('login' => htmlspecialchars($sUser))));
                             break;
                         default:
                             $aResult[] = array('bStateError' => true, 'sMsgTitle' => $this->Lang_Get('common.error.error'), 'sMsg' => $this->Lang_Get('common.error.system.base'));
                     }
                 } 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->Talk_SendNotifyTalkNew($oUser, $this->oUserCurrent, $oTalk);
                     $oViewer = $this->Viewer_GetLocalViewer();
                     $oViewer->Assign('user', $oUser, true);
                     $oViewer->Assign('showActions', true, true);
                     $aResult[] = array('bStateError' => false, 'sMsgTitle' => $this->Lang_Get('common.attention'), 'sMsg' => $this->Lang_Get('user_list_add.notices.success_add', array('login', htmlspecialchars($sUser))), 'user_id' => $oUser->getId(), 'html' => $oViewer->Fetch("component@talk.participants-item"));
                     $bState = true;
                 } else {
                     $aResult[] = array('bStateError' => true, 'sMsgTitle' => $this->Lang_Get('common.error.error'), 'sMsg' => $this->Lang_Get('common.error.system.base'));
                 }
             } else {
                 /**
                  * Добавляем пользователь не принимает сообщения
                  */
                 $aResult[] = array('bStateError' => true, 'sMsgTitle' => $this->Lang_Get('common.error.error'), 'sMsg' => $this->Lang_Get('talk.blacklist.notices.blocked', array('login' => htmlspecialchars($sUser))));
             }
         } else {
             /**
              * Пользователь не найден в базе данных или не активен
              */
             $aResult[] = array('bStateError' => true, 'sMsgTitle' => $this->Lang_Get('common.error.error'), 'sMsg' => $this->Lang_Get('user.notices.not_found', array('login' => htmlspecialchars($sUser))));
         }
     }
     /**
      * Передаем во вьевер массив результатов обработки по каждому пользователю
      */
     $this->Viewer_AssignAjax('users', $aResult);
 }
 /**
  * Отображение списка блогов
  */
 protected function EventShowBlogs()
 {
     /**
      * По какому полю сортировать
      */
     $sOrder = 'blog_rating';
     if (getRequest('order')) {
         $sOrder = getRequestStr('order');
     }
     /**
      * В каком направлении сортировать
      */
     $sOrderWay = 'desc';
     if (getRequest('order_way')) {
         $sOrderWay = getRequestStr('order_way');
     }
     /**
      * Фильтр поиска блогов
      */
     $aFilter = array('exclude_type' => 'personal');
     /**
      * Передан ли номер страницы
      */
     $iPage = preg_match("/^\\d+\$/i", $this->GetEventMatch(2)) ? $this->GetEventMatch(2) : 1;
     /**
      * Получаем список блогов
      */
     $aResult = $this->Blog_GetBlogsByFilter($aFilter, array($sOrder => $sOrderWay), $iPage, Config::Get('module.blog.per_page'));
     $aBlogs = $aResult['collection'];
     /**
      * Формируем постраничность
      */
     $aPaging = $this->Viewer_MakePaging($aResult['count'], $iPage, Config::Get('module.blog.per_page'), Config::Get('pagination.pages.count'), Router::GetPath('blogs'), array('order' => $sOrder, 'order_way' => $sOrderWay));
     /**
      * Загружаем переменные в шаблон
      */
     $this->Viewer_Assign('aPaging', $aPaging);
     $this->Viewer_Assign("aBlogs", $aBlogs);
     $this->Viewer_Assign("sBlogOrder", htmlspecialchars($sOrder));
     $this->Viewer_Assign("sBlogOrderWay", htmlspecialchars($sOrderWay));
     $this->Viewer_Assign("sBlogOrderWayNext", htmlspecialchars($sOrderWay == 'desc' ? 'asc' : 'desc'));
     /**
      * Устанавливаем title страницы
      */
     $this->Viewer_AddHtmlTitle($this->Lang_Get('blog_menu_all_list'));
     /**
      * Устанавливаем шаблон вывода
      */
     $this->SetTemplateAction('index');
 }
 /**
  * Поиск пользователей по логину
  */
 protected function EventAjaxSearch()
 {
     /**
      * Устанавливаем формат Ajax ответа
      */
     $this->Viewer_SetResponseAjax('json');
     /**
      * Формируем фильтр
      */
     $aFilter = array('activate' => 1);
     $sOrderWay = in_array(getRequestStr('order'), array('desc', 'asc')) ? getRequestStr('order') : 'desc';
     $sOrderField = in_array(getRequestStr('sort_by'), array('user_rating', 'user_date_register', 'user_login', 'user_profile_name')) ? getRequestStr('sort_by') : 'user_rating';
     if (is_numeric(getRequestStr('next_page')) and getRequestStr('next_page') > 0) {
         $iPage = getRequestStr('next_page');
     } else {
         $iPage = 1;
     }
     /**
      * Получаем из реквеста первые буквы для поиска пользователей по логину
      */
     $sTitle = getRequest('sText');
     if (is_string($sTitle) and mb_strlen($sTitle, 'utf-8')) {
         $sTitle = str_replace(array('_', '%'), array('\\_', '\\%'), $sTitle);
     } else {
         $sTitle = '';
     }
     /**
      * Как именно искать: совпадение в любой части логина, или только начало или конец логина
      */
     if ($sTitle) {
         if (getRequest('isPrefix')) {
             $sTitle .= '%';
         } elseif (getRequest('isPostfix')) {
             $sTitle = '%' . $sTitle;
         } else {
             $sTitle = '%' . $sTitle . '%';
         }
     }
     if ($sTitle) {
         $aFilter['login'] = $sTitle;
     }
     /**
      * Пол
      */
     if (in_array(getRequestStr('sex'), array('man', 'woman', 'other'))) {
         $aFilter['profile_sex'] = getRequestStr('sex');
     }
     /**
      * Онлайн
      * date_last
      */
     if (getRequest('is_online')) {
         $aFilter['date_last_more'] = date('Y-m-d H:i:s', time() - Config::Get('module.user.time_onlive'));
     }
     /**
      * Geo привязка
      */
     if (getRequestStr('city')) {
         $aFilter['geo_city'] = getRequestStr('city');
     } elseif (getRequestStr('region')) {
         $aFilter['geo_region'] = getRequestStr('region');
     } elseif (getRequestStr('country')) {
         $aFilter['geo_country'] = getRequestStr('country');
     }
     /**
      * Ищем пользователей
      */
     $aResult = $this->User_GetUsersByFilter($aFilter, array($sOrderField => $sOrderWay), $iPage, Config::Get('module.user.per_page'));
     $bHideMore = $iPage * Config::Get('module.user.per_page') >= $aResult['count'];
     /**
      * Формируем ответ
      */
     $oViewer = $this->Viewer_GetLocalViewer();
     $oViewer->Assign('users', $aResult['collection'], true);
     $oViewer->Assign('oUserCurrent', $this->User_GetUserCurrent());
     $oViewer->Assign('textEmpty', $this->Lang_Get('search.alerts.empty'), true);
     $oViewer->Assign('useMore', true, true);
     $oViewer->Assign('hideMore', $bHideMore, true);
     $oViewer->Assign('searchCount', $aResult['count'], true);
     $this->Viewer_AssignAjax('html', $oViewer->Fetch("*****@*****.**"));
     /**
      * Для подгрузки
      */
     $this->Viewer_AssignAjax('count_loaded', count($aResult['collection']));
     $this->Viewer_AssignAjax('next_page', count($aResult['collection']) > 0 ? $iPage + 1 : $iPage);
     $this->Viewer_AssignAjax('hide', $bHideMore);
 }
 /**
  * Удаление/восстановление комментария
  *
  */
 protected function EventCommentDelete()
 {
     /**
      * Есть права на удаление комментария?
      */
     if (!$this->ACL_CanDeleteComment($this->oUserCurrent)) {
         $this->Message_AddErrorSingle($this->Lang_Get('not_access'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Комментарий существует?
      */
     $idComment = getRequestStr('idComment', null, 'post');
     if (!($oComment = $this->Comment_GetCommentById($idComment))) {
         $this->Message_AddErrorSingle($this->Lang_Get('system_error'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Устанавливаем пометку о том, что комментарий удален
      */
     $oComment->setDelete(($oComment->getDelete() + 1) % 2);
     $this->Hook_Run('comment_delete_before', array('oComment' => $oComment));
     if (!$this->Comment_UpdateCommentStatus($oComment)) {
         $this->Message_AddErrorSingle($this->Lang_Get('system_error'), $this->Lang_Get('error'));
         return;
     }
     $this->Hook_Run('comment_delete_after', array('oComment' => $oComment));
     /**
      * Формируем текст ответа
      */
     if ($bState = (bool) $oComment->getDelete()) {
         $sMsg = $this->Lang_Get('comment_delete_ok');
         $sTextToggle = $this->Lang_Get('comment_repair');
     } else {
         $sMsg = $this->Lang_Get('comment_repair_ok');
         $sTextToggle = $this->Lang_Get('comment_delete');
     }
     /**
      * Обновление события в ленте активности
      */
     $this->Stream_write($oComment->getUserId(), 'add_comment', $oComment->getId(), !$oComment->getDelete());
     /**
      * Показываем сообщение и передаем переменные в ajax ответ
      */
     $this->Message_AddNoticeSingle($sMsg, $this->Lang_Get('attention'));
     $this->Viewer_AssignAjax('bState', $bState);
     $this->Viewer_AssignAjax('sTextToggle', $sTextToggle);
 }
 /**
  * Ответ на ajax запрос
  *
  * @param string $sType Варианты: json, jsonIframe, jsonp
  */
 public function DisplayAjax($sType = 'json')
 {
     /**
      * Загружаем статус ответа и сообщение
      */
     $bStateError = false;
     $sMsgTitle = '';
     $sMsg = '';
     $aMsgError = $this->Message_GetError();
     $aMsgNotice = $this->Message_GetNotice();
     if (count($aMsgError) > 0) {
         $bStateError = true;
         $sMsgTitle = $aMsgError[0]['title'];
         $sMsg = $aMsgError[0]['msg'];
     } elseif (count($aMsgNotice) > 0) {
         $sMsgTitle = $aMsgNotice[0]['title'];
         $sMsg = $aMsgNotice[0]['msg'];
     }
     $this->AssignAjax('sMsgTitle', $sMsgTitle);
     $this->AssignAjax('sMsg', $sMsg);
     $this->AssignAjax('bStateError', $bStateError);
     if ($sType == 'json') {
         if ($this->bResponseSpecificHeader and !headers_sent()) {
             header('Content-type: application/json');
         }
         echo json_encode($this->aVarsAjax);
     } elseif ($sType == 'jsonIframe') {
         // Оборачивает json в тег <textarea>, это не дает браузеру выполнить HTML, который вернул iframe
         if ($this->bResponseSpecificHeader and !headers_sent()) {
             header('Content-type: application/json');
         }
         /**
          * Избавляемся от бага, когда в возвращаемом тексте есть &quot;
          */
         echo '<textarea>' . htmlspecialchars(json_encode($this->aVarsAjax)) . '</textarea>';
     } elseif ($sType == 'jsonp') {
         if ($this->bResponseSpecificHeader and !headers_sent()) {
             header('Content-type: application/json');
         }
         $sCallbackName = getRequestStr('jsonpCallbackName') ? getRequestStr('jsonpCallbackName') : 'jsonpCallback';
         $sCallback = getRequestStr($sCallbackName);
         if (!preg_match('#^[a-z0-9\\-\\_]+$#i', $sCallback)) {
             $sCallback = 'callback';
         }
         echo $sCallback . '(' . json_encode($this->aVarsAjax) . ');';
     }
     exit;
 }
 /**
  * Ajax запрос на восстановление пароля
  */
 protected function EventAjaxReminder()
 {
     /**
      * Устанвливаем формат Ajax ответа
      */
     $this->Viewer_SetResponseAjax('json');
     /**
      * Пользователь с таким емайлом существует?
      */
     if (func_check(getRequestStr('mail'), 'mail') and $oUser = $this->User_GetUserByMail(getRequestStr('mail'))) {
         /**
          * Формируем и отправляем ссылку на смену пароля
          */
         $oReminder = Engine::GetEntity('User_Reminder');
         $oReminder->setCode(func_generator(32));
         $oReminder->setDateAdd(date("Y-m-d H:i:s"));
         $oReminder->setDateExpire(date("Y-m-d H:i:s", time() + 60 * 60 * 24 * 7));
         $oReminder->setDateUsed(null);
         $oReminder->setIsUsed(0);
         $oReminder->setUserId($oUser->getId());
         if ($this->User_AddReminder($oReminder)) {
             $this->Message_AddNotice($this->Lang_Get('password_reminder_send_link'));
             $this->Notify_SendReminderCode($oUser, $oReminder);
             return;
         }
     }
     $this->Message_AddError($this->Lang_Get('password_reminder_bad_email'), $this->Lang_Get('error'));
 }
Beispiel #12
0
 /**
  * Загрузка страницы картинок
  */
 protected function EventImageManagerLoadImages()
 {
     // Менеджер изображений может запускаться в том числе и из админки
     // Если передано название скина админки, то используем его, если же
     // нет, то ту тему, которая установлена для сайта
     if (($sAdminTheme = getRequest('admin')) && E::IsAdmin()) {
         C::Set('view.skin', $sAdminTheme);
     }
     // Получим идентификатор пользователя, изображения которого нужно загрузить
     $iUserId = (int) getRequest('profile', FALSE);
     if ($iUserId && E::ModuleUser()->GetUserById($iUserId)) {
         C::Set('menu.data.profile_images.uid', $iUserId);
     } else {
         // Только пользователь может смотреть своё дерево изображений
         if (!E::IsUser()) {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'));
             return;
         }
         $iUserId = E::UserId();
     }
     $sCategory = getRequestStr('category', FALSE);
     $sPage = getRequestStr('page', '1');
     $sTopicId = getRequestStr('topic_id', FALSE);
     if (!$sCategory) {
         return;
     }
     // Страница загрузки картинки с компьютера
     if ($sCategory == 'insert-from-pc') {
         $sImages = E::ModuleViewer()->GetLocalViewer()->Fetch('modals/insert_img/inject.pc.tpl');
         E::ModuleViewer()->AssignAjax('images', $sImages);
         return;
     }
     // Страница загрузки из интернета
     if ($sCategory == 'insert-from-link') {
         $sImages = E::ModuleViewer()->GetLocalViewer()->Fetch("modals/insert_img/inject.link.tpl");
         E::ModuleViewer()->AssignAjax('images', $sImages);
         return;
     }
     $sTemplateName = 'inject.images.tpl';
     $aTplVariables = array();
     $aResources = array('collection' => array());
     $iPages = 0;
     if ($sCategory == 'user') {
         //ок
         // * Аватар и фото пользователя
         $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('target_type' => array('profile_avatar', 'profile_photo'), 'user_id' => $iUserId), $sPage, Config::Get('module.topic.images_per_page'));
         $sTemplateName = 'inject.images.user.tpl';
         $iPages = 0;
     } elseif ($sCategory == '_topic') {
         // * Конкретный топик
         $oTopic = E::ModuleTopic()->GetTopicById($sTopicId);
         if ($oTopic && ($oTopic->isPublished() || $oTopic->getUserId() == E::UserId()) && E::ModuleACL()->IsAllowShowBlog($oTopic->getBlog(), E::User())) {
             $aResourcesId = E::ModuleMresource()->GetCurrentTopicResourcesId($iUserId, $sTopicId);
             if ($aResourcesId) {
                 $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'mresource_id' => $aResourcesId), $sPage, Config::Get('module.topic.images_per_page'));
                 $aResources['count'] = count($aResourcesId);
                 $iPages = ceil($aResources['count'] / Config::Get('module.topic.images_per_page'));
                 $aTplVariables['oTopic'] = $oTopic;
             }
         }
         $sTemplateName = 'inject.images.tpl';
     } elseif ($sCategory == 'talk') {
         // * Письмо
         /** @var ModuleTalk_EntityTalk $oTopic */
         $oTopic = E::ModuleTalk()->GetTalkById($sTopicId);
         if ($oTopic && E::ModuleTalk()->GetTalkUser($sTopicId, $iUserId)) {
             $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'target_type' => 'talk', 'target_id' => $sTopicId), $sPage, Config::Get('module.topic.images_per_page'));
             $aResources['count'] = E::ModuleMresource()->GetMresourcesCountByTargetIdAndUserId('talk', $sTopicId, $iUserId);
             $iPages = ceil($aResources['count'] / Config::Get('module.topic.images_per_page'));
             $aTplVariables['oTopic'] = $oTopic;
         }
         $sTemplateName = 'inject.images.tpl';
     } elseif ($sCategory == 'comments') {
         // * Комментарии
         $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'target_type' => array('talk_comment', 'topic_comment')), $sPage, Config::Get('module.topic.images_per_page'));
         $aResources['count'] = E::ModuleMresource()->GetMresourcesCountByTargetAndUserId(array('talk_comment', 'topic_comment'), $iUserId);
         $iPages = ceil($aResources['count'] / Config::Get('module.topic.images_per_page'));
         $sTemplateName = 'inject.images.tpl';
     } elseif ($sCategory == 'current') {
         //ок
         // * Картинки текущего топика (текст, фотосет, одиночные картинки)
         $aResourcesId = E::ModuleMresource()->GetCurrentTopicResourcesId($iUserId, $sTopicId);
         if ($aResourcesId) {
             $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'mresource_id' => $aResourcesId), $sPage, Config::Get('module.topic.images_per_page'));
             $aResources['count'] = count($aResourcesId);
             $iPages = ceil($aResources['count'] / Config::Get('module.topic.images_per_page'));
         }
         $sTemplateName = 'inject.images.tpl';
     } elseif ($sCategory == 'blog_avatar') {
         // ок
         // * Аватары созданных блогов
         $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('target_type' => 'blog_avatar', 'user_id' => $iUserId), $sPage, Config::Get('module.topic.group_images_per_page'));
         $aResources['count'] = E::ModuleMresource()->GetMresourcesCountByTargetAndUserId('blog_avatar', $iUserId);
         // Получим блоги
         $aBlogsId = array();
         foreach ($aResources['collection'] as $oResource) {
             $aBlogsId[] = $oResource->getTargetId();
         }
         if ($aBlogsId) {
             $aBlogs = E::ModuleBlog()->GetBlogsAdditionalData($aBlogsId);
             $aTplVariables['aBlogs'] = $aBlogs;
         }
         $sTemplateName = 'inject.images.blog.tpl';
         $iPages = ceil($aResources['count'] / Config::Get('module.topic.group_images_per_page'));
     } elseif ($sCategory == 'topics') {
         // ок
         // * Страница топиков
         $aTopicsData = E::ModuleMresource()->GetTopicsPage($iUserId, $sPage, Config::Get('module.topic.group_images_per_page'));
         $aTplVariables['aTopics'] = $aTopicsData['collection'];
         $sTemplateName = 'inject.images.topic.tpl';
         $iPages = ceil($aTopicsData['count'] / Config::Get('module.topic.group_images_per_page'));
         $aResources = array('collection' => array());
     } elseif (in_array($sCategory, E::ModuleTopic()->GetTopicTypes())) {
         // ок
         // * Страница топиков
         $aTopicsData = E::ModuleMresource()->GetTopicsPageByType($iUserId, $sCategory, $sPage, Config::Get('module.topic.group_images_per_page'));
         $aTplVariables['aTopics'] = $aTopicsData['collection'];
         $sTemplateName = 'inject.images.topic.tpl';
         $iPages = ceil($aTopicsData['count'] / Config::Get('module.topic.group_images_per_page'));
         $aResources = array('collection' => array());
     } elseif ($sCategory == 'talks') {
         // ок
         // * Страница писем
         $aTalksData = E::ModuleMresource()->GetTalksPage($iUserId, $sPage, Config::Get('module.topic.group_images_per_page'));
         $aTplVariables['aTalks'] = $aTalksData['collection'];
         $sTemplateName = 'inject.images.talk.tpl';
         $iPages = ceil($aTalksData['count'] / Config::Get('module.topic.group_images_per_page'));
         $aResources = array('collection' => array());
     } else {
         // * Прочие изображения
         $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('target_type' => $sCategory, 'user_id' => $iUserId), $sPage, Config::Get('module.topic.images_per_page'));
         $iPages = ceil($aResources['count'] / Config::Get('module.topic.images_per_page'));
     }
     $aTplVariables['aResources'] = $aResources['collection'];
     $sPath = getRequest('profile', FALSE) ? 'actions/profile/created_photos/' : 'modals/insert_img/';
     $sImages = E::ModuleViewer()->GetLocalViewer()->Fetch($sPath . $sTemplateName, $aTplVariables);
     E::ModuleViewer()->AssignAjax('images', $sImages);
     E::ModuleViewer()->AssignAjax('category', $sCategory);
     E::ModuleViewer()->AssignAjax('page', $sPage);
     E::ModuleViewer()->AssignAjax('pages', $iPages);
 }
 /**
  * Страница со списком плагинов
  *
  */
 protected function EventPlugins()
 {
     $this->sMenuHeadItemSelect = 'plugins';
     /**
      * Получаем название плагина и действие
      */
     if ($sPlugin = getRequestStr('plugin', null, 'get') and $sAction = getRequestStr('action', null, 'get')) {
         return $this->SubmitManagePlugin($sPlugin, $sAction);
     }
     /**
      * Получаем список блогов
      */
     $aPlugins = $this->PluginManager_GetPluginsItems(array('order' => 'name'));
     /**
      * Загружаем переменные в шаблон
      */
     $this->Viewer_Assign('plugins', $aPlugins);
     $this->Viewer_AddHtmlTitle($this->Lang_Get('admin.plugins.title'));
     /**
      * Устанавливаем шаблон вывода
      */
     $this->SetTemplateAction('plugins');
 }
 /**
  * Отписка от блога или пользователя
  *
  */
 protected function EventUnsubscribe()
 {
     /**
      * Устанавливаем формат Ajax ответа
      */
     $this->Viewer_SetResponseAjax('json');
     if (!getRequest('id')) {
         $this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
         return;
     }
     $sType = getRequestStr('type');
     $iType = null;
     /**
      * Определяем от чего отписываемся
      */
     switch ($sType) {
         case 'blogs':
             $iType = ModuleUserfeed::SUBSCRIBE_TYPE_BLOG;
             break;
         case 'users':
             $iType = ModuleUserfeed::SUBSCRIBE_TYPE_USER;
             break;
         default:
             $this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
             return;
     }
     /**
      * Отписываем пользователя
      */
     $this->Userfeed_unsubscribeUser($this->oUserCurrent->getId(), $iType, getRequestStr('id'));
     $this->Message_AddNotice($this->Lang_Get('userfeed_subscribes_updated'), $this->Lang_Get('attention'));
 }
 /**
  * Поиск блогов по названию
  */
 protected function EventAjaxSearch()
 {
     /**
      * Устанавливаем формат Ajax ответа
      */
     $this->Viewer_SetResponseAjax('json');
     /**
      * Фильтр
      */
     $aFilter = array('exclude_type' => 'personal');
     $sOrderWay = in_array(getRequestStr('order'), array('desc', 'asc')) ? getRequestStr('order') : 'desc';
     $sOrderField = in_array(getRequestStr('sort_by'), array('blog_id', 'blog_title', 'blog_count_user', 'blog_count_topic')) ? getRequestStr('sort_by') : 'blog_count_user';
     if (is_numeric(getRequestStr('next_page')) and getRequestStr('next_page') > 0) {
         $iPage = getRequestStr('next_page');
     } else {
         $iPage = 1;
     }
     /**
      * Получаем из реквеста первые буквы блога
      */
     if ($sTitle = getRequestStr('sText')) {
         $sTitle = str_replace('%', '', $sTitle);
     } else {
         $sTitle = '';
     }
     if ($sTitle) {
         $aFilter['title'] = "%{$sTitle}%";
     }
     /**
      * Категории
      */
     if (getRequestStr('category') and $oCategory = $this->Category_GetCategoryById(getRequestStr('category'))) {
         /**
          * Получаем ID всех блогов
          * По сути это костыль, но т.к. блогов обычно не много, то норм
          */
         $aBlogIds = $this->Blog_GetTargetIdsByCategory($oCategory, 1, 1000, true);
         $aFilter['id'] = $aBlogIds ? $aBlogIds : array(0);
     }
     /**
      * Тип
      */
     if (in_array(getRequestStr('type'), array('open', 'close'))) {
         $aFilter['type'] = getRequestStr('type');
     }
     /**
      * Принадлежность
      */
     if ($this->oUserCurrent) {
         if (getRequestStr('relation') == 'my') {
             $aFilter['user_owner_id'] = $this->oUserCurrent->getId();
         } elseif (getRequestStr('relation') == 'join') {
             $aFilter['roles'] = array(ModuleBlog::BLOG_USER_ROLE_USER, ModuleBlog::BLOG_USER_ROLE_ADMINISTRATOR, ModuleBlog::BLOG_USER_ROLE_MODERATOR);
         }
     }
     /**
      * Ищем блоги
      */
     $aResult = $this->Blog_GetBlogsByFilter($aFilter, array($sOrderField => $sOrderWay), $iPage, Config::Get('module.blog.per_page'));
     $bHideMore = $iPage * Config::Get('module.blog.per_page') >= $aResult['count'];
     /**
      * Формируем и возвращает ответ
      */
     $oViewer = $this->Viewer_GetLocalViewer();
     $oViewer->Assign('blogs', $aResult['collection'], true);
     $oViewer->Assign('oUserCurrent', $this->User_GetUserCurrent());
     $oViewer->Assign('textEmpty', $this->Lang_Get('search.alerts.empty'), true);
     $oViewer->Assign('useMore', true, true);
     $oViewer->Assign('hideMore', $bHideMore, true);
     $oViewer->Assign('searchCount', $aResult['count'], true);
     $this->Viewer_AssignAjax('html', $oViewer->Fetch("*****@*****.**"));
     /**
      * Для подгрузки
      */
     $this->Viewer_AssignAjax('count_loaded', count($aResult['collection']));
     $this->Viewer_AssignAjax('next_page', count($aResult['collection']) > 0 ? $iPage + 1 : $iPage);
     $this->Viewer_AssignAjax('hide', $bHideMore);
 }
 /**
  * Обработка кода приглашения при включеном режиме инвайтов
  *
  */
 protected function EventInvite()
 {
     if (!Config::Get('general.reg.invite')) {
         return parent::EventNotFound();
     }
     /**
      * Обработка отправки формы с кодом приглашения
      */
     if (isPost('submit_invite')) {
         /**
          * проверяем код приглашения на валидность
          */
         if ($this->CheckInviteRegister()) {
             $sInviteId = $this->GetInviteRegister();
         } else {
             $sInviteId = getRequestStr('invite_code');
         }
         $oInvate = $this->User_GetInviteByCode($sInviteId);
         if ($oInvate) {
             if (!$this->CheckInviteRegister()) {
                 $this->Session_Set('invite_code', $oInvate->getCode());
             }
             return Router::Action('registration');
         } else {
             $this->Message_AddError($this->Lang_Get('registration_invite_code_error'), $this->Lang_Get('error'));
         }
     }
 }
 /**
  * Удаление пользователя из друзей
  */
 public function EventAjaxFriendDelete()
 {
     /**
      * Устанавливаем формат Ajax ответа
      */
     $this->Viewer_SetResponseAjax('json');
     $sUserId = getRequestStr('idUser', null, 'post');
     /**
      * Если пользователь не авторизирован, возвращаем ошибку
      */
     if (!$this->User_IsAuthorization()) {
         $this->Message_AddErrorSingle($this->Lang_Get('need_authorization'), $this->Lang_Get('error'));
         return;
     }
     $this->oUserCurrent = $this->User_GetUserCurrent();
     /**
      * При попытке добавить в друзья себя, возвращаем ошибку
      */
     if ($this->oUserCurrent->getId() == $sUserId) {
         $this->Message_AddErrorSingle($this->Lang_Get('user_friend_add_self'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Если пользователь не найден, возвращаем ошибку
      */
     if (!($oUser = $this->User_GetUserById($sUserId))) {
         $this->Message_AddErrorSingle($this->Lang_Get('user_friend_del_no'), $this->Lang_Get('error'));
         return;
     }
     $this->oUserProfile = $oUser;
     /**
      * Получаем статус дружбы между пользователями.
      * Если статус не определен, или отличается от принятой заявки,
      * возвращаем ошибку
      */
     $oFriend = $this->User_GetFriend($oUser->getId(), $this->oUserCurrent->getId());
     $aAllowedFriendStatus = array(ModuleUser::USER_FRIEND_ACCEPT + ModuleUser::USER_FRIEND_OFFER, ModuleUser::USER_FRIEND_ACCEPT + ModuleUser::USER_FRIEND_ACCEPT);
     if (!$oFriend || !in_array($oFriend->getFriendStatus(), $aAllowedFriendStatus)) {
         $this->Message_AddErrorSingle($this->Lang_Get('user_friend_del_no'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Удаляем из друзей
      */
     if ($this->User_DeleteFriend($oFriend)) {
         $this->Message_AddNoticeSingle($this->Lang_Get('user_friend_del_ok'), $this->Lang_Get('attention'));
         $oViewerLocal = $this->GetViewerLocal();
         $oViewerLocal->Assign('oUserFriend', $oFriend);
         $this->Viewer_AssignAjax('sToggleText', $oViewerLocal->Fetch("actions/ActionProfile/friend_item.tpl"));
         /**
          * Отправляем пользователю сообщение об удалении дружеской связи
          */
         if (Config::Get('module.user.friend_notice.delete')) {
             $sText = $this->Lang_Get('user_friend_del_notice_text', array('login' => $this->oUserCurrent->getLogin()));
             $oTalk = $this->Talk_SendTalk($this->Lang_Get('user_friend_del_notice_title'), $sText, $this->oUserCurrent, array($oUser), false, false);
             $this->Talk_DeleteTalkUserByArray($oTalk->getId(), $this->oUserCurrent->getId());
         }
         return;
     } else {
         $this->Message_AddErrorSingle($this->Lang_Get('system_error'), $this->Lang_Get('error'));
         return;
     }
 }
 /**
  * Обработка редактирования топика
  *
  * @param ModuleTopic_EntityTopic $oTopic
  * @return mixed
  */
 protected function SubmitEdit($oTopic)
 {
     $oTopic->_setValidateScenario('link');
     /**
      * Сохраняем старое значение идентификатора блога
      */
     $sBlogIdOld = $oTopic->getBlogId();
     /**
      * Заполняем поля для валидации
      */
     $oTopic->setBlogId(getRequestStr('blog_id'));
     $oTopic->setTitle(strip_tags(getRequestStr('topic_title')));
     $oTopic->setLinkUrl(getRequestStr('topic_link_url'));
     $oTopic->setTextSource(getRequestStr('topic_text'));
     $oTopic->setTags(getRequestStr('topic_tags'));
     $oTopic->setUserIp(func_getIp());
     /**
      * Проверка корректности полей формы
      */
     if (!$this->checkTopicFields($oTopic)) {
         return false;
     }
     /**
      * Определяем в какой блог делаем запись
      */
     $iBlogId = $oTopic->getBlogId();
     if ($iBlogId == 0) {
         $oBlog = $this->Blog_GetPersonalBlogByUserId($oTopic->getUserId());
     } else {
         $oBlog = $this->Blog_GetBlogById($iBlogId);
     }
     /**
      * Если блог не определен выдаем предупреждение
      */
     if (!$oBlog) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_unknown'), $this->Lang_Get('error'));
         return false;
     }
     /**
      * Проверяем права на постинг в блог
      */
     if (!$this->ACL_IsAllowBlog($oBlog, $this->oUserCurrent)) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_noallow'), $this->Lang_Get('error'));
         return false;
     }
     /**
      * Проверяем разрешено ли постить топик по времени
      */
     if (isPost('submit_topic_publish') and !$oTopic->getPublishDraft() and !$this->ACL_CanPostTopicTime($this->oUserCurrent)) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic_time_limit'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Теперь можно смело редактировать топик
      */
     $oTopic->setBlogId($oBlog->getId());
     $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');
     }
 }
 /**
  * Проверка поля пользователя на корректность из реквеста
  *
  * @return bool
  */
 public function checkUserField()
 {
     if (!getRequestStr('title')) {
         $this->Message_AddError($this->Lang_Get('user_field_error_add_no_title'), $this->Lang_Get('error'));
         return false;
     }
     if (!getRequestStr('name')) {
         $this->Message_AddError($this->Lang_Get('user_field_error_add_no_name'), $this->Lang_Get('error'));
         return false;
     }
     /**
      * Не допускаем дубликатов по имени
      */
     if ($this->User_userFieldExistsByName(getRequestStr('name'), getRequestStr('id'))) {
         $this->Message_AddError($this->Lang_Get('user_field_error_name_exists'), $this->Lang_Get('error'));
         return false;
     }
     return true;
 }
 /**
  * Подключение/отключение к блогу
  *
  */
 protected function AjaxBlogJoin()
 {
     /**
      * Устанавливаем формат Ajax ответа
      */
     $this->Viewer_SetResponseAjax('json');
     /**
      * Пользователь авторизован?
      */
     if (!$this->oUserCurrent) {
         $this->Message_AddErrorSingle($this->Lang_Get('need_authorization'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Блог существует?
      */
     $idBlog = getRequestStr('idBlog', null, 'post');
     if (!($oBlog = $this->Blog_GetBlogById($idBlog))) {
         $this->Message_AddErrorSingle($this->Lang_Get('system_error'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Проверяем тип блога
      */
     if (!in_array($oBlog->getType(), array('open', 'close', 'invite'))) {
         $this->Message_AddErrorSingle($this->Lang_Get('blog_join_error_invite'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Получаем текущий статус пользователя в блоге
      */
     $oBlogUser = $this->Blog_GetBlogUserByBlogIdAndUserId($oBlog->getId(), $this->oUserCurrent->getId());
     if (!$oBlogUser || $oBlogUser->getUserRole() < ModuleBlog::BLOG_USER_ROLE_GUEST && $oBlog->getType() == 'close') {
         if ($oBlog->getOwnerId() != $this->oUserCurrent->getId()) {
             /**
              * Присоединяем юзера к блогу
              */
             $bResult = false;
             if ($oBlogUser) {
                 $oBlogUser->setUserRole(ModuleBlog::BLOG_USER_ROLE_USER);
                 $bResult = $this->Blog_UpdateRelationBlogUser($oBlogUser);
                 //} elseif($oBlog->getType()=='open' or $oBlog->getType()=='invite') {
             } elseif ($oBlog->getType() != 'close') {
                 $oBlogUserNew = Engine::GetEntity('Blog_BlogUser');
                 $oBlogUserNew->setBlogId($oBlog->getId());
                 $oBlogUserNew->setUserId($this->oUserCurrent->getId());
                 $oBlogUserNew->setUserRole(ModuleBlog::BLOG_USER_ROLE_USER);
                 $bResult = $this->Blog_AddRelationBlogUser($oBlogUserNew);
             }
             if ($bResult) {
                 $this->Message_AddNoticeSingle($this->Lang_Get('blog_join_ok'), $this->Lang_Get('attention'));
                 $this->Viewer_AssignAjax('bState', true);
                 /**
                  * Увеличиваем число читателей блога
                  */
                 $oBlog->setCountUser($oBlog->getCountUser() + 1);
                 $this->Blog_UpdateBlog($oBlog);
                 $this->Viewer_AssignAjax('iCountUser', $oBlog->getCountUser());
                 /**
                  * Добавляем событие в ленту
                  */
                 $this->Stream_write($this->oUserCurrent->getId(), 'join_blog', $oBlog->getId());
                 /**
                  * Добавляем подписку на этот блог в ленту пользователя
                  */
                 $this->Userfeed_subscribeUser($this->oUserCurrent->getId(), ModuleUserfeed::SUBSCRIBE_TYPE_BLOG, $oBlog->getId());
             } else {
                 $sMsg = $oBlog->getType() == 'close' ? $this->Lang_Get('blog_join_error_invite') : $this->Lang_Get('system_error');
                 $this->Message_AddErrorSingle($sMsg, $this->Lang_Get('error'));
                 return;
             }
         } else {
             $this->Message_AddErrorSingle($this->Lang_Get('blog_join_error_self'), $this->Lang_Get('attention'));
             return;
         }
     }
     if ($oBlogUser && $oBlogUser->getUserRole() > ModuleBlog::BLOG_USER_ROLE_GUEST) {
         /**
          * Покидаем блог
          */
         if ($this->Blog_DeleteRelationBlogUser($oBlogUser)) {
             $this->Message_AddNoticeSingle($this->Lang_Get('blog_leave_ok'), $this->Lang_Get('attention'));
             $this->Viewer_AssignAjax('bState', false);
             /**
              * Уменьшаем число читателей блога
              */
             $oBlog->setCountUser($oBlog->getCountUser() - 1);
             $this->Blog_UpdateBlog($oBlog);
             $this->Viewer_AssignAjax('iCountUser', $oBlog->getCountUser());
             /**
              * Удаляем подписку на этот блог в ленте пользователя
              */
             $this->Userfeed_unsubscribeUser($this->oUserCurrent->getId(), ModuleUserfeed::SUBSCRIBE_TYPE_BLOG, $oBlog->getId());
         } else {
             $this->Message_AddErrorSingle($this->Lang_Get('system_error'), $this->Lang_Get('error'));
             return;
         }
     }
 }
 /**
  * Показываем юзеров
  *
  */
 protected function EventIndex()
 {
     /**
      * Получаем статистику
      */
     $this->GetStats();
     /**
      * По какому полю сортировать
      */
     $sOrder = 'user_rating';
     if (getRequest('order')) {
         $sOrder = getRequestStr('order');
     }
     /**
      * В каком направлении сортировать
      */
     $sOrderWay = 'desc';
     if (getRequest('order_way')) {
         $sOrderWay = getRequestStr('order_way');
     }
     $aFilter = array('activate' => 1);
     /**
      * Передан ли номер страницы
      */
     $iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
     /**
      * Получаем список юзеров
      */
     $aResult = $this->User_GetUsersByFilter($aFilter, array($sOrder => $sOrderWay), $iPage, Config::Get('module.user.per_page'));
     $aUsers = $aResult['collection'];
     /**
      * Формируем постраничность
      */
     $aPaging = $this->Viewer_MakePaging($aResult['count'], $iPage, Config::Get('module.user.per_page'), Config::Get('pagination.pages.count'), Router::GetPath('people') . 'index', array('order' => $sOrder, 'order_way' => $sOrderWay));
     /**
      * Получаем алфавитный указатель на список пользователей
      */
     $aPrefixUser = $this->User_GetGroupPrefixUser(1);
     /**
      * Загружаем переменные в шаблон
      */
     $this->Viewer_Assign('aPaging', $aPaging);
     $this->Viewer_Assign('aUsersRating', $aUsers);
     $this->Viewer_Assign('aPrefixUser', $aPrefixUser);
     $this->Viewer_Assign("sUsersOrder", htmlspecialchars($sOrder));
     $this->Viewer_Assign("sUsersOrderWay", htmlspecialchars($sOrderWay));
     $this->Viewer_Assign("sUsersOrderWayNext", htmlspecialchars($sOrderWay == 'desc' ? 'asc' : 'desc'));
     /**
      * Устанавливаем шаблон вывода
      */
     $this->SetTemplateAction('index');
 }
 /**
  * Подготовка запроса на поиск
  *
  * @return array
  */
 private function PrepareRequest()
 {
     $aReq['q'] = getRequestStr('q');
     if (!func_check($aReq['q'], 'text', 2, 255)) {
         /**
          * Если запрос слишком короткий перенаправляем на начальную страницу поиска
          * Хотя тут лучше показывать юзеру в чем он виноват
          */
         Router::Location(Router::GetPath('search'));
     }
     $aReq['sType'] = strtolower(Router::GetActionEvent());
     /**
      * Определяем текущую страницу вывода результата
      */
     $aReq['iPage'] = intval(preg_replace('#^page([1-9]\\d{0,5})$#', '\\1', $this->getParam(0)));
     if (!$aReq['iPage']) {
         $aReq['iPage'] = 1;
     }
     /**
      *  Передача данных в шаблонизатор
      */
     $this->Viewer_Assign('aReq', $aReq);
     return $aReq;
 }
 /**
  * Выводит форму для редактирования профиля и обрабатывает её
  *
  */
 protected function EventProfile()
 {
     /**
      * Устанавливаем title страницы
      */
     $this->Viewer_AddHtmlTitle($this->Lang_Get('settings_menu_profile'));
     $this->Viewer_Assign('aUserFields', $this->User_getUserFields(''));
     $this->Viewer_Assign('aUserFieldsContact', $this->User_getUserFields(array('contact', 'social')));
     /**
      * Загружаем в шаблон JS текстовки
      */
     $this->Lang_AddLangJs(array('settings_profile_field_error_max'));
     /**
      * Если нажали кнопку "Сохранить"
      */
     if (isPost('submit_profile_edit')) {
         $this->Security_ValidateSendForm();
         $bError = false;
         /**
          * Заполняем профиль из полей формы
          */
         /**
          * Определяем гео-объект
          */
         if (getRequest('geo_city')) {
             $oGeoObject = $this->Geo_GetGeoObject('city', getRequestStr('geo_city'));
         } elseif (getRequest('geo_region')) {
             $oGeoObject = $this->Geo_GetGeoObject('region', getRequestStr('geo_region'));
         } elseif (getRequest('geo_country')) {
             $oGeoObject = $this->Geo_GetGeoObject('country', getRequestStr('geo_country'));
         } else {
             $oGeoObject = null;
         }
         /**
          * Проверяем имя
          */
         if (func_check(getRequestStr('profile_name'), 'text', 2, Config::Get('module.user.name_max'))) {
             $this->oUserCurrent->setProfileName(getRequestStr('profile_name'));
         } else {
             $this->oUserCurrent->setProfileName(null);
         }
         /**
          * Проверяем пол
          */
         if (in_array(getRequestStr('profile_sex'), array('man', 'woman', 'other'))) {
             $this->oUserCurrent->setProfileSex(getRequestStr('profile_sex'));
         } else {
             $this->oUserCurrent->setProfileSex('other');
         }
         /**
          * Проверяем дату рождения
          */
         if (func_check(getRequestStr('profile_birthday_day'), 'id', 1, 2) and func_check(getRequestStr('profile_birthday_month'), 'id', 1, 2) and func_check(getRequestStr('profile_birthday_year'), 'id', 4, 4)) {
             $this->oUserCurrent->setProfileBirthday(date("Y-m-d H:i:s", mktime(0, 0, 0, getRequestStr('profile_birthday_month'), getRequestStr('profile_birthday_day'), getRequestStr('profile_birthday_year'))));
         } else {
             $this->oUserCurrent->setProfileBirthday(null);
         }
         /**
          * Проверяем информацию о себе
          */
         if (func_check(getRequestStr('profile_about'), 'text', 1, 3000)) {
             $this->oUserCurrent->setProfileAbout($this->Text_Parser(getRequestStr('profile_about')));
         } else {
             $this->oUserCurrent->setProfileAbout(null);
         }
         /**
          * Ставим дату последнего изменения профиля
          */
         $this->oUserCurrent->setProfileDate(date("Y-m-d H:i:s"));
         /**
          * Запускаем выполнение хуков
          */
         $this->Hook_Run('settings_profile_save_before', array('oUser' => $this->oUserCurrent, 'bError' => &$bError));
         /**
          * Сохраняем изменения профиля
          */
         if (!$bError) {
             if ($this->User_Update($this->oUserCurrent)) {
                 /**
                  * Создаем связь с гео-объектом
                  */
                 if ($oGeoObject) {
                     $this->Geo_CreateTarget($oGeoObject, 'user', $this->oUserCurrent->getId());
                     if ($oCountry = $oGeoObject->getCountry()) {
                         $this->oUserCurrent->setProfileCountry($oCountry->getName());
                     } else {
                         $this->oUserCurrent->setProfileCountry(null);
                     }
                     if ($oRegion = $oGeoObject->getRegion()) {
                         $this->oUserCurrent->setProfileRegion($oRegion->getName());
                     } else {
                         $this->oUserCurrent->setProfileRegion(null);
                     }
                     if ($oCity = $oGeoObject->getCity()) {
                         $this->oUserCurrent->setProfileCity($oCity->getName());
                     } else {
                         $this->oUserCurrent->setProfileCity(null);
                     }
                 } else {
                     $this->Geo_DeleteTargetsByTarget('user', $this->oUserCurrent->getId());
                     $this->oUserCurrent->setProfileCountry(null);
                     $this->oUserCurrent->setProfileRegion(null);
                     $this->oUserCurrent->setProfileCity(null);
                 }
                 $this->User_Update($this->oUserCurrent);
                 /**
                  * Обрабатываем дополнительные поля, type = ''
                  */
                 $aFields = $this->User_getUserFields('');
                 $aData = array();
                 foreach ($aFields as $iId => $aField) {
                     if (isset($_REQUEST['profile_user_field_' . $iId])) {
                         $aData[$iId] = getRequestStr('profile_user_field_' . $iId);
                     }
                 }
                 $this->User_setUserFieldsValues($this->oUserCurrent->getId(), $aData);
                 /**
                  * Динамические поля контактов, type = array('contact','social')
                  */
                 $aType = array('contact', 'social');
                 $aFields = $this->User_getUserFields($aType);
                 /**
                  * Удаляем все поля с этим типом
                  */
                 $this->User_DeleteUserFieldValues($this->oUserCurrent->getId(), $aType);
                 $aFieldsContactType = getRequest('profile_user_field_type');
                 $aFieldsContactValue = getRequest('profile_user_field_value');
                 if (is_array($aFieldsContactType)) {
                     foreach ($aFieldsContactType as $k => $v) {
                         $v = (string) $v;
                         if (isset($aFields[$v]) and isset($aFieldsContactValue[$k]) and is_string($aFieldsContactValue[$k])) {
                             $this->User_setUserFieldsValues($this->oUserCurrent->getId(), array($v => $aFieldsContactValue[$k]), Config::Get('module.user.userfield_max_identical'));
                         }
                     }
                 }
                 $this->Message_AddNoticeSingle($this->Lang_Get('settings_profile_submit_ok'));
                 $this->Hook_Run('settings_profile_save_after', array('oUser' => $this->oUserCurrent));
             } else {
                 $this->Message_AddErrorSingle($this->Lang_Get('system_error'));
             }
         }
     }
     /**
      * Загружаем гео-объект привязки
      */
     $oGeoTarget = $this->Geo_GetTargetByTarget('user', $this->oUserCurrent->getId());
     $this->Viewer_Assign('oGeoTarget', $oGeoTarget);
     /**
      * Загружаем в шаблон список стран, регионов, городов
      */
     $aCountries = $this->Geo_GetCountries(array(), array('sort' => 'asc'), 1, 300);
     $this->Viewer_Assign('aGeoCountries', $aCountries['collection']);
     if ($oGeoTarget) {
         if ($oGeoTarget->getCountryId()) {
             $aRegions = $this->Geo_GetRegions(array('country_id' => $oGeoTarget->getCountryId()), array('sort' => 'asc'), 1, 500);
             $this->Viewer_Assign('aGeoRegions', $aRegions['collection']);
         }
         if ($oGeoTarget->getRegionId()) {
             $aCities = $this->Geo_GetCities(array('region_id' => $oGeoTarget->getRegionId()), array('sort' => 'asc'), 1, 500);
             $this->Viewer_Assign('aGeoCities', $aCities['collection']);
         }
     }
 }
 /**
  * Подгрузка комментариев
  */
 public function EventWallLoadComments()
 {
     $this->Viewer_SetResponseAjax('json');
     if (!$this->WallCheckUserProfile()) {
         return $this->EventErrorDebug();
     }
     if (!($oWall = $this->Wall_GetWallById(getRequestStr('target_id'))) or $oWall->getPid()) {
         return $this->EventErrorDebug();
     }
     // Формируем фильтр для запроса к БД
     $aFilter = array('wall_user_id' => $this->oUserProfile->getId(), 'pid' => $oWall->getId());
     if (is_numeric(getRequest('last_id'))) {
         $aFilter['id_less'] = getRequest('last_id');
     } else {
         if (is_numeric(getRequest('first_id'))) {
             $aFilter['id_more'] = getRequest('first_id');
         } else {
             return $this->EventErrorDebug();
         }
     }
     // Получаем сообщения и формируем ответ
     // Необходимо вернуть все ответы, но ставим "разумное" ограничение
     $aWall = $this->Wall_GetWall($aFilter, array('id' => 'asc'), 1, 300);
     // Передаем переменные
     $this->Viewer_Assign('comments', $aWall['collection'], true);
     $this->Viewer_Assign('oUserCurrent', $this->oUserCurrent);
     // хак, т.к. к этому моменту текущий юзер не загружен в шаблон
     $this->Viewer_AssignAjax('html', $this->Viewer_Fetch('*****@*****.**'));
     $this->Viewer_AssignAjax('count_loaded', count($aWall['collection']));
     if (count($aWall['collection'])) {
         $this->Viewer_AssignAjax('last_id', end($aWall['collection'])->getId());
     }
 }
 /**
  * Вывод обсуждаемых топиков
  */
 protected function EventDiscussed()
 {
     $sPeriod = Config::Get('module.topic.default_period_discussed');
     if (in_array(getRequestStr('period'), array(1, 7, 30, 'all'))) {
         $sPeriod = getRequestStr('period');
     }
     if (!$sPeriod) {
         $sPeriod = 1;
     }
     /**
      * Меню
      */
     $this->sMenuSubItemSelect = 'discussed';
     /**
      * Передан ли номер страницы
      */
     $iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
     if ($iPage == 1 and !getRequest('period')) {
         $this->Viewer_SetHtmlCanonical(Router::GetPath('index') . 'discussed/');
     }
     /**
      * Получаем список топиков
      */
     $aResult = $this->Topic_GetTopicsDiscussed($iPage, Config::Get('module.topic.per_page'), $sPeriod == 'all' ? null : $sPeriod * 60 * 60 * 24);
     /**
      * Если нет топиков за 1 день, то показываем за неделю (7)
      */
     if (!$aResult['count'] and $iPage == 1 and !getRequest('period')) {
         $sPeriod = 7;
         $aResult = $this->Topic_GetTopicsDiscussed($iPage, Config::Get('module.topic.per_page'), $sPeriod == 'all' ? null : $sPeriod * 60 * 60 * 24);
     }
     $aTopics = $aResult['collection'];
     /**
      * Вызов хуков
      */
     $this->Hook_Run('topics_list_show', array('aTopics' => &$aTopics));
     /**
      * Формируем постраничность
      */
     $aPaging = $this->Viewer_MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'), Config::Get('pagination.pages.count'), Router::GetPath('index') . 'discussed', array('period' => $sPeriod));
     /**
      * Загружаем переменные в шаблон
      */
     $this->Viewer_Assign('topics', $aTopics);
     $this->Viewer_Assign('paging', $aPaging);
     $this->Viewer_Assign('periodSelectCurrent', $sPeriod);
     $this->Viewer_Assign('periodSelectRoot', Router::GetPath('index') . 'discussed/');
     /**
      * Устанавливаем шаблон вывода
      */
     $this->SetTemplateAction('index');
     $this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.all_discussed'));
     $this->Viewer_AddHtmlTitle($this->Lang_Get('blog.menu.top_period_' . $sPeriod));
 }
 /**
  * Проверяет наличие security-ключа в сессии
  *
  * @param null|string $sCode Код для проверки, если нет то берется из реквеста
  * @return bool
  */
 public function ValidateSecurityKey($sCode = null)
 {
     if (!$sCode) {
         $sCode = getRequestStr('security_ls_key');
     }
     return $sCode == $this->GetSecurityKey();
 }
 public function EventAjaxPreview()
 {
     $this->Viewer_SetResponseAjax('json');
     /**
      * Пользователь авторизован?
      */
     if (!$this->oUserCurrent) {
         $this->Message_AddErrorSingle($this->Lang_Get('common.error.need_authorization'), $this->Lang_Get('common.error.error'));
         return;
     }
     /**
      * Допустимый тип топика?
      */
     if (!$this->Topic_IsAllowTopicType($sType = getRequestStr('topic_type'))) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic.add.notices.error_type'), $this->Lang_Get('common.error.error'));
         return;
     }
     $aTopicRequest = getRequest('topic');
     /**
      * Проверка на ID при редактировании топика
      */
     $iId = isset($aTopicRequest['id']) ? (int) $aTopicRequest['id'] : null;
     if ($iId and !($oTopicOriginal = $this->Topic_GetTopicById($iId))) {
         return $this->EventErrorDebug();
     }
     /**
      * Создаем объект топика для валидации данных
      */
     $oTopic = Engine::GetEntity('ModuleTopic_EntityTopic');
     $oTopic->setTitle(isset($aTopicRequest['topic_title']) ? strip_tags($aTopicRequest['topic_title']) : '');
     $oTopic->setTextSource(isset($aTopicRequest['topic_text_source']) ? $aTopicRequest['topic_text_source'] : '');
     $oTopic->setTags(isset($aTopicRequest['topic_tags']) ? $aTopicRequest['topic_tags'] : '');
     $oTopic->setDateAdd(date("Y-m-d H:i:s"));
     $oTopic->setDatePublish(date("Y-m-d H:i:s"));
     $oTopic->setUserId($this->oUserCurrent->getId());
     $oTopic->setType($sType);
     $oTopic->setPublish(1);
     $oTopic->setProperties(getRequest('property'));
     /**
      * Перед валидацией аттачим существующие свойста
      */
     if ($iId) {
         $oTopic->setId($iId);
         $a = $oTopic->getPropertyList();
     }
     /**
      * Валидируем необходимые поля топика
      */
     $oTopic->_Validate(array('topic_title', 'topic_text', 'topic_tags', 'topic_type', 'properties'), false);
     if ($oTopic->_hasValidateErrors()) {
         $this->Message_AddErrorSingle($oTopic->_getValidateError());
         return false;
     }
     /**
      * Аттачим дополнительные поля к топику
      */
     $this->Property_AttachPropertiesForTarget($oTopic, $oTopic->getPropertiesObject());
     /**
      * Формируем текст топика
      */
     list($sTextShort, $sTextNew, $sTextCut) = $this->Text_Cut($oTopic->getTextSource());
     $oTopic->setCutText($sTextCut);
     $oTopic->setText($this->Topic_Parser($sTextNew, $oTopic));
     $oTopic->setTextShort($this->Topic_Parser($sTextShort, $oTopic));
     /**
      * Рендерим шаблон для предпросмотра топика
      */
     $oViewer = $this->Viewer_GetLocalViewer();
     $oViewer->Assign('isPreview', true, true);
     $oViewer->Assign('topic', $oTopic, true);
     $sTemplate = '*****@*****.**';
     $sTextResult = $oViewer->Fetch($sTemplate);
     /**
      * Передаем результат в ajax ответ
      */
     $this->Viewer_AssignAjax('sText', $sTextResult);
     return true;
 }
 /**
  * Изменение состояния подписки
  */
 protected function EventAjaxSubscribeToggle()
 {
     /**
      * Устанавливаем формат Ajax ответа
      */
     $this->Viewer_SetResponseAjax('json');
     /**
      * Получаем емайл подписки и проверяем его на валидность
      */
     $sMail = getRequestStr('mail');
     if ($this->oUserCurrent) {
         $sMail = $this->oUserCurrent->getMail();
     }
     if (!func_check($sMail, 'mail')) {
         $this->Message_AddError($this->Lang_Get('registration_mail_error'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Получаем тип объекта подписки
      */
     $sTargetType = getRequestStr('target_type');
     if (!$this->Subscribe_IsAllowTargetType($sTargetType)) {
         $this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
         return;
     }
     $sTargetId = getRequestStr('target_id') ? getRequestStr('target_id') : null;
     $iValue = getRequest('value') ? 1 : 0;
     $oSubscribe = null;
     /**
      * Есть ли доступ к подписке гостям?
      */
     if (!$this->oUserCurrent and !$this->Subscribe_IsAllowTargetForGuest($sTargetType)) {
         $this->Message_AddError($this->Lang_Get('need_authorization'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Проверка объекта подписки
      */
     if (!$this->Subscribe_CheckTarget($sTargetType, $sTargetId, $iValue)) {
         $this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Если подписка еще не существовала, то создаем её
      */
     if ($oSubscribe = $this->Subscribe_AddSubscribeSimple($sTargetType, $sTargetId, $sMail)) {
         $oSubscribe->setStatus($iValue);
         $this->Subscribe_UpdateSubscribe($oSubscribe);
         $this->Message_AddNotice($this->Lang_Get('subscribe_change_ok'), $this->Lang_Get('attention'));
         return;
     }
     $this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
     return;
 }
Beispiel #29
0
 /**
  * Обработчик формирования меню в режиме blogs
  *
  * @param string[] $aFillSet Набор элементов меню
  * @param array $aMenu Само меню
  * @return array
  */
 public function ProcessInsertImageMode($aFillSet, $aMenu = NULL)
 {
     /** @var ModuleMenu_EntityItem[] $aItems */
     $aItems = array();
     // Только пользователь может смотреть своё дерево изображений
     //        if (!E::IsUser()) {
     //            return $aItems;
     //        }
     $sTopicId = getRequestStr('topic_id', getRequestStr('target_id', FALSE));
     if ($sTopicId && !E::ModuleTopic()->GetTopicById($sTopicId)) {
         $sTopicId = FALSE;
     }
     /** @var ModuleMresource_EntityMresourceCategory[] $aResources Категории объектов пользователя */
     $aCategories = E::ModuleMresource()->GetImageCategoriesByUserId(isset($aMenu['uid']) ? $aMenu['uid'] : E::UserId(), $sTopicId);
     // Получим категорию топиков для пользователя
     if ($aTopicsCategory = E::ModuleMresource()->GetTopicsImageCategory(isset($aMenu['uid']) ? $aMenu['uid'] : E::UserId())) {
         foreach ($aTopicsCategory as $oTopicsCategory) {
             $aCategories[] = $oTopicsCategory;
         }
     }
     // Временные изображения
     //        if ($oTmpTopicCategory = E::ModuleMresource()->GetCurrentTopicImageCategory(isset($aMenu['uid']) ? $aMenu['uid'] : E::UserId(), false)) {
     //            $aCategories[] = $oTmpTopicCategory;
     //        }
     if ($sTopicId && ($oCurrentTopicCategory = E::ModuleMresource()->GetCurrentTopicImageCategory(isset($aMenu['uid']) ? $aMenu['uid'] : E::UserId(), $sTopicId))) {
         $aCategories[] = $oCurrentTopicCategory;
     }
     if (!isset($aMenu['protect']) && (!isset($aMenu['uid']) || $aMenu['uid'] == E::UserId())) {
         if ($oTalksCategory = E::ModuleMresource()->GetTalksImageCategory(isset($aMenu['uid']) ? $aMenu['uid'] : E::UserId())) {
             $aCategories[] = $oTalksCategory;
         }
     }
     if ($oCommentsCategory = E::ModuleMresource()->GetCommentsImageCategory(isset($aMenu['uid']) ? $aMenu['uid'] : E::UserId())) {
         $aCategories[] = $oCommentsCategory;
     }
     if ($aCategories) {
         /** @var ModuleMresource_EntityMresourceCategory $oCategory */
         foreach ($aCategories as $oCategory) {
             $aItems['menu_insert_' . $oCategory->getId()] = $this->CreateMenuItem('menu_insert_' . $oCategory->getId(), array('text' => $oCategory->getLabel() . '<span>' . $oCategory->getCount() . '</span>', 'link' => '#', 'active' => FALSE, 'submenu' => array(), 'display' => TRUE, 'options' => array('link_class' => '', 'link_url' => '#', 'class' => 'category-show category-show-' . $oCategory->getId(), 'link_data' => array('category' => $oCategory->getId()))));
         }
     }
     return $aItems;
 }
 /**
  * Отписка от пользователя
  *
  */
 protected function EventUnsubscribe()
 {
     /**
      * Устанавливаем формат Ajax ответа
      */
     $this->Viewer_SetResponseAjax('json');
     /**
      * Пользователь авторизован?
      */
     if (!$this->oUserCurrent) {
         parent::EventNotFound();
     }
     /**
      * Пользователь с таким ID существует?
      */
     if (!$this->User_getUserById(getRequestStr('id'))) {
         $this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
     }
     /**
      * Отписываем
      */
     $this->Stream_unsubscribeUser($this->oUserCurrent->getId(), getRequestStr('id'));
     $this->Message_AddNotice($this->Lang_Get('stream_subscribes_updated'), $this->Lang_Get('attention'));
 }