-
Notifications
You must be signed in to change notification settings - Fork 1
/
EMT.php
3428 lines (3055 loc) · 112 KB
/
EMT.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Evgeny Muravjev Typograph, http://mdash.ru
* Version: 3.5 Gold Master
* Release Date: July 2, 2015
* Authors: Evgeny Muravjev & Alexander Drutsa
*/
class EMT_Lib
{
const LAYOUT_STYLE = 1;
const LAYOUT_CLASS = 2;
const INTERNAL_BLOCK_OPEN = '%%%INTBLOCKO235978%%%';
const INTERNAL_BLOCK_CLOSE = '%%%INTBLOCKC235978%%%';
/**
* Таблица символов
*
* @var array
*/
public static $_charsTable = array(
'"' => array('html' => array('«', '»', '”', '‘', '„', '“', '"', '«', '»'),
'utf8' => array(0x201E, 0x201C, 0x201F, 0x201D, 0x00AB, 0x00BB)),
' ' => array('html' => array(' ', ' ', ' '),
'utf8' => array(0x00A0, 0x2002, 0x2003, 0x2008, 0x2009)),
'-' => array('html' => array(/*'—',*/ '–', '−', '—', '—', '–'),
'utf8' => array(0x002D, /*0x2014,*/ 0x2010, 0x2012, 0x2013)),
'—' => array('html' => array('—'),
'utf8' => array(0x2014)),
'==' => array('html' => array('≡'),
'utf8' => array(0x2261)),
'...' => array('html' => array('…', '…'),
'utf8' => array(0x2026)),
'!=' => array('html' => array('≠', '≠'),
'utf8' => array(0x2260)),
'<=' => array('html' => array('≤', '≤'),
'utf8' => array(0x2264)),
'>=' => array('html' => array('≥', '≥'),
'utf8' => array(0x2265)),
'1/2' => array('html' => array('½', '½'),
'utf8' => array(0x00BD)),
'1/4' => array('html' => array('¼', '¼'),
'utf8' => array(0x00BC)),
'3/4' => array('html' => array('¾', '¾'),
'utf8' => array(0x00BE)),
'+-' => array('html' => array('±', '±'),
'utf8' => array(0x00B1)),
'&' => array('html' => array('&', '&')),
'(tm)' => array('html' => array('™', '™'),
'utf8' => array(0x2122)),
//'(r)' => array('html' => array('<sup>®</sup>', '®', '®'),
'(r)' => array('html' => array('®', '®'),
'utf8' => array(0x00AE)),
'(c)' => array('html' => array('©', '©'),
'utf8' => array(0x00A9)),
'§' => array('html' => array('§', '§'),
'utf8' => array(0x00A7)),
'`' => array('html' => array('́')),
'\'' => array('html' => array('’', '’')),
'x' => array('html' => array('×', '×'),
'utf8' => array('×') /* какой же у него может быть код? */),
);
/**
* Добавление к тегам атрибута 'id', благодаря которому
* при повторном типографирование текста будут удалены теги,
* расставленные данным типографом
*
* @var array
*/
protected static $_typographSpecificTagId = false;
/**
* Костыли для работы с символами UTF-8
*
* @author somebody?
* @param int $c код символа в кодировке UTF-8 (например, 0x00AB)
* @return bool|string
*/
public static function _getUnicodeChar($c)
{
if ($c <= 0x7F) {
return chr($c);
} else if ($c <= 0x7FF) {
return chr(0xC0 | $c >> 6)
. chr(0x80 | $c & 0x3F);
} else if ($c <= 0xFFFF) {
return chr(0xE0 | $c >> 12)
. chr(0x80 | $c >> 6 & 0x3F)
. chr(0x80 | $c & 0x3F);
} else if ($c <= 0x10FFFF) {
return chr(0xF0 | $c >> 18)
. chr(0x80 | $c >> 12 & 0x3F)
. chr(0x80 | $c >> 6 & 0x3F)
. chr(0x80 | $c & 0x3F);
} else {
return false;
}
}
/**
* Удаление кодов HTML из текста
*
* <code>
* // Remove UTF-8 chars:
* $str = EMT_Lib::clear_special_chars('your text', 'utf8');
* // ... or HTML codes only:
* $str = EMT_Lib::clear_special_chars('your text', 'html');
* // ... or combo:
* $str = EMT_Lib::clear_special_chars('your text');
* </code>
*
* @param string $text
* @param mixed $mode
* @return string|bool
*/
public static function clear_special_chars($text, $mode = null)
{
if(is_string($mode)) $mode = array($mode);
if(is_null($mode)) $mode = array('utf8', 'html');
if(!is_array($mode)) return false;
$moder = array();
foreach($mode as $mod) if(in_array($mod, array('utf8','html'))) $moder[] = $mod;
if(count($moder)==0) return false;
foreach (self::$_charsTable as $char => $vals)
{
foreach ($mode as $type)
{
if (isset($vals[$type]))
{
foreach ($vals[$type] as $v)
{
if ('utf8' === $type && is_int($v))
{
$v = self::_getUnicodeChar($v);
}
if ('html' === $type)
{
if(preg_match("/<[a-z]+>/i",$v))
{
$v = self::safe_tag_chars($v, true);
}
}
$text = str_replace($v, $char, $text);
}
}
}
}
return $text;
}
/**
* Удаление тегов HTML из текста
* Тег <br /> будет преобразов в перенос строки \n, сочетание тегов </p><p> -
* в двойной перенос
*
* @param string $text
* @param array $allowableTag массив из тегов, которые будут проигнорированы
* @return string
*/
public static function remove_html_tags($text, $allowableTag = null)
{
$ignore = null;
if (null !== $allowableTag)
{
if (is_string($allowableTag))
{
$allowableTag = array($allowableTag);
}
if (is_array($allowableTag))
{
$tags = array();
foreach ($allowableTag as $tag)
{
if ('<' !== substr($tag, 0, 1) || '>' !== substr($tag, -1, 1)) continue;
if ('/' === substr($tag, 1, 1)) continue;
$tags [] = $tag;
}
$ignore = implode('', $tags);
}
}
$text = preg_replace(array('/\<br\s*\/?>/i', '/\<\/p\>\s*\<p\>/'), array("\n","\n\n"), $text);
$text = strip_tags($text, $ignore);
return $text;
}
/**
* Сохраняем содержимое тегов HTML
*
* Тег 'a' кодируется со специальным префиксом для дальнейшей
* возможности выносить за него кавычки.
*
* @param string $text
* @param bool $safe
* @return string
*/
public static function safe_tag_chars($text, $way)
{
if ($way)
$text = preg_replace_callback('/(\<\/?)([^<>]+?)(\>)/s', create_function('$m','return (strlen($m[1])==1 && substr(trim($m[2]), 0, 1) == \'-\' && substr(trim($m[2]), 1, 1) != \'-\')? $m[0] : $m[1].( substr(trim($m[2]), 0, 1) === "a" ? "%%___" : "" ) . EMT_Lib::encrypt_tag(trim($m[2])) . $m[3];'), $text);
else
$text = preg_replace_callback('/(\<\/?)([^<>]+?)(\>)/s', create_function('$m','return (strlen($m[1])==1 && substr(trim($m[2]), 0, 1) == \'-\' && substr(trim($m[2]), 1, 1) != \'-\')? $m[0] : $m[1].( substr(trim($m[2]), 0, 3) === "%%___" ? EMT_Lib::decrypt_tag(substr(trim($m[2]), 4)) : EMT_Lib::decrypt_tag(trim($m[2])) ) . $m[3];'), $text);
return $text;
}
/**
* Декодриует спец блоки
*
* @param string $text
* @return string
*/
public static function decode_internal_blocks($text)
{
$text = preg_replace_callback('/'.EMT_Lib::INTERNAL_BLOCK_OPEN.'([a-zA-Z0-9\/=]+?)'.EMT_Lib::INTERNAL_BLOCK_CLOSE.'/s', create_function('$m','return EMT_Lib::decrypt_tag($m[1]);'), $text);
return $text;
}
/**
* Кодирует спец блок
*
* @param string $text
* @return string
*/
public static function iblock($text)
{
return EMT_Lib::INTERNAL_BLOCK_OPEN. EMT_Lib::encrypt_tag($text).EMT_Lib::INTERNAL_BLOCK_CLOSE;
}
/**
* Создание тега с защищенным содержимым
*
* @param string $content текст, который будет обрамлен тегом
* @param string $tag тэг
* @param array $attribute список атрибутов, где ключ - имя атрибута, а значение - само значение данного атрибута
* @return string
*/
public static function build_safe_tag($content, $tag = 'span', $attribute = array(), $layout = EMT_Lib::LAYOUT_STYLE )
{
$htmlTag = $tag;
if (self::$_typographSpecificTagId)
{
if(!isset($attribute['id']))
{
$attribute['id'] = 'emt-2' . mt_rand(1000,9999);
}
}
$classname = "";
if (count($attribute))
{
if($layout & EMT_lib::LAYOUT_STYLE)
{
if(isset($attribute['__style']) && $attribute['__style'])
{
if(isset($attribute['style']) && $attribute['style'])
{
$st = trim($attribute['style']);
if(mb_substr($st, -1) != ";") $st .= ";";
$st .= $attribute['__style'];
$attribute['style'] = $st;
} else {
$attribute['style'] = $attribute['__style'];
}
unset($attribute['__style']);
}
}
foreach ($attribute as $attr => $value)
{
if($attr == "__style") continue;
if($attr == "class") {
$classname = "$value";
continue;
}
$htmlTag .= " $attr=\"$value\"";
}
}
if( ($layout & EMT_lib::LAYOUT_CLASS ) && $classname) {
$htmlTag .= " class=\"$classname\"";
}
return "<" . self::encrypt_tag($htmlTag) . ">$content</" . self::encrypt_tag($tag) . ">";
}
/**
* Метод, осуществляющий кодирование (сохранение) информации
* с целью невозможности типографировать ее
*
* @param string $text
* @return string
*/
public static function encrypt_tag($text)
{
return base64_encode($text)."=";
}
/**
* Метод, осуществляющий декодирование информации
*
* @param string $text
* @return string
*/
public static function decrypt_tag($text)
{
return base64_decode(substr($text,0,-1));
}
public static function strpos_ex(&$haystack, $needle, $offset = null)
{
if(is_array($needle))
{
$m = false;
$w = false;
foreach($needle as $n)
{
$p = strpos($haystack, $n , $offset);
if($p===false) continue;
if($m === false)
{
$m = $p;
$w = $n;
continue;
}
if($p < $m)
{
$m = $p;
$w = $n;
}
}
if($m === false) return false;
return array('pos' => $m, 'str' => $w);
}
return strpos($haystack, $needle, $offset);
}
public static function _process_selector_pattern(&$pattern)
{
if($pattern===false) return;
$pattern = preg_quote($pattern , '/');
$pattern = str_replace("\\*", "[a-z0-9_\-]*", $pattern);
$pattern = "/".$pattern."/i";
}
public static function _test_pattern($pattern, $text)
{
if($pattern === false) return true;
return preg_match($pattern, $text);
}
public static function strtolower($string)
{
$convert_to = array(
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
"v", "w", "x", "y", "z", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï",
"ð", "ñ", "ò", "ó", "ô", "õ", "ö", "ø", "ù", "ú", "û", "ü", "ý", "а", "б", "в", "г", "д", "е", "ё", "ж",
"з", "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ы",
"ь", "э", "ю", "я"
);
$convert_from = array(
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
"V", "W", "X", "Y", "Z", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï",
"Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "А", "Б", "В", "Г", "Д", "Е", "Ё", "Ж",
"З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ъ",
"Ь", "Э", "Ю", "Я"
);
return str_replace($convert_from, $convert_to, $string);
}
// взято с http://www.w3.org/TR/html4/sgml/entities.html
protected static $html4_char_ents = array(
'nbsp' => 160,
'iexcl' => 161,
'cent' => 162,
'pound' => 163,
'curren' => 164,
'yen' => 165,
'brvbar' => 166,
'sect' => 167,
'uml' => 168,
'copy' => 169,
'ordf' => 170,
'laquo' => 171,
'not' => 172,
'shy' => 173,
'reg' => 174,
'macr' => 175,
'deg' => 176,
'plusmn' => 177,
'sup2' => 178,
'sup3' => 179,
'acute' => 180,
'micro' => 181,
'para' => 182,
'middot' => 183,
'cedil' => 184,
'sup1' => 185,
'ordm' => 186,
'raquo' => 187,
'frac14' => 188,
'frac12' => 189,
'frac34' => 190,
'iquest' => 191,
'Agrave' => 192,
'Aacute' => 193,
'Acirc' => 194,
'Atilde' => 195,
'Auml' => 196,
'Aring' => 197,
'AElig' => 198,
'Ccedil' => 199,
'Egrave' => 200,
'Eacute' => 201,
'Ecirc' => 202,
'Euml' => 203,
'Igrave' => 204,
'Iacute' => 205,
'Icirc' => 206,
'Iuml' => 207,
'ETH' => 208,
'Ntilde' => 209,
'Ograve' => 210,
'Oacute' => 211,
'Ocirc' => 212,
'Otilde' => 213,
'Ouml' => 214,
'times' => 215,
'Oslash' => 216,
'Ugrave' => 217,
'Uacute' => 218,
'Ucirc' => 219,
'Uuml' => 220,
'Yacute' => 221,
'THORN' => 222,
'szlig' => 223,
'agrave' => 224,
'aacute' => 225,
'acirc' => 226,
'atilde' => 227,
'auml' => 228,
'aring' => 229,
'aelig' => 230,
'ccedil' => 231,
'egrave' => 232,
'eacute' => 233,
'ecirc' => 234,
'euml' => 235,
'igrave' => 236,
'iacute' => 237,
'icirc' => 238,
'iuml' => 239,
'eth' => 240,
'ntilde' => 241,
'ograve' => 242,
'oacute' => 243,
'ocirc' => 244,
'otilde' => 245,
'ouml' => 246,
'divide' => 247,
'oslash' => 248,
'ugrave' => 249,
'uacute' => 250,
'ucirc' => 251,
'uuml' => 252,
'yacute' => 253,
'thorn' => 254,
'yuml' => 255,
'fnof' => 402,
'Alpha' => 913,
'Beta' => 914,
'Gamma' => 915,
'Delta' => 916,
'Epsilon' => 917,
'Zeta' => 918,
'Eta' => 919,
'Theta' => 920,
'Iota' => 921,
'Kappa' => 922,
'Lambda' => 923,
'Mu' => 924,
'Nu' => 925,
'Xi' => 926,
'Omicron' => 927,
'Pi' => 928,
'Rho' => 929,
'Sigma' => 931,
'Tau' => 932,
'Upsilon' => 933,
'Phi' => 934,
'Chi' => 935,
'Psi' => 936,
'Omega' => 937,
'alpha' => 945,
'beta' => 946,
'gamma' => 947,
'delta' => 948,
'epsilon' => 949,
'zeta' => 950,
'eta' => 951,
'theta' => 952,
'iota' => 953,
'kappa' => 954,
'lambda' => 955,
'mu' => 956,
'nu' => 957,
'xi' => 958,
'omicron' => 959,
'pi' => 960,
'rho' => 961,
'sigmaf' => 962,
'sigma' => 963,
'tau' => 964,
'upsilon' => 965,
'phi' => 966,
'chi' => 967,
'psi' => 968,
'omega' => 969,
'thetasym' => 977,
'upsih' => 978,
'piv' => 982,
'bull' => 8226,
'hellip' => 8230,
'prime' => 8242,
'Prime' => 8243,
'oline' => 8254,
'frasl' => 8260,
'weierp' => 8472,
'image' => 8465,
'real' => 8476,
'trade' => 8482,
'alefsym' => 8501,
'larr' => 8592,
'uarr' => 8593,
'rarr' => 8594,
'darr' => 8595,
'harr' => 8596,
'crarr' => 8629,
'lArr' => 8656,
'uArr' => 8657,
'rArr' => 8658,
'dArr' => 8659,
'hArr' => 8660,
'forall' => 8704,
'part' => 8706,
'exist' => 8707,
'empty' => 8709,
'nabla' => 8711,
'isin' => 8712,
'notin' => 8713,
'ni' => 8715,
'prod' => 8719,
'sum' => 8721,
'minus' => 8722,
'lowast' => 8727,
'radic' => 8730,
'prop' => 8733,
'infin' => 8734,
'ang' => 8736,
'and' => 8743,
'or' => 8744,
'cap' => 8745,
'cup' => 8746,
'int' => 8747,
'there4' => 8756,
'sim' => 8764,
'cong' => 8773,
'asymp' => 8776,
'ne' => 8800,
'equiv' => 8801,
'le' => 8804,
'ge' => 8805,
'sub' => 8834,
'sup' => 8835,
'nsub' => 8836,
'sube' => 8838,
'supe' => 8839,
'oplus' => 8853,
'otimes' => 8855,
'perp' => 8869,
'sdot' => 8901,
'lceil' => 8968,
'rceil' => 8969,
'lfloor' => 8970,
'rfloor' => 8971,
'lang' => 9001,
'rang' => 9002,
'loz' => 9674,
'spades' => 9824,
'clubs' => 9827,
'hearts' => 9829,
'diams' => 9830,
'quot' => 34,
'amp' => 38,
'lt' => 60,
'gt' => 62,
'OElig' => 338,
'oelig' => 339,
'Scaron' => 352,
'scaron' => 353,
'Yuml' => 376,
'circ' => 710,
'tilde' => 732,
'ensp' => 8194,
'emsp' => 8195,
'thinsp' => 8201,
'zwnj' => 8204,
'zwj' => 8205,
'lrm' => 8206,
'rlm' => 8207,
'ndash' => 8211,
'mdash' => 8212,
'lsquo' => 8216,
'rsquo' => 8217,
'sbquo' => 8218,
'ldquo' => 8220,
'rdquo' => 8221,
'bdquo' => 8222,
'dagger' => 8224,
'Dagger' => 8225,
'permil' => 8240,
'lsaquo' => 8249,
'rsaquo' => 8250,
'euro' => 8364,
);
/**
* Вернуть уникод символ по html entinty
*
* @param string $entity
* @return string
*/
public static function html_char_entity_to_unicode($entity)
{
if(isset(self::$html4_char_ents[$entity])) return self::_getUnicodeChar(self::$html4_char_ents[$entity]);
return false;
}
/**
* Сконвериторвать все html entity в соответсвующие юникод символы
*
* @param string $text
*/
public static function convert_html_entities_to_unicode(&$text)
{
$text = preg_replace_callback("/\&#([0-9]+)\;/",
create_function('$m', 'return EMT_Lib::_getUnicodeChar(intval($m[1]));')
, $text);
$text = preg_replace_callback("/\&#x([0-9A-F]+)\;/",
create_function('$m', 'return EMT_Lib::_getUnicodeChar(hexdec($m[1]));')
, $text);
$text = preg_replace_callback("/\&([a-zA-Z0-9]+)\;/",
create_function('$m', '$r = EMT_Lib::html_char_entity_to_unicode($m[1]); return $r ? $r : $m[0];')
, $text);
}
public static function rstrpos ($haystack, $needle, $offset = 0){
if(trim($haystack) != "" && trim($needle) != "" && $offset <= mb_strlen($haystack))
{
$last_pos = $offset;
$found = false;
while(($curr_pos = mb_strpos($haystack, $needle, $last_pos)) !== false)
{
$found = true;
$last_pos = $curr_pos + 1;
}
if($found)
{
return $last_pos - 1;
}
else
{
return false;
}
}
else
{
return false;
}
}
public static function ifop($cond, $true, $false) {
return $cond ? $true : $false;
}
function split_number($num) {
return number_format($num, 0, '', ' ');
}
}
/**
* Базовый класс для группы правил обработки текста
* Класс группы должен наследовать, данный класс и задавать
* в нём EMT_Tret::rules и EMT_Tret::$name
*
*/
class EMT_Tret {
/**
* Набор правил в данной группе, который задан изначально
* Его можно менять динамически добавляя туда правила с помощью put_rule
*
* @var unknown_type
*/
public $rules;
public $title;
private $disabled = array();
private $enabled = array();
protected $_text= '';
public $logging = false;
public $logs = false;
public $errors = false;
public $debug_enabled = false;
public $debug_info = array();
private $use_layout = false;
private $use_layout_set = false;
private $class_layout_prefix = false;
public $class_names = array();
public $classes = array();
public $settings = array();
/**
* Защищенные теги
*
* @todo привязать к методам из Jare_Typograph_Tool
*/
const BASE64_PARAGRAPH_TAG = 'cA==='; // p
const BASE64_BREAKLINE_TAG = 'YnIgLw==='; // br / (с пробелом и слэшем)
const BASE64_NOBR_OTAG = 'bm9icg==='; // nobr
const BASE64_NOBR_CTAG = 'L25vYnI=='; // /nobr
/**
* Типы кавычек
*/
const QUOTE_FIRS_OPEN = '«';
const QUOTE_FIRS_CLOSE = '»';
const QUOTE_CRAWSE_OPEN = '„';
const QUOTE_CRAWSE_CLOSE = '“';
private function log($str, $data = null)
{
if(!$this->logging) return;
$this->logs[] = array('info' => $str, 'data' => $data);
}
private function error($info, $data = null)
{
$this->errors[] = array('info' => $info, 'data' => $data);
$this->log('ERROR: '. $info , $data);
}
public function debug($place, &$after_text)
{
if(!$this->debug_enabled) return;
$this->debug_info[] = array(
'place' => $place,
'text' => $after_text,
);
}
/**
* Установить режим разметки для данного Трэта если не было раньше установлено,
* EMT_Lib::LAYOUT_STYLE - с помощью стилей
* EMT_Lib::LAYOUT_CLASS - с помощью классов
*
* @param int $kind
*/
public function set_tag_layout_ifnotset($layout)
{
if($this->use_layout_set) return;
$this->use_layout = $layout;
}
/**
* Установить режим разметки для данного Трэта,
* EMT_Lib::LAYOUT_STYLE - с помощью стилей
* EMT_Lib::LAYOUT_CLASS - с помощью классов
* EMT_Lib::LAYOUT_STYLE|EMT_Lib::LAYOUT_CLASS - оба метода
*
* @param int $kind
*/
public function set_tag_layout($layout = EMT_Lib::LAYOUT_STYLE)
{
$this->use_layout = $layout;
$this->use_layout_set = true;
}
public function set_class_layout_prefix($prefix)
{
$this->class_layout_prefix = $prefix;
}
public function debug_on()
{
$this->debug_enabled = true;
}
public function log_on()
{
$this->debug_enabled = true;
}
private function getmethod($name)
{
if(!$name) return false;
if(!method_exists($this, $name)) return false;
return array($this, $name);
}
private function _pre_parse()
{
$this->pre_parse();
foreach($this->rules as $rule)
{
if(!isset($rule['init'])) continue;
$m = $this->getmethod($rule['init']);
if(!$m) continue;
call_user_func($m);
}
}
private function _post_parse()
{
foreach($this->rules as $rule)
{
if(!isset($rule['deinit'])) continue;
$m = $this->getmethod($rule['deinit']);
if(!$m) continue;
call_user_func($m);
}
$this->post_parse();
}
private function rule_order_sort($a, $b)
{
if($a['order'] == $b['order']) return 0;
if($a['order'] < $b['order']) return -1;
return 1;
}
private function apply_rule($rule)
{
$name = $rule['id'];
//$this->log("Правило $name", "Применяем правило");
$disabled = (isset($this->disabled[$rule['id']]) && $this->disabled[$rule['id']]) || ((isset($rule['disabled']) && $rule['disabled']) && !(isset($this->enabled[$rule['id']]) && $this->enabled[$rule['id']]));
if($disabled)
{
$this->log("Правило $name", "Правило отключено" . ((isset($rule['disabled']) && $rule['disabled'])? " (по умолчанию)" : ""));
return;
}
if(isset($rule['function']) && $rule['function'])
{
if(!(isset($rule['pattern']) && $rule['pattern']))
{
if(method_exists($this, $rule['function']))
{
$this->log("Правило $name", "Используется метод ".$rule['function']." в правиле");
call_user_func(array($this, $rule['function']));
return;
}
if(function_exists($rule['function']))
{
$this->log("Правило $name", "Используется функция ".$rule['function']." в правиле");
call_user_func($rule['function']);
return;
}
$this->error('Функция '.$rule['function'].' из правила '.$rule['id']. " не найдена");
return ;
} else {
if(preg_match("/^[a-z_0-9]+$/i", $rule['function']))
{
if(method_exists($this, $rule['function']))
{
$this->log("Правило $name", "Замена с использованием preg_replace_callback с методом ".$rule['function']."");
$this->_text = preg_replace_callback($rule['pattern'], array($this, $rule['function']), $this->_text);
return;
}
if(function_exists($rule['function']))
{
$this->log("Правило $name", "Замена с использованием preg_replace_callback с функцией ".$rule['function']."");
$this->_text = preg_replace_callback($rule['pattern'], $rule['function'], $this->_text);
return;
}
$this->error('Функция '.$rule['function'].' из правила '.$rule['id']. " не найдена");
} else {
$this->_text = preg_replace_callback($rule['pattern'], create_function('$m', $rule['function']), $this->_text);
$this->log('Замена с использованием preg_replace_callback с инлайн функцией из правила '.$rule['id']);
return;
}
return ;
}
}
if(isset($rule['simple_replace']) && $rule['simple_replace'])
{
if(isset($rule['case_sensitive']) && $rule['case_sensitive'])
{
$this->log("Правило $name", "Простая замена с использованием str_replace");
$this->_text = str_replace($rule['pattern'], $rule['replacement'], $this->_text);
return;
}
$this->log("Правило $name", "Простая замена с использованием str_ireplace");
$this->_text = str_ireplace($rule['pattern'], $rule['replacement'], $this->_text);
return;
}
$pattern = $rule['pattern'];
if(is_string($pattern)) $pattern = array($pattern);
$eval = false;
foreach($pattern as $patt)
{
$chr = substr($patt,0,1);
$preg_arr = explode($chr, $patt);
if(strpos($preg_arr[count($preg_arr)-1], "e")!==false)
{
$eval = true;
break;
}
}
if(!$eval)
{
$this->log("Правило $name", "Замена с использованием preg_replace");
do {
$this->_text = preg_replace($rule['pattern'], $rule['replacement'], $this->_text);
if(!(isset($rule['cycled']) && $rule['cycled'])) break;
} while(preg_match($rule['pattern'], $this->_text));
return;
}
$this->log("Правило $name", "Замена с использованием preg_replace_callback вместо eval");
$k = 0;
foreach($pattern as $patt)
{
$repl = is_string($rule['replacement']) ? $rule['replacement'] : $rule['replacement'][$k];
$chr = substr($patt,0,1);
$preg_arr = explode($chr, $patt);
if(strpos($preg_arr[count($preg_arr)-1], "e")!==false) // eval система
{
$preg_arr[count($preg_arr)-1] = str_replace("e","",$preg_arr[count($preg_arr)-1]);
$patt = implode($chr, $preg_arr);
$this->thereplacement = $repl;
do {
$this->_text = preg_replace_callback($patt, array($this, "thereplcallback"), $this->_text);
if(!(isset($rule['cycled']) && $rule['cycled'])) break;
} while(preg_match($patt, $this->_text));
} else {
do {
$this->_text = preg_replace($patt, $repl, $this->_text);
if(!(isset($rule['cycled']) && $rule['cycled'])) break;
} while(preg_match($patt, $this->_text));
}
$k++;
}
}
protected function preg_replace_e($pattern, $replacement, $text)
{
$chr = substr($pattern,0,1);
$preg_arr = explode($chr, $pattern);
if(strpos($preg_arr[count($preg_arr)-1], "e")===false) return preg_replace($pattern, $replacement, $text);
$preg_arr[count($preg_arr)-1] = str_replace("e","",$preg_arr[count($preg_arr)-1]);
$patt = implode($chr, $preg_arr);
$this->thereplacement = $replacement;
return preg_replace_callback($patt, array($this, "thereplcallback"), $text);
}