/** * 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 _getSitemapData($sType, $iPage) { if ($iPage < 1) { $iPage = 1; } $sChangeFreq = C::Get('plugin.sitemap.' . $sType . '.changefreq'); if (!$sChangeFreq) { $sChangeFreq = C::Get('plugin.sitemap.default.sitemap.changefreq'); } $nPriority = C::Get('plugin.sitemap.' . $sType . '.priority'); if (!$nPriority) { $nPriority = C::Get('plugin.sitemap.default.sitemap.priority'); } $sLastMod = $this->_getSitemapLastmod($sType, $iPage); $aItem = array('loc' => F::File_RootUrl(true) . 'sitemap_' . $sType . '_' . $iPage . '.xml'); if ($sChangeFreq) { $aItem['changefreq'] = $sChangeFreq; } if ($nPriority) { $aItem['priority'] = $nPriority; } if ($sLastMod) { $aItem['lastmod'] = $sLastMod; } return $aItem; }
/** * Возвращает URL до профиля пользователя * * @param string|null $sUrlMask - еcли передан параметр, то формирует URL по этой маске * @param bool $bFullUrl - возвращать полный путь (или относительный, если false) * * @return string */ public function getProfileUrl($sUrlMask = null, $bFullUrl = true) { $sKey = '-url-' . ($sUrlMask ? $sUrlMask : '') . ($bFullUrl ? '-1' : '-0'); $sUrl = $this->getProp($sKey); if (!is_null($sUrl)) { return $sUrl; } if (!$sUrlMask) { $sUrlMask = R::GetUserUrlMask(); } if (!$sUrlMask) { // формирование URL по умолчанию $sUrl = R::GetPath('profile/' . $this->getLogin()); $this->setProp($sKey, $sUrl); return $sUrl; } $aReplace = array('%user_id%' => $this->GetId(), '%login%' => $this->GetLogin()); $sUrl = strtr($sUrlMask, $aReplace); if (strpos($sUrl, '/')) { list($sAction, $sPath) = explode('/', $sUrl, 2); $sUrl = R::GetPath($sAction) . $sPath; } else { $sUrl = F::File_RootUrl() . $sUrl; } if (substr($sUrl, -1) !== '/') { $sUrl .= '/'; } $this->setProp($sKey, $sUrl); return $sUrl; }
/** * Приведение адреса к абсолютному виду * * Путь в $sLocation может быть как абсолютным, так и относительным. * Абсолютный путь определяется по наличию хоста * * Если задан относительный путь, то итоговый URL определяется в зависимости от второго парамтера. * Если $bRealHost == false (по умолчанию), то за основу берется root-адрес сайта, который задан в конфигурации. * В противном случае основа адреса - это реальный адрес хоста из $_SERVER['SERVER_NAME'] * * @param string $sLocation - адрес перехода (напр., 'http://ya.ru/demo/', '/123.html', 'blog/add/') * @param bool $bRealHost - в случае относительной адресации брать адрес хоста из конфига или реальный * * @return string */ public static function RealUrl($sLocation, $bRealHost = false) { // если парсером хост не обнаружен, то задан относительный путь if (!parse_url($sLocation, PHP_URL_HOST)) { if (!$bRealHost) { $sUrl = F::File_RootUrl() . $sLocation; } else { $sUrl = static::UrlBase() . '/' . $sLocation; } } else { $sUrl = $sLocation; } return F::File_NormPath($sUrl); }
/** * Возвращает полный URL до топика * * @param string|null $sUrlMask - еcли передан параметр, то формирует URL по этой маске * @param bool $bFullUrl - возвращать полный путь (или относительный, если false) * * @return string */ public function getLink($sUrlMask = null, $bFullUrl = true) { $sKey = '_url-' . ($sUrlMask ? $sUrlMask : '') . ($bFullUrl ? '-1' : '-0'); $sUrl = $this->getProp($sKey); if (!is_null($sUrl)) { return $sUrl; } if (!$sUrlMask) { $sUrlMask = R::GetTopicUrlMask(); } if (!$sUrlMask) { // формирование URL по умолчанию в LS-стиле if ($this->getBlog()->getType() == 'personal') { $sUrl = R::GetPath('blog') . $this->getId() . '.html'; } else { $sUrl = $this->getBlog()->getLink() . $this->getId() . '.html'; } $this->setProp($sKey, $sUrl); return $sUrl; } // ЧПУ по маске $sCreateDate = strtotime($this->GetDateAdd()); $aReplace = array('%year%' => date('Y', $sCreateDate), '%month%' => date('m', $sCreateDate), '%day%' => date('d', $sCreateDate), '%hour%' => date('H', $sCreateDate), '%minute%' => date('i', $sCreateDate), '%second%' => date('s', $sCreateDate), '%topic_type%' => $this->GetTopicType(), '%topic_id%' => $this->GetId(), '%topic_url%' => $this->GetTopicUrl(), '%login%' => $this->GetUser()->GetLogin(), '%blog_url%' => $this->GetBlog()->GetUrl()); if (substr($sUrlMask, -1) == '%') { $sUrlMask .= '/'; } $sUrl = strtr($sUrlMask, $aReplace); if ($bFullUrl) { if ($sUrl[0] == '/') { $sUrl = F::File_RootUrl() . substr($sUrl, 1); } else { $sUrl = F::File_RootUrl() . $sUrl; } } $this->setProp($sKey, $sUrl); return $sUrl; }
/** * Завершаем работу модуля * */ public function Shutdown() { // * Делаем выгрузку необходимых текстовок в шаблон в виде js $this->AssignToJs(); if (Config::Get('lang.multilang')) { E::ModuleViewer()->AddHtmlHeadTag('<link rel="alternate" hreflang="x-default" href="' . R::Url('link') . '">'); $aLangs = Config::Get('lang.allow'); foreach ($aLangs as $sLang) { E::ModuleViewer()->AddHtmlHeadTag('<link rel="alternate" hreflang="' . $sLang . '" href="' . trim(F::File_RootUrl($sLang), '/') . R::Url('path') . '">'); } } }
/** * Returns full url to media resource * * @return string */ public function GetUrl() { $sUrl = $this->GetPathUrl(); if (substr($sUrl, 0, 1) == '@') { $sUrl = F::File_NormPath(F::File_RootUrl() . '/' . substr($sUrl, 1)); } return $sUrl; }
/** * Редактирование топика * */ protected function EventEdit() { // * Получаем номер топика из URL и проверяем существует ли он $iTopicId = intval($this->GetParam(0)); if (!$iTopicId || !($oTopic = E::ModuleTopic()->GetTopicById($iTopicId))) { return parent::EventNotFound(); } // * Получаем тип контента if (!($this->oContentType = E::ModuleTopic()->GetContentTypeByUrl($oTopic->getType()))) { return parent::EventNotFound(); } E::ModuleViewer()->Assign('oContentType', $this->oContentType); $this->sMenuSubItemSelect = $this->oContentType->getContentUrl(); // * Есть права на редактирование if (!E::ModuleACL()->IsAllowEditTopic($oTopic, $this->oUserCurrent)) { return parent::EventNotFound(); } $aBlogFilter = array('user' => $this->oUserCurrent, 'content_type' => $this->oContentType); $aBlogsAllow = $this->_getAllowBlogs($aBlogFilter); // Такой тип контента не разрешен для пользователя ни в одном из типов блогов if (!$aBlogsAllow) { return parent::EventNotFound(); } // * Вызов хука E::ModuleHook()->Run('topic_edit_show', array('oTopic' => $oTopic)); // * Загружаем переменные в шаблон E::ModuleViewer()->Assign('bPersonalBlog', $this->bPersonalBlogEnabled); E::ModuleViewer()->Assign('aBlogsAllow', $aBlogsAllow); E::ModuleViewer()->Assign('bEditDisabled', $oTopic->getQuestionCountVote() == 0 ? false : true); E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('topic_topic_edit')); // * Устанавливаем шаблон вывода $this->SetTemplateAction('add'); E::ModuleViewer()->Assign('sMode', 'edit'); // * Проверяем, отправлена ли форма с данными if ($this->IsPost()) { // * Обрабатываем отправку формы $xResult = $this->SubmitEdit($oTopic); if ($xResult !== false) { return $xResult; } } else { /** * Заполняем поля формы для редактирования * Только перед отправкой формы! */ $_REQUEST['topic_title'] = $oTopic->getTitle(); $_REQUEST['topic_text'] = $oTopic->getTextSource(); $_REQUEST['blog_id'] = $oTopic->getBlogId(); $_REQUEST['topic_id'] = $oTopic->getId(); $_REQUEST['topic_publish_index'] = $oTopic->getPublishIndex(); $_REQUEST['topic_forbid_comment'] = $oTopic->getForbidComment(); $_REQUEST['topic_main_photo'] = $oTopic->getPhotosetMainPhotoId(); $_REQUEST['topic_field_link'] = $oTopic->getSourceLink(); $_REQUEST['topic_field_tags'] = $oTopic->getTags(); $_REQUEST['topic_field_question'] = $oTopic->getQuestionTitle(); $_REQUEST['topic_field_answers'] = array(); $_REQUEST['topic_show_photoset'] = $oTopic->getShowPhotoset(); $aAnswers = $oTopic->getQuestionAnswers(); foreach ($aAnswers as $aAnswer) { $_REQUEST['topic_field_answers'][] = $aAnswer['text']; } foreach ($this->oContentType->getFields() as $oField) { if ($oTopic->getField($oField->getFieldId())) { $sValue = $oTopic->getField($oField->getFieldId())->getValueSource(); if ($oField->getFieldType() == 'file') { $sValue = unserialize($sValue); } $_REQUEST['fields'][$oField->getFieldId()] = $sValue; } } } $sUrlMask = R::GetTopicUrlMask(); if (strpos($sUrlMask, '%topic_url%') === false) { // Нет в маске URL $aEditTopicUrl = array('before' => $oTopic->getLink($sUrlMask), 'input' => '', 'after' => ''); } else { // В маске есть URL, вместо него нужно вставить <input> $aUrlMaskParts = explode('%topic_url%', $sUrlMask); $aEditTopicUrl = array('before' => $aUrlMaskParts[0] ? $oTopic->getLink($aUrlMaskParts[0]) : F::File_RootUrl(), 'input' => $oTopic->getTopicUrl() ? $oTopic->getTopicUrl() : $oTopic->MakeTopicUrl(), 'after' => isset($aUrlMaskParts[1]) && $aUrlMaskParts[1] ? $oTopic->getLink($aUrlMaskParts[1], false) : ''); } if (!isset($_REQUEST['topic_url_input'])) { $_REQUEST['topic_url_input'] = $aEditTopicUrl['input']; } else { $aEditTopicUrl['input'] = $_REQUEST['topic_url_input']; } if (!isset($_REQUEST['topic_url_short'])) { $_REQUEST['topic_url_short'] = $oTopic->getUrlShort(); } E::ModuleViewer()->Assign('aEditTopicUrl', $aEditTopicUrl); // Old style templates compatibility $_REQUEST['topic_url_before'] = $aEditTopicUrl['before']; $_REQUEST['topic_url'] = $aEditTopicUrl['input']; $_REQUEST['topic_url_after'] = $aEditTopicUrl['after']; E::ModuleViewer()->Assign('oTopic', $oTopic); // Добавим картинки фотосета для вывода E::ModuleViewer()->Assign('aPhotos', E::ModuleMresource()->GetMresourcesRelByTarget('photoset', $oTopic->getId())); }
/** * @param string $sAction * * @return string */ public function _getPath($sAction) { // Если пользователь запросил action по умолчанию $sPage = $sAction == 'default' ? $this->aConfigRoute['config']['action_default'] : $sAction; // Смотрим, есть ли правило rewrite $sPage = static::getInstance()->RestorePath($sPage); // Маппинг доменов if (!empty($this->aConfigRoute['domains']['backward'])) { if (isset($this->aConfigRoute['domains']['backward'][$sPage])) { $sResult = $this->aConfigRoute['domains']['backward'][$sPage]; if ($sResult[1] != '/') { $sResult = '//' . $sResult; if (substr($sResult, -1) !== '/') { $sResult .= '/'; } } // Кешируем $this->aConfigRoute['domains']['backward'][$sPage] = $sResult; return $sResult; } $sPattern = F::StrMatch($this->aConfigRoute['domains']['backward_keys'], $sPage, true, $aMatches); if ($sPattern) { $sResult = '//' . $this->aConfigRoute['domains']['backward'][$sPattern]; if (!empty($aMatches[1])) { $sResult = str_replace('*', $aMatches[1], $sResult); } if (substr($sResult, -1) !== '/') { $sResult .= '/'; } // Кешируем $this->aConfigRoute['domains']['backward'][$sPage] = $sResult; return $sResult; } } return rtrim(F::File_RootUrl(true), '/') . "/{$sPage}/"; }
/** * Возвращает валидный Html код тега <img> * * @param string $sUrl * @param array $aParams * * @return string */ public function BuildHTML($sUrl, $aParams) { if (substr($sUrl, 0, 1) == '@') { $sUrl = F::File_RootUrl() . substr($sUrl, 1); } $sText = '<img src="' . $sUrl . '" '; if (isset($aParams['title']) && $aParams['title'] != '') { $sText .= ' title="' . htmlspecialchars($aParams['title']) . '" '; // * Если не определен ALT заполняем его тайтлом if (!isset($aParams['alt'])) { $aParams['alt'] = $aParams['title']; } } if (isset($aParams['img_width']) && is_numeric($aParams['img_width'])) { $sText .= " width=\"{$aParams['img_width']}%\""; } if (isset($aParams['align']) && in_array($aParams['align'], array('left', 'right', 'center'))) { if ($aParams['align'] == 'center') { $sText .= ' class="image-center"'; } else { $sText .= ' align="' . htmlspecialchars($aParams['align']) . '" '; } } $sAlt = isset($aParams['alt']) ? ' alt="' . htmlspecialchars($aParams['alt']) . '"' : ' alt=""'; $sText .= $sAlt . ' />'; return $sText; }
/** * Sets full url of resource * * @param $sUrl */ public function SetUrl($sUrl) { if ($sUrl[0] === '@') { $sPathUrl = substr($sUrl, 1); $sUrl = F::File_RootUrl() . $sPathUrl; } else { $sPathUrl = F::File_LocalUrl($sUrl); } if ($sPathUrl) { // Сохраняем относительный путь $this->SetPathUrl('@' . trim($sPathUrl, '/')); if (!$this->getPathFile()) { $this->SetFile(F::File_Url2Dir($sUrl)); } } else { // Сохраняем абсолютный путь $this->SetPathUrl($sUrl); } if (is_null($this->GetPathFile())) { if (is_null($this->GetLink())) { $this->SetLink(true); } if (is_null($this->GetType())) { $this->SetType(ModuleMresource::TYPE_HREF); } } $this->RecalcHash(); }
/** * Приведение адреса к абсолютному виду * * Путь в $sLocation может быть как абсолютным, так и относительным. * Абсолютный путь определяется по наличию хоста * * Если задан относительный путь, то итоговый URL определяется в зависимости от второго парамтера. * Если $bRealHost == false (по умолчанию), то за основу берется root-адрес сайта, который задан в конфигурации. * В противном случае основа адреса - это реальный адрес хоста из $_SERVER['SERVER_NAME'] * * @param string $sLocation - адрес перехода (напр., 'http://ya.ru/demo/', '/123.html', 'blog/add/') * @param bool $bRealHost - в случае относительной адресации брать адрес хоста из конфига или реальный * * @return string */ public static function RealUrl($sLocation, $bRealHost = false) { $sProtocol = static::HttpProtocol(); $aParts = parse_url($sLocation); // если парсером хост не обнаружен, то задан относительный путь if (!isset($aParts['host'])) { if (!$bRealHost) { $sUrl = F::File_RootUrl() . $sLocation; } else { if (strpos($sProtocol, 'HTTPS') === 0) { $sUrl = 'https://'; } else { $sUrl = 'http://'; } if (isset($_SERVER['SERVER_NAME'])) { $sUrl .= $_SERVER['SERVER_NAME']; } if (substr($sLocation, 0, 1) == '/') { $sUrl .= $sLocation; } else { if (isset($_SERVER['REQUEST_URI'])) { $sUri = $_SERVER['REQUEST_URI']; if ($n = strpos($sUri, '?')) { $sUri = substr($sUri, 0, $n); } if ($n = strpos($sUri, '#')) { $sUri = substr($sUri, 0, $n); } $sUrl .= '/' . $sUri; } $sUrl .= '/' . $sLocation; } } } else { $sUrl = $sLocation; } return F::File_NormPath($sUrl); }