/** * Обрабатывает ссылку на конкретный комментарий, определят к какому топику он относится и перенаправляет на него * Актуально при использовании постраничности комментариев */ protected function EventShowComment() { $iCommentId = $this->sCurrentEvent; /** * Проверяем к чему относится комментарий */ if (!($oComment = $this->Comment_GetCommentById($iCommentId))) { return parent::EventNotFound(); } if ($oComment->getTargetType() != 'topic' or !($oTopic = $oComment->getTarget())) { return parent::EventNotFound(); } /** * Определяем необходимую страницу для отображения комментария */ if (!Config::Get('module.comment.use_nested') or !Config::Get('module.comment.nested_per_page')) { Router::Location($oTopic->getUrl() . '#comment' . $oComment->getId()); } $iPage = $this->Comment_GetPageCommentByTargetId($oComment->getTargetId(), $oComment->getTargetType(), $oComment); if ($iPage == 1) { Router::Location($oTopic->getUrl() . '#comment' . $oComment->getId()); } else { Router::Location($oTopic->getUrl() . "?cmtpage={$iPage}#comment" . $oComment->getId()); } exit; }
public function Init() { E::ModuleViewer()->SetResponseAjax('json'); if (!E::IsAdmin()) { Router::Location('error/404/'); } $this->oUserCurrent = E::User(); }
protected function EventMakeAdm() { if (!$this->User_IsAuthorization()) { return parent::EventNotFound(); } if (!$this->User_GetUserCurrent()->isAdministrator()) { return parent::EventNotFound(); } $aPair = $this->PluginAdm_Admalgoritm_getPair(); Router::Location('admin'); }
protected function EventAlbums() { $sUserLogin = $this->sCurrentEvent; if (!($this->oUserProfile = $this->User_GetUserByLogin($sUserLogin))) { return parent::EventNotFound(); } $iPage = $this->GetParamEventMatch(1, 2) ? $this->GetParamEventMatch(1, 2) : 1; /** * Выполняем редирект на новый URL, в новых версиях LS экшен "my" будет удален */ $sPage = $iPage == 1 ? '' : "page{$iPage}/"; Router::Location($this->oUserProfile->getUserWebPath() . 'created/albums/' . $sPage); }
/** * Отписка от подписки */ protected function EventUnsubscribe() { if ($oSubscribe = $this->Subscribe_GetSubscribeByKey($this->getParam(0)) and $oSubscribe->getStatus() == 1) { $oSubscribe->setStatus(0); $oSubscribe->setDateRemove(date("Y-m-d H:i:s")); $this->Subscribe_UpdateSubscribe($oSubscribe); $this->Message_AddNotice($this->Lang_Get('subscribe_change_ok'), null, true); } /** * Получаем URL для редиректа */ if (!($sUrl = $this->Subscribe_GetUrlTarget($oSubscribe->getTargetType(), $oSubscribe->getTargetId()))) { $sUrl = Router::GetPath('index'); } Router::Location($sUrl); }
protected function EventPagesAction($sAdminAction = null) { if ($sAdminAction) { $oPage = $this->PluginPage_Page_GetPageById($this->_getRequestCheck('page_id')); if ($oPage) { if ($sAdminAction == 'activate' or $sAdminAction == 'deactivate') { $oPage->setActive($sAdminAction == 'activate' ? 1 : 0); if ($this->PluginPage_Page_UpdatePage($oPage)) { $this->Message_AddNotice($this->Lang_Get('adm_action_ok'), $this->Lang_Get('attention'), true); } else { $this->Message_AddError($this->Lang_Get('adm_action_err'), $this->Lang_Get('error'), true); } } } } Router::Location(Router::GetPath('admin') . 'pages/'); }
/** * Удаление топика * * @return void */ protected function EventDelete() { $this->Security_ValidateSendForm(); // * Получаем номер топика из УРЛ и проверяем существует ли он $sTopicId = $this->GetParam(0); if (!($oTopic = $this->Topic_GetTopicById($sTopicId))) { return parent::EventNotFound(); } // * проверяем есть ли право на удаление топика if (!$this->ACL_IsAllowDeleteTopic($oTopic, $this->oUserCurrent)) { return parent::EventNotFound(); } // * Гарантировано удаляем топик и его зависимости $this->Hook_Run('topic_delete_before', array('oTopic' => $oTopic)); $this->PluginAceadminpanel_Admin_DelTopic($oTopic->GetId()); $this->Hook_Run('topic_delete_after', array('oTopic' => $oTopic)); // * Перенаправляем на страницу со списком топиков из блога этого топика Router::Location($oTopic->getBlog()->getUrlFull()); }
/** * Отписка от подписки */ protected function EventUnsubscribe() { /** * Получаем подписку по ключу */ if ($oSubscribe = $this->Subscribe_GetSubscribeByKey($this->getParam(0)) and $oSubscribe->getStatus() == 1) { /** * Отписываем пользователя */ $oSubscribe->setStatus(0); $oSubscribe->setDateRemove(date("Y-m-d H:i:s")); $this->Subscribe_UpdateSubscribe($oSubscribe); $this->Message_AddNotice($this->Lang_Get('common.success.save'), null, true); } /** * Получаем URL для редиректа */ if (!($sUrl = $this->Subscribe_GetUrlTarget($oSubscribe->getTargetType(), $oSubscribe->getTargetId()))) { $sUrl = Router::GetPath('index'); } Router::Location($sUrl); }
protected function EventSeopackDelete() { $this->sMainMenuItem = 'content'; E::ModuleSecurity()->ValidateSendForm(); if ($oSeopack = E::ModuleSeopack()->GetSeopackBySeopackId($this->GetParam(0))) { $oSeopack->Delete(); E::ModuleMessage()->AddNotice(E::ModuleLang()->Get('plugin.seopack.seopack_admin_action_delete_ok') . null, true); Router::Location('admin/seopack/'); } else { E::ModuleMessage()->AddError(E::ModuleLang()->Get('plugin.seopack.seopack_admin_action_delete_error'), E::ModuleLang()->Get('error')); } $this->SetTemplateAction('seopack_list'); }
/** * Активация\деактивация плагина * * @param string $sPlugin * @param string $sAction */ protected function SubmitManagePlugin($sPlugin, $sAction) { if (!in_array($sAction, array('activate', 'deactivate'))) { $this->Message_AddError($this->Lang_Get('plugins_unknown_action'), $this->Lang_Get('error'), true); Router::Location(Router::GetPath('plugins')); } /** * Активируем\деактивируем плагин */ if ($bResult = $this->Plugin_Toggle($sPlugin, $sAction)) { $this->Message_AddNotice($this->Lang_Get('plugins_action_ok'), $this->Lang_Get('attention'), true); } else { if (!($aMessages = $this->Message_GetErrorSession()) or !count($aMessages)) { $this->Message_AddErrorSingle($this->Lang_Get('system_error'), $this->Lang_Get('error'), true); } } /** * Возвращаем на страницу управления плагинами */ Router::Location(Router::GetPath('admin') . 'plugins/'); }
/** * Поиск и формирование результата * * @param array $aReq * @param int $iLimit * * @return array|bool */ protected function PrepareResults($aReq, $iLimit) { // * Количество результатов по типам $aRes = array(); foreach ($this->sTypesEnabled as $sType => $aExtra) { $aRes['aCounts'][$sType] = intval(E::ModuleSphinx()->GetNumResultsByType($aReq['q'], $sType, $aExtra)); } if ($aRes['aCounts'][$aReq['sType']] == 0) { // * Объектов необходимого типа не найдено unset($this->sTypesEnabled[$aReq['sType']]); // * Проверяем отсальные типы foreach (array_keys($this->sTypesEnabled) as $sType) { if ($aRes['aCounts'][$sType]) { Router::Location(Router::GetPath('search') . $sType . '/?q=' . $aReq['q']); } } } elseif (($aReq['iPage'] - 1) * $iLimit <= $aRes['aCounts'][$aReq['sType']]) { // * Ищем $this->aSphinxRes = E::ModuleSphinx()->FindContent($aReq['q'], $aReq['sType'], ($aReq['iPage'] - 1) * $iLimit, $iLimit, $this->sTypesEnabled[$aReq['sType']]); // * Возможно демон Сфинкса не доступен if (false === $this->aSphinxRes) { return false; } $this->bIsResults = true; // * Формируем постраничный вывод $aPaging = E::ModuleViewer()->MakePaging($aRes['aCounts'][$aReq['sType']], $aReq['iPage'], $iLimit, Config::Get('pagination.pages.count'), Router::GetPath('search') . $aReq['sType'], array('q' => $aReq['q'])); E::ModuleViewer()->Assign('aPaging', $aPaging); } $this->SetTemplateAction('results'); E::ModuleViewer()->AddHtmlTitle($aReq['q']); E::ModuleViewer()->Assign('bIsResults', $this->bIsResults); return $aRes; }
/** * Обрабатываем процесс разлогинивания * */ protected function EventExit() { $this->Security_ValidateSendForm(); $this->User_Logout(); //$this->Viewer_Assign('bRefreshToHome',true); Router::Location(Config::Get('path.root.web') . '/'); }
/** * Обработка напоминания пароля, подтверждение смены пароля * * @return string|null */ protected function EventReminder() { if (E::IsUser()) { // Для авторизованного юзера восстанавливать нечего Router::Location('/'); } else { // Устанавливаем title страницы E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('password_reminder')); $this->_eventRecovery(false); } }
/** * Активация\деактивация плагина * * @param string $sPlugin Имя плагина * @param string $sAction Действие */ protected function SubmitManagePlugin($sPlugin, $sAction) { $this->Security_ValidateSendForm(); if (!in_array($sAction, array('activate', 'deactivate', 'remove', 'apply_update'))) { $this->Message_AddError($this->Lang_Get('admin.plugins.notices.unknown_action'), $this->Lang_Get('common.error.error'), true); Router::Location(Router::GetPath('admin/plugins')); } $bResult = false; /** * Активируем\деактивируем плагин */ if ($sAction == 'activate') { $bResult = $this->PluginManager_ActivatePlugin($sPlugin); } elseif ($sAction == 'deactivate') { $bResult = $this->PluginManager_DeactivatePlugin($sPlugin); } elseif ($sAction == 'remove') { $bResult = $this->PluginManager_RemovePlugin($sPlugin); } elseif ($sAction == 'apply_update') { $this->PluginManager_ApplyPluginUpdate($sPlugin); $bResult = true; } if ($bResult) { $this->Message_AddNotice($this->Lang_Get('admin.plugins.notices.action_ok'), $this->Lang_Get('common.attention'), true); } else { if (!($aMessages = $this->Message_GetErrorSession()) or !count($aMessages)) { $this->Message_AddErrorSingle($this->Lang_Get('common.error.system.base'), $this->Lang_Get('common.error.error'), true); } } /** * Возвращаем на страницу управления плагинами */ Router::Location(Router::GetPath('admin') . 'plugins/'); }
/** * Страница создания письма */ 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'); } }
/** * Обрабатываем процесс залогинивания * По факту только отображение шаблона, дальше вступает в дело Ajax * */ protected function EventLogin() { /** * Если уже авторизирован */ if ($this->User_GetUserCurrent()) { Router::Location(Config::Get('path.root.web') . '/'); } $this->Viewer_AddHtmlTitle($this->Lang_Get('login')); }
/** * Показывает страничку регистрации и обрабатывает её * * @return unknown */ protected function EventIndex() { /** * Если нажали кнопку "Зарегистрироваться" */ if (isPost('submit_register')) { //Проверяем входные данные $bError = false; /** * Проверка логина */ if (!func_check(getRequest('login'), 'login', 3, 30)) { $this->Message_AddError($this->Lang_Get('registration_login_error'), $this->Lang_Get('error')); $bError = true; } /** * Проверка мыла */ if (!func_check(getRequest('mail'), 'mail')) { $this->Message_AddError($this->Lang_Get('registration_mail_error'), $this->Lang_Get('error')); $bError = true; } /** * Проверка пароля */ if (!func_check(getRequest('password'), 'password', 5)) { $this->Message_AddError($this->Lang_Get('registration_password_error'), $this->Lang_Get('error')); $bError = true; } elseif (getRequest('password') != getRequest('password_confirm')) { $this->Message_AddError($this->Lang_Get('registration_password_error_different'), $this->Lang_Get('error')); $bError = true; } /** * Проверка капчи(циферки с картинки) */ if (!isset($_SESSION['captcha_keystring']) or $_SESSION['captcha_keystring'] != strtolower(getRequest('captcha'))) { $this->Message_AddError($this->Lang_Get('registration_captcha_error'), $this->Lang_Get('error')); $bError = true; } /** * А не занят ли логин? */ if ($this->User_GetUserByLogin(getRequest('login'))) { $this->Message_AddError($this->Lang_Get('registration_login_error_used'), $this->Lang_Get('error')); $bError = true; } /** * А не занято ли мыло? */ if ($this->User_GetUserByMail(getRequest('mail'))) { $this->Message_AddError($this->Lang_Get('registration_mail_error_used'), $this->Lang_Get('error')); $bError = true; } /** * Если всё то пробуем зарегить */ if (!$bError) { /** * Создаем юзера */ $oUser = Engine::GetEntity('User'); $oUser->setLogin(getRequest('login')); $oUser->setMail(getRequest('mail')); $oUser->setPassword(func_encrypt(getRequest('password'))); $oUser->setDateRegister(date("Y-m-d H:i:s")); $oUser->setIpRegister(func_getIp()); /** * Если используется активация, то генерим код активации */ if (Config::Get('general.reg.activation')) { $oUser->setActivate(0); $oUser->setActivateKey(md5(func_generator() . time())); } else { $oUser->setActivate(1); $oUser->setActivateKey(null); } /** * Регистрируем */ if ($this->User_Add($oUser)) { /** * Убиваем каптчу */ unset($_SESSION['captcha_keystring']); /** * Создаем персональный блог */ $this->Blog_CreatePersonalBlog($oUser); /** * Если юзер зарегистрировался по приглашению то обновляем инвайт */ if (Config::Get('general.reg.invite') and $oInvite = $this->User_GetInviteByCode($this->GetInviteRegister())) { $oInvite->setUserToId($oUser->getId()); $oInvite->setDateUsed(date("Y-m-d H:i:s")); $oInvite->setUsed(1); $this->User_UpdateInvite($oInvite); } /** * Если стоит регистрация с активацией то проводим её */ if (Config::Get('general.reg.activation')) { /** * Отправляем на мыло письмо о подтверждении регистрации */ $this->Notify_SendRegistrationActivate($oUser, getRequest('password')); Router::Location(Router::GetPath('registration') . 'confirm/'); } else { $this->Notify_SendRegistration($oUser, getRequest('password')); $this->Viewer_Assign('bRefreshToHome', true); $oUser = $this->User_GetUserById($oUser->getId()); $this->User_Authorization($oUser, false); $this->SetTemplateAction('ok'); $this->DropInviteRegister(); } } else { $this->Message_AddErrorSingle($this->Lang_Get('system_error')); return Router::Action('error'); } } } }
/** * Установка языка интерфейса * * @return void */ public function SetLang() { if (!$this->User_IsInit()) { $this->User_Init(); } if ($this->PluginL10n_L10n_GetLangFromUrl()) { // берем язык интерфейса с урла Config::Set('lang.current', $this->PluginL10n_L10n_GetLangFromUrl()); } elseif ($this->User_IsAuthorization()) { // если в урле пусто - // для авторизированных пользователей проверяем какой язык интерфейса // выбран по умолчанию и устанавливаем его в качестве текущего $oUser = $this->User_GetUserCurrent(); Config::Set('lang.current', $oUser->getUserLang()); } elseif (isset($_SERVER['REMOTE_ADDR']) && Config::Get('plugin.l10n.use_geoip')) { // для остальных язык будет передаваться по GeoIP require_once Plugin::GetPath(__CLASS__) . 'classes/lib/external/GeoIp/Wrapper.php'; $gi = new GeoIp_Wrapper(); // 2х значный код страны - он же код языка $country = $gi->getCountryCodeByAddr($_SERVER['REMOTE_ADDR']); $ruSpeaks = Config::Get('plugin.l10n.ru.countries'); // @todo refact if ($country == 'ua') { Config::Set('lang.current', $this->PluginL10n_L10n_GetLangByAlias('uk')); setlocale(LC_ALL, "uk_UA.UTF-8"); } else { Config::Set('lang.current', $this->PluginL10n_L10n_GetLangByAlias('ru')); setlocale(LC_ALL, "ru_RU.UTF-8"); date_default_timezone_set('Europe/Moscow'); // See http://php.net/manual/en/timezones.php } // if (in_array($country, $ruSpeaks)) { // Config::Set('lang.current', $this->PluginL10n_L10n_GetLangByAlias('ru')); // // setlocale(LC_ALL, "ru_RU.UTF-8"); // date_default_timezone_set('Europe/Moscow'); // See http://php.net/manual/en/timezones.php // } else { // Config::Set('lang.current', $this->PluginL10n_L10n_GetLangByAlias('en')); // // setlocale(LC_ALL, "en_EN.UTF-8"); // } } else { Config::Set('lang.current', Config::Get('lang.default')); } $sLang = $this->PluginL10n_L10n_GetAliasByLang(Config::Get('lang.current')); $sWebPath = Router::GetPathWebCurrent(); /** * Проверяем, включено ли принудительно проставление языка в урле, не является ли это CLI или Аяксом */ if (Config::Get('plugin.l10n.lang_in_url') && $sWebPath && !$this->isAjax()) { /** * Проверям, был ли язык в урле, и не главная ли это страница */ if (!Router::getLang() && rtrim($sWebPath, '/') != Config::Get('path.root.web')) { $sWebPath = str_replace(Config::Get('path.root.web'), Config::Get('path.root.web') . '/' . $sLang, $sWebPath); Router::Location($sWebPath); } $this->PluginL10n_L10n_SetLangForUrl($sLang); } $sConfigFile = Config::Get('path.root.server') . '/config/plugins/l10n/config.' . $sLang . '.php'; if (file_exists($sConfigFile)) { Config::LoadFromFile($sConfigFile); } $this->UpdateBlockRoutes(); $this->Viewer_Assign('sLangCurrent', $this->PluginL10n_L10n_GetAliasByLang(Config::Get('lang.current'))); }
protected function EventPluginsActivate($sPlugin) { if ($bResult = $this->PluginAceadminpanel_Plugin_Activate($sPlugin)) { $this->Message_AddNotice($this->Lang_Get('plugins_action_ok'), $this->Lang_Get('attention'), true); } else { if (!($aMessages = $this->Message_GetErrorSession()) or !sizeof($aMessages)) { $this->Message_AddErrorSingle($this->Lang_Get('system_error') . ' (unknown error)', $this->Lang_Get('error'), true); } } // * Возвращаемся на страницу управления плагинами if ($this->sPageRef) { Router::Location($this->sPageRef); } else { Router::Location(Router::GetPath('admin') . 'site/plugins/'); } }
/** * Страница создания письма */ 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'); } }
/** * Добавление пользователя в друзья, по отправленной заявке */ public function EventFriendOffer() { require_once Config::Get('path.root.engine') . '/lib/external/XXTEA/encrypt.php'; $sUserId = xxtea_decrypt(base64_decode(rawurldecode(getRequest('code'))), Config::Get('module.talk.encrypt')); if (!$sUserId) { return $this->EventNotFound(); } list($sUserId, ) = explode('_', $sUserId, 2); $sAction = $this->GetParam(0); /** * Получаем текущего пользователя */ if (!$this->User_IsAuthorization()) { return $this->EventNotFound(); } $this->oUserCurrent = $this->User_GetUserCurrent(); /** * Получаем объект пользователя приславшего заявку, * если пользователь не найден, переводим в раздел сообщений (Talk) - * так как пользователь мог перейти сюда либо из talk-сообщений, * либо из e-mail письма-уведомления */ if (!($oUser = $this->User_GetUserById($sUserId))) { $this->Message_AddError($this->Lang_Get('user_not_found'), $this->Lang_Get('error'), true); Router::Location(Router::GetPath('talk')); return; } /** * Получаем связь дружбы из базы данных. * Если связь не найдена либо статус отличен от OFFER, * переходим в раздел Talk и возвращаем сообщение об ошибке */ $oFriend = $this->User_GetFriend($this->oUserCurrent->getId(), $oUser->getId(), 0); if (!$oFriend || !in_array($oFriend->getFriendStatus(), array(ModuleUser::USER_FRIEND_OFFER + ModuleUser::USER_FRIEND_NULL))) { $sMessage = $oFriend ? $this->Lang_Get('user_friend_offer_already_done') : $this->Lang_Get('user_friend_offer_not_found'); $this->Message_AddError($sMessage, $this->Lang_Get('error'), true); Router::Location(Router::GetPath('talk')); return; } /** * Устанавливаем новый статус связи */ $oFriend->setStatusTo($sAction == 'accept' ? ModuleUser::USER_FRIEND_ACCEPT : ModuleUser::USER_FRIEND_REJECT); if ($this->User_UpdateFriend($oFriend)) { $sMessage = $sAction == 'accept' ? $this->Lang_Get('user_friend_add_ok') : $this->Lang_Get('user_friend_offer_reject'); $this->Message_AddNoticeSingle($sMessage, $this->Lang_Get('attention'), true); $this->NoticeFriendOffer($oUser, $sAction); } else { $this->Message_AddErrorSingle($this->Lang_Get('system_error'), $this->Lang_Get('error'), true); } Router::Location(Router::GetPath('talk')); }
/** * Выводит список комментариев которые написал юзер * Перенаправляет на профиль пользователя * */ protected function EventComments() { /** * Получаем логин из УРЛа */ $sUserLogin = $this->sCurrentEvent; /** * Проверяем есть ли такой юзер */ if (!($this->oUserProfile = $this->User_GetUserByLogin($sUserLogin))) { return parent::EventNotFound(); } /** * Передан ли номер страницы */ $iPage = $this->GetParamEventMatch(1, 2) ? $this->GetParamEventMatch(1, 2) : 1; /** * Выполняем редирект на новый URL, в новых версиях LS экшен "my" будет удален */ $sPage = $iPage == 1 ? '' : "page{$iPage}/"; Router::Location($this->oUserProfile->getUserWebPath() . 'created/comments/' . $sPage); }
protected function EventDelete() { $this->Security_ValidateSendForm(); /** * Получаем номер топика из УРЛ и проверяем существует ли он */ $sTopicId = $this->GetParam(0); if (!($oTopic = $this->Topic_GetTopicById($sTopicId))) { return parent::EventNotFound(); } /** * проверяем есть ли право на удаление топика */ if (!$this->ACL_IsAllowDeleteTopic($oTopic, $this->oUserCurrent)) { $this->Message_AddErrorSingle($this->Rbac_GetMsgLast()); return Router::Action('error'); } /** * Удаляем топик */ $this->Hook_Run('topic_delete_before', array('oTopic' => $oTopic)); $this->Topic_DeleteTopic($oTopic); $this->Hook_Run('topic_delete_after', array('oTopic' => $oTopic)); /** * Перенаправляем на страницу со списком топиков из блога этого топика */ Router::Location($oTopic->getBlog()->getUrlFull()); }
/** * Обработка редактирования топика * * @param unknown_type $oTopic * @return unknown */ protected function SubmitEdit($oTopic) { /** * Проверка корректности полей формы */ if (!$this->checkTopicFields()) { 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; } /** * Теперь можно смело редактировать топик */ $oTopic->setBlogId($oBlog->getId()); $oTopic->setTitle(getRequest('topic_title')); $oTopic->setText(htmlspecialchars(getRequest('topic_text'))); $oTopic->setTextShort(htmlspecialchars(getRequest('topic_text'))); $oTopic->setTextSource(getRequest('topic_text')); $oTopic->setLinkUrl(getRequest('topic_link_url')); $oTopic->setTags(getRequest('topic_tags')); $oTopic->setUserIp(func_getIp()); $oTopic->setTextHash(md5($oTopic->getType() . $oTopic->getText() . $oTopic->getLinkUrl())); /** * Проверяем топик на уникальность */ 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->oUserCurrent->isAdministrator()) { 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 ($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'); } }
/** * Обработка редактирования топика * * @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'); } }
/** * Обработка редактирования топика * * @param ModuleTopic_EntityTopic $oTopic * @return mixed */ protected function SubmitEdit($oTopic) { $oTopic->_setValidateScenario('topic'); /** * Сохраняем старое значение идентификатора блога */ $sBlogIdOld = $oTopic->getBlogId(); /** * Заполняем поля для валидации */ $oTopic->setBlogId(getRequestStr('blog_id')); $oTopic->setTitle(strip_tags(getRequestStr('topic_title'))); $oTopic->setTextSource(getRequestStr('topic_text')); $oTopic->setTags(getRequestStr('topic_tags')); $oTopic->setUserIp(func_getIp()); /** * Проверка корректности полей формы */ if (!$this->checkTopicFields($oTopic)) { return false; } /** * Определяем в какой блог делаем запись */ $iBlogId = $oTopic->getBlogId(); if ($iBlogId == 0) { $oBlog = $this->Blog_GetPersonalBlogByUserId($oTopic->getUserId()); } else { $oBlog = $this->Blog_GetBlogById($iBlogId); } /** * Если блог не определен выдаем предупреждение */ if (!$oBlog) { $this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_unknown'), $this->Lang_Get('error')); return false; } /** * Проверяем права на постинг в блог */ if (!$this->ACL_IsAllowBlog($oBlog, $this->oUserCurrent)) { $this->Message_AddErrorSingle($this->Lang_Get('topic_create_blog_error_noallow'), $this->Lang_Get('error')); return false; } /** * Проверяем разрешено ли постить топик по времени */ if (isPost('submit_topic_publish') and !$oTopic->getPublishDraft() and !$this->ACL_CanPostTopicTime($this->oUserCurrent)) { $this->Message_AddErrorSingle($this->Lang_Get('topic_time_limit'), $this->Lang_Get('error')); return; } $oTopic->setBlogId($oBlog->getId()); /** * Получаемый и устанавливаем разрезанный текст по тегу <cut> */ list($sTextShort, $sTextNew, $sTextCut) = $this->Text_Cut($oTopic->getTextSource()); $oTopic->setCutText($sTextCut); $oTopic->setText($this->Text_Parser($sTextNew)); $oTopic->setTextShort($this->Text_Parser($sTextShort)); /** * Публикуем или сохраняем в черновиках */ $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, $oTopic->getUser()); } 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'); } }
/** * Обработка напоминания пароля * */ 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')); } } }
/** * Update album */ public function EventUpdateAlbum() { $this->sMenuItemSelect = 'album'; $this->sMenuSubItemSelect = 'update'; $this->Viewer_AddHtmlTitle($this->Lang_Get('plugin.lsgallery.lsgallery_update_album_title')); $sId = $this->GetParam(0); if (!($oAlbum = $this->PluginLsgallery_Album_GetAlbumById($sId))) { return $this->EventNotFound(); } if (!$this->ACL_AllowUpdateAlbum($this->oUserCurrent, $oAlbum)) { $this->Message_AddErrorSingle($this->Lang_Get('not_access'), $this->Lang_Get('error')); return Router::Action('error'); } $this->SetTemplateAction('create'); $this->Viewer_Assign('aLocalizedTypes', PluginLsgallery_ModuleAlbum_EntityAlbum::getLocalizedTypes($this)); $this->Viewer_Assign('oAlbumEdit', $oAlbum); if (isPost('submit_create_album')) { if (!$this->_checkAlbumFields($oAlbum)) { return; } $oAlbum->setTitle(getRequest('album_title')); $oAlbum->setDescription(getRequest('album_description')); $oAlbum->setType(getRequest('album_type')); if ($this->PluginLsgallery_Album_UpdateAlbum($oAlbum)) { Router::Location($oAlbum->getUrlFull()); } else { $this->Message_AddErrorSingle($this->Lang_Get('system_error'), $this->Lang_Get('error')); return Router::Action('error'); } } else { $_REQUEST['album_id'] = $oAlbum->getId(); $_REQUEST['album_title'] = $oAlbum->getTitle(); $_REQUEST['album_description'] = $oAlbum->getDescription(); $_REQUEST['album_type'] = $oAlbum->getType(); } }
/** * Удаление блога * * @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()); } }
/** * Поиск и формирование результата * * @param unknown_type $aReq * @param unknown_type $iLimit * @return unknown */ protected function PrepareResults($aReq, $iLimit) { /** * Количество результатов по типам */ foreach ($this->sTypesEnabled as $sType => $aExtra) { $aRes['aCounts'][$sType] = intval($this->Sphinx_GetNumResultsByType($aReq['q'], $sType, $aExtra)); } if ($aRes['aCounts'][$aReq['sType']] == 0) { /** * Объектов необходимого типа не найдено */ unset($this->sTypesEnabled[$aReq['sType']]); /** * Проверяем отсальные типы */ foreach (array_keys($this->sTypesEnabled) as $sType) { if ($aRes['aCounts'][$sType]) { Router::Location(Router::GetPath('search') . $sType . '/?q=' . $aReq['q']); } } } elseif (($aReq['iPage'] - 1) * $iLimit <= $aRes['aCounts'][$aReq['sType']]) { /** * Ищем */ $this->aSphinxRes = $this->Sphinx_FindContent($aReq['q'], $aReq['sType'], ($aReq['iPage'] - 1) * $iLimit, $iLimit, $this->sTypesEnabled[$aReq['sType']]); /** * Возможно демон Сфинкса не доступен */ if (FALSE === $this->aSphinxRes) { return FALSE; } $this->bIsResults = TRUE; /** * Формируем постраничный вывод */ $aPaging = $this->Viewer_MakePaging($aRes['aCounts'][$aReq['sType']], $aReq['iPage'], $iLimit, 4, Router::GetPath('search') . $aReq['sType'], array('q' => $aReq['q'])); $this->Viewer_Assign('aPaging', $aPaging); } $this->SetTemplateAction('results'); $this->Viewer_AddHtmlTitle($aReq['q']); $this->Viewer_Assign('bIsResults', $this->bIsResults); return $aRes; }