ModuleText

Package engine.modules
Inheritance class ModuleText » Module » LsObject
Since 1.0
Source Code /engine/modules/text/Text.class.php
Модуль обработки текста на основе типографа Jevix Позволяет вырезать из текста лишние HTML теги и предотвращает различные попытки внедрить в текст JavaScript
$sText=$this->Text_Parser($sTestSource);
Настройки парсинга находятся в конфиге /config/jevix.php

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
bIsInit bool Указывает на то, была ли проведенна инициализация модуля Module
oEngine Engine Объект ядра Module
oJevix Jevix Объект типографа ModuleText

Public Methods

Hide inherited methods

MethodDescriptionDefined By
CallbackTagLs() Обработка тега ls в тексте ModuleText
CodeSourceParser() Подсветка исходного кода ModuleText
Cut() Производить резрезание текста по тегу cut. ModuleText
GetJevix() Возвращает объект Jevix ModuleText
Init() Инициализация модуля ModuleText
JevixParser() Парсинг текста с помощью Jevix ModuleText
LoadJevixConfig() Загружает конфиг Jevix'а ModuleText
Parser() Парсит текст, применя все парсеры ModuleText
SetInit() Помечает модуль как инициализированный Module
Shutdown() Метод срабатывает при завершении работы ядра Module
VideoParser() Парсинг текста на предмет видео ModuleText
__call() Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля Module
__construct() При создании модуля передаем объект ядра Module
isInit() Возвращает значение флага инициализации модуля Module

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
FlashParamParser() Заменяет все вхождения короткого тега на длиную версию ModuleText
JevixConfig() Конфигурирует типограф ModuleText
__clone() Блокируем копирование/клонирование объекта Module

Property Details

oJevix property
protected Jevix $oJevix;

Объект типографа

Method Details

CallbackTagLs() method
public string CallbackTagLs(string $sTag, array $aParams)
$sTag string Тег на ктором сработал колбэк
$aParams array Список параметров тега
{return} string
Source Code: /engine/modules/text/Text.class.php#250 (show)
public function CallbackTagLs($sTag,$aParams) {
    
$sText='';
    if (isset(
$aParams['user'])) {
        if (
$oUser=$this->User_getUserByLogin($aParams['user'])) {
            
$sText.="<a href=\"{$oUser->getUserWebPath()}\" class=\"ls-user\">{$oUser->getLogin()}</a> ";
        }
    }
    return 
$sText;
}

Обработка тега ls в тексте

<ls user="admin" />

CodeSourceParser() method
public mixed CodeSourceParser(string $sText)
$sText string Исходный текст
{return} mixed
Source Code: /engine/modules/text/Text.class.php#199 (show)
public function CodeSourceParser($sText) {
    
$sText=str_replace("<code>",'<pre class="prettyprint"><code>',$sText);
    
$sText=str_replace("</code>",'</code></pre>',$sText);
    return 
$sText;
}

Подсветка исходного кода

Cut() method
public array Cut(string $sText)
$sText string Исходный текст
{return} array
Source Code: /engine/modules/text/Text.class.php#218 (show)
public function Cut($sText) {
    
$sTextShort $sText;
    
$sTextNew   $sText;
    
$sTextCut   null;

    
$sTextTemp=str_replace("\r\n",'[<rn>]',$sText);
    
$sTextTemp=str_replace("\n",'[<n>]',$sTextTemp);

    if (
preg_match("/^(.*)<cut(.*)>(.*)$/Ui",$sTextTemp,$aMatch)) {
        
$aMatch[1]=str_replace('[<rn>]',"\r\n",$aMatch[1]);
        
$aMatch[1]=str_replace('[<n>]',"\r\n",$aMatch[1]);
        
$aMatch[3]=str_replace('[<rn>]',"\r\n",$aMatch[3]);
        
$aMatch[3]=str_replace('[<n>]',"\r\n",$aMatch[3]);
        
$sTextShort=$aMatch[1];
        
$sTextNew=$aMatch[1].' <a name="cut"></a> '.$aMatch[3];
        if (
preg_match('/^\s*name\s*=\s*"(.+)"\s*\/?$/Ui',$aMatch[2],$aMatchCut)) {
            
$sTextCut=trim($aMatchCut[1]);
        }
    }

    return array(
$sTextShort,$sTextNew,$sTextCut htmlspecialchars($sTextCut) : null);
}

Производить резрезание текста по тегу cut. Возвращаем массив вида:

array(
		$sTextShort - текст до тега <cut>
		$sTextNew   - весь текст за исключением удаленного тега
		$sTextCut   - именованное значение <cut>
)

FlashParamParser() method
protected string FlashParamParser(string $sText)
$sText string Исходный текст
{return} string
Source Code: /engine/modules/text/Text.class.php#161 (show)
protected function FlashParamParser($sText) {
    if (
preg_match_all("@(<\s*param\s*name\s*=\s*(?:\"|').*(?:\"|')\s*value\s*=\s*(?:\"|').*(?:\"|'))\s*/?\s*>(?!</param>)@Ui",$sText,$aMatch)) {
        foreach (
$aMatch[1] as $key => $str) {
            
$str_new=$str.'></param>';
            
$sText=str_replace($aMatch[0][$key],$str_new,$sText);
        }
    }
    if (
preg_match_all("@(<\s*embed\s*.*)\s*/?\s*>(?!</embed>)@Ui",$sText,$aMatch)) {
        foreach (
$aMatch[1] as $key => $str) {
            
$str_new=$str.'></embed>';
            
$sText=str_replace($aMatch[0][$key],$str_new,$sText);
        }
    }
    
/**
     * Удаляем все <param name="wmode" value="*"></param>
     */
    
if (preg_match_all("@(<param\s.*name=(?:\"|')wmode(?:\"|').*>\s*</param>)@Ui",$sText,$aMatch)) {
        foreach (
$aMatch[1] as $key => $str) {
            
$sText=str_replace($aMatch[0][$key],'',$sText);
        }
    }
    
/**
     * А теперь после <object> добавляем <param name="wmode" value="opaque"></param>
     * Решение не фантан, но главное работает :)
     */
    
if (preg_match_all("@(<object\s.*>)@Ui",$sText,$aMatch)) {
        foreach (
$aMatch[1] as $key => $str) {
            
$sText=str_replace($aMatch[0][$key],$aMatch[0][$key].'<param name="wmode" value="opaque"></param>',$sText);
        }
    }
    return 
$sText;
}

Заменяет все вхождения короткого тега на длиную версию Заменяет все вхождения короткого тега на длиную версию

GetJevix() method
public Jevix GetJevix()
{return} Jevix
Source Code: /engine/modules/text/Text.class.php#94 (show)
public function GetJevix() {
    return 
$this->oJevix;
}

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

Init() method
public void Init()
Source Code: /engine/modules/text/Text.class.php#43 (show)
public function Init() {
    
/**
     * Создаем объект типографа и запускаем его конфигурацию
     */
    
$this->oJevix = new Jevix();
    
$this->JevixConfig();
}

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

JevixConfig() method
protected void JevixConfig()
Source Code: /engine/modules/text/Text.class.php#54 (show)
protected function JevixConfig() {
    
// загружаем конфиг
    
$this->LoadJevixConfig();
}

Конфигурирует типограф

JevixParser() method
public string JevixParser(string $sText, array &$aError=NULL)
$sText string Исходный текст
$aError array Возвращает список возникших ошибок
{return} string
Source Code: /engine/modules/text/Text.class.php#104 (show)
public function JevixParser($sText,&$aError=null) {
    
// Если конфиг пустой, то загружаем его
    
if (!count($this->oJevix->tagsRules)) {
        
$this->LoadJevixConfig();
    }
    
$sResult=$this->oJevix->parse($sText,$aError);
    return 
$sResult;
}

Парсинг текста с помощью Jevix

LoadJevixConfig() method
public void LoadJevixConfig(string $sType='default', bool $bClear=true)
$sType string Тип конфига
$bClear bool Очищать предыдущий конфиг или нет
Source Code: /engine/modules/text/Text.class.php#64 (show)
public function LoadJevixConfig($sType='default',$bClear=true) {
    if (
$bClear) {
        
$this->oJevix->tagsRules=array();
    }
    
$aConfig=Config::Get('jevix.'.$sType);
    if (
is_array($aConfig)) {
        foreach (
$aConfig as $sMethod => $aExec) {
            foreach (
$aExec as $aParams) {
                if (
in_array(strtolower($sMethod),array_map("strtolower",array('cfgSetTagCallbackFull','cfgSetTagCallback')))) {
                    if (isset(
$aParams[1][0]) and $aParams[1][0]=='_this_') {
                        
$aParams[1][0]=$this;
                    }
                }
                
call_user_func_array(array($this->oJevix,$sMethod), $aParams);
            }
        }
        
/**
         * Хардкодим некоторые параметры
         */
        
unset($this->oJevix->entities1['&']); // разрешаем в параметрах символ &
        
if (Config::Get('view.noindex') and isset($this->oJevix->tagsRules['a'])) {
            
$this->oJevix->cfgSetTagParamDefault('a','rel','nofollow',true);
        }
    }
}

Загружает конфиг Jevix'а

Parser() method
public string Parser(string $sText)
$sText string Исходный текст
{return} string
Source Code: /engine/modules/text/Text.class.php#144 (show)
public function Parser($sText) {
    if (!
is_string($sText)) {
        return 
'';
    }
    
$sResult=$this->FlashParamParser($sText);
    
$sResult=$this->JevixParser($sResult);
    
$sResult=$this->VideoParser($sResult);
    
$sResult=$this->CodeSourceParser($sResult);
    return 
$sResult;
}

Парсит текст, применя все парсеры

VideoParser() method
public string VideoParser(string $sText)
$sText string Исходный текст
{return} string
Source Code: /engine/modules/text/Text.class.php#119 (show)
public function VideoParser($sText) {
    
/**
     * youtube.com
     */
    
$sText preg_replace('/<video>http:\/\/(?:www\.|)youtube\.com\/watch\?v=([a-zA-Z0-9_\-]+)(&.+)?<\/video>/Ui''<iframe width="560" height="315" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>'$sText);
    
/**
     * vimeo.com
     */
    
$sText preg_replace('/<video>http:\/\/(?:www\.|)vimeo\.com\/(\d+).*<\/video>/i''<iframe src="http://player.vimeo.com/video/$1" width="500" height="281" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'$sText);
    
/**
     * rutube.ru
     */
    
$sText preg_replace('/<video>http:\/\/(?:www\.|)rutube\.ru\/tracks\/(\d+)\.html.*<\/video>/Ui''<OBJECT width="470" height="353"><PARAM name="movie" value="http://video.rutube.ru/$1"></PARAM><PARAM name="wmode" value="window"></PARAM><PARAM name="allowFullScreen" value="true"></PARAM><EMBED src="http://video.rutube.ru/$1" type="application/x-shockwave-flash" wmode="window" width="470" height="353" allowFullScreen="true" ></EMBED></OBJECT>'$sText);
    
/**
     * video.yandex.ru
     */
    
$sText preg_replace('/<video>http:\/\/video\.yandex\.ru\/users\/([a-zA-Z0-9_\-]+)\/view\/(\d+).*<\/video>/i''<object width="467" height="345"><param name="video" value="http://video.yandex.ru/users/$1/view/$2/get-object-by-url/redirect"></param><param name="allowFullScreen" value="true"></param><param name="scale" value="noscale"></param><embed src="http://video.yandex.ru/users/$1/view/$2/get-object-by-url/redirect" type="application/x-shockwave-flash" width="467" height="345" allowFullScreen="true" scale="noscale" ></embed></object>'$sText);
    return 
$sText;
}

Парсинг текста на предмет видео Находит теги

<video></video>
и реобразовываетих в видео