1
0
Fork 0
mirror of https://github.com/Oreolek/ifhub.club.git synced 2024-06-26 03:30:48 +03:00

update Jevix

This commit is contained in:
Mzhelskiy Maxim 2010-01-24 14:58:06 +00:00
parent b0f33a7e53
commit 80225d40f1
2 changed files with 1328 additions and 1269 deletions

View file

@ -10,6 +10,13 @@
* @version 1.01
*
* История версий:
* 1.1:
* + cfgSetTagParamsAutoAdd() deprecated. Вместо него следует использовать cfgSetTagParamDefault() с более удобным синтаксисом
* + Исправлен критический баг с обработкой атрибутов тегов https://code.google.com/p/jevix/issues/detail?id=1
* + Удаление атрибутов тегов с пустым значением. Атрибуты без значений (checked, nowrap) теперь превращаются в checked="checked"
* + Исправлен тест, проведена небольшая ревизия кода
* 1.02:
* + Функции для работы со строками заменены на аналогичные mb_*, чтобы не перегружать через mbstring.func_overload (ev.y0ga@mail.ru)
* 1.01
* + cfgSetAutoReplace теперь регистронезависимый
* + Возможность указать через cfgSetTagIsEmpty теги с пустым содержанием, которые не будут адалены парсером (rus.engine)
@ -87,10 +94,10 @@ class Jevix{
const STATE_INSIDE_TAG = 3;
const STATE_INSIDE_NOTEXT_TAG = 4;
const STATE_INSIDE_PREFORMATTED_TAG = 5;
const STATE_INSIDE_CALLBACK_TAG = 6;
public $tagsRules = array();
public $entities0 = array('"'=>'&quot;', "'"=>'&#39;', '&'=>'&amp;', '<'=>'&lt;', '>'=>'&gt;');
public $entities1 = array();
public $entities1 = array('"'=>'&quot;', "'"=>'&#39;', '&'=>'&amp;', '<'=>'&lt;', '>'=>'&gt;');
public $entities2 = array('<'=>'&lt;', '>'=>'&gt;', '"'=>'&quot;');
public $textQuotes = array(array('«', '»'), array('„', '“'));
public $dash = "";
@ -143,7 +150,8 @@ class Jevix{
const TR_TAG_NO_TYPOGRAPHY = 12; // Отключение типографирования для тега
const TR_TAG_IS_EMPTY = 13; // Не короткий тег с пустым содержанием имеет право существовать
const TR_TAG_NO_AUTO_BR = 14; // Тег в котором не нужна авто-расстановка <br>
const TR_TAG_BLOCK_TYPE = 15; // Тег после которого не нужна автоподстановка доп. <br>
const TR_TAG_CALLBACK = 15; // Тег обрабатывается callback-функцией
const TR_TAG_BLOCK_TYPE = 16; // Тег после которого не нужна автоподстановка доп. <br>
/**
* Классы символов генерируются symclass.php
@ -307,18 +315,38 @@ class Jevix{
* CONFIGURATION: Adding autoadd attributes and their values to tag. If the 'rewrite' set as true, the attribute value will be replaced
* @param string $tag tag
* @param string|array $params array of pairs array('name'=>attributeName, 'value'=>attributeValue, 'rewrite'=>true|false)
* @deprecated устаревший синтаксис. Используйте cfgSetTagParamDefault
*/
function cfgSetTagParamsAutoAdd($tag, $params){
throw new Exception("cfgSetTagParamsAutoAdd() is Deprecated. Use cfgSetTagParamDefault() instead");
}
/**
* КОНФИГУРАЦИЯ: Установка дефолтных значений для атрибутов тега
* @param string $tag тег
* @param string $param атрибут
* @param string $value значение
* @param boolean $isRewrite заменять указанное значение дефолтным
*/
function cfgSetTagParamDefault($tag, $param, $value, $isRewrite = false){
if(!isset($this->tagsRules[$tag])) throw new Exception("Tag $tag is missing in allowed tags list");
if (is_array($params) and !isset($params[0])) $params = array($params);
if(!isset($this->tagsRules[$tag][self::TR_PARAM_AUTO_ADD])) {
$this->tagsRules[$tag][self::TR_PARAM_AUTO_ADD] = array();
}
foreach($params as $aParamValue){
$this->tagsRules[$tag][self::TR_PARAM_AUTO_ADD][$aParamValue['name']] = array('value'=>$aParamValue['value'],'rewrite'=>$aParamValue['rewrite']);
}
$this->tagsRules[$tag][self::TR_PARAM_AUTO_ADD][$param] = array('value'=>$value, 'rewrite'=>$isRewrite);
}
/**
* КОНФИГУРАЦИЯ: Устанавливаем callback-функцию на обработку содержимого тега
* @param string $tag тег
* @param mixed $callback функция
*/
function cfgSetTagCallback($tag, $callback = null){
if(!isset($this->tagsRules[$tag])) throw new Exception("Тег $tag отсутствует в списке разрешённых тегов");
$this->tagsRules[$tag][self::TR_TAG_CALLBACK] = $callback;
}
/**
* Автозамена
@ -506,7 +534,7 @@ class Jevix{
*/
protected function matchStr($str, $skipSpaces = false){
$this->saveState();
$len = strlen($str);
$len = mb_strlen($str, 'UTF-8');
$test = '';
while($len-- && $this->curChClass){
$test.=$this->curCh;
@ -529,7 +557,7 @@ class Jevix{
* @return string найденый символ или false
*/
protected function skipUntilCh($ch){
$chPos = strpos($this->text, $ch, $this->curPos);
$chPos = mb_strpos($this->text, $ch, $this->curPos, 'UTF-8');
if($chPos){
return $this->goToPosition($chPos);
} else {
@ -653,6 +681,8 @@ class Jevix{
} elseif(!empty($this->tagsRules[$tag][self::TR_TAG_NO_TYPOGRAPHY])) {
$this->noTypoMode = true;
$this->state = self::STATE_INSIDE_TAG;
} elseif(array_key_exists($tag, $this->tagsRules) && array_key_exists(self::TR_TAG_CALLBACK, $this->tagsRules[$tag])){
$this->state = self::STATE_INSIDE_CALLBACK_TAG;
} else {
$this->state = self::STATE_INSIDE_TAG;
}
@ -663,6 +693,8 @@ class Jevix{
$content = '';
if($this->state == self::STATE_INSIDE_PREFORMATTED_TAG){
$this->preformatted($content, $tag);
} elseif($this->state == self::STATE_INSIDE_CALLBACK_TAG){
$this->callback($content, $tag);
} else {
$this->anyThing($content, $tag);
}
@ -701,6 +733,28 @@ class Jevix{
}
}
protected function callback(&$content = '', $insideTag = null){
while($this->curChClass){
if($this->curCh == '<'){
$tag = '';
$this->saveState();
// Пытаемся найти закрывающийся тег
$isClosedTag = $this->tagClose($tag);
// Возвращаемся назад, если тег был найден
if($isClosedTag) $this->restoreState();
// Если закрылось то, что открылось - заканчиваем и возвращаем true
if($isClosedTag && $tag == $insideTag) {
if ($callback = $this->tagsRules[$tag][self::TR_TAG_CALLBACK]) {
$content = call_user_func($callback, $content);
}
return;
}
}
$content.= $this->curCh;
$this->getCh();
}
}
protected function tagOpen(&$name, &$params, &$short = false){
$restore = $this->saveState();
@ -711,7 +765,7 @@ class Jevix{
$this->restoreState();
return false;
}
$name=strtolower($name);
$name=mb_strtolower($name, 'UTF-8');
// Пробуем получить список атрибутов тега
if($this->curCh != '>' && $this->curCh != '/') $this->tagParams($params);
@ -756,7 +810,7 @@ class Jevix{
if(!$this->matchCh('=', true)){
// Стремная штука - параметр без значения <input type="checkbox" checked>, <td nowrap class=b>
if(($this->curCh=='>' || ($this->curChClass & self::LAT) == self::LAT)){
$value = null;
$value = $name;
return true;
} else {
$this->restoreState();
@ -817,7 +871,7 @@ class Jevix{
$this->restoreState();
return false;
}
$name=strtolower($name);
$name=mb_strtolower($name, 'UTF-8');
$this->skipSpaces();
if(!$this->matchCh('>')) {
$this->restoreState();
@ -828,7 +882,7 @@ class Jevix{
protected function makeTag($tag, $params, $content, $short, $parentTag = null){
$this->curParentTag=$parentTag;
$tag = strtolower($tag);
$tag = mb_strtolower($tag, 'UTF-8');
// Получаем правила фильтрации тега
$tagRules = isset($this->tagsRules[$tag]) ? $this->tagsRules[$tag] : null;
@ -855,7 +909,7 @@ class Jevix{
$resParams = array();
foreach($params as $param=>$value){
$param = strtolower($param);
$param = mb_strtolower($param, 'UTF-8');
$value = trim($value);
if(empty($value)) continue;
@ -945,8 +999,14 @@ class Jevix{
}
// Собираем тег
$text='<'.$tag;
// Параметры
foreach($resParams as $param=>$value) $text.=' '.$param.'="'.$value.'"';
foreach($resParams as $param => $value) {
if (!empty($value)) {
$text.=' '.$param.'="'.$value.'"';
}
}
// Закрытие тега (если короткий то без контента)
$text.= $short && $this->isXHTMLMode ? '/>' : '>';
if(isset($tagRules[self::TR_TAG_CONTAINER])) $text .= "\r\n";
@ -981,11 +1041,10 @@ class Jevix{
// Преобразуем тег в текст
$tagText = $this->makeTag($tag, $params, $text, $shortTag, $parentTag);
$content.=$tagText;
// Пропускаем пробелы после <br> и запрещённых тегов, которые вырезаются парсером
if ($tag=='br') {
$this->skipNL();
}elseif (isset($this->tagsRules[$tag]) and isset($this->tagsRules[$tag][self::TR_TAG_BLOCK_TYPE])) {
} elseif (isset($this->tagsRules[$tag]) and isset($this->tagsRules[$tag][self::TR_TAG_BLOCK_TYPE])) {
$count=0;
$this->skipNL($count,2);
} elseif (empty($tagText)){
@ -1223,7 +1282,7 @@ class Jevix{
if ($this->curParentTag
and isset($this->tagsRules[$this->curParentTag])
and isset($this->tagsRules[$this->curParentTag][self::TR_TAG_NO_AUTO_BR])
and (is_null($this->openedTag) or $this->curParentTag==$this->openedTag)
and (is_null($this->openedTag) or isset($this->tagsRules[$this->openedTag][self::TR_TAG_NO_AUTO_BR]))
) {
// пропускаем <br/>
} else {
@ -1268,7 +1327,7 @@ class Jevix{
$this->getCh();
}
if(!strlen($url)) {
if(!mb_strlen($url, 'UTF-8')) {
$this->restoreState();
return false;
}
@ -1281,7 +1340,7 @@ class Jevix{
$this->getCh();
}
if(!strlen($url)) {
if(!mb_strlen($url, 'UTF-8')) {
$this->restoreState();
return false;
}

View file

@ -74,9 +74,9 @@ class LsText extends Module {
// Не нужна авто-расстановка <br>
$this->oJevix->cfgSetTagNoAutoBr(array('ul','ol','object'));
// Теги с обязательными параметрами
$this->oJevix->cfgSetTagParamsAutoAdd('embed',array(array('name'=>'wmode','value'=>'opaque','rewrite'=>true)));
$this->oJevix->cfgSetTagParamDefault('embed','wmode','opaque',true);
if (Config::Get('view.noindex')) {
$this->oJevix->cfgSetTagParamsAutoAdd('a',array(array('name'=>'rel','value'=>'nofollow','rewrite'=>true)));
$this->oJevix->cfgSetTagParamDefault('a','rel','nofollow',true);
}
// Отключение авто-добавления <br>
$this->oJevix->cfgSetAutoBrMode(true);