/**
  * Отправляет пользователю сообщение о добавлении его в друзья
  *
  * @param ModuleUser_EntityUser $oUserTo
  * @param ModuleUser_EntityUser $oUserFrom
  * @param string $sText
  */
 public function SendUserMarkImageNew(ModuleUser_EntityUser $oUserTo, ModuleUser_EntityUser $oUserFrom, $sText)
 {
     /**
      * Если в конфигураторе указан отложенный метод отправки,
      * то добавляем задание в массив. В противном случае,
      * сразу отсылаем на email
      */
     if (Config::Get('module.notify.delayed')) {
         $oNotifyTask = Engine::GetEntity('Notify_Task', array('user_mail' => $oUserTo->getMail(), 'user_login' => $oUserTo->getLogin(), 'notify_text' => $sText, 'notify_subject' => $this->Lang_Get('plugin.lsgallery.lsgallery_marked_subject'), 'date_created' => date("Y-m-d H:i:s"), 'notify_task_status' => self::NOTIFY_TASK_STATUS_NULL));
         if (Config::Get('module.notify.insert_single')) {
             $this->aTask[] = $oNotifyTask;
         } else {
             $this->oMapper->AddTask($oNotifyTask);
         }
     } else {
         /**
          * Отправляем мыло
          */
         $this->Mail_SetAdress($oUserTo->getMail(), $oUserTo->getLogin());
         $this->Mail_SetSubject($this->Lang_Get('plugin.lsgallery.lsgallery_marked_subject'));
         $this->Mail_SetBody($sText);
         $this->Mail_setHTML();
         $this->Mail_Send();
     }
 }
 /**
  * Авторизовывает юзера
  *
  * @param ModuleUser_EntityUser $oUser	Объект пользователя
  * @param bool $bRemember	Запоминать пользователя или нет
  * @param string $sKey	Ключ авторизации для куков
  * @return bool
  */
 public function Authorization(ModuleUser_EntityUser $oUser, $bRemember = true, $sKey = null)
 {
     if (!Config::Get('plugin.blacklist.check_authorization') || $oUser && $oUser->isAdministrator() || $oUser && !$this->PluginBlacklist_ModuleBlacklist_blackMail($oUser->getMail(), $oUser->getLogin())) {
         return parent::Authorization($oUser, $bRemember, $sKey);
     }
     $this->Message_AddErrorSingle($this->Lang_Get(Config::Get('plugin.blacklist.check_ip_exact') ? 'plugin.blacklist.user_in_exact_blacklist' : 'plugin.blacklist.user_in_blacklist'));
     return false;
 }
 /**
  * Обновляет юзера
  *
  * @param ModuleUser_EntityUser $oUser Объект пользователя
  * @return bool
  */
 public function Update(ModuleUser_EntityUser $oUser)
 {
     $sql = "UPDATE " . Config::Get('db.table.user') . "\n      SET\n        user_password = ? ,\n        user_mail = ? ,\n        user_skill = ? ,\n        user_date_activate = ? ,\n        user_date_comment_last = ? ,\n        user_rating = ? ,\n        user_count_vote = ? ,\n        user_activate = ? ,\n                user_activate_key = ? ,\n        user_profile_name = ? ,\n        user_profile_sex = ? ,\n        user_profile_country = ? ,\n        user_profile_region = ? ,\n        user_profile_city = ? ,\n        user_profile_birthday = ? ,\n        user_profile_about = ? ,\n        user_profile_date = ? ,\n        user_profile_avatar = ?  ,\n        user_profile_foto = ? ,\n        user_settings_notice_new_topic = ?  ,\n        user_settings_notice_new_comment = ? ,\n        user_settings_notice_new_talk = ?  ,\n        user_settings_notice_reply_comment = ? ,\n        user_settings_notice_new_friend = ? ,\n        user_settings_timezone = ?\n      WHERE user_id = ?\n    ";
     if ($this->oDb->query($sql, $oUser->getPassword(), $oUser->getMail(), $oUser->getSkill(), $oUser->getDateActivate(), $oUser->getDateCommentLast(), $oUser->getRating(), $oUser->getCountVote(), $oUser->getActivate(), $oUser->getActivateKey(), $oUser->getProfileName(), $oUser->getProfileSex(), $oUser->getProfileCountry(), $oUser->getProfileRegion(), $oUser->getProfileCity(), $oUser->getProfileBirthday(), $oUser->getProfileAbout(), $oUser->getProfileDate(), $oUser->getProfileAvatar(), $oUser->getProfileFoto(), $oUser->getSettingsNoticeNewTopic(), $oUser->getSettingsNoticeNewComment(), $oUser->getSettingsNoticeNewTalk(), $oUser->getSettingsNoticeReplyComment(), $oUser->getSettingsNoticeNewFriend(), $oUser->getSettingsTimezone(), $oUser->getId())) {
         return true;
     }
     return false;
 }
Esempio n. 4
0
 /**
  * Изменение состояния подписки
  */
 protected function EventAjaxSubscribeToggle()
 {
     /**
      * Устанавливаем формат Ajax ответа
      */
     E::ModuleViewer()->SetResponseAjax('json');
     /**
      * Получаем емайл подписки и проверяем его на валидность
      */
     $sMail = F::GetRequestStr('mail');
     if ($this->oUserCurrent) {
         $sMail = $this->oUserCurrent->getMail();
     }
     if (!F::CheckVal($sMail, 'mail')) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('registration_mail_error'), E::ModuleLang()->Get('error'));
         return;
     }
     /**
      * Получаем тип объекта подписки
      */
     $sTargetType = F::GetRequestStr('target_type');
     if (!E::ModuleSubscribe()->IsAllowTargetType($sTargetType)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     $sTargetId = F::GetRequestStr('target_id') ? F::GetRequestStr('target_id') : null;
     $iValue = F::GetRequest('value') ? 1 : 0;
     $oSubscribe = null;
     /**
      * Есть ли доступ к подписке гостям?
      */
     if (!$this->oUserCurrent && !E::ModuleSubscribe()->IsAllowTargetForGuest($sTargetType)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return;
     }
     /**
      * Проверка объекта подписки
      */
     if (!E::ModuleSubscribe()->CheckTarget($sTargetType, $sTargetId, $iValue)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     /**
      * Если подписка еще не существовала, то создаем её
      */
     if ($oSubscribe = E::ModuleSubscribe()->AddSubscribeSimple($sTargetType, $sTargetId, $sMail, $this->oUserCurrent ? $this->oUserCurrent->getId() : null)) {
         $oSubscribe->setStatus($iValue);
         E::ModuleSubscribe()->UpdateSubscribe($oSubscribe);
         E::ModuleMessage()->AddNotice(E::ModuleLang()->Get('subscribe_change_ok'), E::ModuleLang()->Get('attention'));
         return;
     }
     E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
     return;
 }
 /**
  * Изменение состояния подписки
  */
 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('field.email.notices.error'), $this->Lang_Get('common.error.error'));
         return;
     }
     /**
      * Получаем тип объекта подписки
      */
     $sTargetType = getRequestStr('target_type');
     if (!$this->Subscribe_IsAllowTargetType($sTargetType)) {
         return $this->EventErrorDebug();
     }
     $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('common.error.need_authorization'), $this->Lang_Get('common.error.error'));
         return;
     }
     /**
      * Проверка объекта подписки
      */
     if (!$this->Subscribe_CheckTarget($sTargetType, $sTargetId, $iValue)) {
         return $this->EventErrorDebug();
     }
     /**
      * Если подписка еще не существовала, то создаем её
      */
     if ($oSubscribe = $this->Subscribe_AddSubscribeSimple($sTargetType, $sTargetId, $sMail, $this->oUserCurrent ? $this->oUserCurrent->getId() : null)) {
         $oSubscribe->setStatus($iValue);
         $this->Subscribe_UpdateSubscribe($oSubscribe);
         $this->Message_AddNotice($this->Lang_Get('common.success.save'), $this->Lang_Get('common.attention'));
         return;
     }
     return $this->EventErrorDebug();
 }
Esempio n. 6
0
 /**
  * Форма смены пароля, емайла
  */
 protected function EventAccount()
 {
     /**
      * Устанавливаем title страницы
      */
     E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('settings_menu_profile'));
     $this->sMenuSubItemSelect = 'account';
     /**
      * Если нажали кнопку "Сохранить"
      */
     if (isPost('submit_account_edit')) {
         E::ModuleSecurity()->ValidateSendForm();
         $bError = false;
         /**
          * Проверка мыла
          */
         if (F::CheckVal(F::GetRequestStr('mail'), 'mail')) {
             if (($oUserMail = E::ModuleUser()->GetUserByMail(F::GetRequestStr('mail'))) && $oUserMail->getId() != $this->oUserCurrent->getId()) {
                 E::ModuleMessage()->AddError(E::ModuleLang()->Get('settings_profile_mail_error_used'), E::ModuleLang()->Get('error'));
                 $bError = true;
             }
         } else {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('settings_profile_mail_error'), E::ModuleLang()->Get('error'));
             $bError = true;
         }
         /**
          * Проверка на смену пароля
          */
         if ($sPassword = $this->GetPost('password')) {
             if (($nMinLen = Config::Get('module.security.password_len')) < 3) {
                 $nMinLen = 3;
             }
             if (F::CheckVal($sPassword, 'password', $nMinLen)) {
                 if ($sPassword == $this->GetPost('password_confirm')) {
                     if (E::ModuleSecurity()->CheckSalted($this->oUserCurrent->getPassword(), $this->GetPost('password_now'), 'pass')) {
                         $this->oUserCurrent->setPassword($sPassword, true);
                     } else {
                         $bError = true;
                         E::ModuleMessage()->AddError(E::ModuleLang()->Get('settings_profile_password_current_error'), E::ModuleLang()->Get('error'));
                     }
                 } else {
                     $bError = true;
                     E::ModuleMessage()->AddError(E::ModuleLang()->Get('settings_profile_password_confirm_error'), E::ModuleLang()->Get('error'));
                 }
             } else {
                 $bError = true;
                 E::ModuleMessage()->AddError(E::ModuleLang()->Get('settings_profile_password_new_error', array('num' => $nMinLen)), E::ModuleLang()->Get('error'));
             }
         }
         /**
          * Ставим дату последнего изменения
          */
         $this->oUserCurrent->setProfileDate(F::Now());
         /**
          * Запускаем выполнение хуков
          */
         E::ModuleHook()->Run('settings_account_save_before', array('oUser' => $this->oUserCurrent, 'bError' => &$bError));
         /**
          * Сохраняем изменения
          */
         if (!$bError) {
             if (E::ModuleUser()->Update($this->oUserCurrent)) {
                 E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('settings_account_submit_ok'));
                 /**
                  * Подтверждение смены емайла
                  */
                 if (F::GetRequestStr('mail') && F::GetRequestStr('mail') != $this->oUserCurrent->getMail()) {
                     if ($oChangemail = E::ModuleUser()->MakeUserChangemail($this->oUserCurrent, F::GetRequestStr('mail'))) {
                         if ($oChangemail->getMailFrom()) {
                             E::ModuleMessage()->AddNotice(E::ModuleLang()->Get('settings_profile_mail_change_from_notice'));
                         } else {
                             E::ModuleMessage()->AddNotice(E::ModuleLang()->Get('settings_profile_mail_change_to_notice'));
                         }
                     }
                 }
                 E::ModuleHook()->Run('settings_account_save_after', array('oUser' => $this->oUserCurrent));
             } else {
                 E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'));
             }
         }
     }
 }
Esempio n. 7
0
 /**
  * Универсальный метод отправки уведомлений на email
  *
  * @param ModuleUser_EntityUser|string $oUserTo Кому отправляем (пользователь или email)
  * @param string $sTemplate Шаблон для отправки
  * @param string $sSubject Тема письма
  * @param array $aAssign Ассоциативный массив для загрузки переменных в шаблон письма
  * @param string|null $sPluginName Плагин из которого происходит отправка
  */
 public function Send($oUserTo, $sTemplate, $sSubject, $aAssign = array(), $sPluginName = null)
 {
     if ($oUserTo instanceof ModuleUser_EntityUser) {
         $sMail = $oUserTo->getMail();
         $sName = $oUserTo->getLogin();
     } else {
         $sMail = $oUserTo;
         $sName = '';
     }
     /**
      * Передаём в шаблон переменные
      */
     foreach ($aAssign as $k => $v) {
         $this->oViewerLocal->Assign($k, $v);
     }
     /**
      * Формируем шаблон
      */
     $sBody = $this->oViewerLocal->Fetch($this->GetTemplatePath($sTemplate, $sPluginName));
     /**
      * Если в конфигураторе указан отложенный метод отправки,
      * то добавляем задание в массив. В противном случае,
      * сразу отсылаем на email
      */
     if (Config::Get('module.notify.delayed')) {
         $oNotifyTask = Engine::GetEntity('Notify_Task', array('user_mail' => $sMail, 'user_login' => $sName, 'notify_text' => $sBody, 'notify_subject' => $sSubject, 'date_created' => date("Y-m-d H:i:s"), 'notify_task_status' => self::NOTIFY_TASK_STATUS_NULL));
         if (Config::Get('module.notify.insert_single')) {
             $this->aTask[] = $oNotifyTask;
         } else {
             $this->oMapper->AddTask($oNotifyTask);
         }
     } else {
         /**
          * Отправляем мыло
          */
         $this->Mail_SetAdress($sMail, $sName);
         $this->Mail_SetSubject($sSubject);
         $this->Mail_SetBody($sBody);
         $this->Mail_setHTML();
         $this->Mail_Send();
     }
 }
Esempio n. 8
0
 /**
  * Обработка добавление комментария к топику
  *
  */
 protected function SubmitComment()
 {
     /**
      * Проверям авторизован ли пользователь
      */
     if (!$this->User_IsAuthorization()) {
         $this->Message_AddErrorSingle($this->Lang_Get('need_authorization'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Проверяем топик
      */
     if (!($oTopic = $this->Topic_GetTopicById(getRequestStr('cmt_target_id')))) {
         $this->Message_AddErrorSingle($this->Lang_Get('system_error'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Возможность постить коммент в топик в черновиках
      */
     if (!$oTopic->getPublish() and $this->oUserCurrent->getId() != $oTopic->getUserId() and !$this->oUserCurrent->isAdministrator()) {
         $this->Message_AddErrorSingle($this->Lang_Get('system_error'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Проверяем разрешено ли постить комменты
      */
     if (!$this->ACL_CanPostComment($this->oUserCurrent) and !$this->oUserCurrent->isAdministrator()) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic_comment_acl'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Проверяем разрешено ли постить комменты по времени
      */
     if (!$this->ACL_CanPostCommentTime($this->oUserCurrent) and !$this->oUserCurrent->isAdministrator()) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic_comment_limit'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Проверяем запрет на добавления коммента автором топика
      */
     if ($oTopic->getForbidComment()) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic_comment_notallow'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Проверяем текст комментария
      */
     $sText = $this->Text_Parser(getRequestStr('comment_text'));
     if (!func_check($sText, 'text', 2, 100000)) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic_comment_add_text_error'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Проверям на какой коммент отвечаем
      */
     $sParentId = (int) getRequest('reply');
     if (!func_check($sParentId, 'id')) {
         $this->Message_AddErrorSingle($this->Lang_Get('system_error'), $this->Lang_Get('error'));
         return;
     }
     $oCommentParent = null;
     if ($sParentId != 0) {
         /**
          * Проверяем существует ли комментарий на который отвечаем
          */
         if (!($oCommentParent = $this->Comment_GetCommentById($sParentId))) {
             $this->Message_AddErrorSingle($this->Lang_Get('system_error'), $this->Lang_Get('error'));
             return;
         }
         /**
          * Проверяем из одного топика ли новый коммент и тот на который отвечаем
          */
         if ($oCommentParent->getTargetId() != $oTopic->getId()) {
             $this->Message_AddErrorSingle($this->Lang_Get('system_error'), $this->Lang_Get('error'));
             return;
         }
     } else {
         /**
          * Корневой комментарий
          */
         $sParentId = null;
     }
     /**
      * Проверка на дублирующий коммент
      */
     if ($this->Comment_GetCommentUnique($oTopic->getId(), 'topic', $this->oUserCurrent->getId(), $sParentId, md5($sText))) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic_comment_spam'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Создаём коммент
      */
     $oCommentNew = Engine::GetEntity('Comment');
     $oCommentNew->setTargetId($oTopic->getId());
     $oCommentNew->setTargetType('topic');
     $oCommentNew->setTargetParentId($oTopic->getBlog()->getId());
     $oCommentNew->setUserId($this->oUserCurrent->getId());
     $oCommentNew->setText($sText);
     $oCommentNew->setDate(date("Y-m-d H:i:s"));
     $oCommentNew->setUserIp(func_getIp());
     $oCommentNew->setPid($sParentId);
     $oCommentNew->setTextHash(md5($sText));
     $oCommentNew->setPublish($oTopic->getPublish());
     /**
      * Добавляем коммент
      */
     $this->Hook_Run('comment_add_before', array('oCommentNew' => $oCommentNew, 'oCommentParent' => $oCommentParent, 'oTopic' => $oTopic));
     if ($this->Comment_AddComment($oCommentNew)) {
         $this->Hook_Run('comment_add_after', array('oCommentNew' => $oCommentNew, 'oCommentParent' => $oCommentParent, 'oTopic' => $oTopic));
         $this->Viewer_AssignAjax('sCommentId', $oCommentNew->getId());
         if ($oTopic->getPublish()) {
             /**
              * Добавляем коммент в прямой эфир если топик не в черновиках
              */
             $oCommentOnline = Engine::GetEntity('Comment_CommentOnline');
             $oCommentOnline->setTargetId($oCommentNew->getTargetId());
             $oCommentOnline->setTargetType($oCommentNew->getTargetType());
             $oCommentOnline->setTargetParentId($oCommentNew->getTargetParentId());
             $oCommentOnline->setCommentId($oCommentNew->getId());
             $this->Comment_AddCommentOnline($oCommentOnline);
         }
         /**
          * Сохраняем дату последнего коммента для юзера
          */
         $this->oUserCurrent->setDateCommentLast(date("Y-m-d H:i:s"));
         $this->User_Update($this->oUserCurrent);
         /**
          * Список емайлов на которые не нужно отправлять уведомление
          */
         $aExcludeMail = array($this->oUserCurrent->getMail());
         /**
          * Отправляем уведомление тому на чей коммент ответили
          */
         if ($oCommentParent and $oCommentParent->getUserId() != $oTopic->getUserId() and $oCommentNew->getUserId() != $oCommentParent->getUserId()) {
             $oUserAuthorComment = $oCommentParent->getUser();
             $aExcludeMail[] = $oUserAuthorComment->getMail();
             $this->Notify_SendCommentReplyToAuthorParentComment($oUserAuthorComment, $oTopic, $oCommentNew, $this->oUserCurrent);
         }
         /**
          * Отправка уведомления автору топика
          */
         $this->Subscribe_Send('topic_new_comment', $oTopic->getId(), 'notify.comment_new.tpl', $this->Lang_Get('notify_subject_comment_new'), array('oTopic' => $oTopic, 'oComment' => $oCommentNew, 'oUserComment' => $this->oUserCurrent), $aExcludeMail);
         /**
          * Добавляем событие в ленту
          */
         $this->Stream_write($oCommentNew->getUserId(), 'add_comment', $oCommentNew->getId(), $oTopic->getPublish() && $oTopic->getBlog()->getType() != 'close');
     } else {
         $this->Message_AddErrorSingle($this->Lang_Get('system_error'), $this->Lang_Get('error'));
     }
 }
 /**
  * Форма смены пароля, емайла
  */
 protected function EventAccount()
 {
     /**
      * Устанавливаем title страницы
      */
     $this->Viewer_AddHtmlTitle($this->Lang_Get('settings_menu_profile'));
     $this->sMenuSubItemSelect = 'account';
     /**
      * Если нажали кнопку "Сохранить"
      */
     if (isPost('submit_account_edit')) {
         $this->Security_ValidateSendForm();
         $bError = false;
         /**
          * Проверка мыла
          */
         if (func_check(getRequestStr('mail'), 'mail')) {
             if ($oUserMail = $this->User_GetUserByMail(getRequestStr('mail')) and $oUserMail->getId() != $this->oUserCurrent->getId()) {
                 $this->Message_AddError($this->Lang_Get('settings_profile_mail_error_used'), $this->Lang_Get('error'));
                 $bError = true;
             }
         } else {
             $this->Message_AddError($this->Lang_Get('settings_profile_mail_error'), $this->Lang_Get('error'));
             $bError = true;
         }
         /**
          * Проверка на смену пароля
          */
         if (getRequestStr('password', '') != '') {
             if (func_check(getRequestStr('password'), 'password', 5)) {
                 if (getRequestStr('password') == getRequestStr('password_confirm')) {
                     if (func_encrypt(getRequestStr('password_now')) == $this->oUserCurrent->getPassword()) {
                         $this->oUserCurrent->setPassword(func_encrypt(getRequestStr('password')));
                     } else {
                         $bError = true;
                         $this->Message_AddError($this->Lang_Get('settings_profile_password_current_error'), $this->Lang_Get('error'));
                     }
                 } else {
                     $bError = true;
                     $this->Message_AddError($this->Lang_Get('settings_profile_password_confirm_error'), $this->Lang_Get('error'));
                 }
             } else {
                 $bError = true;
                 $this->Message_AddError($this->Lang_Get('settings_profile_password_new_error'), $this->Lang_Get('error'));
             }
         }
         /**
          * Ставим дату последнего изменения
          */
         $this->oUserCurrent->setProfileDate(date("Y-m-d H:i:s"));
         /**
          * Запускаем выполнение хуков
          */
         $this->Hook_Run('settings_account_save_before', array('oUser' => $this->oUserCurrent, 'bError' => &$bError));
         /**
          * Сохраняем изменения
          */
         if (!$bError) {
             if ($this->User_Update($this->oUserCurrent)) {
                 $this->Message_AddNoticeSingle($this->Lang_Get('settings_account_submit_ok'));
                 /**
                  * Подтверждение смены емайла
                  */
                 if (getRequestStr('mail') and getRequestStr('mail') != $this->oUserCurrent->getMail()) {
                     if ($oChangemail = $this->User_MakeUserChangemail($this->oUserCurrent, getRequestStr('mail'))) {
                         if ($oChangemail->getMailFrom()) {
                             $this->Message_AddNotice($this->Lang_Get('settings_profile_mail_change_from_notice'));
                         } else {
                             $this->Message_AddNotice($this->Lang_Get('settings_profile_mail_change_to_notice'));
                         }
                     }
                 }
                 $this->Hook_Run('settings_account_save_after', array('oUser' => $this->oUserCurrent));
             } else {
                 $this->Message_AddErrorSingle($this->Lang_Get('system_error'));
             }
         }
     }
 }
Esempio n. 10
0
 /**
  * Обработка добавлени топика
  *
  * @return mixed
  */
 protected function SubmitAdd()
 {
     /**
      * Проверяем отправлена ли форма с данными(хотяб одна кнопка)
      */
     if (!isPost('submit_topic_publish') and !isPost('submit_topic_save')) {
         return false;
     }
     $oTopic = Engine::GetEntity('Topic');
     $oTopic->_setValidateScenario('link');
     /**
      * Заполняем поля для валидации
      */
     $oTopic->setBlogId(getRequestStr('blog_id'));
     $oTopic->setTitle(strip_tags(getRequestStr('topic_title')));
     $oTopic->setTextSource(getRequestStr('topic_text'));
     $oTopic->setTags(getRequestStr('topic_tags'));
     $oTopic->setUserId($this->oUserCurrent->getId());
     $oTopic->setType('link');
     $oTopic->setLinkUrl(getRequestStr('topic_link_url'));
     $oTopic->setDateAdd(date("Y-m-d H:i:s"));
     $oTopic->setUserIp(func_getIp());
     /**
      * Проверка корректности полей формы
      */
     if (!$this->checkTopicFields($oTopic)) {
         return false;
     }
     /**
      * Определяем в какой блог делаем запись
      */
     $iBlogId = $oTopic->getBlogId();
     if ($iBlogId == 0) {
         $oBlog = $this->Blog_GetPersonalBlogByUserId($this->oUserCurrent->getId());
     } else {
         $oBlog = $this->Blog_GetBlogById($iBlogId);
     }
     /**
      * Если блог не определен выдаем предупреждение
      */
     if (!$oBlog) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_unknown'), $this->Lang_Get('error'));
         return false;
     }
     /**
      * Проверяем права на постинг в блог
      */
     if (!$this->ACL_IsAllowBlog($oBlog, $this->oUserCurrent)) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_noallow'), $this->Lang_Get('error'));
         return false;
     }
     /**
      * Проверяем разрешено ли постить топик по времени
      */
     if (isPost('submit_topic_publish') and !$this->ACL_CanPostTopicTime($this->oUserCurrent)) {
         $this->Message_AddErrorSingle($this->Lang_Get('topic_time_limit'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Теперь можно смело добавлять топик к блогу
      */
     $oTopic->setBlogId($oBlog->getId());
     $oTopic->setText($this->Text_Parser($oTopic->getTextSource()));
     $oTopic->setTextShort($oTopic->getText());
     $oTopic->setCutText(null);
     /**
      * Публикуем или сохраняем
      */
     if (isset($_REQUEST['submit_topic_publish'])) {
         $oTopic->setPublish(1);
         $oTopic->setPublishDraft(1);
     } else {
         $oTopic->setPublish(0);
         $oTopic->setPublishDraft(0);
     }
     /**
      * Принудительный вывод на главную
      */
     $oTopic->setPublishIndex(0);
     if ($this->ACL_IsAllowPublishIndex($this->oUserCurrent)) {
         if (getRequest('topic_publish_index')) {
             $oTopic->setPublishIndex(1);
         }
     }
     /**
      * Запрет на комментарии к топику
      */
     $oTopic->setForbidComment(0);
     if (getRequest('topic_forbid_comment')) {
         $oTopic->setForbidComment(1);
     }
     /**
      * Запускаем выполнение хуков
      */
     $this->Hook_Run('topic_add_before', array('oTopic' => $oTopic, 'oBlog' => $oBlog));
     /**
      * Добавляем топик
      */
     if ($this->Topic_AddTopic($oTopic)) {
         $this->Hook_Run('topic_add_after', array('oTopic' => $oTopic, 'oBlog' => $oBlog));
         /**
          * Получаем топик, чтоб подцепить связанные данные
          */
         $oTopic = $this->Topic_GetTopicById($oTopic->getId());
         /**
          * Обновляем количество топиков в блоге
          */
         $this->Blog_RecalculateCountTopicByBlogId($oTopic->getBlogId());
         /**
          * Добавляем автора топика в подписчики на новые комментарии к этому топику
          */
         $this->Subscribe_AddSubscribeSimple('topic_new_comment', $oTopic->getId(), $this->oUserCurrent->getMail());
         //Делаем рассылку спама всем, кто состоит в этом блоге
         if ($oTopic->getPublish() == 1 and $oBlog->getType() != 'personal') {
             $this->Topic_SendNotifyTopicNew($oBlog, $oTopic, $this->oUserCurrent);
         }
         /**
          * Добавляем событие в ленту
          */
         $this->Stream_write($oTopic->getUserId(), 'add_topic', $oTopic->getId(), $oTopic->getPublish() && $oBlog->getType() != 'close');
         Router::Location($oTopic->getUrl());
     } else {
         $this->Message_AddErrorSingle($this->Lang_Get('system_error'));
         return Router::Action('error');
     }
 }
Esempio n. 11
0
 /**
  * Обработка формы добавление поста
  *
  */
 protected function submitPostAdd($oForum = null, $oTopic = null)
 {
     if (!($oForum && $oTopic)) {
         return false;
     }
     /**
      * Проверяем разрешено ли постить
      */
     if (!$this->ACL_CanAddForumPost($this->oUserCurrent)) {
         $this->Message_AddErrorSingle($this->Lang_Get('plugin.forum.reply_not_allow'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Проверяем разрешено ли постить по времени
      */
     if (!$this->ACL_CanAddForumPostTime($this->oUserCurrent)) {
         $this->Message_AddErrorSingle($this->Lang_Get('plugin.forum.reply_time_limit'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Проверяем не закрыто ли обсуждение
      */
     if ($oTopic->getState() == 1 and !$this->ACL_CanAddForumPostClose($this->oUserCurrent)) {
         $this->Message_AddErrorSingle($this->Lang_Get('plugin.forum.reply_not_allow_close'), $this->Lang_Get('error'));
         return;
     }
     /**
      * Создаём
      */
     $oPost = Engine::GetEntity('PluginForum_Forum_Post');
     $oPost->_setValidateScenario('post');
     /**
      * Заполняем поля для валидации
      */
     $oPost->setTitle(forum_parse_title(getRequestStr('post_title')));
     $oPost->setTopicId($oTopic->getId());
     $oPost->setUserIp(func_getIp());
     $oPost->setText($this->PluginForum_Forum_TextParse(getRequestStr('post_text')));
     $oPost->setTextSource(getRequestStr('post_text'));
     $oPost->setTextHash(md5(getRequestStr('post_text')));
     $oPost->setDateAdd(date('Y-m-d H:i:s'));
     if (!$this->User_IsAuthorization()) {
         $oPost->setUserId(0);
         $oPost->setGuestName(strip_tags(getRequestStr('guest_name')));
     } else {
         $oPost->setUserId($this->oUserCurrent->getId());
     }
     if (getRequestStr('replyto')) {
         $oPost->setParentId((int) getRequestStr('replyto'));
     }
     /**
      * Вложения
      */
     $sTargetTmp = isset($_COOKIE['ls_fattach_target_tmp']) ? $_COOKIE['ls_fattach_target_tmp'] : 'null';
     $aFiles = $this->PluginForum_Forum_GetFileItemsByTargetTmp($sTargetTmp);
     /**
      * Проверяем поля формы
      */
     if (!$this->checkPostFields($oPost)) {
         return false;
     }
     /**
      * Вызов хуков
      */
     $this->Hook_Run('forum_post_add_before', array('oPost' => $oPost, 'oTopic' => $oTopic, 'oForum' => $oForum));
     /**
      * Добавляем
      */
     if ($this->PluginForum_Forum_AddPost($oPost)) {
         $this->Hook_Run('forum_post_add_after', array('oPost' => $oPost, 'oTopic' => $oTopic, 'oForum' => $oForum));
         /**
          * Привязываем вложения к id поста
          * TODO: здесь нужно это делать одним запросом, а не перебором сущностей
          */
         if (count($aFiles)) {
             foreach ($aFiles as $oFile) {
                 $oFile->setTargetTmp(null);
                 $this->PluginForum_Forum_UpdateFile($oFile);
                 $oPost->files->add($oFile);
             }
             $oPost->Update();
             $this->PluginForum_Forum_UpdatePost($oPost);
         }
         /**
          * Удаляем временную куку
          */
         setcookie('ls_fattach_target_tmp', null);
         /**
          * Обновляем инфу в топике
          */
         $oTopic->setLastPostId($oPost->getId());
         $oTopic->setLastPostDate($oPost->getDateAdd());
         $oTopic->setCountPost((int) $oTopic->getCountPost() + 1);
         $this->PluginForum_Forum_SaveTopic($oTopic);
         /**
          * Обновляем инфу в форуме
          */
         $oForum->setLastPostId($oPost->getId());
         $oForum->setLastPostDate($oPost->getDateAdd());
         $oForum->setCountPost((int) $oForum->getCountPost() + 1);
         $this->PluginForum_Forum_SaveForum($oForum);
         /**
          * Обновляем инфу о пользователе
          */
         $this->PluginForum_Forum_increaseUserPosts($this->oUserCurrent);
         /**
          * Список емайлов на которые не нужно отправлять уведомление
          */
         $aExcludeMail = array();
         if ($this->oUserCurrent) {
             /**
              * Исключаем автора поста из списка рассылки
              */
             $aExcludeMail[] = $this->oUserCurrent->getMail();
             /**
              * Добавляем событие в ленту
              */
             $this->Stream_write($oPost->getUserId(), 'add_forum_post', $oPost->getId());
         }
         /**
          * Отправка уведомления подписчикам темы
          */
         $this->PluginForum_Forum_SendSubscribeNewPost($oTopic->getId(), array('oForum' => $oForum, 'oTopic' => $oTopic, 'oPost' => $oPost, 'oUser' => $this->oUserCurrent), $aExcludeMail);
         /**
          * Отправка уведомления на отвеченные посты
          */
         $this->PluginForum_Forum_SendNotifyReply($oPost, $aExcludeMail);
         Router::Location($oPost->getUrlFull());
     } else {
         $this->Message_AddErrorSingle($this->Lang_Get('system_error'));
         return Router::Action('error');
     }
 }
Esempio n. 12
0
 /**
  * Обработка добавление комментария к топику
  *
  */
 protected function SubmitComment()
 {
     // * Проверям авторизован ли пользователь
     if (!E::ModuleUser()->IsAuthorization()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return;
     }
     // * Проверяем топик
     if (!($oTopic = E::ModuleTopic()->GetTopicById(F::GetRequestStr('cmt_target_id')))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     // * Возможность постить коммент в топик в черновиках
     if (!$oTopic->getPublish()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     // * Проверяем разрешено ли постить комменты
     switch (E::ModuleACL()->CanPostComment($this->oUserCurrent, $oTopic)) {
         case ModuleACL::CAN_TOPIC_COMMENT_ERROR_BAN:
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_banned'), E::ModuleLang()->Get('attention'));
             return;
         case ModuleACL::CAN_TOPIC_COMMENT_FALSE:
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_acl'), E::ModuleLang()->Get('error'));
             return;
     }
     // * Проверяем разрешено ли постить комменты по времени
     if (!E::ModuleACL()->CanPostCommentTime($this->oUserCurrent)) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_limit'), E::ModuleLang()->Get('error'));
         return;
     }
     // * Проверяем запрет на добавления коммента автором топика
     if ($oTopic->getForbidComment()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_notallow'), E::ModuleLang()->Get('error'));
         return;
     }
     // * Проверяем текст комментария
     $sText = E::ModuleText()->Parse(F::GetRequestStr('comment_text'));
     if (!F::CheckVal($sText, 'text', Config::Val('module.comment.min_length', 2), Config::Val('module.comment.max_length', 10000))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_text_len', array('min' => 2, 'max' => Config::Val('module.comment.max_length', 10000))), E::ModuleLang()->Get('error'));
         return;
     }
     $iMin = Config::Val('module.comment.min_length', 2);
     $iMax = Config::Val('module.comment.max_length', 0);
     if (!F::CheckVal($sText, 'text', $iMin, $iMax)) {
         if ($iMax) {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_text_len', array('min' => $iMin, 'max' => $iMax)), E::ModuleLang()->Get('error'));
         } else {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_text_min', array('min' => $iMin)), E::ModuleLang()->Get('error'));
         }
         return;
     }
     // * Проверям на какой коммент отвечаем
     if (!$this->isPost('reply')) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     $oCommentParent = null;
     $iParentId = intval(F::GetRequest('reply'));
     if ($iParentId != 0) {
         // * Проверяем существует ли комментарий на который отвечаем
         if (!($oCommentParent = E::ModuleComment()->GetCommentById($iParentId))) {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
             return;
         }
         // * Проверяем из одного топика ли новый коммент и тот на который отвечаем
         if ($oCommentParent->getTargetId() != $oTopic->getId()) {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
             return;
         }
     } else {
         // * Корневой комментарий
         $iParentId = null;
     }
     // * Проверка на дублирующий коммент
     if (E::ModuleComment()->GetCommentUnique($oTopic->getId(), 'topic', $this->oUserCurrent->getId(), $iParentId, md5($sText))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_spam'), E::ModuleLang()->Get('error'));
         return;
     }
     // * Создаём коммент
     /** @var ModuleComment_EntityComment $oCommentNew */
     $oCommentNew = E::GetEntity('Comment');
     $oCommentNew->setTargetId($oTopic->getId());
     $oCommentNew->setTargetType('topic');
     $oCommentNew->setTargetParentId($oTopic->getBlog()->getId());
     $oCommentNew->setUserId($this->oUserCurrent->getId());
     $oCommentNew->setText($sText);
     $oCommentNew->setDate(F::Now());
     $oCommentNew->setUserIp(F::GetUserIp());
     $oCommentNew->setPid($iParentId);
     $oCommentNew->setTextHash(md5($sText));
     $oCommentNew->setPublish($oTopic->getPublish());
     // * Добавляем коммент
     E::ModuleHook()->Run('comment_add_before', array('oCommentNew' => $oCommentNew, 'oCommentParent' => $oCommentParent, 'oTopic' => $oTopic));
     if (E::ModuleComment()->AddComment($oCommentNew)) {
         E::ModuleHook()->Run('comment_add_after', array('oCommentNew' => $oCommentNew, 'oCommentParent' => $oCommentParent, 'oTopic' => $oTopic));
         E::ModuleViewer()->AssignAjax('sCommentId', $oCommentNew->getId());
         if ($oTopic->getPublish()) {
             // * Добавляем коммент в прямой эфир если топик не в черновиках
             /** @var ModuleComment_EntityCommentOnline $oCommentOnline */
             $oCommentOnline = E::GetEntity('Comment_CommentOnline');
             $oCommentOnline->setTargetId($oCommentNew->getTargetId());
             $oCommentOnline->setTargetType($oCommentNew->getTargetType());
             $oCommentOnline->setTargetParentId($oCommentNew->getTargetParentId());
             $oCommentOnline->setCommentId($oCommentNew->getId());
             E::ModuleComment()->AddCommentOnline($oCommentOnline);
         }
         // * Список емайлов на которые не нужно отправлять уведомление
         $aExcludeMail = array($this->oUserCurrent->getMail());
         // * Отправляем уведомление тому на чей коммент ответили
         if ($oCommentParent && $oCommentParent->getUserId() != $oTopic->getUserId() && $oCommentNew->getUserId() != $oCommentParent->getUserId()) {
             $oUserAuthorComment = $oCommentParent->getUser();
             $aExcludeMail[] = $oUserAuthorComment->getMail();
             E::ModuleNotify()->SendCommentReplyToAuthorParentComment($oUserAuthorComment, $oTopic, $oCommentNew, $this->oUserCurrent);
         }
         // issue 131 (https://github.com/altocms/altocms/issues/131)
         // Не работает настройка уведомлений о комментариях к своим топикам
         // Уберём автора топика из рассылки
         /** @var ModuleTopic_EntityTopic $oTopic */
         $aExcludeMail[] = $oTopic->getUser()->getMail();
         // Отправим ему сообщение через отдельный метод, который проверяет эту настройку
         /** @var ModuleComment_EntityComment $oCommentNew */
         E::ModuleNotify()->SendCommentNewToAuthorTopic($oTopic->getUser(), $oTopic, $oCommentNew, $this->oUserCurrent);
         // * Отправка уведомления всем, кто подписан на топик кроме автора
         E::ModuleSubscribe()->Send('topic_new_comment', $oTopic->getId(), 'comment_new.tpl', E::ModuleLang()->Get('notify_subject_comment_new'), array('oTopic' => $oTopic, 'oComment' => $oCommentNew, 'oUserComment' => $this->oUserCurrent), $aExcludeMail);
         // * Подписываем автора коммента на обновления в трекере
         $oTrack = E::ModuleSubscribe()->AddTrackSimple('topic_new_comment', $oTopic->getId(), $this->oUserCurrent->getId());
         if ($oTrack) {
             //если пользователь не отписался от обновлений топика
             if (!$oTrack->getStatus()) {
                 $oTrack->setStatus(1);
                 E::ModuleSubscribe()->UpdateTrack($oTrack);
             }
         }
         // * Добавляем событие в ленту
         E::ModuleStream()->Write($oCommentNew->getUserId(), 'add_comment', $oCommentNew->getId(), $oTopic->getPublish() && !$oTopic->getBlog()->IsPrivate());
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
     }
 }
Esempio n. 13
0
 /**
  * Универсальный метод отправки уведомлений на email
  *
  * @param ModuleUser_EntityUser|string $xUserTo     Кому отправляем (пользователь или email)
  * @param string                       $sTemplate   Шаблон для отправки
  * @param string                       $sSubject    Тема письма
  * @param array                        $aAssign     Ассоциативный массив для загрузки переменных в шаблон письма
  * @param string|null                  $sPluginName Плагин из которого происходит отправка
  * @param bool                         $bForceSend  Отправлять сразу, даже при опции module.notify.delayed = true
  *
  * @return bool
  */
 public function Send($xUserTo, $sTemplate, $sSubject, $aAssign = array(), $sPluginName = null, $bForceSend = false)
 {
     if ($xUserTo instanceof ModuleUser_EntityUser) {
         $sMail = $xUserTo->getMail();
         $sName = $xUserTo->getLogin();
     } else {
         $sMail = $xUserTo;
         $sName = '';
     }
     /**
      * Передаём в шаблон переменные
      */
     foreach ($aAssign as $sVarName => $sValue) {
         $this->oViewerLocal->Assign($sVarName, $sValue);
     }
     /**
      * Формируем шаблон
      */
     $sTemplate = $this->sPrefix . $sTemplate;
     $sBody = $this->oViewerLocal->Fetch($this->GetTemplatePath($sTemplate, $sPluginName));
     /**
      * Если в конфигураторе указан отложенный метод отправки,
      * то добавляем задание в массив. В противном случае,
      * сразу отсылаем на email
      */
     if (Config::Get('module.notify.delayed') && !$bForceSend) {
         $oNotifyTask = E::GetEntity('Notify_Task', array('user_mail' => $sMail, 'user_login' => $sName, 'notify_text' => $sBody, 'notify_subject' => $sSubject, 'date_created' => F::Now(), 'notify_task_status' => self::NOTIFY_TASK_STATUS_NULL));
         if (Config::Get('module.notify.insert_single')) {
             $this->aTask[] = $oNotifyTask;
             $bResult = true;
         } else {
             $bResult = $this->oMapper->AddTask($oNotifyTask);
         }
     } else {
         // * Отправляем e-mail
         E::ModuleMail()->SetAdress($sMail, $sName);
         E::ModuleMail()->SetSubject($sSubject);
         E::ModuleMail()->SetBody($sBody);
         E::ModuleMail()->SetHTML();
         $bResult = E::ModuleMail()->Send();
     }
     return $bResult;
 }
Esempio n. 14
0
 /**
  * Обработка добавления топика
  *
  * @return bool|string
  */
 protected function SubmitAdd()
 {
     // * Проверяем отправлена ли форма с данными (хотяб одна кнопка)
     if (!F::isPost('submit_topic_publish') && !F::isPost('submit_topic_draft') && !F::isPost('submit_topic_save')) {
         return false;
     }
     /** @var ModuleTopic_EntityTopic $oTopic */
     $oTopic = E::GetEntity('Topic');
     $oTopic->_setValidateScenario('topic');
     // * Заполняем поля для валидации
     $oTopic->setBlogId(F::GetRequestStr('blog_id'));
     // issue 151 (https://github.com/altocms/altocms/issues/151)
     // Некорректная обработка названия блога
     // $oTopic->setTitle(strip_tags(F::GetRequestStr('topic_title')));
     $oTopic->setTitle(E::ModuleTools()->RemoveAllTags(F::GetRequestStr('topic_title')));
     $oTopic->setTextSource(F::GetRequestStr('topic_text'));
     $oTopic->setUserId($this->oUserCurrent->getId());
     $oTopic->setType($this->oContentType->getContentUrl());
     if ($this->oContentType->isAllow('link')) {
         $oTopic->setSourceLink(F::GetRequestStr('topic_field_link'));
     }
     $oTopic->setTags(F::GetRequestStr('topic_field_tags'));
     $oTopic->setDateAdd(F::Now());
     $oTopic->setUserIp(F::GetUserIp());
     $sTopicUrl = E::ModuleTopic()->CorrectTopicUrl($oTopic->MakeTopicUrl());
     $oTopic->setTopicUrl($sTopicUrl);
     // * Проверка корректности полей формы
     if (!$this->checkTopicFields($oTopic)) {
         return false;
     }
     // * Определяем в какой блог делаем запись
     $nBlogId = $oTopic->getBlogId();
     if ($nBlogId == 0) {
         $oBlog = E::ModuleBlog()->GetPersonalBlogByUserId($this->oUserCurrent->getId());
     } else {
         $oBlog = E::ModuleBlog()->GetBlogById($nBlogId);
     }
     // * Если блог не определен, то выдаем предупреждение
     if (!$oBlog) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_create_blog_error_unknown'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Проверяем права на постинг в блог
     if (!E::ModuleACL()->IsAllowBlog($oBlog, $this->oUserCurrent)) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_create_blog_error_noallow'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Проверяем разрешено ли постить топик по времени
     if (F::isPost('submit_topic_publish') && !E::ModuleACL()->CanPostTopicTime($this->oUserCurrent)) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_time_limit'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Теперь можно смело добавлять топик к блогу
     $oTopic->setBlogId($oBlog->getId());
     // * Получаемый и устанавливаем разрезанный текст по тегу <cut>
     list($sTextShort, $sTextNew, $sTextCut) = E::ModuleText()->Cut($oTopic->getTextSource());
     $oTopic->setCutText($sTextCut);
     $oTopic->setText(E::ModuleText()->Parser($sTextNew));
     // Получаем ссылки, полученные при парсинге текста
     $oTopic->setTextLinks(E::ModuleText()->GetLinks());
     $oTopic->setTextShort(E::ModuleText()->Parser($sTextShort));
     // * Варианты ответов
     if ($this->oContentType->isAllow('poll') && F::GetRequestStr('topic_field_question') && F::GetRequest('topic_field_answers', array())) {
         $oTopic->setQuestionTitle(strip_tags(F::GetRequestStr('topic_field_question')));
         $oTopic->clearQuestionAnswer();
         $aAnswers = F::GetRequest('topic_field_answers', array());
         foreach ($aAnswers as $sAnswer) {
             $sAnswer = trim((string) $sAnswer);
             if ($sAnswer) {
                 $oTopic->addQuestionAnswer($sAnswer);
             }
         }
     }
     $aPhotoSetData = E::ModuleMresource()->GetPhotosetData('photoset', 0);
     $oTopic->setPhotosetCount($aPhotoSetData['count']);
     if ($aPhotoSetData['cover']) {
         $oTopic->setPhotosetMainPhotoId($aPhotoSetData['cover']);
     }
     // * Публикуем или сохраняем
     if (isset($_REQUEST['submit_topic_publish'])) {
         $oTopic->setPublish(1);
         $oTopic->setPublishDraft(1);
         $oTopic->setDateShow(F::Now());
     } else {
         $oTopic->setPublish(0);
         $oTopic->setPublishDraft(0);
     }
     // * Принудительный вывод на главную
     $oTopic->setPublishIndex(0);
     if (E::ModuleACL()->IsAllowPublishIndex($this->oUserCurrent)) {
         if (F::GetRequest('topic_publish_index')) {
             $oTopic->setPublishIndex(1);
         }
     }
     // * Запрет на комментарии к топику
     $oTopic->setForbidComment(F::GetRequest('topic_forbid_comment', 0));
     // Разрешение/запрет индексации контента топика изначально - как у блога
     if ($oBlogType = $oBlog->GetBlogType()) {
         // Если тип блога определен, то берем из типа блога...
         $oTopic->setTopicIndexIgnore($oBlogType->GetIndexIgnore());
     } else {
         // ...если нет, то индексацию разрешаем
         $oTopic->setTopicIndexIgnore(false);
     }
     $oTopic->setShowPhotoset(F::GetRequest('topic_show_photoset', 0));
     // * Запускаем выполнение хуков
     E::ModuleHook()->Run('topic_add_before', array('oTopic' => $oTopic, 'oBlog' => $oBlog));
     // * Добавляем топик
     if ($this->_addTopic($oTopic)) {
         E::ModuleHook()->Run('topic_add_after', array('oTopic' => $oTopic, 'oBlog' => $oBlog));
         // * Получаем топик, чтоб подцепить связанные данные
         $oTopic = E::ModuleTopic()->GetTopicById($oTopic->getId());
         // * Обновляем количество топиков в блоге
         E::ModuleBlog()->RecalculateCountTopicByBlogId($oTopic->getBlogId());
         // * Добавляем автора топика в подписчики на новые комментарии к этому топику
         E::ModuleSubscribe()->AddSubscribeSimple('topic_new_comment', $oTopic->getId(), $this->oUserCurrent->getMail(), $this->oUserCurrent->getId());
         // * Подписываем автора топика на обновления в трекере
         if ($oTrack = E::ModuleSubscribe()->AddTrackSimple('topic_new_comment', $oTopic->getId(), $this->oUserCurrent->getId())) {
             // Если пользователь не отписался от обновлений топика
             if (!$oTrack->getStatus()) {
                 $oTrack->setStatus(1);
                 E::ModuleSubscribe()->UpdateTrack($oTrack);
             }
         }
         // * Делаем рассылку всем, кто состоит в этом блоге
         if ($oTopic->getPublish() == 1 && $oBlog->getType() != 'personal') {
             E::ModuleTopic()->SendNotifyTopicNew($oBlog, $oTopic, $this->oUserCurrent);
         }
         /**
          * Привязываем фото к ID топика
          */
         if (isset($aPhotos) && count($aPhotos)) {
             E::ModuleTopic()->AttachTmpPhotoToTopic($oTopic);
         }
         // * Удаляем временную куку
         E::ModuleSession()->DelCookie('ls_photoset_target_tmp');
         // Обработаем фотосет
         if ($this->oContentType->isAllow('photoset') && ($sTargetTmp = E::ModuleSession()->GetCookie(ModuleUploader::COOKIE_TARGET_TMP))) {
             // Уберем у ресурса флаг временного размещения и удалим из куки target_tmp
             E::ModuleSession()->DelCookie(ModuleUploader::COOKIE_TARGET_TMP);
         }
         // * Добавляем событие в ленту
         E::ModuleStream()->Write($oTopic->getUserId(), 'add_topic', $oTopic->getId(), $oTopic->getPublish() && (!$oBlog->getBlogType() || !$oBlog->getBlogType()->IsPrivate()));
         R::Location($oTopic->getUrl());
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'));
         F::SysWarning('System Error');
         return R::Action('error');
     }
 }
Esempio n. 15
0
 /**
  * Обработка добавление комментария к топику
  *
  */
 protected function SubmitComment()
 {
     $oTopic = $this->Topic_GetTopicById(getRequestStr('comment_target_id'));
     $sText = getRequestStr('comment_text');
     $sParentId = (int) getRequest('reply');
     $oCommentParent = null;
     if (!$sParentId) {
         /**
          * Корневой комментарий
          */
         $sParentId = null;
     } else {
         /**
          * Родительский комментарий
          */
         $oCommentParent = $this->Comment_GetCommentById($sParentId);
     }
     /**
      * Проверка на соответсвие комментария требованиям безопасности
      */
     if (!$this->CheckComment($oTopic, $sText)) {
         return;
     }
     /**
      * Проверка на соответсвие комментария родительскому коментарию
      */
     if (!$this->CheckParentComment($oTopic, $sText, $oCommentParent)) {
         return;
     }
     /**
      * Создаём коммент
      */
     $oCommentNew = Engine::GetEntity('Comment');
     $oCommentNew->setTargetId($oTopic->getId());
     $oCommentNew->setTargetType('topic');
     $oCommentNew->setTargetParentId($oTopic->getBlog()->getId());
     $oCommentNew->setUserId($this->oUserCurrent->getId());
     $oCommentNew->setText($this->Text_Parser($sText));
     $oCommentNew->setTextSource($sText);
     $oCommentNew->setDate(date("Y-m-d H:i:s"));
     $oCommentNew->setUserIp(func_getIp());
     $oCommentNew->setPid($sParentId);
     $oCommentNew->setTextHash(md5($sText));
     $oCommentNew->setPublish($oTopic->getPublish());
     /**
      * Добавляем коммент
      */
     $this->Hook_Run('comment_add_before', array('oCommentNew' => $oCommentNew, 'oCommentParent' => $oCommentParent, 'oTopic' => $oTopic));
     if ($this->Comment_AddComment($oCommentNew)) {
         $this->Hook_Run('comment_add_after', array('oCommentNew' => $oCommentNew, 'oCommentParent' => $oCommentParent, 'oTopic' => $oTopic));
         $this->Viewer_AssignAjax('sCommentId', $oCommentNew->getId());
         if ($oTopic->getPublish()) {
             /**
              * Добавляем коммент в прямой эфир если топик не в черновиках
              */
             $oCommentOnline = Engine::GetEntity('Comment_CommentOnline');
             $oCommentOnline->setTargetId($oCommentNew->getTargetId());
             $oCommentOnline->setTargetType($oCommentNew->getTargetType());
             $oCommentOnline->setTargetParentId($oCommentNew->getTargetParentId());
             $oCommentOnline->setCommentId($oCommentNew->getId());
             $this->Comment_AddCommentOnline($oCommentOnline);
         }
         /**
          * Сохраняем дату последнего коммента для юзера
          */
         $this->oUserCurrent->setDateCommentLast(date("Y-m-d H:i:s"));
         $this->User_Update($this->oUserCurrent);
         /**
          * Фиксируем ID у media файлов комментария
          */
         $this->Media_ReplaceTargetTmpById('comment', $oCommentNew->getId());
         /**
          * Список емайлов на которые не нужно отправлять уведомление
          */
         $aExcludeMail = array($this->oUserCurrent->getMail());
         /**
          * Отправляем уведомление тому на чей коммент ответили
          */
         if ($oCommentParent and $oCommentParent->getUserId() != $oTopic->getUserId() and $oCommentNew->getUserId() != $oCommentParent->getUserId()) {
             $oUserAuthorComment = $oCommentParent->getUser();
             $aExcludeMail[] = $oUserAuthorComment->getMail();
             $this->Topic_SendNotifyCommentReplyToAuthorParentComment($oUserAuthorComment, $oTopic, $oCommentNew, $this->oUserCurrent);
         }
         /**
          * Отправка уведомления автору топика
          */
         $this->Subscribe_Send('topic_new_comment', $oTopic->getId(), 'comment_new.tpl', $this->Lang_Get('emails.comment_new.subject'), array('oTopic' => $oTopic, 'oComment' => $oCommentNew, 'oUserComment' => $this->oUserCurrent), $aExcludeMail);
         /**
          * Добавляем событие в ленту
          */
         $this->Stream_write($oCommentNew->getUserId(), 'add_comment', $oCommentNew->getId(), $oTopic->getPublish() && $oTopic->getBlog()->getType() != 'close');
     } else {
         $this->Message_AddErrorSingle($this->Lang_Get('common.error.system.base'), $this->Lang_Get('common.error.error'));
     }
 }
Esempio n. 16
0
 /**
  * Формирование процесса смены емайла в профиле пользователя
  *
  * @param ModuleUser_EntityUser $oUser	Объект пользователя
  * @param string $sMailNew	Новый емайл
  * @return bool|ModuleUser_EntityChangemail
  */
 public function MakeUserChangemail($oUser, $sMailNew)
 {
     $oChangemail = Engine::GetEntity('ModuleUser_EntityChangemail');
     $oChangemail->setUserId($oUser->getId());
     $oChangemail->setDateAdd(date("Y-m-d H:i:s"));
     $oChangemail->setDateExpired(date("Y-m-d H:i:s", time() + 3 * 24 * 60 * 60));
     // 3 дня для смены емайла
     $oChangemail->setMailFrom($oUser->getMail() ? $oUser->getMail() : '');
     $oChangemail->setMailTo($sMailNew);
     $oChangemail->setCodeFrom(func_generator(32));
     $oChangemail->setCodeTo(func_generator(32));
     if ($this->AddUserChangemail($oChangemail)) {
         /**
          * Если у пользователя раньше не было емайла, то сразу шлем подтверждение на новый емайл
          */
         if (!$oChangemail->getMailFrom()) {
             $oChangemail->setConfirmFrom(1);
             $this->User_UpdateUserChangemail($oChangemail);
             /**
              * Отправляем уведомление на новый емайл
              */
             $this->Notify_Send($oChangemail->getMailTo(), 'notify.user_changemail_to.tpl', $this->Lang_Get('notify_subject_user_changemail'), array('oUser' => $oUser, 'oChangemail' => $oChangemail));
         } else {
             /**
              * Отправляем уведомление на старый емайл
              */
             $this->Notify_Send($oUser, 'notify.user_changemail_from.tpl', $this->Lang_Get('notify_subject_user_changemail'), array('oUser' => $oUser, 'oChangemail' => $oChangemail));
         }
         return $oChangemail;
     }
     return false;
 }
Esempio n. 17
0
 /**
  * Формирование процесса смены емайла в профиле пользователя
  *
  * @param ModuleUser_EntityUser $oUser       Объект пользователя
  * @param string                $sMailNew    Новый емайл
  *
  * @return bool|ModuleUser_EntityChangemail
  */
 public function MakeUserChangemail($oUser, $sMailNew)
 {
     /** @var ModuleUser_EntityChangemail $oChangemail */
     $oChangemail = E::GetEntity('ModuleUser_EntityChangemail');
     $oChangemail->setUserId($oUser->getId());
     $oChangemail->setDateAdd(date('Y-m-d H:i:s'));
     $oChangemail->setDateExpired(date('Y-m-d H:i:s', time() + 3 * 24 * 60 * 60));
     // 3 дня для смены емайла
     $oChangemail->setMailFrom($oUser->getMail() ? $oUser->getMail() : '');
     $oChangemail->setMailTo($sMailNew);
     $oChangemail->setCodeFrom(F::RandomStr(32));
     $oChangemail->setCodeTo(F::RandomStr(32));
     if ($this->AddUserChangemail($oChangemail)) {
         // * Если у пользователя раньше не было емайла, то сразу шлем подтверждение на новый емайл
         if (!$oChangemail->getMailFrom()) {
             $oChangemail->setConfirmFrom(1);
             E::ModuleUser()->UpdateUserChangemail($oChangemail);
             // * Отправляем уведомление на новый емайл
             E::ModuleNotify()->Send($oChangemail->getMailTo(), 'user_changemail_to.tpl', E::ModuleLang()->Get('notify_subject_user_changemail'), array('oUser' => $oUser, 'oChangemail' => $oChangemail), null, true);
         } else {
             // * Отправляем уведомление на старый емайл
             E::ModuleNotify()->Send($oUser, 'user_changemail_from.tpl', E::ModuleLang()->Get('notify_subject_user_changemail'), array('oUser' => $oUser, 'oChangemail' => $oChangemail), null, true);
         }
         return $oChangemail;
     }
     return false;
 }
Esempio n. 18
0
 /**
  * Универсальный метод отправки уведомлений на email
  *
  * @param ModuleUser_EntityUser|string $oUserTo Кому отправляем (пользователь или email)
  * @param string $sTemplate Шаблон для отправки
  * @param string $sSubject Тема письма
  * @param array $aAssign Ассоциативный массив для загрузки переменных в шаблон письма
  * @param string|null $sPluginName Плагин из которого происходит отправка
  * @param bool $bForceSend Отправлять сразу, даже при опции module.notify.delayed = true
  */
 public function Send($oUserTo, $sTemplate, $sSubject, $aAssign = array(), $sPluginName = null, $bForceSend = false)
 {
     if ($oUserTo instanceof ModuleUser_EntityUser) {
         $sMail = $oUserTo->getMail();
         $sName = $oUserTo->getLogin();
     } else {
         $sMail = $oUserTo;
         $sName = '';
     }
     /**
      * Передаём в шаблон переменные
      */
     foreach ($aAssign as $k => $v) {
         $this->oViewerLocal->Assign($k, $v);
     }
     /**
      * Формируем шаблон
      */
     $sBody = $this->oViewerLocal->Fetch($this->GetTemplatePath($sTemplate, $sPluginName));
     /**
      * Если в конфигураторе указан отложенный метод отправки,
      * то добавляем задание в массив. В противном случае,
      * сразу отсылаем на email
      */
     $oNotifyTask = Engine::GetEntity('Notify_Task');
     $oNotifyTask->setUserMail($sMail);
     $oNotifyTask->setUserLogin($sName);
     $oNotifyTask->setNotifyText($sBody);
     $oNotifyTask->setNotifySubject($sSubject);
     $oNotifyTask->setDateCreated(date("Y-m-d H:i:s"));
     $oNotifyTask->setNotifyTaskStatus(self::NOTIFY_TASK_STATUS_NULL);
     if (Config::Get('module.notify.delayed') and !$bForceSend) {
         if (Config::Get('module.notify.insert_single')) {
             $this->aTask[] = $oNotifyTask;
         } else {
             $this->oMapper->AddTask($oNotifyTask);
         }
     } else {
         /**
          * Отправляем мыло
          */
         $this->SendTask($oNotifyTask);
     }
 }