/** * Проверка рекапчи * * @param string $sKeyString Строка с кодомвернутым от рекапчи * @param string $sKeyName Наименование поля рекапчи * * @return bool */ public function Verify($sKeyString, $sKeyName = null) { /** @var string $xResult Результат валидации рекапчи который получен от гугла в формате json */ $xResult = file_get_contents(str_replace(array('%SECRET%', '%RESPONSE%', '%IP%'), array(Config::Get('plugin.recaptcha.secret_key'), $sKeyString, F::GetUserIp()), "https://www.google.com/recaptcha/api/siteverify?secret=%SECRET%&response=%RESPONSE%&remoteip=%IP%")); // Декодируем ответ $xResult = json_decode($xResult); // Учитывая возможные сбои вернём результат через собачку return @$xResult->success; }
/** * Добавляет голосование * * @param ModuleVote_EntityVote $oVote Объект голосования * * @return bool */ public function AddVote(ModuleVote_EntityVote $oVote) { if (!$oVote->getIp()) { $oVote->setIp(F::GetUserIp()); } if ($this->oMapper->AddVote($oVote)) { E::ModuleCache()->Delete("vote_{$oVote->getTargetType()}_{$oVote->getTargetId()}_{$oVote->getVoterId()}"); E::ModuleCache()->CleanByTags(array("vote_update_{$oVote->getTargetType()}_{$oVote->getVoterId()}", "vote_update_{$oVote->getTargetType()}_{$oVote->getTargetId()}", "vote_update_{$oVote->getTargetType()}")); return true; } return false; }
/** * Добавление записи на стену * * @param ModuleWall_EntityWall $oWall Объект записи на стене * * @return bool|ModuleWall_EntityWall */ public function AddWall($oWall) { if (!$oWall->getDateAdd()) { $oWall->setDateAdd(F::Now()); } if (!$oWall->getIp()) { $oWall->setIp(F::GetUserIp()); } if ($iId = $this->oMapper->AddWall($oWall)) { $oWall->setId($iId); /** * Обновляем данные у родительской записи */ if ($oPidWall = $oWall->GetPidWall()) { $this->UpdatePidWall($oPidWall); } return $oWall; } return false; }
/** * Создание пользовательской сессии * * @param ModuleUser_EntityUser $oUser - Объект пользователя * @param string $sKey - Сессионный ключ * * @return bool */ protected function CreateSession(ModuleUser_EntityUser $oUser, $sKey) { E::ModuleCache()->CleanByTags(array('user_session_update')); E::ModuleCache()->Delete("user_session_{$oUser->getId()}"); /** @var $oSession ModuleUser_EntitySession */ $oSession = E::GetEntity('User_Session'); $oSession->setUserId($oUser->getId()); $oSession->setKey($sKey); $oSession->setIpLast(F::GetUserIp()); $oSession->setIpCreate(F::GetUserIp()); $oSession->setDateLast(F::Now()); $oSession->setDateCreate(F::Now()); $oSession->setUserAgentHash(); if ($this->oMapper->CreateSession($oSession)) { if ($nSessionLimit = Config::Get('module.user.max_session_history')) { $this->LimitSession($oUser, $nSessionLimit); } $oUser->setLastSession($sKey); if ($this->Update($oUser)) { $this->oSession = $oSession; return true; } } return false; }
/** * @return bool */ public function IsBannedByIp() { // return ($this->GetProp('ban_ip')); // issue 258 {@link https://github.com/altocms/altocms/issues/258} $bResult = $this->GetProp('ban_ip'); if (is_null($bResult)) { $bResult = (bool) E::ModuleUser()->IpIsBanned(F::GetUserIp()); $this->setProp('ban_ip', $bResult); } return $bResult; }
protected function _eventUsersCmdMessageSeparate() { $bOk = true; $sTitle = F::GetRequest('talk_title'); $sText = E::ModuleText()->Parser(F::GetRequest('talk_text')); $sDate = date(F::Now()); $sIp = F::GetUserIp(); if ($sUsers = $this->GetPost('users_list')) { $aUsers = explode(',', str_replace(' ', '', $sUsers)); } else { $aUsers = array(); } if ($aUsers) { // Если указано, то шлем самому себе со списком получателей if (F::GetRequest('send_copy_self')) { $oSelfTalk = E::GetEntity('Talk_Talk'); $oSelfTalk->setUserId($this->oUserCurrent->getId()); $oSelfTalk->setUserIdLast($this->oUserCurrent->getId()); $oSelfTalk->setTitle($sTitle); $oSelfTalk->setText(E::ModuleText()->Parser('To: <i>' . $sUsers . '</i>' . "\n\n" . 'Msg: ' . $this->GetPost('talk_text'))); $oSelfTalk->setDate($sDate); $oSelfTalk->setDateLast($sDate); $oSelfTalk->setUserIp($sIp); if ($oSelfTalk = E::ModuleTalk()->AddTalk($oSelfTalk)) { $oTalkUser = E::GetEntity('Talk_TalkUser'); $oTalkUser->setTalkId($oSelfTalk->getId()); $oTalkUser->setUserId($this->oUserCurrent->getId()); $oTalkUser->setDateLast($sDate); E::ModuleTalk()->AddTalkUser($oTalkUser); // уведомление по e-mail $oUserToMail = $this->oUserCurrent; E::ModuleNotify()->SendTalkNew($oUserToMail, $this->oUserCurrent, $oSelfTalk); } else { $bOk = false; } } if ($bOk) { // теперь рассылаем остальным - каждому отдельное сообщение foreach ($aUsers as $sUserLogin) { if ($sUserLogin && $sUserLogin != $this->oUserCurrent->getLogin() && ($oUserRecipient = E::ModuleUser()->GetUserByLogin($sUserLogin))) { $oTalk = E::GetEntity('Talk_Talk'); $oTalk->setUserId($this->oUserCurrent->getId()); $oTalk->setUserIdLast($this->oUserCurrent->getId()); $oTalk->setTitle($sTitle); $oTalk->setText($sText); $oTalk->setDate($sDate); $oTalk->setDateLast($sDate); $oTalk->setUserIp($sIp); if ($oTalk = E::ModuleTalk()->AddTalk($oTalk)) { $oTalkUser = E::GetEntity('Talk_TalkUser'); $oTalkUser->setTalkId($oTalk->getId()); $oTalkUser->setUserId($oUserRecipient->GetId()); $oTalkUser->setDateLast(null); E::ModuleTalk()->AddTalkUser($oTalkUser); // Отправка самому себе, чтобы можно было читать ответ $oTalkUser = E::GetEntity('Talk_TalkUser'); $oTalkUser->setTalkId($oTalk->getId()); $oTalkUser->setUserId($this->oUserCurrent->getId()); $oTalkUser->setDateLast($sDate); E::ModuleTalk()->AddTalkUser($oTalkUser); // Отправляем уведомления $oUserToMail = E::ModuleUser()->GetUserById($oUserRecipient->GetId()); E::ModuleNotify()->SendTalkNew($oUserToMail, $this->oUserCurrent, $oTalk); } else { $bOk = false; break; } } } } } if ($bOk) { E::ModuleMessage()->AddNotice(E::ModuleLang()->Get('action.admin.msg_sent_ok'), null, true); } else { E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), null, true); } }
/** * Обработка добавление комментария к письму * */ protected function SubmitComment() { // * Проверям авторизован ли пользователь if (!E::ModuleUser()->IsAuthorization()) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error')); return false; } // * Проверяем разговор if (!($oTalk = E::ModuleTalk()->GetTalkById(F::GetRequestStr('cmt_target_id')))) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error')); return false; } if (!($oTalkUser = E::ModuleTalk()->GetTalkUser($oTalk->getId(), $this->oUserCurrent->getId()))) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error')); return false; } // * Проверяем разрешено ли отправлять инбокс по времени if (!E::ModuleACL()->CanPostTalkCommentTime($this->oUserCurrent)) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('talk_time_limit'), E::ModuleLang()->Get('error')); return false; } // * Проверяем текст комментария $sText = E::ModuleText()->Parser(F::GetRequestStr('comment_text')); $iMin = intval(Config::Get('module.talk.min_length')); $iMax = intval(Config::Get('module.talk.max_length')); if (!F::CheckVal($sText, 'text', $iMin, $iMax)) { if ($iMax) { E::ModuleMessage()->AddError(E::ModuleLang()->Get('talk_create_text_error_len', array('min' => $iMin, 'max' => $iMax)), E::ModuleLang()->Get('error')); } else { E::ModuleMessage()->AddError(E::ModuleLang()->Get('talk_create_text_error_min', array('min' => $iMin)), E::ModuleLang()->Get('error')); } return false; } // * Проверям на какой коммент отвечаем $sParentId = (int) F::GetRequest('reply'); if (!F::CheckVal($sParentId, 'id')) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error')); return false; } $oCommentParent = null; if ($sParentId != 0) { // * Проверяем существует ли комментарий на который отвечаем if (!($oCommentParent = E::ModuleComment()->GetCommentById($sParentId))) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error')); return false; } // * Проверяем из одного топика ли новый коммент и тот на который отвечаем if ($oCommentParent->getTargetId() != $oTalk->getId()) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error')); return false; } } else { // * Корневой комментарий $sParentId = null; } // * Проверка на дублирующий коммент if (E::ModuleComment()->GetCommentUnique($oTalk->getId(), 'talk', $this->oUserCurrent->getId(), $sParentId, md5($sText))) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_spam'), E::ModuleLang()->Get('error')); return false; } // * Создаём комментарий /** @var ModuleComment_EntityComment $oCommentNew */ $oCommentNew = E::GetEntity('Comment'); $oCommentNew->setTargetId($oTalk->getId()); $oCommentNew->setTargetType('talk'); $oCommentNew->setUserId($this->oUserCurrent->getId()); $oCommentNew->setText($sText); $oCommentNew->setDate(F::Now()); $oCommentNew->setUserIp(F::GetUserIp()); $oCommentNew->setPid($sParentId); $oCommentNew->setTextHash(md5($sText)); $oCommentNew->setPublish(1); // * Добавляем коммент E::ModuleHook()->Run('talk_comment_add_before', array('oCommentNew' => $oCommentNew, 'oCommentParent' => $oCommentParent, 'oTalk' => $oTalk)); if (E::ModuleComment()->AddComment($oCommentNew)) { E::ModuleHook()->Run('talk_comment_add_after', array('oCommentNew' => $oCommentNew, 'oCommentParent' => $oCommentParent, 'oTalk' => $oTalk)); E::ModuleViewer()->AssignAjax('sCommentId', $oCommentNew->getId()); $oTalk->setDateLast(F::Now()); $oTalk->setUserIdLast($oCommentNew->getUserId()); $oTalk->setCommentIdLast($oCommentNew->getId()); $oTalk->setCountComment($oTalk->getCountComment() + 1); E::ModuleTalk()->UpdateTalk($oTalk); // * Отсылаем уведомления всем адресатам $aUsersTalk = E::ModuleTalk()->GetUsersTalk($oTalk->getId(), ModuleTalk::TALK_USER_ACTIVE); foreach ($aUsersTalk as $oUserTalk) { if ($oUserTalk->getId() != $oCommentNew->getUserId()) { E::ModuleNotify()->SendTalkCommentNew($oUserTalk, $this->oUserCurrent, $oTalk, $oCommentNew); } } // * Увеличиваем число новых комментов E::ModuleTalk()->IncreaseCountCommentNew($oTalk->getId(), $oCommentNew->getUserId()); return true; } else { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error')); } return false; }
/** * Формирует и отправляет личное сообщение * * @param string $sTitle Заголовок сообщения * @param string $sText Текст сообщения * @param int|ModuleUser_EntityUser $oUserFrom Пользователь от которого отправляем * @param array|int|ModuleUser_EntityUser $aUserTo Пользователь которому отправляем * @param bool $bSendNotify Отправлять или нет уведомление на емайл * @param bool $bUseBlacklist Исклюать или нет пользователей из блэклиста * * @return ModuleTalk_EntityTalk|bool */ public function SendTalk($sTitle, $sText, $oUserFrom, $aUserTo, $bSendNotify = true, $bUseBlacklist = true) { $iUserIdFrom = $oUserFrom instanceof ModuleUser_EntityUser ? $oUserFrom->getId() : (int) $oUserFrom; if (!is_array($aUserTo)) { $aUserTo = array($aUserTo); } $aUserIdTo = array($iUserIdFrom); if ($bUseBlacklist) { $aUserInBlacklist = $this->GetBlacklistByTargetId($iUserIdFrom); } foreach ($aUserTo as $oUserTo) { $nUserIdTo = $oUserTo instanceof ModuleUser_EntityUser ? $oUserTo->getId() : (int) $oUserTo; if (!$bUseBlacklist || !in_array($nUserIdTo, $aUserInBlacklist)) { $aUserIdTo[] = $nUserIdTo; } } $aUserIdTo = array_unique($aUserIdTo); if (!empty($aUserIdTo)) { $oTalk = E::GetEntity('Talk'); $oTalk->setUserId($iUserIdFrom); $oTalk->setTitle($sTitle); $oTalk->setText($sText); $oTalk->setDate(date('Y-m-d H:i:s')); $oTalk->setDateLast(date('Y-m-d H:i:s')); $oTalk->setUserIdLast($oTalk->getUserId()); $oTalk->setUserIp(F::GetUserIp()); if ($oTalk = $this->AddTalk($oTalk)) { foreach ($aUserIdTo as $iUserId) { $oTalkUser = E::GetEntity('Talk_TalkUser'); $oTalkUser->setTalkId($oTalk->getId()); $oTalkUser->setUserId($iUserId); if ($iUserId == $iUserIdFrom) { $oTalkUser->setDateLast(date('Y-m-d H:i:s')); } else { $oTalkUser->setDateLast(null); } $this->AddTalkUser($oTalkUser); if ($bSendNotify) { if ($iUserId != $iUserIdFrom) { $oUserFrom = E::ModuleUser()->GetUserById($iUserIdFrom); $oUserToMail = E::ModuleUser()->GetUserById($iUserId); E::ModuleNotify()->SendTalkNew($oUserToMail, $oUserFrom, $oTalk); } } } return $oTalk; } } return false; }
/** * Обработка Ajax регистрации */ protected function EventAjaxRegistration() { // * Устанавливаем формат Ajax ответа E::ModuleViewer()->SetResponseAjax('json'); E::ModuleSecurity()->ValidateSendForm(); // * Создаем объект пользователя и устанавливаем сценарий валидации /** @var ModuleUser_EntityUser $oUser */ $oUser = E::GetEntity('ModuleUser_EntityUser'); $oUser->_setValidateScenario('registration'); // * Заполняем поля (данные) $oUser->setLogin($this->GetPost('login')); $oUser->setMail($this->GetPost('mail')); $oUser->setPassword($this->GetPost('password')); $oUser->setPasswordConfirm($this->GetPost('password_confirm')); $oUser->setCaptcha($this->GetPost('captcha')); $oUser->setDateRegister(F::Now()); $oUser->setIpRegister(F::GetUserIp()); // * Если используется активация, то генерим код активации if (Config::Get('general.reg.activation')) { $oUser->setActivate(0); $oUser->setActivationKey(F::RandomStr()); } else { $oUser->setActivate(1); $oUser->setActivationKey(null); } E::ModuleHook()->Run('registration_validate_before', array('oUser' => $oUser)); // * Запускаем валидацию if ($oUser->_Validate()) { // Сбросим капчу // issue#342. E::ModuleSession()->Drop(E::ModuleCaptcha()->GetKeyName()); E::ModuleHook()->Run('registration_validate_after', array('oUser' => $oUser)); $oUser->setPassword($oUser->getPassword(), true); if ($this->_addUser($oUser)) { E::ModuleHook()->Run('registration_after', array('oUser' => $oUser)); // * Подписываем пользователя на дефолтные события в ленте активности E::ModuleStream()->SwitchUserEventDefaultTypes($oUser->getId()); // * Если юзер зарегистрировался по приглашению то обновляем инвайт if (Config::Get('general.reg.invite') && ($oInvite = E::ModuleUser()->GetInviteByCode($this->GetInviteRegister()))) { $oInvite->setUserToId($oUser->getId()); $oInvite->setDateUsed(F::Now()); $oInvite->setUsed(1); E::ModuleUser()->UpdateInvite($oInvite); } // * Если стоит регистрация с активацией то проводим её if (Config::Get('general.reg.activation')) { // * Отправляем на мыло письмо о подтверждении регистрации E::ModuleNotify()->SendRegistrationActivate($oUser, F::GetRequestStr('password')); E::ModuleViewer()->AssignAjax('sUrlRedirect', R::GetPath('registration') . 'confirm/'); } else { E::ModuleNotify()->SendRegistration($oUser, F::GetRequestStr('password')); $oUser = E::ModuleUser()->GetUserById($oUser->getId()); // * Сразу авторизуем E::ModuleUser()->Authorization($oUser, false); $this->DropInviteRegister(); // * Определяем URL для редиректа после авторизации $sUrl = Config::Get('module.user.redirect_after_registration'); if (F::GetRequestStr('return-path')) { $sUrl = F::GetRequestStr('return-path'); } E::ModuleViewer()->AssignAjax('sUrlRedirect', $sUrl ? $sUrl : Config::Get('path.root.url')); E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('registration_ok')); } } else { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error')); return; } } else { // * Получаем ошибки E::ModuleViewer()->AssignAjax('aErrors', $oUser->_getValidateErrors()); } }
/** * Обработка добавление комментария к топику * */ 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')); } }
/** * Обработка редактирования топика * * @param ModuleTopic_EntityTopic $oTopic * * @return mixed */ protected function SubmitEdit($oTopic) { $oTopic->_setValidateScenario('topic'); // * Сохраняем старое значение идентификатора блога $iBlogIdOld = $oTopic->getBlogId(); // * Заполняем поля для валидации $iBlogId = F::GetRequestStr('blog_id'); // if blog_id is empty then save blog not changed if (is_numeric($iBlogId)) { $oTopic->setBlogId($iBlogId); } // 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')); if ($this->oContentType->isAllow('link')) { $oTopic->setSourceLink(F::GetRequestStr('topic_field_link')); } $oTopic->setTags(F::GetRequestStr('topic_field_tags')); $oTopic->setUserIp(F::GetUserIp()); if ($this->oUserCurrent && ($this->oUserCurrent->isAdministrator() || $this->oUserCurrent->isModerator())) { if (F::GetRequestStr('topic_url') && $oTopic->getTopicUrl() != F::GetRequestStr('topic_url')) { $sTopicUrl = E::ModuleTopic()->CorrectTopicUrl(F::TranslitUrl(F::GetRequestStr('topic_url'))); $oTopic->setTopicUrl($sTopicUrl); } } // * Проверка корректности полей формы if (!$this->checkTopicFields($oTopic)) { return false; } // * Определяем в какой блог делаем запись $nBlogId = $oTopic->getBlogId(); if ($nBlogId == 0) { $oBlog = E::ModuleBlog()->GetPersonalBlogByUserId($oTopic->getUserId()); } 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 (isPost('submit_topic_publish') && !$oTopic->getPublishDraft() && !E::ModuleACL()->CanPostTopicTime($this->oUserCurrent)) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_time_limit'), E::ModuleLang()->Get('error')); return; } $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->getQuestionCountVote() == 0) { $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', $oTopic->getId()); $oTopic->setPhotosetCount($aPhotoSetData['count']); $oTopic->setPhotosetMainPhotoId($aPhotoSetData['cover']); // * Publish or save as a draft $bSendNotify = false; if (isset($_REQUEST['submit_topic_publish'])) { // If the topic has not been published then sets date of show (publication date) if (!$oTopic->getPublish() && !$oTopic->getDateShow()) { $oTopic->setDateShow(F::Now()); } $oTopic->setPublish(1); if ($oTopic->getPublishDraft() == 0) { $oTopic->setPublishDraft(1); $oTopic->setDateAdd(F::Now()); $bSendNotify = true; } } else { $oTopic->setPublish(0); } // * Принудительный вывод на главную if (E::ModuleACL()->IsAllowPublishIndex($this->oUserCurrent)) { if (F::GetRequest('topic_publish_index')) { $oTopic->setPublishIndex(1); } else { $oTopic->setPublishIndex(0); } } // * Запрет на комментарии к топику $oTopic->setForbidComment(F::GetRequest('topic_forbid_comment', 0)); // Если запрет на индексацию не устанавливался вручную, то задаем, как у блога $oBlogType = $oBlog->GetBlogType(); if ($oBlogType && !$oTopic->getIndexIgnoreLock()) { $oTopic->setTopicIndexIgnore($oBlogType->GetIndexIgnore()); } else { $oTopic->setTopicIndexIgnore(false); } $oTopic->setShowPhotoset(F::GetRequest('topic_show_photoset', 0)); E::ModuleHook()->Run('topic_edit_before', array('oTopic' => $oTopic, 'oBlog' => $oBlog)); // * Сохраняем топик if ($this->_updateTopic($oTopic)) { E::ModuleHook()->Run('topic_edit_after', array('oTopic' => $oTopic, 'oBlog' => $oBlog, 'bSendNotify' => &$bSendNotify)); // * Обновляем данные в комментариях, если топик был перенесен в новый блог if ($iBlogIdOld != $oTopic->getBlogId()) { E::ModuleComment()->UpdateTargetParentByTargetId($oTopic->getBlogId(), 'topic', $oTopic->getId()); E::ModuleComment()->UpdateTargetParentByTargetIdOnline($oTopic->getBlogId(), 'topic', $oTopic->getId()); } // * Обновляем количество топиков в блоге if ($iBlogIdOld != $oTopic->getBlogId()) { E::ModuleBlog()->RecalculateCountTopicByBlogId($iBlogIdOld); } E::ModuleBlog()->RecalculateCountTopicByBlogId($oTopic->getBlogId()); // * Добавляем событие в ленту E::ModuleStream()->Write($oTopic->getUserId(), 'add_topic', $oTopic->getId(), $oTopic->getPublish() && (!$oBlogType || !$oBlog->getBlogType()->IsPrivate())); // * Рассылаем о новом топике подписчикам блога if ($bSendNotify) { E::ModuleTopic()->SendNotifyTopicNew($oBlog, $oTopic, $oTopic->getUser()); } if (!$oTopic->getPublish() && !$this->oUserCurrent->isAdministrator() && !$this->oUserCurrent->isModerator() && $this->oUserCurrent->getId() != $oTopic->getUserId()) { R::Location($oBlog->getUrlFull()); } R::Location($oTopic->getUrl()); } else { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error')); F::SysWarning('System Error'); return R::Action('error'); } }
protected function _statKey() { return 'module.search.last_queries.ip_' . F::GetUserIp(); }
function func_getIp() { return F::GetUserIp(); }
/** * Создает подписку, если уже есть, то возвращает существующую * * @param string $sTargetType Тип * @param string $sTargetId ID владельца * @param string $sUserId ID юзера * * @return ModuleSubscribe_EntityTrack|bool */ public function AddTrackSimple($sTargetType, $sTargetId, $sUserId) { if (!$sUserId) { return false; } if (!($oTrack = E::ModuleSubscribe()->GetTrackByTargetAndUser($sTargetType, $sTargetId, $sUserId))) { $oTrack = E::GetEntity('ModuleSubscribe_EntityTrack'); $oTrack->setTargetType($sTargetType); $oTrack->setTargetId($sTargetId); $oTrack->setUserId($sUserId); $oTrack->setDateAdd(date('Y-m-d H:i:s')); $oTrack->setKey(F::RandomStr(32)); $oTrack->setIp(F::GetUserIp()); $oTrack->setStatus(1); E::ModuleSubscribe()->AddTrack($oTrack); } return $oTrack; }