ModuleViewer

Package framework.modules
Inheritance class ModuleViewer » Module » LsObject
Since 1.0
Source Code /framework/classes/modules/viewer/Viewer.class.php
Модуль обработки шаблонов используя шаблонизатор Smarty

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
_aBehaviors Список поведений в виде готовых объектов, формируется автоматически LsObject
aBehaviors array Список поведений LsObject
aBlockRules array Массив правил организации блоков ModuleViewer
aBlocks array Коллекция(массив) блоков ModuleViewer
aHtmlHeadFiles array Html код для подключения js,css ModuleViewer
aHtmlRssAlternate array Альтернативный адрес страницы по RSS ModuleViewer
aHtmlTitleParts array Список элементов/частей из которых строится заголовок страницы ModuleViewer
aMenu array Список меню для рендеринга ModuleViewer
aMenuFetch array Скомпилированные меню ModuleViewer
aVarsAjax array Переменные для отдачи при ajax запросе ModuleViewer
aVarsJs array Переменные для загрузки в JS (используется ls.registry) ModuleViewer
bIsInit bool Указывает на то, была ли проведенна инициализация модуля Module
bResponseSpecificHeader bool Отправляет специфичный для ответа header ModuleViewer
oSmarty Smarty Объект Smarty ModuleViewer
sHtmlCanonical string Указание поисковику основного URL страницы, для борьбы с дублями ModuleViewer
sHtmlDescription string SEO описание страницы ModuleViewer
sHtmlKeywords string SEO ключевые слова страницы ModuleViewer
sHtmlTitleSeparation string Разделитель заголовка HTML страницы ModuleViewer
sResponseAjax string Определяет тип ответа при ajax запросе ModuleViewer

Public Methods

Hide inherited methods

MethodDescriptionDefined By
AddBehaviorHook() Добавляет хук поведения LsObject
AddBlock() Добавляет блок для отображения ModuleViewer
AddBlocks() Добавляет список блоков ModuleViewer
AddHtmlTitle() Добавляет часть заголовка страницы через разделитель ModuleViewer
AddMenu() Добавить меню в контейнер ModuleViewer
Append() Добавляет переменную к уже существующим в шаблоне ModuleViewer
AppendScript() Добавляет js файл в конец списка ModuleViewer
AppendStyle() Добавляет css файл в конец списка ModuleViewer
Assign() Загружает переменную в шаблон ModuleViewer
AssignAjax() Загружаем переменную в ajax ответ ModuleViewer
AssignJs() Загружаем переменную в JS ModuleViewer
AttachBehavior() Присоединяет поведение к объекту LsObject
ClearBlocks() Удаляет блоки группы ModuleViewer
ClearBlocksAll() Удаляет блоки всех групп ModuleViewer
ClearCompiledTemplates() Очищает кеш компиленных шаблонов ModuleViewer
CreateSmartyObject() Создает и возвращает объект Smarty ModuleViewer
DetachBehavior() Отсоединяет поведение от объекта LsObject
Display() Выводит на экран(браузер) обработанный шаблон ModuleViewer
DisplayAjax() Ответ на ajax запрос ModuleViewer
Fetch() Возвращает обработанный шаблон ModuleViewer
GetBehavior() Возвращает объект поведения по его имени LsObject
GetBehaviors() Возвращает все объекты поведения LsObject
GetBlocks() Возвращает список блоков ModuleViewer
GetHtmlTitle() Возвращает текущий заголовок страницы ModuleViewer
GetHtmlTitleSeparation() Возвращает разделитель заголовков страниц ModuleViewer
GetLocalViewer() Получает локальную копию модуля ModuleViewer
GetResponseAjax() Возвращает тип отдачи контекта ModuleViewer
GetSmartyObject() Возвращает объект Smarty ModuleViewer
Init() Инициализация модуля ModuleViewer
MakePaging() Формирует постраничный вывод ModuleViewer
PrependScript() Добавляет js файл в начало списка ModuleViewer
PrependStyle() Добавляет css файл в начало списка ModuleViewer
RemoveBehaviorHook() Удаляет хук поведения LsObject
RunBehaviorHook() Запускает хук поведения на выполнение LsObject
SetHtmlCanonical() Устанавливает основной адрес страницы ModuleViewer
SetHtmlDescription() Устанавливает описание страницы desciption ModuleViewer
SetHtmlHeadFiles() Устанавливает список файлов для вывода в хидере страницы ModuleViewer
SetHtmlKeywords() Устанавливает ключевые слова keywords ModuleViewer
SetHtmlRssAlternate() Устанавливает альтернативный адрес страницы по RSS ModuleViewer
SetHtmlTitle() Устанавливаем заголовок страницы(тег title) ModuleViewer
SetHtmlTitleSeparation() Устанавливает разделитель заголовков страниц ModuleViewer
SetInit() Помечает модуль как инициализированный Module
SetResponseAjax() Устанавливает тип отдачи при ajax запросе, если null то выполняется обычный вывод шаблона в браузер ModuleViewer
Shutdown() Загружаем переменные в шаблон при завершении модуля ModuleViewer
SmartyDefaultTemplateHandler() Обработка поиска файла шаблона, если его не смог найти шаблонизатор Smarty ModuleViewer
TemplateExists() Проверяет существование шаблона ModuleViewer
VarAssign() Выполняет загрузку необходимый(возможно даже системный :)) переменных в шалон ModuleViewer
__call() Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля LsObject
__clone() Блокируем копирование/клонирование объекта Module
__construct() Конструктор, запускается автоматически при создании объекта LsObject
__get() Обработка доступа к объекты поведения LsObject
isInit() Возвращает значение флага инициализации модуля Module

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
BuildBlocks() Анализируем правила и наборы массивов ModuleViewer
BuildHeadFiles() Строит массив для подключения css и js, ModuleViewer
BuildMenu() Компилирует меню по контейнерам ModuleViewer
DefineTypeBlock() Определяет тип блока ModuleViewer
InitBlockParams() Инициализируем параметры отображения блоков ModuleViewer
PrepareBehaviors() Инициализация поведений LsObject
SortBlocks() Сортируем блоки ModuleViewer
_SortBlocks() Вспомагательная функция для сортировки блоков по приоритетности ModuleViewer

Property Details

aBlockRules property
protected array $aBlockRules;

Массив правил организации блоков

aBlocks property
protected array $aBlocks;

Коллекция(массив) блоков

aHtmlHeadFiles property
protected array $aHtmlHeadFiles;

Html код для подключения js,css

aHtmlRssAlternate property
protected array $aHtmlRssAlternate;

Альтернативный адрес страницы по RSS

aHtmlTitleParts property
protected array $aHtmlTitleParts;

Список элементов/частей из которых строится заголовок страницы

aMenu property
protected array $aMenu;

Список меню для рендеринга

aMenuFetch property
protected array $aMenuFetch;

Скомпилированные меню

aVarsAjax property
protected array $aVarsAjax;

Переменные для отдачи при ajax запросе

aVarsJs property
protected array $aVarsJs;

Переменные для загрузки в JS (используется ls.registry)

bResponseSpecificHeader property
protected bool $bResponseSpecificHeader;

Отправляет специфичный для ответа header

oSmarty property
protected Smarty $oSmarty;

Объект Smarty

sHtmlCanonical property
protected string $sHtmlCanonical;

Указание поисковику основного URL страницы, для борьбы с дублями

sHtmlDescription property
protected string $sHtmlDescription;

SEO описание страницы

sHtmlKeywords property
protected string $sHtmlKeywords;

SEO ключевые слова страницы

sHtmlTitleSeparation property
protected string $sHtmlTitleSeparation;

Разделитель заголовка HTML страницы

sResponseAjax property
protected string $sResponseAjax;

Определяет тип ответа при ajax запросе

Method Details

AddBlock() method
public bool AddBlock(string $sGroup, string $sName, array $aParams=array ( ), int $iPriority=5)
$sGroup string Группа блоков
$sName string Название блока Можно передать название блока, тогда для обработки данных блока будет вызван обработчик из /classes/blocks/, либо передать путь до шаблона, тогда будет выполнено обычное подключение шаблона
$aParams array Параметры блока, которые будут переданы обработчику блока
$iPriority int Приоритет, согласно которому сортируются блоки
{return} bool
Source Code: /framework/classes/modules/viewer/Viewer.class.php#531 (show)
public function AddBlock($sGroup$sName$aParams = array(), $iPriority 5)
{
    
/**
     * Если не указана директория шаблона, но указана приналежность к плагину,
     * то "вычисляем" правильную директорию
     */
    
if (!isset($aParams['dir']) and isset($aParams['plugin'])) {
        
$aParams['dir'] = Plugin::GetTemplatePath($aParams['plugin']);
    }
    
/**
     * Если смогли определить тип блока то добавляем его
     */
    
$sType $this->DefineTypeBlock($sName, isset($aParams['plugin']) ? $aParams['plugin'] : null);
    if (
$sType == 'undefined') {
        return 
false;
    }
    
/**
     * Если тип "template" и есть параметр "dir", то получаем полный путь до шаблона
     */
    
if ($sType == 'template' and isset($aParams['dir'])) {
        
$sName rtrim($aParams['dir'], '/') . '/' ltrim($sName'/');
    }
    
$this->aBlocks[$sGroup][] = array(
        
'type'     => $sType,
        
'name'     => $sName,
        
'params'   => $aParams,
        
'priority' => $iPriority,
    );
    return 
true;
}

Добавляет блок для отображения

AddBlocks() method
public void AddBlocks(string $sGroup, array $aBlocks, bool $ClearBlocks=true)
$sGroup string Группа блоков
$aBlocks array Список названий блоков с параметрами
$this->Viewer_AddBlocks('right',array('tags',array('block'=>'stream','priority'=>100)));
$ClearBlocks bool Очищать или нет перед добавлением блоки в данной группе
Source Code: /framework/classes/modules/viewer/Viewer.class.php#572 (show)
public function AddBlocks($sGroup$aBlocks$ClearBlocks true)
{
    
/**
     * Удаляем ранее добавленые блоки
     */
    
if ($ClearBlocks) {
        
$this->ClearBlocks($sGroup);
    }
    foreach (
$aBlocks as $sBlock) {
        if (
is_array($sBlock)) {
            
$this->AddBlock(
                
$sGroup,
                
$sBlock['block'],
                isset(
$sBlock['params']) ? $sBlock['params'] : array(),
                isset(
$sBlock['priority']) ? $sBlock['priority'] : 5
            
);
        } else {
            
$this->AddBlock($sGroup$sBlock);
        }
    }
}

Добавляет список блоков

AddHtmlTitle() method
public void AddHtmlTitle(string $sText)
$sText string Заголовок
Source Code: /framework/classes/modules/viewer/Viewer.class.php#910 (show)
public function AddHtmlTitle($sText)
{
    
$this->aHtmlTitleParts[] = $sText;
}

Добавляет часть заголовка страницы через разделитель

AddMenu() method
public void AddMenu(string $sContainer, string $sTemplate)
$sContainer string
$sTemplate string
Source Code: /framework/classes/modules/viewer/Viewer.class.php#1079 (show)
public function AddMenu($sContainer$sTemplate)
{
    
$this->aMenu[strtolower($sContainer)] = $sTemplate;
}

Добавить меню в контейнер

Append() method
public void Append($mName $mName, null $mValue=NULL, bool $bMerge=false)
$mName $mName Имя переменной в шаблоне или ассоциативный массив со списком переменных
$mValue null Значение переменной
$bMerge bool Необходимость мержа (слияния) переменных
Source Code: /framework/classes/modules/viewer/Viewer.class.php#446 (show)
public function Append($mName$mValue null$bMerge false)
{
    
$this->oSmarty->append($mName$mValue$bMerge);
}

Добавляет переменную к уже существующим в шаблоне Значение переменной преобразуется к типу array

AppendScript() method
public bool AppendScript($sJs $sJs, array $aParams=array ( ), bool $bReplace=false)
$sJs $sJs Файл js
$aParams array Параметры, например, можно указать параметр 'name'=>'jquery.plugin.foo' для исключения повторного добавления файла с таким именем
$bReplace bool Заменять файл или нет
{return} bool
Source Code: /framework/classes/modules/viewer/Viewer.class.php#831 (show)
public function AppendScript($sJs$aParams = array(), $bReplace false)
{
    return 
$this->Asset_AddJs($sJs$aParamsfalse$bReplace);
}

Добавляет js файл в конец списка

AppendStyle() method
public bool AppendStyle($sCss $sCss, array $aParams=array ( ), bool $bReplace=false)
$sCss $sCss Файл css стилей
$aParams array Параметры, например, можно указать параметр 'name'=>'blueprint' для исключения повторного добавления файла с таким именем
$bReplace bool Заменять файл или нет
{return} bool
Source Code: /framework/classes/modules/viewer/Viewer.class.php#857 (show)
public function AppendStyle($sCss$aParams = array(), $bReplace false)
{
    return 
$this->Asset_AddCss($sCss$aParamsfalse$bReplace);
}

Добавляет css файл в конец списка

Assign() method
public void Assign(string|array $mName, mixed $mValue=NULL, bool $bLocal=false, bool $bByRef=false)
$mName string|array Имя переменной в шаблоне или ассоциативный массив со списком параметров
$mValue mixed Значение переменной. $bByRef = true, то значение должно быть в виде массива array(&$mValue) для корректной работы передачи по ссылке
$bLocal bool Загружает переменную в локальную область видимости шаблонизатора (доступна только для конкретного шаблона)
$bByRef bool Загружает переменную по ссылке
Source Code: /framework/classes/modules/viewer/Viewer.class.php#429 (show)
public function Assign($mName$mValue null$bLocal false$bByRef false)
{
    if (
$bByRef and isset($mValue[0])) {
        
$this->oSmarty->assignByRef($mName$mValue[0]);
    } else {
        
$this->oSmarty->assign($mName$mValuefalse$bLocal);
    }
}

Загружает переменную в шаблон

AssignAjax() method
public void AssignAjax(string|array $sName, mixed $value=NULL)
$sName string|array Имя переменной в шаблоне или ассоциативный массив со списком параметров
$value mixed Значение переменной
Source Code: /framework/classes/modules/viewer/Viewer.class.php#457 (show)
public function AssignAjax($sName$value null)
{
    if (
is_array($sName)) {
        foreach (
$sName as $sKey => $mVal) {
            
$this->aVarsAjax[$sKey] = $mVal;
        }
    } else {
        
$this->aVarsAjax[$sName] = $value;
    }
}

Загружаем переменную в ajax ответ

AssignJs() method
public void AssignJs($sName $sName, null $value=NULL)
$sName $sName
$value null
Source Code: /framework/classes/modules/viewer/Viewer.class.php#474 (show)
public function AssignJs($sName$value null)
{
    if (
is_array($sName)) {
        foreach (
$sName as $sKey => $mVal) {
            
$this->aVarsJs[$sKey] = $mVal;
        }
    } else {
        
$this->aVarsJs[$sName] = $value;
    }
}

Загружаем переменную в JS

BuildBlocks() method
protected void BuildBlocks()
Source Code: /framework/classes/modules/viewer/Viewer.class.php#663 (show)
protected function BuildBlocks()
{
    
$sAction strtolower(Router::GetAction());
    
$sEvent strtolower(Router::GetActionEvent());
    
$sEventName strtolower(Router::GetActionEventName());
    foreach (
$this->aBlockRules as $sName => $aRule) {
        
$bUse false;
        
/**
         * Если в правиле не указан список блоков, нам такое не нужно
         */
        
if (!array_key_exists('blocks'$aRule)) {
            continue;
        }
        
/**
         * Если не задан action для исполнения и нет ни одного шаблона path,
         * или текущий не входит в перечисленные в правиле
         * то выбираем следующее правило
         */
        
if (!array_key_exists('action'$aRule) && !array_key_exists('path'$aRule)) {
            continue;
        }
        if (isset(
$aRule['action'])) {
            if (
in_array($sAction, (array)$aRule['action'])) {
                
$bUse true;
            }
            if (
array_key_exists($sAction, (array)$aRule['action'])) {
                
/**
                 * Если задан список event`ов и текущий в него не входит,
                 * переходи к следующему действию.
                 */
                
foreach ((array)$aRule['action'][$sAction] as $sEventPreg) {
                    if (
substr($sEventPreg01) == '/') {
                        
/**
                         * Это регулярное выражение
                         */
                        
if (preg_match($sEventPreg$sEvent)) {
                            
$bUse true;
                            break;
                        }
                    } elseif (
substr($sEventPreg01) == '{') {
                        
/**
                         * Это имя event'a (именованный евент, если его нет, то совпадает с именем метода евента в экшене)
                         */
                        
if (trim($sEventPreg'{}') == $sEventName) {
                            
$bUse true;
                            break;
                        }
                    } else {
                        
/**
                         * Это название event`a
                         */
                        
if ($sEvent == $sEventPreg) {
                            
$bUse true;
                            break;
                        }
                    }
                }
            }
        }
        
/**
         * Если не найдено совпадение по паре Action/Event,
         * переходим к поиску по regexp путей.
         */
        
if (!$bUse && isset($aRule['path'])) {
            
$sPath rtrim(Router::GetPathWebCurrent(), "/");
            
/**
             * Проверяем последовательно каждый regexp
             */
            
foreach ((array)$aRule['path'] as $sRulePath) {
                
$sPattern "~" str_replace(array('/''*'), array('\/''[\w\-]+'), $sRulePath) . "~";
                if (
preg_match($sPattern$sPath)) {
                    
$bUse true;
                    break 
1;
                }
            }

        }

        if (
$bUse) {
            
/**
             * Если задан режим очистки блоков, сначала чистим старые блоки
             */
            
if (isset($aRule['clear'])) {
                switch (
true) {
                    
/**
                     * Если установлен в true, значит очищаем все
                     */
                    
case  ($aRule['clear'] === true):
                        
$this->ClearBlocksAll();
                        break;

                    case 
is_string($aRule['clear']):
                        
$this->ClearBlocks($aRule['clear']);
                        break;

                    case 
is_array($aRule['clear']):
                        foreach (
$aRule['clear'] as $sGroup) {
                            
$this->ClearBlocks($sGroup);
                        }
                        break;
                }
            }
            
/**
             * Добавляем все блоки, указанные в параметре blocks
             */
            
foreach ($aRule['blocks'] as $sGroup => $aBlocks) {
                foreach ((array)
$aBlocks as $sName => $aParams) {
                    
/**
                     * Если название блока указывается в параметрах
                     */
                    
if (is_int($sName)) {
                        if (
is_array($aParams)) {
                            
$sName $aParams['block'];
                        }
                    }
                    
/**
                     * Если $aParams не являются массивом, значит передано только имя блока
                     */
                    
if (!is_array($aParams)) {
                        
$this->AddBlock($sGroup$aParams);
                    } else {
                        
$this->AddBlock(
                            
$sGroup$sName,
                            isset(
$aParams['params']) ? $aParams['params'] : array(),
                            isset(
$aParams['priority']) ? $aParams['priority'] : 5
                        
);
                    }
                }
            }
        }
    }
}

Анализируем правила и наборы массивов получаем окончательные списки блоков

BuildHeadFiles() method
protected void BuildHeadFiles()
Source Code: /framework/classes/modules/viewer/Viewer.class.php#880 (show)
protected function BuildHeadFiles()
{
    
$this->SetHtmlHeadFiles($this->Asset_BuildHeadItems());
}

Строит массив для подключения css и js, преобразовывает их в строку для HTML

BuildMenu() method
protected void BuildMenu()
Source Code: /framework/classes/modules/viewer/Viewer.class.php#1088 (show)
protected function BuildMenu()
{
    foreach (
$this->aMenu as $sContainer => $sTemplate) {
        
$this->aMenuFetch[$sContainer] = $this->Fetch($sTemplate);
    }
}

Компилирует меню по контейнерам

ClearBlocks() method
public void ClearBlocks(string $sGroup)
$sGroup string
Source Code: /framework/classes/modules/viewer/Viewer.class.php#599 (show)
public function ClearBlocks($sGroup)
{
    
$this->aBlocks[$sGroup] = array();
}

Удаляет блоки группы

ClearBlocksAll() method
public void ClearBlocksAll()
Source Code: /framework/classes/modules/viewer/Viewer.class.php#608 (show)
public function ClearBlocksAll()
{
    foreach (
$this->aBlocks as $sGroup => $aBlock) {
        
$this->aBlocks[$sGroup] = array();
    }
}

Удаляет блоки всех групп

ClearCompiledTemplates() method
public void ClearCompiledTemplates()
Source Code: /framework/classes/modules/viewer/Viewer.class.php#340 (show)
public function ClearCompiledTemplates()
{
    
$this->oSmarty->clearCompiledTemplate();
}

Очищает кеш компиленных шаблонов

CreateSmartyObject() method
public Smarty CreateSmartyObject()
{return} Smarty
Source Code: /framework/classes/modules/viewer/Viewer.class.php#332 (show)
public function CreateSmartyObject()
{
    return new 
SmartyLS();
}

Создает и возвращает объект Smarty

DefineTypeBlock() method
protected string DefineTypeBlock(string $sName, string|null $sPlugin=NULL)
$sName string Название блока
$sPlugin string|null код плагина, если блок принадлежит плагину
{return} string ('block','template','undefined')
Source Code: /framework/classes/modules/viewer/Viewer.class.php#636 (show)
protected function DefineTypeBlock($sName$sPlugin null)
{
    
$sDir $sPlugin Plugin::GetTemplatePath($sPlugin) : null;
    
/**
     * Если ли обработчик блока?
     */
    
$sClassBlock = ($sPlugin 'Plugin' func_camelize($sPlugin) . '_' '') . 'Block' func_camelize($sName);
    if (
class_exists($sClassBlock)) {
        return 
'block';
    } elseif (
$this->TemplateExists(is_null($sDir) ? $sName rtrim($sDir'/') . '/' ltrim($sName'/'))) {
        
/**
         * Если найден шаблон по имени блока то считаем его простым шаблоном
         */
        
return 'template';
    } else {
        
/**
         * Считаем что тип не определен
         */
        
throw new Exception('Can not find the block`s template: ' $sName);
        return 
'undefined';
    }
}

Определяет тип блока

Display() method
public void Display(string $sTemplate)
$sTemplate string Шаблон для вывода
Source Code: /framework/classes/modules/viewer/Viewer.class.php#298 (show)
public function Display($sTemplate)
{
    if (
$this->sResponseAjax) {
        
$this->DisplayAjax($this->sResponseAjax);
    }
    
/**
     * Если шаблон найден то выводим, иначе ошибка
     * Предварительно проверяем наличие делегата
     */
    
if ($sTemplate) {
        
$sTemplate $this->Plugin_GetDelegate('template'$sTemplate);
        if (
$this->TemplateExists($sTemplate)) {
            
$this->oSmarty->display($sTemplate);
        } else {
            throw new 
Exception('Can not find the template: ' $sTemplate);
        }
    }
}

Выводит на экран(браузер) обработанный шаблон

DisplayAjax() method
public void DisplayAjax(string $sType='json')
$sType string Варианты: json, jsonIframe, jsonp
Source Code: /framework/classes/modules/viewer/Viewer.class.php#350 (show)
public function DisplayAjax($sType 'json')
{
    
/**
     * Загружаем статус ответа и сообщение
     */
    
$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'];
    } elseif (
count($aMsgNotice) > 0) {
        
$sMsgTitle $aMsgNotice[0]['title'];
        
$sMsg $aMsgNotice[0]['msg'];
    }
    
$this->AssignAjax('sMsgTitle'$sMsgTitle);
    
$this->AssignAjax('sMsg'$sMsg);
    
$this->AssignAjax('bStateError'$bStateError);
    if (
$sType == 'json') {
        if (
$this->bResponseSpecificHeader and !headers_sent()) {
            
header('Content-type: application/json');
        }
        echo 
json_encode($this->aVarsAjax);
    } elseif (
$sType == 'jsonIframe') {
        
// Оборачивает json в тег <textarea>, это не дает браузеру выполнить HTML, который вернул iframe
        
if ($this->bResponseSpecificHeader and !headers_sent()) {
            
header('Content-type: application/json');
        }
        
/**
         * Избавляемся от бага, когда в возвращаемом тексте есть &quot;
         */
        
echo '<textarea>' htmlspecialchars(json_encode($this->aVarsAjax)) . '</textarea>';
    } elseif (
$sType == 'jsonp') {
        if (
$this->bResponseSpecificHeader and !headers_sent()) {
            
header('Content-type: application/json');
        }
        echo 
getRequest('jsonpCallback''callback') . '(' json_encode($this->aVarsAjax) . ');';
    }
    exit();
}

Ответ на ajax запрос

Fetch() method
public string Fetch(string $sTemplate)
$sTemplate string Шаблон для рендеринга
{return} string
Source Code: /framework/classes/modules/viewer/Viewer.class.php#491 (show)
public function Fetch($sTemplate)
{
    
/**
     * Проверяем наличие делегата
     */
    
$sTemplate $this->Plugin_GetDelegate('template'$sTemplate);
    return 
$this->oSmarty->fetch($sTemplate);
}

Возвращает обработанный шаблон

GetBlocks() method
public array GetBlocks(bool $bSort=false)
$bSort bool Выполнять или нет сортировку блоков
{return} array
Source Code: /framework/classes/modules/viewer/Viewer.class.php#621 (show)
public function GetBlocks($bSort false)
{
    if (
$bSort) {
        
$this->SortBlocks();
    }
    return 
$this->aBlocks;
}

Возвращает список блоков

GetHtmlTitle() method
public string GetHtmlTitle(bool $bSortReverse=true)
$bSortReverse bool Направаление сортировки частей заголовка
{return} string
Source Code: /framework/classes/modules/viewer/Viewer.class.php#922 (show)
public function GetHtmlTitle($bSortReverse true)
{
    
$aParts $this->aHtmlTitleParts;
    if (
$bSortReverse) {
        
$aParts array_reverse($aParts);
    }
    return 
join($this->sHtmlTitleSeparation$aParts);
}

Возвращает текущий заголовок страницы

GetHtmlTitleSeparation() method
public string GetHtmlTitleSeparation()
{return} string
Source Code: /framework/classes/modules/viewer/Viewer.class.php#936 (show)
public function GetHtmlTitleSeparation()
{
    return 
$this->sHtmlTitleSeparation;
}

Возвращает разделитель заголовков страниц

GetLocalViewer() method
public ModuleViewer GetLocalViewer()
{return} ModuleViewer
Source Code: /framework/classes/modules/viewer/Viewer.class.php#196 (show)
public function GetLocalViewer()
{
    
$sClass $this->Plugin_GetDelegate('module'__CLASS__);

    
$oViewerLocal = new $sClass(Engine::getInstance());
    
$oViewerLocal->Init(true);
    
$oViewerLocal->VarAssign();
    
$oViewerLocal->Assign('aLang'$this->Lang_GetLangMsg());
    return 
$oViewerLocal;
}

Получает локальную копию модуля

GetResponseAjax() method
public string GetResponseAjax()
{return} string
Source Code: /framework/classes/modules/viewer/Viewer.class.php#399 (show)
public function GetResponseAjax()
{
    return 
$this->sResponseAjax;
}

Возвращает тип отдачи контекта

GetSmartyObject() method
public Smarty GetSmartyObject()
{return} Smarty
Source Code: /framework/classes/modules/viewer/Viewer.class.php#322 (show)
public function GetSmartyObject()
{
    return 
$this->oSmarty;
}

Возвращает объект Smarty

Init() method
public void Init($bLocal=false)
$bLocal
Source Code: /framework/classes/modules/viewer/Viewer.class.php#137 (show)
public function Init($bLocal false)
{
    
$this->Hook_Run('viewer_init_start'compact('bLocal'));
    
/**
     * Load template config
     */
    
if (!$bLocal) {
        if (
file_exists($sFile Config::Get('path.smarty.template') . '/settings/config/config.php')) {
            
Config::LoadFromFile($sFilefalse);
        }
    }
    
/**
     * Разделитель заголовков страниц
     */
    
$this->SetHtmlTitleSeparation(Config::Get('view.title_separator'));
    
/**
     * Заголовок HTML страницы
     */
    
$this->AddHtmlTitle(Config::Get('view.name'));
    
/**
     * SEO ключевые слова страницы
     */
    
$this->sHtmlKeywords Config::Get('view.keywords');
    
/**
     * SEO описание страницы
     */
    
$this->sHtmlDescription Config::Get('view.description');

    
/**
     * Создаём объект Smarty и устанавливаем необходимые параметры
     */
    
$this->oSmarty $this->CreateSmartyObject();
    
$this->oSmarty->error_reporting error_reporting() & ~E_NOTICE// подавляем NOTICE ошибки - в этом вся прелесть смарти )
    
$this->oSmarty->setTemplateDir(array_merge((array)Config::Get('path.smarty.template'),
        array(
Config::Get('path.application.plugins.server') . '/')));
    
$this->oSmarty->compile_check Config::Get('smarty.compile_check');
    
$this->oSmarty->force_compile Config::Get('smarty.force_compile');
    
/**
     * Для каждого скина устанавливаем свою директорию компиляции шаблонов
     */
    
$sCompilePath Config::Get('path.smarty.compiled') . '/' Config::Get('view.skin');
    if (!
is_dir($sCompilePath)) {
        @
mkdir($sCompilePath0777true);
    }
    
$this->oSmarty->setCompileDir($sCompilePath);
    
$sCachePath Config::Get('path.smarty.cache');
    if (!
is_dir($sCachePath)) {
        @
mkdir($sCachePath0777true);
    }
    
$this->oSmarty->setCacheDir($sCachePath);
    
$this->oSmarty->addPluginsDir(array(Config::Get('path.smarty.plug'), 'plugins'));
    
$this->oSmarty->default_template_handler_func = array($this'SmartyDefaultTemplateHandler');
}

Инициализация модуля

InitBlockParams() method
protected void InitBlockParams()
Source Code: /framework/classes/modules/viewer/Viewer.class.php#514 (show)
protected function InitBlockParams()
{
    if (
$aRules Config::Get('block')) {
        
$this->aBlockRules $aRules;
    }
}

Инициализируем параметры отображения блоков

MakePaging() method
public array MakePaging(int $iCount, int $iCurrentPage, int $iCountPerPage, int $iCountPageLine, string $sBaseUrl, array $aGetParamsList=array ( ))
$iCount int Общее количество элементов
$iCurrentPage int Текущая страница
$iCountPerPage int Количество элементов на одну страницу
$iCountPageLine int Количество ссылок на другие страницы
$sBaseUrl string Базовый URL, к нему будет добавлять постикс /pageN/ и GET параметры
$aGetParamsList array Список GET параметров, которые необходимо передавать при постраничном переходе
{return} array
Source Code: /framework/classes/modules/viewer/Viewer.class.php#1007 (show)
public function MakePaging(
    
$iCount,
    
$iCurrentPage,
    
$iCountPerPage,
    
$iCountPageLine,
    
$sBaseUrl,
    
$aGetParamsList = array()
) {
    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 $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 false;
    
$iPrevPage $iCurrentPage $iCurrentPage false;

    
$sGetParams '';
    if (
is_string($aGetParamsList) or count($aGetParamsList)) {
        
$sGetParams '?' . (is_array($aGetParamsList) ? http_build_query($aGetParamsList'',
                
'&') : $aGetParamsList);
    }
    
$aPaging = array(
        
'aPagesLeft'   => $aPagesLeft,
        
'aPagesRight'  => $aPagesRight,
        
'iCount'       => $iCount,
        
'iCountPage'   => $iCountPage,
        
'iCurrentPage' => $iCurrentPage,
        
'iNextPage'    => $iNextPage,
        
'iPrevPage'    => $iPrevPage,
        
'sBaseUrl'     => rtrim(func_urlspecialchars($sBaseUrl), '/'),
        
'sGetParams'   => $sGetParams,
    );
    
/**
     * Избавляемся от дублирования страниц с page=1
     */
    
if ($aPaging['iCurrentPage'] == 1) {
        
$this->SetHtmlCanonical($aPaging['sBaseUrl'] . '/' $aPaging['sGetParams']);
    } else {
        
/**
         * Избавляемся от дублирования title страниц - добавляем "Страница N"
         */
        
$this->AddHtmlTitle($this->Lang_Get('pagination.page_with_number',
            array(
'number' => $aPaging['iCurrentPage'])));
    }
    return 
$aPaging;
}

Формирует постраничный вывод

protected void MenuVarAssign()
Source Code: /framework/classes/modules/viewer/Viewer.class.php#287 (show)
protected function MenuVarAssign()
{
    
$this->Assign("aMenuFetch"$this->aMenuFetch);
    
$this->Assign("aMenuContainers"array_keys($this->aMenu));
}

Загружаем содержимое menu-контейнеров

PrependScript() method
public bool PrependScript($sJs $sJs, array $aParams=array ( ), bool $bReplace=false)
$sJs $sJs Файл js
$aParams array Параметры, например, можно указать параметр 'name'=>'jquery.plugin.foo' для исключения повторного добавления файла с таким именем
$bReplace bool Заменять файл или нет
{return} bool
Source Code: /framework/classes/modules/viewer/Viewer.class.php#844 (show)
public function PrependScript($sJs$aParams = array(), $bReplace false)
{
    return 
$this->Asset_AddJs($sJs$aParamstrue$bReplace);
}

Добавляет js файл в начало списка

PrependStyle() method
public bool PrependStyle($sCss $sCss, array $aParams=array ( ), bool $bReplace=false)
$sCss $sCss Файл css стилей
$aParams array Параметры, например, можно указать параметр 'name'=>'blueprint' для исключения повторного добавления файла с таким именем
$bReplace bool Заменять файл или нет
{return} bool
Source Code: /framework/classes/modules/viewer/Viewer.class.php#870 (show)
public function PrependStyle($sCss$aParams = array(), $bReplace false)
{
    return 
$this->Asset_AddCss($sCss$aParamstrue$bReplace);
}

Добавляет css файл в начало списка

SetHtmlCanonical() method
public void SetHtmlCanonical(string $sUrl, bool $bRewrite=false)
$sUrl string URL страницы
$bRewrite bool Перезаписывать URL, если он уже установлен
Source Code: /framework/classes/modules/viewer/Viewer.class.php#977 (show)
public function SetHtmlCanonical($sUrl$bRewrite false)
{
    if (!
$this->sHtmlCanonical or $bRewrite) {
        
$this->sHtmlCanonical $sUrl;
    }
}

Устанавливает основной адрес страницы

SetHtmlDescription() method
public void SetHtmlDescription(string $sText)
$sText string Описание
Source Code: /framework/classes/modules/viewer/Viewer.class.php#966 (show)
public function SetHtmlDescription($sText)
{
    
$this->sHtmlDescription $sText;
}

Устанавливает описание страницы desciption

SetHtmlHeadFiles() method
public void SetHtmlHeadFiles(array $aText)
$aText array Список файлов
Source Code: /framework/classes/modules/viewer/Viewer.class.php#890 (show)
public function SetHtmlHeadFiles($aText)
{
    
$this->aHtmlHeadFiles $aText;
}

Устанавливает список файлов для вывода в хидере страницы

SetHtmlKeywords() method
public void SetHtmlKeywords(string $sText)
$sText string Кейворды
Source Code: /framework/classes/modules/viewer/Viewer.class.php#956 (show)
public function SetHtmlKeywords($sText)
{
    
$this->sHtmlKeywords $sText;
}

Устанавливает ключевые слова keywords

SetHtmlRssAlternate() method
public void SetHtmlRssAlternate(string $sUrl, string $sTitle)
$sUrl string URL
$sTitle string Заголовок
Source Code: /framework/classes/modules/viewer/Viewer.class.php#990 (show)
public function SetHtmlRssAlternate($sUrl$sTitle)
{
    
$this->aHtmlRssAlternate['title'] = htmlspecialchars($sTitle);
    
$this->aHtmlRssAlternate['url'] = htmlspecialchars($sUrl);
}

Устанавливает альтернативный адрес страницы по RSS

SetHtmlTitle() method
public void SetHtmlTitle(string|array $mText)
$mText string|array Заголовок
Source Code: /framework/classes/modules/viewer/Viewer.class.php#900 (show)
public function SetHtmlTitle($mText)
{
    
$this->aHtmlTitleParts is_array($mText) ? $mText : array($mText);
}

Устанавливаем заголовок страницы(тег title)

SetHtmlTitleSeparation() method
public void SetHtmlTitleSeparation($sSep $sSep)
$sSep $sSep
Source Code: /framework/classes/modules/viewer/Viewer.class.php#946 (show)
public function SetHtmlTitleSeparation($sSep)
{
    
$this->sHtmlTitleSeparation $sSep;
}

Устанавливает разделитель заголовков страниц

SetResponseAjax() method
public void SetResponseAjax(string $sResponseAjax='json', bool $bResponseSpecificHeader=true, bool $bValidate=true)
$sResponseAjax string Тип ответа
$bResponseSpecificHeader bool Установливать специфичные тиру заголовки через header()
$bValidate bool Производить или нет валидацию формы через Security::ValidateSendForm
Source Code: /framework/classes/modules/viewer/Viewer.class.php#411 (show)
public function SetResponseAjax($sResponseAjax 'json'$bResponseSpecificHeader true$bValidate true)
{
    
// Для возможности кросс-доменных запросов
    
if ($sResponseAjax != 'jsonp' && $bValidate) {
        
$this->Security_ValidateSendForm();
    }
    
$this->sResponseAjax $sResponseAjax;
    
$this->bResponseSpecificHeader $bResponseSpecificHeader;
}

Устанавливает тип отдачи при ajax запросе, если null то выполняется обычный вывод шаблона в браузер

Shutdown() method
public void Shutdown()
Source Code: /framework/classes/modules/viewer/Viewer.class.php#1142 (show)
public function Shutdown()
{
    
/**
     * Получаем настройки блоков из конфигов
     */
    
$this->InitBlockParams();
    
/**
     * Добавляем блоки по предзагруженным правилам из конфигов
     */
    
$this->BuildBlocks();

    
$this->SortBlocks();
    
/**
     * Добавляем JS и CSS по предписанным правилам
     */
    
$this->BuildHeadFiles();
    
$this->VarAssign();
    
/**
     * Рендерим меню для шаблонов и передаем контейнеры в шаблон
     */
    
$this->BuildMenu();
    
$this->MenuVarAssign();
}

Загружаем переменные в шаблон при завершении модуля

SmartyDefaultTemplateHandler() method
public string|bool SmartyDefaultTemplateHandler(string $sType, string $sName, string &$sContent, int &$iTimestamp, Smarty $oSmarty)
$sType string Тип шаблона/ресурса
$sName string Имя шаблона - имя файла
$sContent string Возврат содержания шаблона при return true;
$iTimestamp int Возврат даты модификации шаблона при return true;
$oSmarty Smarty Объект Smarty
{return} string|bool
Source Code: /framework/classes/modules/viewer/Viewer.class.php#1105 (show)
public function SmartyDefaultTemplateHandler($sType$sName, &$sContent, &$iTimestamp$oSmarty)
{
    
/**
     * Название шаблона может содержать, как полный путь до файла шаблона, так и относительный любого из каталога в $oSmarty->getTemplateDir()
     * По дефолту каталоги такие: /templates/skin/[name]/ и /plugins/
     */
    /**
     * Задача: если это файл плагина для текущего шаблона, то смотрим этот же файл шаблона плагина в /default/
     */
    
if (Config::Get('view.skin') != 'default') {
        
// /root/plugins/[plugin name]/templates/skin/[skin name]/dir/test.tpl
        
if (preg_match('@^' preg_quote(Config::Get('path.application.plugins.server')) . '/([\w\-_]+)/templates/skin/' preg_quote(Config::Get('view.skin')) . '/@i',
            
$sName$aMatch)) {
            
$sFile str_replace($aMatch[0],
                
Config::Get('path.application.plugins.server') . '/' $aMatch[1] . '/templates/skin/default/',
                
$sName);
            if (
$this->TemplateExists($sFile)) {
                return 
$sFile;
            }
        }
        
// [plugin name]/templates/skin/[skin name]/dir/test.tpl
        
if (preg_match('@^([\w\-_]+)/templates/skin/' preg_quote(Config::Get('view.skin')) . '/@i'$sName,
            
$aMatch)) {
            
$sFile Config::Get('path.application.plugins.server') . '/' str_replace($aMatch[0],
                    
$aMatch[1] . '/templates/skin/default/'$sName);
            if (
$this->TemplateExists($sFile)) {
                return 
$sFile;
            }
        }
    }
    return 
false;
}

Обработка поиска файла шаблона, если его не смог найти шаблонизатор Smarty

SortBlocks() method
protected void SortBlocks()
Source Code: /framework/classes/modules/viewer/Viewer.class.php#812 (show)
protected function SortBlocks()
{
    
/**
     * Сортируем блоки по приоритетности
     */
    
foreach ($this->aBlocks as $sGroup => $aBlocks) {
        
uasort($aBlocks, array($this'_SortBlocks'));
        
$this->aBlocks[$sGroup] = array_reverse($aBlocks);
    }
}

Сортируем блоки

TemplateExists() method
public bool TemplateExists(string $sTemplate)
$sTemplate string Шаблон
{return} bool
Source Code: /framework/classes/modules/viewer/Viewer.class.php#506 (show)
public function TemplateExists($sTemplate)
{
    return 
$this->oSmarty->templateExists($sTemplate);
}

Проверяет существование шаблона

VarAssign() method
public void VarAssign()
Source Code: /framework/classes/modules/viewer/Viewer.class.php#211 (show)
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());
    
/**
     * Short Engine aliases
     */
    
$this->Assign("LS"LS::getInstance());
    
/**
     * Загружаем объект доступа к конфигурации
     */
    
$this->Assign("oConfig"Config::getInstance());
    
/**
     * Загружаем роутинг с учетом правил rewrite
     */
    
$aRouter = array();
    
$aPages Config::Get('router.page');

    if (!
$aPages or !is_array($aPages)) {
        throw new 
Exception('Router rules is underfined.');
    }
    foreach (
$aPages as $sPage => $aAction) {
        
$aRouter[$sPage] = Router::GetPath($sPage);
    }
    
$this->Assign("aRouter"$aRouter);
    
/**
     * Загружаем в шаблон блоки
     */
    
$this->Assign("aBlocks"$this->aBlocks);
    
/**
     * Загружаем в шаблон JS переменные
     */
    
$this->Assign("aVarsJs"$this->aVarsJs);
    
/**
     * Загружаем HTML заголовки
     */
    
$this->Assign("sHtmlTitle"htmlspecialchars($this->GetHtmlTitle(Config::Get('view.title_sort_reverse'))));
    
$this->Assign("sHtmlKeywords"htmlspecialchars($this->sHtmlKeywords));
    
$this->Assign("sHtmlDescription"htmlspecialchars($this->sHtmlDescription));
    
$this->Assign("aHtmlHeadFiles"$this->aHtmlHeadFiles);
    
$this->Assign("aHtmlRssAlternate"$this->aHtmlRssAlternate);
    
$this->Assign("sHtmlCanonical"func_urlspecialchars($this->sHtmlCanonical));
    
/**
     * Загружаем список активных плагинов
     */
    
$aPlugins Engine::getInstance()->GetPlugins();
    
$this->Assign("aPluginActive"array_fill_keys(array_keys($aPlugins), true));
    
/**
     * Загружаем пути до шаблонов плагинов
     */
    
$aTemplateWebPathPlugin = array();
    
$aTemplatePathPlugin = array();
    foreach (
$aPlugins as $k => $oPlugin) {
        
$aTemplateWebPathPlugin[$k] = Plugin::GetTemplateWebPath(get_class($oPlugin));
        
$aTemplatePathPlugin[$k] = Plugin::GetTemplatePath(get_class($oPlugin));
    }
    
$this->Assign("aTemplateWebPathPlugin"$aTemplateWebPathPlugin);
    
$this->Assign("aTemplatePathPlugin"$aTemplatePathPlugin);
    
/**
     * Загружаем security-ключ
     */
    
$this->Assign("LIVESTREET_SECURITY_KEY"$this->Security_GetSecurityKey());
}

Выполняет загрузку необходимый(возможно даже системный :)) переменных в шалон

_SortBlocks() method
protected int _SortBlocks(array $a, array $b)
$a array
$b array
{return} int
Source Code: /framework/classes/modules/viewer/Viewer.class.php#803 (show)
protected function _SortBlocks($a$b)
{
    return (
$a["priority"] - $b["priority"]);
}

Вспомагательная функция для сортировки блоков по приоритетности