1
0
Fork 0
mirror of https://github.com/Oreolek/ifhub.club.git synced 2024-06-26 11:40:48 +03:00
ifhub.club/engine/modules/viewer/Viewer.class.php

539 lines
15 KiB
PHP
Raw Normal View History

<?php
2008-09-21 09:36:57 +03:00
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
require_once(Config::Get('path.root.engine').'/lib/external/Smarty-2.6.19/libs/Smarty.class.php');
2008-09-21 09:36:57 +03:00
/**
* Модуль обработки шаблонов используя шаблонизатор Smarty
*
*/
class LsViewer extends Module {
2008-09-21 09:36:57 +03:00
/**
* Объект Smarty
*
* @var Smarty
*/
protected $oSmarty;
2008-09-21 09:36:57 +03:00
/**
* Коллекция(массив) блоков
2008-09-21 09:36:57 +03:00
*
* @var array
*/
protected $aBlocks=array();
/**
* Массив правил организации блоков
*
* @var array
*/
protected $_aBlockRules = array();
2008-09-21 09:36:57 +03:00
/**
* Заголовок HTML страницы
*
* @var unknown_type
*/
protected $sHtmlTitle;
/**
* SEO ключевые слова страницы
*
* @var unknown_type
*/
protected $sHtmlKeywords;
/**
* SEO описание страницы
*
* @var unknown_type
*/
protected $sHtmlDescription;
2008-09-21 09:36:57 +03:00
/**
* Разделитель заголовка HTML страницы
*
* @var unknown_type
*/
protected $sHtmlTitleSeparation=' / ';
/**
* Альтернативный адрес страницы по RSS
*
* @var array
*/
protected $aHtmlRssAlternate=null;
2009-06-24 19:58:21 +03:00
/**
* Переменные для отдачи при ajax запросе
*
* @var unknown_type
*/
protected $aVarsAjax=array();
/**
* Определяет тип ответа при ajax запросе
*
* @var unknown_type
*/
protected $sResponseAjax=null;
2008-09-21 09:36:57 +03:00
/**
* Инициализация модуля
*
*/
public function Init() {
/**
* Заголовок HTML страницы
*/
$this->sHtmlTitle=Config::Get('view.name');
/**
* SEO ключевые слова страницы
*/
$this->sHtmlKeywords=Config::Get('view.keywords');
/**
* SEO описание страницы
*/
$this->sHtmlDescription=Config::Get('view.description');
2008-09-21 09:36:57 +03:00
/**
* Создаём объект Smarty и устанавливаем необходиму параметры
*/
$this->oSmarty = new Smarty();
$this->oSmarty->template_dir=Config::Get('path.smarty.template');
$this->oSmarty->compile_dir=Config::Get('path.smarty.compiled');
$this->oSmarty->cache_dir=Config::Get('path.smarty.cache');
$this->oSmarty->plugins_dir=array(Config::Get('path.smarty.plug'),'plugins');
2008-09-21 09:36:57 +03:00
/**
* Подключаем к Smarty небольшой плагинчик форматирования даты
*/
$this->oSmarty->register_function("date_format", "func_date_smarty");
/**
* Получаем настройки блоков
*/
$this->_InitBlockParams();
2008-09-21 09:36:57 +03:00
}
/**
* Выполняет загрузку необходимый(возможно даже системный :)) переменных в шалон
*
*/
public function VarAssign() {
/**
* Загружаем весь $_REQUEST, предварительно обработав его функцией func_htmlspecialchars()
*/
$aRequest=$_REQUEST;
func_htmlspecialchars($aRequest);
$this->Assign("_aRequest",$aRequest);
/**
* Параметры стандартной сессии
*/
$this->Assign("_sPhpSessionName",session_name());
$this->Assign("_sPhpSessionId",session_id());
/**
* Загружаем часть конфигурации
*/
$aConfig=Config::Get();
foreach ((array)Config::Get('view.no_assign') as $sGroup) {
unset($aConfig[$sGroup]);
}
$this->Assign("aConfig",$aConfig);
/**
* Загружаем роутинг с учетом правил rewrite
*/
$aRouter=array();
foreach ($aConfig['router']['page'] as $sPage=>$aAction) {
$aRouter[$sPage]=Router::GetPath($sPage);
}
$this->Assign("aRouter",$aRouter);
$this->Assign("aBlocks",$this->aBlocks);
2008-09-21 09:36:57 +03:00
/**
* Загружаем HTML заголовки
*/
$this->Assign("sHtmlTitle",htmlspecialchars($this->sHtmlTitle));
$this->Assign("sHtmlKeywords",htmlspecialchars($this->sHtmlKeywords));
$this->Assign("sHtmlDescription",htmlspecialchars($this->sHtmlDescription));
$this->Assign("aHtmlRssAlternate",$this->aHtmlRssAlternate);
2008-09-21 09:36:57 +03:00
}
/**
* Выводит на экран(браузер) обработанный шаблон
*
* @param string $sTemplate
*/
public function Display($sTemplate) {
2009-06-24 19:58:21 +03:00
if ($this->sResponseAjax) {
$this->DisplayAjax($this->sResponseAjax);
}
2008-09-21 09:36:57 +03:00
/**
* Если шаблон найден то выводим, иначе ошибка
*/
if ($this->TemplateExists($sTemplate)) {
$this->oSmarty->display($sTemplate);
} else {
throw new Exception($this->Lang_Get('system_error_template').': '.$sTemplate);
2008-09-21 09:36:57 +03:00
}
}
2009-06-24 19:58:21 +03:00
/**
* Ответ на ajax запрос
*
* @param unknown_type $sType - jsHttpRequest или json
*/
public function DisplayAjax($sType='jsHttpRequest') {
/**
* Загружаем статус ответа и сообщение
*/
$bStateError=false;
$sMsgTitle='';
$sMsg='';
$aMsgError=$this->Message_GetError();
$aMsgNotice=$this->Message_GetNotice();
if (count($aMsgError)>0) {
$bStateError=true;
$sMsgTitle=$aMsgError[0]['title'];
$sMsg=$aMsgError[0]['msg'];
}
if (count($aMsgNotice)>0) {
$sMsgTitle=$aMsgNotice[0]['title'];
$sMsg=$aMsgNotice[0]['msg'];
}
2009-09-20 21:47:25 +03:00
$this->AssignAjax('sMsgTitle',$sMsgTitle);
$this->AssignAjax('sMsg',$sMsg);
$this->AssignAjax('bStateError',$bStateError);
2009-07-05 00:41:42 +03:00
if ($sType=='jsHttpRequest') {
2009-06-24 19:58:21 +03:00
foreach ($this->aVarsAjax as $key => $value) {
$GLOBALS['_RESULT'][$key]=$value;
}
} elseif ($sType=='json') {
if (!headers_sent()) {
header('Content-type: application/json');
}
echo json_encode($this->aVarsAjax);
}
exit();
}
/**
* Устанавливает тип отдачи при ajax запросе, если null то выполняется обычный вывод шаблона в браузер
*
* @param unknown_type $sResponseAjax
*/
public function SetResponseAjax($sResponseAjax='jsHttpRequest') {
/**
* Проверка на безопасную обработку ajax запроса
*/
2009-07-05 00:41:42 +03:00
if ($sResponseAjax) {
if ($sResponseAjax=='jsHttpRequest') {
require_once(Config::Get('path.root.engine')."/lib/external/JsHttpRequest/JsHttpRequest.php");
2009-07-05 00:41:42 +03:00
$JsHttpRequest = new JsHttpRequest("UTF-8");
}
2009-06-24 19:58:21 +03:00
$this->Security_ValidateSendForm();
}
$this->sResponseAjax=$sResponseAjax;
}
2008-09-21 09:36:57 +03:00
/**
* Загружает переменную в шаблон
*
* @param string $sName
* @param unknown_type $value
*/
public function Assign($sName,$value) {
$this->oSmarty->assign($sName, $value);
}
2009-06-24 19:58:21 +03:00
/**
* Загружаем переменную в ajax ответ
*
* @param unknown_type $sName
* @param unknown_type $value
*/
2009-09-20 21:47:25 +03:00
public function AssignAjax($sName,$value) {
2009-06-24 19:58:21 +03:00
$this->aVarsAjax[$sName]=$value;
}
2008-09-21 09:36:57 +03:00
/**
* Возвращает обработанный шаблон
*
* @param string $sTemplate
* @return string
*/
public function Fetch($sTemplate) {
return $this->oSmarty->fetch($sTemplate);
}
/**
* Проверяет существование шаблона
*
* @param string $sTemplate
* @return bool
*/
public function TemplateExists($sTemplate) {
return $this->oSmarty->template_exists($sTemplate);
}
/**
* Инициализируем параметры отображения блоков
*/
protected function _InitBlockParams() {
$this->_aBlockRules = Config::Get('block');
}
2008-09-21 09:36:57 +03:00
/**
* Добавляет блок для отображения
*
* @param string $sName
* @param arra $aParams - параметры блока, которые будут переданы обработчику блока
*/
public function AddBlock($sGroup,$sName,$aParams=array()) {
2008-09-21 09:36:57 +03:00
/**
* Если смогли определить тип блока то добавляем его
*/
$sType=$this->DefineTypeBlock($sName);
if ($sType=='undefined') {
return false;
}
$this->aBlocks[$sGroup][$sName]=array(
2008-09-21 09:36:57 +03:00
'type' => $sType,
'name' => $sName,
'params' => $aParams,
);
return true;
}
/**
* Добавляет список блоков
*
* @param array $aBlocks
*/
public function AddBlocks($sGroup,$aBlocks) {
2008-09-21 09:36:57 +03:00
/**
* Удаляем ранее добавленые блоки
*/
$this->ClearBlocks($sGroup);
2008-09-21 09:36:57 +03:00
foreach ($aBlocks as $sBlock) {
$this->AddBlock($sGroup,$sBlock);
2008-09-21 09:36:57 +03:00
}
}
/**
* Удаляет блоки группы
*
*/
public function ClearBlocks($sGroup) {
$this->aBlocks[$sGroup]=array();
}
/**
* Удаляет блоки всех групп
2008-09-21 09:36:57 +03:00
*
* @param unknown_type $sGroup
2008-09-21 09:36:57 +03:00
*/
public function ClearBlocksAll() {
foreach ($this->aBlocks as $sGroup => $aBlock) {
$this->aBlocks[$sGroup]=array();
}
2008-09-21 09:36:57 +03:00
}
/**
* Определяет тип блока
*
* @param string $sName
* @return string('block','template','undefined')
*/
protected function DefineTypeBlock($sName) {
if ($this->TemplateExists('block.'.$sName.'.tpl')) {
/**
* Если найден шаблон вида block.name.tpl то считаем что тип 'block'
*/
return 'block';
} elseif ($this->TemplateExists($sName)) {
/**
* Если найден шаблон по имени блока то считаем его простым шаблоном
*/
return 'template';
} else {
/**
* Считаем что тип не определен
*/
throw new Exception($this->Lang_Get('system_error_template_block').': '.$sName);
2008-09-21 09:36:57 +03:00
return 'undefined';
}
}
/**
* Анализируем правила и наборы массивов
* получаем окончательные списки блоков
*/
protected function _BuildBlocks() {
$sAction = strtolower(Router::GetAction());
$sEvent = strtolower(Router::GetActionEvent());
foreach($this->_aBlockRules as $sName => $aRule) {
$bUse=false;
/**
* Если в правиле не указан список блоков, нам такое не нужно
*/
if(!array_key_exists('blocks',$aRule)) continue;
/**
* Если не задан action для исполнения,
* или текущий не входит в перечисленные в правиле
* то выбираем следующее правило
*/
if(!$aRule['action']) continue;
if(in_array($sAction, (array)$aRule['action'])) $bUse=true;
if(array_key_exists($sAction,(array)$aRule['action'])) {
/**
* Если задан список event`ов и текущий в него не входит,
* переходи к следующему действию. Если список не задан,
* считаем что правило действует для всех event`ов.
*/
if(!$sEvent
|| in_array($sEvent,(array)$aRule['event'][$sAction]))
$bUse=true;
}
if($bUse){
/**
* Добавляем все блоки, указанные в параметре blocks
*/
foreach ($aRule['blocks'] as $sGroup => $aBlocks) {
foreach ((array)$aBlocks as $sName=>$aParams) {
/**
* Если $aParams не являются массивом, значит передано только имя блока
*/
if(!is_array($aParams)) {
$this->AddBlock($sGroup,$aParams);
} else {
$this->AddBlock($sGroup,$sName,$aParams);
}
}
}
}
}
return true;
}
2008-09-21 09:36:57 +03:00
/**
* Устанавливаем заголовок страницы(тег <title>)
*
* @param string $sText
*/
public function SetHtmlTitle($sText) {
$this->sHtmlTitle=$sText;
}
/**
* Добавляет часть заголовка страницы через разделитель
*
* @param string $sText
*/
public function AddHtmlTitle($sText) {
$this->sHtmlTitle=$sText.$this->sHtmlTitleSeparation.$this->sHtmlTitle;
}
/**
* Возвращает текущий заголовок страницы
*
* @return unknown
*/
public function GetHtmlTitle() {
return $this->sHtmlTitle;
}
/**
* Устанавливает ключевые слова keywords
*
* @param string $sText
*/
public function SetHtmlKeywords($sText) {
$this->sHtmlKeywords=$sText;
}
/**
* Устанавливает описание страницы desciption
*
* @param string $sText
*/
public function SetHtmlDescription($sText) {
$this->sHtmlDescription=$sText;
2008-09-21 09:36:57 +03:00
}
/**
* Устанавливает альтернативный адрес страницы по RSS
*
* @param string $sText
*/
public function SetHtmlRssAlternate($sUrl,$sTitle) {
$this->aHtmlRssAlternate['title']=htmlspecialchars($sTitle);
$this->aHtmlRssAlternate['url']=htmlspecialchars($sUrl);
}
2008-09-21 09:36:57 +03:00
/**
* Формирует постраничный вывод
*
* @param int $iCount
* @param int $iCurrentPage
* @param int $iCountPerPage
* @param int $iCountPageLine
* @param string $sBaseUrl
* @param array(name=>value) $aGetParamsList
2008-09-21 09:36:57 +03:00
* @return array()
*/
public function MakePaging($iCount,$iCurrentPage,$iCountPerPage,$iCountPageLine,$sBaseUrl,$aGetParamsList=array()) {
2008-09-21 09:36:57 +03:00
if ($iCount==0) {
return false;
}
$iCountPage=ceil($iCount/$iCountPerPage);
if (!preg_match("/^[1-9]\d*$/i",$iCurrentPage)) {
$iCurrentPage=1;
}
if ($iCurrentPage>$iCountPage) {
$iCurrentPage=$iCountPage;
}
$aPagesLeft=array();
$iTemp=$iCurrentPage-$iCountPageLine;
$iTemp = $iTemp<1 ? 1 : $iTemp;
for ($i=$iTemp;$i<$iCurrentPage;$i++) {
$aPagesLeft[]=$i;
}
$aPagesRight=array();
for ($i=$iCurrentPage+1;$i<=$iCurrentPage+$iCountPageLine and $i<=$iCountPage;$i++) {
$aPagesRight[]=$i;
}
$iNextPage = $iCurrentPage<$iCountPage ? $iCurrentPage+1 : false;
$iPrevPage = $iCurrentPage>1 ? $iCurrentPage-1 : false;
$sGetParams='';
foreach ($aGetParamsList as $sName => $sValue) {
$sGetParams.=$sName.'='.urlencode($sValue).'&';
}
if ($sGetParams!='') {
$sGetParams='?'.trim($sGetParams,'&');
}
2008-09-21 09:36:57 +03:00
$aPaging=array(
'aPagesLeft' => $aPagesLeft,
'aPagesRight' => $aPagesRight,
'iCountPage' => $iCountPage,
'iCurrentPage' => $iCurrentPage,
'iNextPage' => $iNextPage,
'iPrevPage' => $iPrevPage,
'sBaseUrl' => $sBaseUrl,
'sGetParams' => $sGetParams,
2008-09-21 09:36:57 +03:00
);
return $aPaging;
}
2009-07-26 16:43:16 +03:00
/**
* Загружаем переменные в шаблон при завершении модуля
*
*/
public function Shutdown() {
/**
* Добавляем блоки по предзагруженным правилам
*/
$this->_BuildBlocks();
2009-07-26 16:43:16 +03:00
$this->VarAssign();
}
2008-09-21 09:36:57 +03:00
}
?>