protected function EventSkin() { $aParams = $this->GetParams(); $sSkinName = array_shift($aParams); $sRelPath = implode('/', $aParams); $sOriginalFile = Config::Get('path.skins.dir') . $sSkinName . '/' . $sRelPath; if (F::File_Exists($sOriginalFile)) { $sAssetFile = F::File_GetAssetDir() . 'skin/' . $sSkinName . '/' . $sRelPath; if (F::File_Copy($sOriginalFile, $sAssetFile)) { if (headers_sent($sFile, $nLine)) { $sUrl = F::File_GetAssetUrl() . 'skin/' . $sSkinName . '/' . $sRelPath; if (strpos($sUrl, '?')) { $sUrl .= '&' . uniqid(); } else { $sUrl .= '?' . uniqid(); } R::Location($sUrl); } else { header_remove(); if ($sMimeType = F::File_MimeType($sAssetFile)) { header('Content-Type: ' . $sMimeType); } echo file_get_contents($sAssetFile); exit; } } } F::HttpHeader('404 Not Found'); exit; }
public function EventDownloadFile() { $this->SetTemplate(false); $sTopicId = $this->GetParam(0); $sFieldId = $this->GetParam(1); E::ModuleSecurity()->ValidateSendForm(); if (!($oTopic = E::ModuleTopic()->GetTopicById($sTopicId))) { return parent::EventNotFound(); } if (!($this->oType = E::ModuleTopic()->GetContentType($oTopic->getType()))) { return parent::EventNotFound(); } if (!($oField = E::ModuleTopic()->GetContentFieldById($sFieldId))) { return parent::EventNotFound(); } if ($oField->getContentId() != $this->oType->getContentId()) { return parent::EventNotFound(); } //получаем объект файла $oFile = $oTopic->getFieldFile($oField->getFieldId()); //получаем объект поля топика, содержащий данные о файле $oValue = $oTopic->getField($oField->getFieldId()); if ($oFile && $oValue) { if (preg_match("/^(http:\\/\\/)/i", $oFile->getFileUrl())) { $sFullPath = $oFile->getFileUrl(); R::Location($sFullPath); } else { $sFullPath = Config::Get('path.root.dir') . $oFile->getFileUrl(); } $sFilename = $oFile->getFileName(); /* * Обновляем данные */ $aFileObj = array(); $aFileObj['file_name'] = $oFile->getFileName(); $aFileObj['file_url'] = $oFile->getFileUrl(); $aFileObj['file_size'] = $oFile->getFileSize(); $aFileObj['file_extension'] = $oFile->getFileExtension(); $aFileObj['file_downloads'] = $oFile->getFileDownloads() + 1; $sText = serialize($aFileObj); $oValue->setValue($sText); $oValue->setValueSource($sText); //сохраняем E::ModuleTopic()->UpdateContentFieldValue($oValue); /* * Отдаем файл */ header('Content-type: ' . $oFile->getFileExtension()); header('Content-Disposition: attachment; filename="' . $sFilename . '"'); F::File_PrintChunked($sFullPath); } else { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('content_download_file_error')); return R::Action('error'); } }
/** * Инициализация экшена * */ public function Init() { /** * issue #104, {@see https://github.com/altocms/altocms/issues/104} * Проверим, не пришли ли мы в ошибку с логаута, если да, то перейдем на главную, * поскольку страница на самом деле есть, но только когда мы авторизованы. */ if (isset($_SERVER['HTTP_REFERER']) && E::ModuleSession()->GetCookie('lgp') === md5(F::RealUrl($_SERVER['HTTP_REFERER']) . 'logout')) { return R::Location((string) Config::Get('module.user.logout.redirect')); } /** * Устанавливаем дефолтный евент */ $this->SetDefaultEvent('index'); /** * Запрешаем отображать статистику выполнения */ R::SetIsShowStats(false); }
/** * Отписка от подписки */ protected function EventUnsubscribe() { /** * Получаем подписку по ключу */ $oSubscribe = E::ModuleSubscribe()->GetSubscribeByKey($this->getParam(0)); if ($oSubscribe && $oSubscribe->getStatus() == 1) { /** * Отписываем пользователя */ $oSubscribe->setStatus(0); $oSubscribe->setDateRemove(F::Now()); E::ModuleSubscribe()->UpdateSubscribe($oSubscribe); E::ModuleMessage()->AddNotice(E::ModuleLang()->Get('subscribe_change_ok'), null, true); } /** * Получаем URL для редиректа */ if (!($sUrl = E::ModuleSubscribe()->GetUrlTarget($oSubscribe->getTargetType(), $oSubscribe->getTargetId()))) { $sUrl = R::GetPath('index'); } R::Location($sUrl); }
/** * Makes image with new size */ public function EventUploads() { // Раз оказались здесь, то нет соответствующего изображения. Пробуем его создать $sUrl = F::File_RootUrl() . '/' . $this->sCurrentEvent . '/' . implode('/', $this->GetParams()); $sFile = F::File_Url2Dir($sUrl); $sNewFile = E::ModuleImg()->Duplicate($sFile); if (!$sNewFile) { if (preg_match('/\\-(\\d+)x(\\d+)\\.[a-z]{3}$/i', $sFile, $aMatches)) { $nSize = $aMatches[1]; } else { $nSize = 0; } if (strpos(basename($sFile), 'avatar_blog') === 0) { // Запрашивается аватар блога $sNewFile = E::ModuleImg()->AutoresizeSkinImage($sFile, 'avatar_blog', $nSize ? $nSize : self::BLOG_AVATAR_SIZE); } elseif (strpos(basename($sFile), 'avatar') === 0) { // Запрашивается аватар $sNewFile = E::ModuleImg()->AutoresizeSkinImage($sFile, 'avatar', $nSize ? $nSize : self::USER_AVATAR_SIZE); } elseif (strpos(basename($sFile), 'user_photo') === 0) { // Запрашивается фото $sNewFile = E::ModuleImg()->AutoresizeSkinImage($sFile, 'user_photo', $nSize ? $nSize : self::USER_PHOTO_SIZE); } } // Если файл успешно создан, то выводим его if ($sNewFile) { if (headers_sent($sFile, $nLine)) { R::Location($sUrl . '?rnd=' . uniqid()); } else { header_remove(); E::ModuleImg()->RenderFile($sNewFile); exit; } } F::HttpHeader('404 Not Found'); exit; }
/** * Обрабатываем процесс разлогинивания * */ protected function EventExit() { E::ModuleSecurity()->ValidateSendForm(); E::ModuleUser()->Logout(); $iShowTime = Config::Val('module.user.logout.show_exit', 3); $sRedirect = Config::Get('module.user.logout.redirect'); if (!$sRedirect) { if (isset($_SERVER['HTTP_REFERER']) && F::File_IsLocalUrl($_SERVER['HTTP_REFERER'])) { $sRedirect = $_SERVER['HTTP_REFERER']; } } /** * issue #104, {@see https://github.com/altocms/altocms/issues/104} * Установим в lgp (last_good_page) хэш имени страницы с постфиксом "logout". Такая * кука будет означать, что на этой странице пользователь вышел с сайта. Время 60 - * заранее достаточное время, что бы произошел редирект на страницу HTTP_REFERER. Если * же эта страница выпадет в 404 то в экшене ActionError уйдем на главную, поскольку * эта страница недоступна стала после выхода с сайта, а до этого была вполне ничего. */ if ($iShowTime) { $sUrl = F::RealUrl($sRedirect); $sReferrer = Config::Get('path.root.web') . R::GetAction() . "/" . R::GetActionEvent() . '/?security_key=' . F::GetRequest('security_key', ''); E::ModuleSession()->SetCookie('lgp', md5($sReferrer . 'logout'), 60); E::ModuleViewer()->SetHtmlHeadTag('meta', array('http-equiv' => 'Refresh', 'Content' => $iShowTime . '; url=' . $sUrl)); } elseif ($sRedirect) { // Если установлена пользовтаельская страница выхода, то считаем, // что она без ошибки и смело не нее редиректим, в других случаях // возможна 404 if (!Config::Get('module.user.logout.redirect')) { E::ModuleSession()->SetCookie('lgp', md5(F::RealUrl($sRedirect) . 'logout'), 60); } R::Location($sRedirect); exit; } else { // E::ModuleViewer()->Assign('bRefreshToHome', true); // Время показа страницы выхода не задано, поэтому просто редирект R::Location(Config::Get('path.root.web')); exit; } }
protected function EventDeleteField() { $this->sMainMenuItem = 'settings'; E::ModuleSecurity()->ValidateSendForm(); $iContentFieldId = intval($this->GetParam(0)); if (!$iContentFieldId) { return parent::EventNotFound(); } $oField = E::ModuleTopic()->GetContentFieldById($iContentFieldId); if ($oField) { $oContentType = E::ModuleTopic()->GetContentTypeById($oField->getContentId()); } else { $oContentType = null; } if (E::ModuleTopic()->DeleteField($iContentFieldId)) { E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('action.admin.contenttypes_success_fielddelete'), null, true); if ($oContentType) { R::Location('admin/settings-contenttypes/edit/' . $oContentType->getContentId() . '/'); } else { R::Location('admin/settings-contenttypes/'); } } return false; }
/** * Страница создания письма */ protected function EventAdd() { $this->sMenuSubItemSelect = 'add'; E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('talk_menu_inbox_create')); // * Получаем список друзей $aUsersFriend = E::ModuleUser()->GetUsersFriend($this->oUserCurrent->getId()); if ($aUsersFriend['collection']) { E::ModuleViewer()->Assign('aUsersFriend', $aUsersFriend['collection']); } // * Проверяем отправлена ли форма с данными if (!F::isPost('submit_talk_add')) { return false; } // * Проверка корректности полей формы if (!$this->checkTalkFields()) { return false; } // * Проверяем разрешено ли отправлять инбокс по времени if (!E::ModuleACL()->CanSendTalkTime($this->oUserCurrent)) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('talk_time_limit'), E::ModuleLang()->Get('error')); return false; } // * Отправляем письмо if ($oTalk = E::ModuleTalk()->SendTalk(E::ModuleText()->Parser(strip_tags(F::GetRequestStr('talk_title'))), E::ModuleText()->Parser(F::GetRequestStr('talk_text')), $this->oUserCurrent, $this->aUsersId)) { E::ModuleMresource()->CheckTargetTextForImages('talk', $oTalk->getId(), $oTalk->getText()); R::Location(R::GetPath('talk') . 'read/' . $oTalk->getId() . '/'); } else { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error')); return R::Action('error'); } }
/** * Удаление блога * */ protected function EventDeleteBlog() { E::ModuleSecurity()->ValidateSendForm(); // * Проверяем передан ли в УРЛе номер блога $nBlogId = intval($this->GetParam(0)); if (!$nBlogId || !($oBlog = E::ModuleBlog()->GetBlogById($nBlogId))) { return parent::EventNotFound(); } $this->oCurrentBlog = $oBlog; // * Проверям авторизован ли пользователь if (!E::ModuleUser()->IsAuthorization()) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('not_access'), E::ModuleLang()->Get('error')); return R::Action('error'); } // * проверяем есть ли право на удаление блога if (!($nAccess = E::ModuleACL()->IsAllowDeleteBlog($oBlog, $this->oUserCurrent))) { return parent::EventNotFound(); } $aTopics = E::ModuleTopic()->GetTopicsByBlogId($nBlogId); switch ($nAccess) { case ModuleACL::CAN_DELETE_BLOG_EMPTY_ONLY: if (is_array($aTopics) && count($aTopics)) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('blog_admin_delete_not_empty'), E::ModuleLang()->Get('error'), true); R::Location($oBlog->getUrlFull()); } break; case ModuleACL::CAN_DELETE_BLOG_WITH_TOPICS: /* * Если указан идентификатор блога для перемещения, * то делаем попытку переместить топики. * * (-1) - выбран пункт меню "удалить топики". */ $nNewBlogId = intval(F::GetRequestStr('topic_move_to')); if ($nNewBlogId > 0 && is_array($aTopics) && count($aTopics)) { if (!($oBlogNew = E::ModuleBlog()->GetBlogById($nNewBlogId))) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('blog_admin_delete_move_error'), E::ModuleLang()->Get('error'), true); R::Location($oBlog->getUrlFull()); } // * Если выбранный блог является персональным, возвращаем ошибку if ($oBlogNew->getType() == 'personal') { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('blog_admin_delete_move_personal'), E::ModuleLang()->Get('error'), true); R::Location($oBlog->getUrlFull()); } // * Перемещаем топики E::ModuleTopic()->MoveTopics($nBlogId, $nNewBlogId); } break; default: return parent::EventNotFound(); } // * Удаляяем блог и перенаправляем пользователя к списку блогов E::ModuleHook()->Run('blog_delete_before', array('sBlogId' => $nBlogId)); if ($this->_deleteBlog($oBlog)) { E::ModuleHook()->Run('blog_delete_after', array('sBlogId' => $nBlogId)); E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('blog_admin_delete_success'), E::ModuleLang()->Get('attention'), true); R::Location(R::GetPath('blogs')); } else { R::Location($oBlog->getUrlFull()); } }
/** * Переход по ссылке с подсчетом количества переходов * */ protected function EventGo() { // * Получаем номер топика из УРЛ и проверяем существует ли он $iTopicId = intval($this->GetParam(0)); if (!$iTopicId || !($oTopic = E::ModuleTopic()->GetTopicById($iTopicId)) || !$oTopic->getPublish()) { return parent::EventNotFound(); } // * проверяем есть ли ссылка на источник if (!$oTopic->getSourceLink()) { return parent::EventNotFound(); } // * увелививаем число переходов по ссылке $oTopic->setSourceLinkCountJump($oTopic->getSourceLinkCountJump() + 1); E::ModuleTopic()->UpdateTopic($oTopic); // * собственно сам переход по ссылке R::Location($oTopic->getSourceLink()); }
/** * Выводит список комментариев которые написал юзер * Перенаправляет на профиль пользователя * */ protected function EventComments() { /** * Получаем логин из УРЛа */ $sUserLogin = $this->sCurrentEvent; /** * Проверяем есть ли такой юзер */ if (!($this->oUserProfile = E::ModuleUser()->GetUserByLogin($sUserLogin))) { return parent::EventNotFound(); } /** * Передан ли номер страницы */ $iPage = $this->GetParamEventMatch(1, 2) ? $this->GetParamEventMatch(1, 2) : 1; /** * Выполняем редирект на новый URL, в новых версиях LS экшен "my" будет удален */ $sPage = $iPage == 1 ? '' : "page{$iPage}/"; R::Location($this->oUserProfile->getUserWebPath() . 'created/comments/' . $sPage); }
/** * Редактирование поля контента * * @param ModuleTopic_EntityContentType $oContentType * @param ModuleTopic_EntityField $oField * @return bool */ protected function SubmitEditField($oContentType, $oField) { // * Проверяем отправлена ли форма с данными if (!F::isPost('submit_field')) { return false; } // * Проверка корректности полей формы if (!$this->CheckFieldsField($oContentType)) { return false; } if (!E::ModuleTopic()->GetFieldValuesCount($oField->getFieldId())) { // Нет ещё ни одного значения этого поля, тогда можно сменить ещё и тип $oField->setFieldType(F::GetRequest('field_type')); } $oField->setFieldName(F::GetRequest('field_name')); $oField->setFieldDescription(F::GetRequest('field_description')); $oField->setFieldRequired(F::GetRequest('field_required')); if ($oField->getFieldType() == 'select') { $oField->setOptionValue('select', F::GetRequest('field_values')); } $sOldFieldUniqueName = $oField->getFieldUniqueName(); if (F::GetRequest('field_unique_name_translit')) { $oField->setFieldUniqueName(F::TranslitUrl(F::GetRequest('field_name'))); } else { $oField->setFieldUniqueName(F::TranslitUrl(F::GetRequest('field_unique_name'))); } try { if (E::ModuleTopic()->UpdateContentField($oField)) { E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('action.admin.contenttypes_success_fieldedit'), null, true); R::Location('admin/settings-contenttypes/edit/' . $oContentType->getContentId() . '/'); } } catch (Exception $e) { // Если ошибка дублирования уникального ключа, то выводим соответствующее сообщение if (1062 == $e->getCode()) { $sNewFieldUniqueName = $oField->getFieldUniqueName(); $oField->setFieldUniqueName($sOldFieldUniqueName); E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('plugin.contentfieldsx.error_field_unique_name_duplicate', array('unique_name' => htmlspecialchars($sNewFieldUniqueName))), null, false); } } return false; }
/** * Обрабатывает ссылку на конкретный комментарий, определят к какому топику он относится и перенаправляет на него * Актуально при использовании постраничности комментариев */ protected function EventShowComment() { $iCommentId = $this->sCurrentEvent; // * Проверяем к чему относится комментарий if (!($oComment = E::ModuleComment()->GetCommentById($iCommentId))) { return parent::EventNotFound(); } if ($oComment->getTargetType() != 'topic' || !($oTopic = $oComment->getTarget())) { return parent::EventNotFound(); } // * Определяем необходимую страницу для отображения комментария if (!Config::Get('module.comment.use_nested') || !Config::Get('module.comment.nested_per_page')) { R::Location($oTopic->getUrl() . '#comment' . $oComment->getId()); } $iPage = E::ModuleComment()->GetPageCommentByTargetId($oComment->getTargetId(), $oComment->getTargetType(), $oComment); if ($iPage == 1) { R::Location($oTopic->getUrl() . '#comment' . $oComment->getId()); } else { R::Location($oTopic->getUrl() . "?cmtpage={$iPage}#comment" . $oComment->getId()); } exit; }
/** * Добавление пользователя в друзья, по отправленной заявке */ public function EventFriendOffer() { F::IncludeLib('XXTEA/encrypt.php'); /** * Из реквеста дешефруем ID польователя */ $sUserId = xxtea_decrypt(base64_decode(rawurldecode(F::GetRequestStr('code'))), Config::Get('module.talk.encrypt')); if (!$sUserId) { return $this->EventNotFound(); } list($sUserId, ) = explode('_', $sUserId, 2); $sAction = $this->GetParam(0); /** * Получаем текущего пользователя */ if (!E::ModuleUser()->IsAuthorization()) { return $this->EventNotFound(); } $this->oUserCurrent = E::ModuleUser()->GetUserCurrent(); /** * Получаем объект пользователя приславшего заявку, * если пользователь не найден, переводим в раздел сообщений (Talk) - * так как пользователь мог перейти сюда либо из talk-сообщений, * либо из e-mail письма-уведомления */ if (!($oUser = E::ModuleUser()->GetUserById($sUserId))) { E::ModuleMessage()->AddError(E::ModuleLang()->Get('user_not_found'), E::ModuleLang()->Get('error'), true); R::Location(R::GetPath('talk')); return; } /** * Получаем связь дружбы из базы данных. * Если связь не найдена либо статус отличен от OFFER, * переходим в раздел Talk и возвращаем сообщение об ошибке */ $oFriend = E::ModuleUser()->GetFriend($this->oUserCurrent->getId(), $oUser->getId(), 0); if (!$oFriend || !in_array($oFriend->getFriendStatus(), array(ModuleUser::USER_FRIEND_OFFER + ModuleUser::USER_FRIEND_NULL))) { $sMessage = $oFriend ? E::ModuleLang()->Get('user_friend_offer_already_done') : E::ModuleLang()->Get('user_friend_offer_not_found'); E::ModuleMessage()->AddError($sMessage, E::ModuleLang()->Get('error'), true); R::Location('talk'); return; } /** * Устанавливаем новый статус связи */ $oFriend->setStatusTo($sAction == 'accept' ? ModuleUser::USER_FRIEND_ACCEPT : ModuleUser::USER_FRIEND_REJECT); if (E::ModuleUser()->UpdateFriend($oFriend)) { $sMessage = $sAction == 'accept' ? E::ModuleLang()->Get('user_friend_add_ok') : E::ModuleLang()->Get('user_friend_offer_reject'); E::ModuleMessage()->AddNoticeSingle($sMessage, E::ModuleLang()->Get('attention'), true); $this->NoticeFriendOffer($oUser, $sAction); } else { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'), true); } R::Location('talk'); }