Example #1
0
 /**
  * Поиск комментариев
  *
  * @return unknown
  */
 function EventComments()
 {
     /**
      * Ищем
      */
     $aReq = $this->PrepareRequest();
     $aRes = $this->PrepareResults($aReq, Config::Get('module.comment.per_page'));
     if (FALSE === $aRes) {
         $this->Message_AddErrorSingle($this->Lang_Get('system_error'));
         return Router::Action('error');
     }
     /**
      * Если поиск дал результаты
      */
     if ($this->bIsResults) {
         /**
          *  Получаем топик-объекты по списку идентификаторов
          */
         $aComments = $this->Comment_GetCommentsAdditionalData(array_keys($this->aSphinxRes['matches']));
         /** 
          * Делаем сниппеты 
          */
         foreach ($aComments as $oComment) {
             $oComment->setText($this->Sphinx_GetSnippet(htmlspecialchars($oComment->getText()), 'comments', $aReq['q'], '<span class="searched-item">', '</span>'));
         }
         /**
          *  Отправляем данные в шаблон 
          */
         $this->Viewer_Assign('aRes', $aRes);
         $this->Viewer_Assign('aComments', $aComments);
     }
 }
 /**
  * Добавление новой записи
  */
 protected function EventAdd()
 {
     /**
      * Устанавливаем title страницы
      */
     $this->Viewer_AddHtmlTitle($this->Lang_Get('plugin.testimonials.add_testimonial_title'));
     /**
      * Проверяем авторизован ли пользователь
      */
     if (!$this->User_IsAuthorization()) {
         $this->Message_AddErrorSingle($this->Lang_Get('not_access'), $this->Lang_Get('error'));
         return Router::Action('error');
     }
     /**
      * Запускаем проверку корректности ввода полей.
      * Дополнительно проверяем, что был отправлен POST запрос.
      */
     if (!$this->checkTestimonialFields()) {
         return false;
     }
     /**
      * Если все ок, заполняем свойства
      */
     $oTestimonial = Engine::GetEntity('PluginTestimonials_Testimonials');
     $oTestimonial->setTextSource(getRequestStr('text'));
     /**
      * Парсим текст на предмет разных ХТМЛ тегов
      */
     $sText = $this->Text_Parser(getRequestStr('text'));
     $oTestimonial->setText($sText);
     $oTestimonial->setUserId($this->oUserCurrent->getId());
     $oTestimonial->setDateAdd(date("Y-m-d H:i:s"));
     /**
      * Проверяем права на постинг
      */
     if (!$this->PluginTestimonials_ACL_CanAddTestimonial($this->oUserCurrent)) {
         $this->Message_AddErrorSingle($this->Lang_Get('plugin.testimonials.create_error_noallow'), $this->Lang_Get('error'));
         return false;
     }
     /**
      * Проверяем разрешено ли постить по времени
      */
     if (isPost('submit_testimonial_save') and !$this->PluginTestimonials_ACL_CanPostTestimonialTime($this->oUserCurrent)) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic_time_limit'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Добавляем запись
      */
     if ($this->PluginTestimonials_Testimonials_AddTestimonial($oTestimonial)) {
         /**
          * Добавляем событие в ленту
          */
         $this->Stream_write($oTestimonial->getUserId(), 'add_testimonial', $oTestimonial->getId());
         Router::Location(Router::GetPath('testimonials'));
     } else {
         $this->Message_AddError($this->Lang_Get('system_error'));
     }
 }
Example #3
0
 protected function EventMyStuff()
 {
     $sUserLogin = $this->sCurrentEvent;
     if (strtolower($this->GetParam(1, 'noth')) == 'new') {
         return Router::Action('mine', 'new', array($sUserLogin, 'friends'));
     }
     return Router::Action('mine', 'index', array($sUserLogin, 'friends'));
 }
 public function Init()
 {
     $this->oUserCurrent = $this->User_GetUserCurrent();
     if (Config::Get('plugin.popupinfo.Only_Registered_Users_Can_See_Info_Tips') and !$this->oUserCurrent) {
         return Router::Action('error');
     }
     $this->SetDefaultEvent('getuserinfo');
 }
 public function InitAction()
 {
     if (Config::Get('general.close') and Config::Get('plugin.getlasttopics.enable_rss')) {
         $sUrl = @$_SERVER['REDIRECT_URL'];
         if (Router::GetAction() == 'login' and substr_count($sUrl, '/rss') > 0) {
             Router::Action('rss', 'login');
         }
     }
 }
 /**
  * Обработка хука инициализации экшенов
  * Может выполняться несколько раз, например, при использовании внутренних реврайтов
  */
 public function InitAction()
 {
     /**
      * Проверка на закрытый режим
      */
     $oUserCurrent = $this->User_GetUserCurrent();
     if (!$oUserCurrent and Config::Get('general.close') and !Router::CheckIsCurrentAction((array) Config::Get('general.close_exceptions'))) {
         Router::Action('auth/login');
     }
 }
Example #7
0
 protected function EventShowCatUsers()
 {
     //Получаем категорию из адресной строки
     $sFirstCat = $this->sCurrentEvent;
     //Первая категория соответсвует имени эвента
     $aParam = $this->GetParams();
     //Последний параметр может оказаться номером страницы, проверяем
     $iPage = 1;
     if (isset($aParam[count($aParam) - 1])) {
         if (preg_match("/^page\\d+\$/i", $aParam[count($aParam) - 1])) {
             $sPage = array_pop($aParam);
             $iPage = (int) substr($sPage, 4);
         }
     }
     array_unshift($aParam, $sFirstCat);
     //Категории пользователей отделяются от категорий блогов словом cat
     $sFullBlogCatName = '';
     $sFullUserCatName = '';
     if (($iCatPosition = array_search('cat', $aParam)) !== false) {
         $aUserCats = array_slice($aParam, 0, $iCatPosition);
         $aBlogCats = array_slice($aParam, $iCatPosition + 1);
         $sFullBlogCatName = strtoupper(implode(':', $aBlogCats));
     } else {
         $aUserCats = $aParam;
     }
     $sFullUserCatName = strtoupper(implode(':', $aUserCats));
     if ($sFullUserCatName && !$this->PluginUsercats_ModuleCategory_IsFullCategoryExist($sFullUserCatName)) {
         return parent::EventNotFound();
     }
     if ($sFullBlogCatName && !$this->PluginCommunitycats_ModuleCategory_IsFullCategoryExist($sFullBlogCatName)) {
         return parent::EventNotFound();
     }
     if (!$sFullBlogCatName && !$sFullUserCatName) {
         return Router::Action('people', 'good');
     }
     //Получаем список пользователей
     $aFilters = array();
     if ($sFullUserCatName) {
         $aFilters['aUserFilter'] = array('beginLike' => array('user_cat' => $sFullUserCatName));
     }
     if ($sFullBlogCatName) {
         $aFilters['aBlogFilter'] = array('beginLike' => array('blog_cat' => $sFullBlogCatName), 'eq' => array('blog_type' => 'personal'));
     }
     $aUsers = $this->PluginUsercats_ModuleCategory_GetUsersByFilters($aFilters, array(), array('iPage' => $iPage, 'iElementsPerPage' => Config::Get('module.user.per_page')), false);
     $iCountUsers = $this->PluginUsercats_ModuleCategory_GetCountUsersByFilters($aFilters);
     //Формируем постраничность
     $aPaging = $this->Viewer_MakePaging($iCountUsers, $iPage, Config::Get('module.user.per_page'), 4, Router::GetPath('people') . implode('/', $aParam));
     //Загружаем переменные в шаблон
     $this->Viewer_Assign('aPath', $aParam);
     $this->Viewer_Assign('aPaging', $aPaging);
     $this->Viewer_Assign('aUsersRating', $aUsers);
     $this->GetStats();
     //Устанавливаем шаблон вывода
     $this->SetTemplateAction('index');
 }
Example #8
0
 public function CheckSearch($aVars)
 {
     if (!MYSEARCH_HOOK_ENABLE) {
         return;
     }
     if (Router::GetAction() == 'search') {
         if (getRequest('q') && isset($_SERVER["HTTP_REFERER"]) && preg_match('|/search/(\\w+)/|', $_SERVER["HTTP_REFERER"], $m)) {
             $sActionEvent = $m[1];
         } else {
             $sActionEvent = Router::GetActionEvent();
         }
         Router::Action('mysearch', $sActionEvent, Router::GetParams());
     }
 }
Example #9
0
 /**
  * Логика инициализации
  *
  */
 public function InitAction()
 {
     /**
      * Проверяем наличие директории install
      */
     if (is_dir(rtrim(Config::Get('path.root.server'), '/') . '/install')) {
         $this->Message_AddErrorSingle($this->Lang_Get('install_directory_exists'));
         Router::Action('error');
     }
     if (!$this->oUserCurrent and Config::Get('general.close') and Router::GetAction() != 'registration' and Router::GetAction() != 'login') {
         Router::Action('login');
     }
     $this->Hook_Run('init_action');
 }
 protected function EventAdd()
 {
     $xResult = E::Module('PluginMagicrules\\Rule')->CheckRuleAction('create_topic', $this->oUserCurrent);
     if ($xResult === true) {
         return parent::EventAdd();
     } else {
         if (is_string($xResult)) {
             E::ModuleMessage()->AddErrorSingle($xResult, E::ModuleLang()->Get('attention'));
             return Router::Action('error');
         } else {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('plugin.magicrules.check_rule_action_error'), E::ModuleLang()->Get('attention'));
             return Router::Action('error');
         }
     }
 }
Example #11
0
 /**
  * Инициализация 
  *
  * @return unknown
  */
 public function Init()
 {
     /**
      * Проверяем авторизован ли юзер
      */
     if (!$this->User_IsAuthorization()) {
         $this->Message_AddErrorSingle($this->Lang_Get('not_access'), $this->Lang_Get('error'));
         return Router::Action('error');
     }
     /**
      * Получаем текущего юзера
      */
     $this->oUserCurrent = $this->User_GetUserCurrent();
     $this->SetDefaultEvent('profile');
     $this->Viewer_AddHtmlTitle($this->Lang_Get('settings_menu'));
 }
 /**
  * Добавление записи на стену
  */
 public function EventWallAdd()
 {
     // * Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json');
     // * Пользователь авторизован?
     if (!E::IsUser()) {
         return parent::EventNotFound();
     }
     $xResult = E::Module('PluginMagicrules\\Rule')->CheckRuleAction('create_wall', E::User());
     if ($xResult === true) {
         return parent::EventWallAdd();
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('plugin.magicrules.check_rule_action_error'), E::ModuleLang()->Get('attention'));
         return Router::Action('error');
     }
 }
Example #13
0
 private function UserBanned($oUser)
 {
     if ($oUser) {
         if ($oUser->IsBannedUnlim()) {
             $sText = $this->Lang_Get('adm_banned2_text');
         } else {
             $sText = $this->Lang_Get('adm_banned1_text', array('date' => $oUser->GetBanLine()));
         }
         $this->Message_AddErrorSingle($sText, $this->Lang_Get('adm_denied_title'));
         $oUser->setKey(uniqid(time(), true));
         $this->User_Update($oUser);
         $this->User_Logout();
     }
     $this->Session_DropSession();
     Router::Action('error');
 }
Example #14
0
 protected function ajaxSendMessage()
 {
     $this->Viewer_SetResponseAjax('json');
     if (!$this->User_IsAuthorization()) {
         return Router::Action('error');
     }
     $iTopicId = (int) getRequest('topicId');
     $sEmail = trim((string) getRequest('email'));
     $sMessage = htmlspecialchars(getRequest('message'));
     if (preg_match('/^[a-z0-9](?:[-._a-z]+[a-z0-9])?@[a-z0-9][-_a-z]+[a-z0-9](?:\\.[a-z0-9][-_a-z0-9]+[a-z0-9])?\\.[a-z]{2,6}$/i', $sEmail)) {
         if ($this->PluginSendtofriend_ModuleSendtofriend_SendMessage($sEmail, $sMessage, $iTopicId)) {
             $this->Message_AddNoticeSingle($this->Lang_Get('sendtofriend_msg_success'), $this->Lang_Get('sendtofriend_msgTitle_success'));
             return;
         }
     }
     $this->Message_AddErrorSingle($this->Lang_Get('sendtofriend_msg_error'), $this->Lang_Get('sendtofriend_msgTitle_error'));
 }
 /**
  * @return string|void
  */
 protected function EventVoteUser()
 {
     // * Пользователь авторизован?
     if (!E::IsUser()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return;
     }
     $xResult = E::Module('PluginMagicrules\\Rule')->CheckRuleAction('vote_user', E::User(), array('vote_value' => (int) $this->getPost('value')));
     if (true === $xResult) {
         return parent::EventVoteUser();
     } else {
         if (is_string($xResult)) {
             E::ModuleMessage()->AddErrorSingle($xResult, E::ModuleLang()->Get('attention'));
             return Router::Action('error');
         } else {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('plugin.magicrules.check_rule_action_error'), E::ModuleLang()->Get('attention'));
             return Router::Action('error');
         }
     }
 }
Example #16
0
 /**
  * Обработка хука инициализации экшенов
  */
 public function InitAction()
 {
     /**
      * Проверяем наличие директории install
      */
     if (is_dir(rtrim(Config::Get('path.root.server'), '/') . '/install')) {
         $this->Message_AddErrorSingle($this->Lang_Get('install_directory_exists'));
         Router::Action('error');
     }
     /**
      * Проверка на закрытый режим
      */
     $oUserCurrent = $this->User_GetUserCurrent();
     if (!$oUserCurrent and Config::Get('general.close') and Router::GetAction() != 'registration' and Router::GetAction() != 'login') {
         Router::Action('login');
     }
     /**
      * Запуск обработки сборщика
      */
     $this->Ls_SenderRun();
 }
 /**
  * Инициализация
  *
  * @return null
  */
 public function Init()
 {
     /**
      * Проверяем авторизован ли юзер
      */
     if (!$this->User_IsAuthorization()) {
         $this->Message_AddErrorSingle($this->Lang_Get('not_access'));
         return Router::Action('error');
     }
     /**
      * Получаем текущего юзера
      */
     $this->oUserCurrent = $this->User_GetUserCurrent();
     /**
      * Проверяем является ли юзер администратором
      */
     if (!$this->oUserCurrent->isAdministrator()) {
         $this->Message_AddErrorSingle($this->Lang_Get('not_access'));
         return Router::Action('error');
     }
     $this->SetDefaultEvent('report');
 }
 /**
  * Обработка напоминания пароля
  *
  */
 protected function EventReminder()
 {
     $this->Viewer_AddHtmlTitle($this->Lang_Get('password_reminder'));
     if ($this->GetParam(0) == 'send') {
         $this->SetTemplateAction('reminder_send');
         return;
     }
     /**
      * Проверка кода на восстановление пароля и генерация нового пароля
      */
     if (func_check($this->GetParam(0), 'md5')) {
         if ($oReminder = $this->User_GetReminderByCode($this->GetParam(0))) {
             if (!$oReminder->getIsUsed() and strtotime($oReminder->getDateExpire()) > time() and $oUser = $this->User_GetUserById($oReminder->getUserId())) {
                 $sNewPassword = func_generator(7);
                 $oUser->setPassword(func_encrypt($sNewPassword));
                 if ($this->User_Update($oUser)) {
                     $oReminder->setDateUsed(date("Y-m-d H:i:s"));
                     $oReminder->setIsUsed(1);
                     $this->User_UpdateReminder($oReminder);
                     $this->Notify_SendReminderPassword($oUser, $sNewPassword);
                     $this->SetTemplateAction('reminder_confirm');
                     return;
                 }
             }
         }
         $this->Message_AddErrorSingle($this->Lang_Get('password_reminder_bad_code'), $this->Lang_Get('error'));
         return Router::Action('error');
     }
     /**
      * Обрабатываем запрос на смену пароля
      */
     if (isPost('submit_reminder')) {
         if (func_check(getRequest('mail'), 'mail') and $oUser = $this->User_GetUserByMail(getRequest('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->Notify_SendReminderCode($oUser, $oReminder);
                 Router::Location(Router::GetPath('login') . 'reminder/send/');
             }
         } else {
             $this->Message_AddError($this->Lang_Get('password_reminder_bad_email'), $this->Lang_Get('error'));
         }
     }
 }
Example #19
0
 /**
  * Страница создания письма
  */
 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()) {
         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(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('common.error.system.base'));
         return Router::Action('error');
     }
 }
 /**
  * Обработка редактирования топика
  *
  * @param unknown_type $oTopic
  * @return unknown
  */
 protected function SubmitEdit($oTopic)
 {
     /**
      * Проверка корректности полей формы
      */
     if (!$this->checkTopicFields($oTopic)) {
         return false;
     }
     /**
      * Определяем в какой блог делаем запись
      */
     $iBlogId = getRequest('blog_id');
     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;
     }
     /**
      * Сохраняем старое значение идентификатора блога
      */
     $sBlogIdOld = $oTopic->getBlogId();
     /**
      * Теперь можно смело редактировать топик
      */
     $oTopic->setBlogId($oBlog->getId());
     $oTopic->setText(htmlspecialchars(getRequest('topic_text')));
     $oTopic->setTextShort(htmlspecialchars(getRequest('topic_text')));
     $oTopic->setTextSource(getRequest('topic_text'));
     $oTopic->setTags(getRequest('topic_tags'));
     $oTopic->setUserIp(func_getIp());
     /**
      * изменяем вопрос/ответы только если еще никто не голосовал
      */
     if ($oTopic->getQuestionCountVote() == 0) {
         $oTopic->setTitle(getRequest('topic_title'));
         $oTopic->clearQuestionAnswer();
         foreach (getRequest('answer', array()) as $sAnswer) {
             $oTopic->addQuestionAnswer($sAnswer);
         }
     }
     $oTopic->setTextHash(md5($oTopic->getType() . $oTopic->getText() . $oTopic->getTitle()));
     /**
      * Проверяем топик на уникальность
      */
     if ($oTopicEquivalent = $this->Topic_GetTopicUnique($this->oUserCurrent->getId(), $oTopic->getTextHash())) {
         if ($oTopicEquivalent->getId() != $oTopic->getId()) {
             $this->Message_AddErrorSingle($this->Lang_Get('topic_create_text_error_unique'), $this->Lang_Get('error'));
             return false;
         }
     }
     /**
      * Публикуем или сохраняем в черновиках
      */
     $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');
     }
 }
Example #21
0
 /**
  * Страница создания письма
  */
 protected function EventAdd()
 {
     $this->sMenuSubItemSelect = 'add';
     $this->Viewer_AddHtmlTitle($this->Lang_Get('talk_menu_inbox_create'));
     /**
      * Получаем список друзей
      */
     $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->checkTalkFields()) {
         return false;
     }
     /**
      * Проверяем разрешено ли отправлять инбокс по времени
      */
     if (!$this->ACL_CanSendTalkTime($this->oUserCurrent)) {
         $this->Message_AddErrorSingle($this->Lang_Get('talk_time_limit'), $this->Lang_Get('error'));
         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)) {
         Router::Location(Router::GetPath('talk') . 'read/' . $oTalk->getId() . '/');
     } else {
         $this->Message_AddErrorSingle($this->Lang_Get('system_error'));
         return Router::Action('error');
     }
 }
 /**
  * Добавление топика
  *
  */
 protected function EventAdd()
 {
     $sTopicType = $this->GetParam(0);
     $iBlogId = (int) getRequest('blog_id');
     if (!($oTopicType = $this->Topic_GetTopicType($sTopicType))) {
         return parent::EventNotFound();
     }
     /**
      * Проверяем права на создание топика
      */
     if (!$this->ACL_CanAddTopic($this->oUserCurrent, $oTopicType)) {
         $this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
         return Router::Action('error');
     }
     $this->sMenuSubItemSelect = $sTopicType;
     /**
      * Получаем доступные блоги по типам
      */
     $aBlogs = array();
     $aBlogs['open'] = $this->Blog_GetBlogsByType('open');
     /**
      * Убираем из списка блоги в которые не доступен постинг
      */
     foreach ($aBlogs['open'] as $k => $oBlogOpen) {
         if (!$this->ACL_IsAllowBlog($oBlogOpen, $this->oUserCurrent)) {
             unset($aBlogs['open'][$k]);
         }
     }
     if ($this->oUserCurrent->isAdministrator()) {
         $aBlogs['close'] = $this->Blog_GetBlogsByType('close');
     } else {
         $aBlogs['close'] = $this->Blog_GetBlogsByTypeAndUserId('close', $this->oUserCurrent->getId());
     }
     /**
      * Вызов хуков
      */
     $this->Hook_Run('topic_add_show', array('aBlogs' => &$aBlogs));
     /**
      * Проверяем на отсутствие блогов
      */
     $bSkipBlogs = true;
     foreach ($aBlogs as $aBlogsType) {
         if ($aBlogsType) {
             $bSkipBlogs = false;
         }
     }
     /**
      * Загружаем переменные в шаблон
      */
     $this->Viewer_Assign('topicType', $oTopicType);
     $this->Viewer_Assign('blogsAllow', $aBlogs);
     $this->Viewer_Assign('skipBlogs', $bSkipBlogs);
     $this->Viewer_Assign('blogId', $iBlogId);
     $this->Viewer_AddHtmlTitle($this->Lang_Get('topic.add.title.add'));
     $this->SetTemplateAction('add');
 }
 /**
  * AJAX удаление фото
  *
  */
 protected function EventDeleteImage()
 {
     /**
      * Проверяем авторизован ли юзер
      */
     if (!$this->User_IsAuthorization()) {
         $this->Message_AddErrorSingle($this->Lang_Get('not_access'), $this->Lang_Get('error'));
         return Router::Action('error');
     }
     /* @var $oImage PluginLsgallery_ModuleImage_EntityImage */
     $oImage = $this->PluginLsgallery_Image_GetImageById(getRequest('id'));
     if ($oImage) {
         /* @var $oAlbum PluginLsgallery_ModuleAlbum_EntityAlbum */
         $oAlbum = $this->PluginLsgallery_Album_GetAlbumById($oImage->getAlbumId());
         if (!$oAlbum || !$this->ACL_AllowAdminAlbumImages($this->oUserCurrent, $oAlbum)) {
             $this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
             return false;
         }
         $this->PluginLsgallery_Image_DeleteImage($oImage);
         $this->Message_AddNotice($this->Lang_Get('plugin.lsgallery.lsgallery_image_deleted'), $this->Lang_Get('attention'));
         return;
     }
     $this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
 }
Example #24
0
    //echo $_SERVER['REQUEST_URI'];
    require_once 'conf.php';
    require_once 'router.php';
    $req_uri = filter_input(INPUT_SERVER, 'REQUEST_URI');
    //echo $req_uri;
    //$post_get = (filter_input_array(INPUT_POST) ?: array()) + (filter_input_array(INPUT_GET) ?: array());
    $post = filter_input_array(INPUT_POST);
    if (isset($post)) {
        foreach ($post as $k => $zzz) {
            tester::TEST($k . "=>" . $zzz);
        }
    }
    /*    if (isset($_POST["test_zzz"]))
            tester::TEST("____hura");
        else
            tester::TEST("____QQQ");*/
    $router = new Router($req_uri, $post);
    $ctrl = $router->Controller() ?: DEFAULT_CTRL;
    if (strtolower($ctrl) == 'index.php') {
        $ctrl = DEFAULT_CTRL;
    }
    $ctrl_php = 'controller_' . strtolower($ctrl) . '.php';
    $ctrl_class = 'Controller' . $ctrl;
    $action = $router->Action() ?: DEFAULT_ACTION;
    $params = $router->Params();
    require_once DIR_CTRL . $ctrl_php;
    $controller = new $ctrl_class();
    $controller->{$action}($params);
} catch (Exception $ex) {
    echo 'Error!!!' . $ex;
}
 /**
  * Обработка напоминания пароля, подтверждение смены пароля
  *
  */
 protected function EventReminder()
 {
     /**
      * Устанавливаем title страницы
      */
     $this->Viewer_AddHtmlTitle($this->Lang_Get('password_reminder'));
     /**
      * Проверка кода на восстановление пароля и генерация нового пароля
      */
     if (func_check($this->GetParam(0), 'md5')) {
         /**
          * Проверка кода подтверждения
          */
         if ($oReminder = $this->User_GetReminderByCode($this->GetParam(0))) {
             if (!$oReminder->getIsUsed() and strtotime($oReminder->getDateExpire()) > time() and $oUser = $this->User_GetUserById($oReminder->getUserId())) {
                 $sNewPassword = func_generator(7);
                 $oUser->setPassword(func_encrypt($sNewPassword));
                 if ($this->User_Update($oUser)) {
                     $oReminder->setDateUsed(date("Y-m-d H:i:s"));
                     $oReminder->setIsUsed(1);
                     $this->User_UpdateReminder($oReminder);
                     $this->Notify_SendReminderPassword($oUser, $sNewPassword);
                     $this->SetTemplateAction('reminder_confirm');
                     return;
                 }
             }
         }
         $this->Message_AddErrorSingle($this->Lang_Get('password_reminder_bad_code'), $this->Lang_Get('error'));
         return Router::Action('error');
     }
 }
 public function Init()
 {
     return Router::Action('error', '404');
 }
Example #27
0
 /**
  * Вызывается в том случаи если не найден евент который запросили через URL
  * По дефолту происходит перекидывание на страницу ошибки, это можно переопределить в наследнике
  * @see Router::Action
  *
  * @return string
  */
 protected function EventNotFound()
 {
     return Router::Action('error', '404');
 }
 /**
  * Выводит отладочную информацию в стандартном сообщении
  * Этим методом можно завершать выполнение евента в случае системной ошибки, например, не удалось найти топик по его ID при голосовании в ajax обработчике
  *
  */
 protected function EventErrorDebug()
 {
     if (Config::Get('sys.debug.action_error')) {
         $aTrace = debug_backtrace(false);
         $aCaller = array_shift($aTrace);
         $aCallerSource = array_shift($aTrace);
         $aPathinfo = pathinfo($aCaller['file']);
         $sMsg = $aPathinfo['basename'] . ' [' . $aCallerSource['class'] . $aCallerSource['type'] . $aCallerSource['function'] . ': ' . $aCaller['line'] . ']';
         $this->Message_AddErrorSingle($sMsg, 'System error');
         if ($this->Viewer_GetResponseAjax()) {
             return true;
         } else {
             return Router::Action('error', '500');
         }
     } else {
         if ($this->Viewer_GetResponseAjax()) {
             $this->Message_AddErrorSingle('System error');
             return true;
         } else {
             return Router::Action('error', '500');
         }
     }
 }
Example #29
0
 /**
  * Удаление блога
  *
  * @return bool
  */
 protected function EventDeleteBlog()
 {
     $this->Security_ValidateSendForm();
     /**
      * Проверяем передан ли в УРЛе номер блога
      */
     $sBlogId = $this->GetParam(0);
     if (!($oBlog = $this->Blog_GetBlogById($sBlogId))) {
         return parent::EventNotFound();
     }
     /**
      * Проверям авторизован ли пользователь
      */
     if (!$this->User_IsAuthorization()) {
         $this->Message_AddErrorSingle($this->Lang_Get('not_access'), $this->Lang_Get('error'));
         return Router::Action('error');
     }
     /**
      * проверяем есть ли право на удаление топика
      */
     if (!($bAccess = $this->ACL_IsAllowDeleteBlog($oBlog, $this->oUserCurrent))) {
         return parent::EventNotFound();
     }
     $aTopics = $this->Topic_GetTopicsByBlogId($sBlogId);
     switch ($bAccess) {
         case ModuleACL::CAN_DELETE_BLOG_EMPTY_ONLY:
             if (is_array($aTopics) and count($aTopics)) {
                 $this->Message_AddErrorSingle($this->Lang_Get('blog_admin_delete_not_empty'), $this->Lang_Get('error'), true);
                 Router::Location($oBlog()->getUrlFull());
             }
             break;
         case ModuleACL::CAN_DELETE_BLOG_WITH_TOPICS:
             /**
              * Если указан идентификатор блога для перемещения,
              * то делаем попытку переместить топики.
              * 
              * (-1) - выбран пункт меню "удалить топики".
              */
             if ($sBlogIdNew = getRequest('topic_move_to') and $sBlogIdNew != -1 and is_array($aTopics) and count($aTopics)) {
                 if (!($oBlogNew = $this->Blog_GetBlogById($sBlogIdNew))) {
                     $this->Message_AddErrorSingle($this->Lang_Get('blog_admin_delete_move_error'), $this->Lang_Get('error'), true);
                     Router::Location($oBlog()->getUrlFull());
                 }
                 /**
                  * Если выбранный блог является персональным, возвращаем ошибку
                  */
                 if ($oBlogNew->getType() == 'personal') {
                     $this->Message_AddErrorSingle($this->Lang_Get('blog_admin_delete_move_personal'), $this->Lang_Get('error'), true);
                     Router::Location($oBlog()->getUrlFull());
                 }
                 /**
                  * Перемещаем топики
                  */
                 $this->Topic_MoveTopics($sBlogId, $sBlogIdNew);
             }
             break;
         default:
             return parent::EventNotFound();
     }
     /**
      * Удаляяем блог и перенаправляем пользователя к списку блогов
      */
     $this->Hook_Run('blog_delete_before', array('sBlogId' => $sBlogId));
     if ($this->Blog_DeleteBlog($sBlogId)) {
         $this->Hook_Run('blog_delete_after', array('sBlogId' => $sBlogId));
         $this->Message_AddNoticeSingle($this->Lang_Get('blog_admin_delete_success'), $this->Lang_Get('attention'), true);
         Router::Location(Router::GetPath('blogs'));
     } else {
         Router::Location($oBlog()->getUrlFull());
     }
 }
Example #30
0
 /**
  * Поиск комментариев
  *
  */
 function EventComments()
 {
     // * Ищем
     $aReq = $this->PrepareRequest();
     $aRes = $this->PrepareResults($aReq, Config::Get('module.comment.per_page'));
     if (false === $aRes) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'));
         return Router::Action('error');
     }
     // * Если поиск дал результаты
     if ($this->bIsResults) {
         // *  Получаем топик-объекты по списку идентификаторов
         $aComments = E::ModuleComment()->GetCommentsAdditionalData(array_keys($this->aSphinxRes['matches']));
         // * Конфигурируем парсер
         $oTextParser = ModuleText::newTextParser('search');
         $aErrors = array();
         // * Делаем сниппеты
         /** @var ModuleComment_EntityComment $oComment */
         foreach ($aComments as $oComment) {
             $oComment->setText($oTextParser->parse(E::ModuleSphinx()->GetSnippet(htmlspecialchars($oComment->getText()), 'comments', $aReq['q'], '<span class="searched-item">', '</span>'), $aErrors));
         }
         /**
          *  Отправляем данные в шаблон
          */
         E::ModuleViewer()->Assign('aRes', $aRes);
         E::ModuleViewer()->Assign('aComments', $aComments);
     }
 }