/
HTML.php
1845 lines (1697 loc) · 87.1 KB
/
HTML.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
/**
* Класс для обработки HTML
*
* @created 2009-12-02
* @license http://creativecommons.org/licenses/by-sa/3.0/
* @author Nasibullin Rinat: http://orangetie.ru/, http://rin-nas.moikrug.ru/
* @charset UTF-8
* @version 2.0.11
*/
class HTML
{
/**
* Regular expression for tag attributes.
* Correct parse dirty and broken HTML in a singlebyte or multibyte UTF-8 charset!
*
* В библиотеке PCRE для PHP \s - это любой пробельный символ, а именно класс символов [\x09\x0a\x0c\x0d\x20\xa0] или, по другому, [\t\n\f\r \xa0]
* Если \s используется с модификатором /u, то \s трактуется как [\x09\x0a\x0c\x0d\x20]
*
* @var string
*/
public static $re_attrs = '(?![a-zA-Z\d]) #statement, which follows after a tag
#correct attributes
(?>
[^>"\'`]++
| (?<=[\=\x00-\x20\x7f]|\xc2\xa0) "[^"]*+"
| (?<=[\=\x00-\x20\x7f]|\xc2\xa0) \'[^\']*+\'
| (?<=[\=\x00-\x20\x7f]|\xc2\xa0) `[^`]*+`
)*+
#incorrect attributes
[^>]*+';
/**
* Допустимые тэги и атрибуты, которым присваивается URL
* Служебные атрибуты: alt, title, target, rel
* @var array
*/
public static $url_tags = array(
'body' => 'background',
'table' => 'background',
'tr' => 'background',
'td' => 'background',
'img' => 'src|longdesc|alt',
'frame' => 'src|longdesc',
'iframe' => 'src|longdesc',
'input' => 'src|alt',
'script' => 'src',
'a' => 'href|title|rel|target',
'area' => 'href|alt|rel|target',
'link' => 'href|title|rel',
'base' => 'href',
'object' => 'classid|codebase|data|usemap',
'applet' => 'codebase|alt', #HTML-4.01 deprecated tag
'form' => 'action',
'q' => 'cite',
'ins' => 'cite',
'del' => 'cite',
'blockquote' => 'cite',
'head' => 'profile',
);
/**
* @var array
*/
private static $_safe_tags;
/**
* @var array
*/
private static $_safe_attrs;
/**
* @var array
*/
private static $_safe_attr_links;
/**
* @var array
*/
private static $_safe_protocols;
/**
* @var array
*/
private static $_normalize_links;
/**
* @var array
*/
private static $_subdomains_map = array();
#запрещаем создание экземпляра класса, вызов методов этого класса только статически!
private function __construct() {}
/**
*
* @param array|null $subdomains_map
* Пример:
* array(
* 'static' => 'http://yandex.st',
* 'resize' => 'http://resize.yandex.ru',
* 'feedback' => 'http://feedback.yandex.ru',
* )
*/
public static function init(array $subdomains_map = null)
{
if ($subdomains_map) self::$_subdomains_map = $subdomains_map;
}
/**
* Возвращает строку с HTML кодом атрибутов для использования в тэге.
* Все названия атрибутов преобразуются в нижний регистр.
*
* @param array|null $attrs Массив атрибутов тэгов
* @param string $delim Для значения атрибута в виде массива используется
* разделитель, через который будет склейка массива в строку
* @param bool $is_null_value_check Если значение одного из атрибутов равно NULL, возвращается NULL
* @return string|bool|null Returns FALSE if error occured
*/
public static function attrs($attrs, $delim = ', ', $is_null_value_check = false)
{
if (! ReflectionTypeHint::isValid()) return false;
if (is_null($attrs)) return null;
$a = array();
foreach ($attrs as $attr => $value)
{
if ($is_null_value_check && is_null($value)) return null;
$attr = strtolower($attr);
if (is_bool($value))
{
if ($value) $a[] = $attr . '="' . htmlspecialchars($attr) . '"';
continue;
}
if (is_array($value))
{
if ($attr === 'class') $delim = ' ';
elseif ($attr === 'style' || preg_match('/^on[a-z]+/siSX', $attr)) $delim = ';';
elseif (array_key_exists($attr, self::_url_attrs())
&& strpos('alt|title|target|rel', $attr) === false) $value = URL::build($value);
if (is_array($value)) $value = implode($delim, $value);
}
if (is_scalar($value)) $a[] = $attr . '="' . htmlspecialchars($value) . '"';
}
return implode(' ', $a);
}
/**
* Возвращает строку с HTML кодом непарного тэга.
*
* @param string $name Название тэга
* @param array|null $attrs Массив атрибутов тэгов
* @param bool $is_null_value_check Если значение одного из атрибутов равно NULL, то тэг не выводится
* @return string|bool|null Returns FALSE if error occured
*/
public function tag($name, array $attrs = null, $is_null_value_check = true)
{
if (! ReflectionTypeHint::isValid()) return false;
$attrs = self::attrs($attrs, ', ', $is_null_value_check);
if (! is_string($attrs)) return $attrs;
if (strlen($attrs) > 0) $attrs = ' ' . $attrs;
return '<' . strtolower($name) . $attrs . ' />';
}
/**
* Возвращает строку с URL для использования в атрибутах тэгов,
* например для <a href="...">, <img src="..."> и др.
*
* @param string|array|null $s
* @param bool $is_html_quote
* @return string|bool|null
*/
public static function url($s, $is_html_quote = true)
{
if (! ReflectionTypeHint::isValid()) return false;
if (is_null($s)) return $s;
if (is_array($s)) $s = URL::build($s);
if ($s === false) return false;
return $is_html_quote ? htmlspecialchars($s) : $s;
}
/**
* Формирование ссылки на файл.
* Для файлов, имеющих расширение через точку и не имеющих знака вопроса,
* дописывается время модификации в unixtime, например:
* /path/to/file.ext?12345678 (файл найден)
* /path/to/file.ext?0#404 (файл не найден)
*
* @param string|null $filename
* @param bool $is_html_quote
* @return string|bool|null
*/
public static function src($filename, $is_html_quote = true)
{
if (! ReflectionTypeHint::isValid()) return false;
if (is_null($filename)) return $filename;
$dir = dirname($_SERVER['SCRIPT_FILENAME']);
$www_dir = substr($dir, strlen($_SERVER['DOCUMENT_ROOT']));
$query_string = '';
if (substr($filename, 0, 2) === '//') $s = $www_dir . substr_replace($filename, '/' . $_REQUEST['lang'] . '/', 0, 2);
#смотрим наличие протокола (ftp://, http://, mysql://, ...)
elseif (strpos($filename, '://') !== false && preg_match('~^[a-z][-a-z\d_]{2,19}+(?<![-_]):\/\/~sSX', $filename)) $s = $filename;
elseif (strpos($filename, '?') === false &&
#смотрим наличие расширения файла
pathinfo($filename, PATHINFO_EXTENSION) &&
#смотрим наличие номера версии, например: /ajax/libs/jquery/1.4.2/jquery.min.js
! preg_match('~\d\.\d~sSX', $filename))
{
$mtime = file_exists($dir . $filename) ? @filemtime($dir . $filename) : null;
$s = $www_dir . $filename . $query_string = '?' . intval($mtime);
if (! $mtime) $s .= '#404'; #специальная сигнатура '?0#404' может облегчить поиск ошибок в HTML коде
}
else $s = $www_dir . rtrim($filename, '?') . $query_string;
return $is_html_quote ? htmlspecialchars($s) : $s;
}
/**
*
* @param scalar|array|null $s
* @param string|null $delim
* @return string|bool|null returns FALSE if error occured
*/
public static function quote($s, $delim = null)
{
if (! ReflectionTypeHint::isValid()) return false;
if (is_null($s)) return $s;
if (is_array($s))
{
if ($delim === null)
{
trigger_error('If 1-st parameter an array, a string type expected in 2-nd paramater, ' . gettype($delim) . ' given', E_USER_WARNING);
return false;
}
$s = implode($delim, $s);
}
return htmlspecialchars($s);
}
/**
* Convert special HTML entities back to characters
* @param string|null $s
* @param int $quote_style
* ENT_COMPAT Will convert double-quotes and leave single-quotes alone (default)
* ENT_QUOTES Will convert both double and single quotes
* ENT_NOQUOTES Will leave both double and single quotes unconverted
* @return string|bool|null
*/
public static function unquote($s, $quote_style = ENT_COMPAT)
{
if (! ReflectionTypeHint::isValid()) return false;
if (is_null($s)) return $s;
return htmlspecialchars_decode($s, $quote_style);
}
/**
* Более продвинутый аналог strip_tags() для корректного вырезания тэгов из html кода.
* Функция strip_tags(), в зависимости от контекста, может работать некорректно.
* Возможности:
* - корректно обрабатываются вхождения типа "a < b > c"
* - корректно обрабатывается "грязный" html, когда в значениях атрибутов тэгов могут встречаться символы < >
* - корректно обрабатывается разбитый html
* - вырезаются комментарии, скрипты, стили, PHP, Perl, ASP код, MS Word тэги, CDATA
* - автоматически форматируется текст, если он содержит html код
* - защита от подделок типа: "<<fake>script>alert('hi')</</fake>script>"
*
* @param string|array|null $s
* @param array|null $allowable_tags Массив тэгов, которые не будут вырезаны
* Пример: 'b' -- тэг останется с атрибутами, '<b>' -- тэг останется без атрибутов
* @param bool $is_format_spaces Форматировать пробелы и переносы строк?
* Вид текста на выходе (plain) максимально приближеется виду текста в браузере на входе.
* Другими словами, грамотно преобразует text/html в text/plain.
* Текст форматируется только в том случае, если были вырезаны какие-либо тэги.
* @param array $pair_tags Массив имён парных тэгов, которые будут удалены вместе с содержимым
* См. значения по умолчанию
* @param array $para_tags Массив имён парных тэгов, которые будут восприниматься как параграфы (если $is_format_spaces = true)
* См. значения по умолчанию
* @return string|bool|null
*/
public static function strip_tags(
$s,
array $allowable_tags = null,
$is_format_spaces = true,
array $pair_tags = array('script', 'style', 'map', 'iframe', 'frameset', 'object', 'applet', 'comment', 'button', 'textarea', 'select'),
array $para_tags = array(
#Paragraph boundaries are inserted at every block-level HTML tag. Namely, those are (as taken from HTML 4 standard)
'address', 'blockquote', 'caption', 'center', 'dd', 'div', 'dl', 'dt', 'h1', 'h2', 'h3', 'h4', 'h5', 'li', 'menu', 'ol', 'p', 'pre', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'ul',
#Extended
'form', 'title',
)
)
{
if (! ReflectionTypeHint::isValid()) return false;
if (is_null($s)) return $s;
static $_callback_type = false;
static $_allowable_tags = array();
static $_para_tags = array();
if (is_array($s))
{
if ($_callback_type === 'strip_tags')
{
$tag = strtolower($s[1]);
if ($_allowable_tags)
{
#tag with attributes
if (array_key_exists($tag, $_allowable_tags)) return $s[0];
#tag without attributes
if (array_key_exists('<' . $tag . '>', $_allowable_tags))
{
if (substr($s[0], 0, 2) === '</') return '</' . $tag . '>';
if (substr($s[0], -2) === '/>') return '<' . $tag . ' />';
return '<' . $tag . '>';
}
}
if ($tag === 'br') return "\r\n";
if ($_para_tags && array_key_exists($tag, $_para_tags)) return "\r\n\r\n";
return '';
}
trigger_error('Unknown callback type "' . $_callback_type . '"!', E_USER_ERROR);
}
if (($pos = strpos($s, '<')) === false || strpos($s, '>', $pos) === false) #speed improve
{
#tags are not found
return $s;
}
$length = strlen($s);
#unpaired tags (opening, closing, !DOCTYPE, MS Word namespace)
$re_tags = '~ <[/!]?+
(
[a-zA-Z][a-zA-Z\d]*+
(?>:[a-zA-Z][a-zA-Z\d]*+)?
) #1
' . self::$re_attrs . '
>
~sxSX';
$patterns = array(
'/<([\?\%]) .*? \\1>/sxSX', #встроенный PHP, Perl, ASP код
'/<\!\[CDATA\[ .*? \]\]>/sxSX', #блоки CDATA
#'/<\!\[ [\x20\r\n\t]* [a-zA-Z] .*? \]>/sxSX', #DEPRECATED MS Word тэги типа <![if! vml]>...<![endif]>
'/<\!--.*?-->/sSX', #комментарии
#MS Word тэги типа "<![if! vml]>...<![endif]>",
#условное выполнение кода для IE типа "<!--[if expression]> HTML <![endif]-->"
#условное выполнение кода для IE типа "<![if expression]> HTML <![endif]>"
#см. http://www.tigir.com/comments.htm
'/ <\! (?:--)?+
\[
(?> [^\]"\']+ | "[^"]*" | \'[^\']*\' )*
\]
(?:--)?+
>
/sxSX',
);
if ($pair_tags)
{
#парные тэги вместе с содержимым:
foreach ($pair_tags as $k => $v) $pair_tags[$k] = preg_quote($v, '/');
$patterns[] = '/ <((?i:' . implode('|', $pair_tags) . '))' . self::$re_attrs . '(?<!\/)>
.*?
<\/(?i:\\1)' . self::$re_attrs . '>
/sxSX';
#на больших текстах может быть PREG_BACKTRACK_LIMIT_ERROR, увеличиваем ограничение
ini_set('pcre.backtrack_limit', 1000000);
}
$i = 0; #защита от зацикливания
$max = 99;
while ($i < $max)
{
$s2 = preg_replace($patterns, '', $s);
if ((function_exists('preg_last_error') && preg_last_error() !== PREG_NO_ERROR) || $s2 === false) #PHP >= 5.1.6 support
{
$i = 999;
break;
}
if ($i == 0)
{
$is_html = ($s2 != $s || preg_match($re_tags, $s2));
if (function_exists('preg_last_error') && preg_last_error() !== PREG_NO_ERROR)
{
$i = 999;
break;
}
if ($is_html)
{
if ($is_format_spaces)
{
/*
В библиотеке PCRE для PHP \s - это любой пробельный символ, а именно класс символов [\x09\x0a\x0c\x0d\x20\xa0] или, по другому, [\t\n\f\r \xa0]
Если \s используется с модификатором /u, то \s трактуется как [\x09\x0a\x0c\x0d\x20]
Браузер не делает различия между пробельными символами, друг за другом подряд идущие символы воспринимаются как один
*/
if (version_compare(PHP_VERSION, '5.2.0', '>='))
{
$s2 = preg_replace('/ [\x09\x0a\x0c\x0d]++
| <((?i:pre|textarea))' . self::$re_attrs . '(?<!\/)> #1
.+?
<\/(?i:\\1)' . self::$re_attrs . '>
\K
/sxSX', ' ', $s2);
}
else
{
$s2 = preg_replace('/ [\x09\x0a\x0c\x0d]++
| ( #1
<((?i:pre|textarea))' . self::$re_attrs . '(?<!\/)> #2
.+?
<\/(?i:\\2)' . self::$re_attrs . '>
)
/sxSX', '$1 ', $s2);
}
if ((function_exists('preg_last_error') && preg_last_error() !== PREG_NO_ERROR) || $s2 === false)
{
$i = 999;
break;
}
}
#массив тэгов, которые не будут вырезаны
if ($allowable_tags) $_allowable_tags = array_flip($allowable_tags);
#парные тэги, которые будут восприниматься как параграфы
if ($para_tags) $_para_tags = array_flip($para_tags);
}
}#if
#tags processing
if ($is_html)
{
$_callback_type = 'strip_tags';
$s2 = preg_replace_callback($re_tags, array('self', __FUNCTION__), $s2);
$_callback_type = false;
if ((function_exists('preg_last_error') && preg_last_error() !== PREG_NO_ERROR) || $s2 === false)
{
$i = 999;
break;
}
}
if ($s === $s2) break;
$s = $s2; $i++;
}
if ($i >= $max) $s = strip_tags($s); #too many cycles for replace...
if ($is_format_spaces && strlen($s) !== $length)
{
#remove a duplicate spaces
$s = preg_replace('/\x20\x20++/sSX', ' ', trim($s));
#remove a spaces before and after new lines
$s = str_replace(array("\r\n\x20", "\x20\r\n"), "\r\n", $s);
#replace 3 and more new lines to 2 new lines
$s = preg_replace('/[\r\n]{3,}+/sSX', "\r\n\r\n", $s);
}
return $s;
}
/**
* Определяем наличие html кода (сущности не рассматриваем)
*
* @param string|null $s Текст
* @param array|null $no_html_tags Таги, которые не являются HTML
* @return bool|null
*/
public static function is_html($s, array $no_html_tags = null)
{
if (! ReflectionTypeHint::isValid()) return false;
if ($s === null) return null;
$regexp = '~(?> <[a-zA-Z][a-zA-Z\d]*+ {no_html_tags_open_re}' . self::$re_attrs . '> # open pair tag / self-closed tag
| </[a-zA-Z][a-zA-Z\d]*+ {no_html_tags_close_re}> # closed tag
| <!-- .*? --> # comment
| <![A-Z] .*? > # DOCTYPE, ENTITY
| <\!\[CDATA\[ .*? \]\]> # CDATA
| <\? .*? \?> # instructions
| <\% .*? \%> # instructions
# MS Word, IE (Internet Explorer) condition tags
| <! (?:--)?+
\[
(?> [^\]"\'`]+
| "[^"]*"
| \'[^\']*\'
| `[^`]*`
)*+
\]
(?:--)?+
>
)
~sxSX';
$regexp = str_replace('{no_html_tags_open_re}', $no_html_tags ? '(?<!<(?i:' . implode('|', $no_html_tags) . '))' : '', $regexp);
$regexp = str_replace('{no_html_tags_close_re}', $no_html_tags ? '(?<!/(?i:' . implode('|', $no_html_tags) . '))' : '', $regexp);
return (bool) preg_match($regexp, $s);
}
/**
* Разбивает текст на параграфы, используя для этого html тэги (<p></p>, <br />).
* Или, другими словами, переводит текст из text/plain в text/html.
* "Красная строка" (отступ в начале абзаца) поддерживается, дублирующие пробелы вырезаются.
*
* Текст возвращается без изменений если:
* * текст уже содержит html код или
* * текст не содержит переносов строк
*
* @see nl2br()
* @link http://daringfireball.net/projects/markdown/
* @param string|null $s текст
* @param bool $is_single обрамлять тэгами единственно найденный парагаграф?
* @param bool &$is_html возвращает TRUE, если текст явл. HTML кодом, иначе FALSE
* @param array $no_html_tags тэги, которые не являются HTML
* @return string|bool|null returns FALSE if error occured
*/
public static function paragraph($s, $is_single = false, &$is_html = false, array $no_html_tags = array('notypo'))
{
if (! ReflectionTypeHint::isValid()) return false;
if (is_null($s)) return $s;
#определяем наличие html кода
$is_html = self::is_html($s, $no_html_tags);
if (! $is_html)
{
#рег. выражение для разбивки текста text/plain на параграфы
#"красная строка" (отступ в начале абзаца) поддерживается!
$a = preg_split('/(\r\n|[\r\n])(?>[\x20\t]|\\1)+/sSX', trim($s), -1, PREG_SPLIT_NO_EMPTY);
$a = array_map('trim', $a);
$a = preg_replace('/[\r\n]++/sSX', "<br />\r\n", $a);
if (count($a) > intval(! (bool)$is_single)) $s = '<p>' . implode("</p>\r\n\r\n<p>", $a) . '</p>';
else $s = implode('', $a);
$s = preg_replace('/\x20\x20++/sSX', ' ', $s); #вырезаем лишние пробелы
}
return $s;
}
/**
* "Подсветка" найденных слов для результатов поисковых систем.
* Ищет все вхождения цифр или целых слов в html коде и обрамляет их заданными тэгами.
* Текст должен быть в кодировке UTF-8.
*
* @param string|null $s Текст, в котором искать
* @param array|null $words Массив поисковых слов
* @param bool $is_case_sensitive Искать с учётом от регистра?
* @param string $tpl HTML шаблон для замены
* @return string|bool|null returns FALSE if error occured
*/
public static function words_highlight(
$s,
array $words = null,
$is_case_sensitive = false,
$tpl = '<span class="highlight">%s</span>')
{
if (! ReflectionTypeHint::isValid()) return false;
if (is_null($s)) return $s;
#оптимизация для пустых значений
if (! strlen($s) || ! $words) return $s;
#оптимизация
#{{{
$s2 = UTF8::lowercase($s);
foreach ($words as $k => $word)
{
$word = UTF8::lowercase(trim($word, "\x00..\x20\x7f*"));
if ($word == '' || strpos($s2, $word) === false) unset($words[$k]);
}
if (! $words) return $s;
#}}}
#d($words);
#кэширование построения рег. выражения для "подсвечивания" слов в функции при повторных вызовах
static $func_cache = array();
$cache_id = md5(serialize(array($words, $is_case_sensitive, $tpl)));
if (! array_key_exists($cache_id, $func_cache))
{
$re_words = array();
foreach ($words as $word)
{
$is_mask = (substr($word, -1) === '*');
if ($is_mask) $word = rtrim($word, '*');
$is_digit = ctype_digit($word);
#рег. выражение для поиска слова с учётом регистра или цифр:
$re_word = preg_quote($word, '~');
#рег. выражение для поиска слова НЕЗАВИСИМО от регистра:
if (! $is_case_sensitive && ! $is_digit)
{
if (UTF8::is_ascii($word)) $re_word = '(?i:' . $re_word . ')';
#для русских и др. букв, т. к. флаг /u и (?i:слово) не помогают :(
else
{
$lc = UTF8::str_split(UTF8::lowercase($re_word));
$uc = UTF8::str_split(UTF8::uppercase($re_word));
$re_word = array();
foreach ($lc as $i => $tmp)
{
$re_word[] = '[' . $lc[$i] . $uc[$i] . ']';
}
$re_word = implode('', $re_word);
}
}
#d($re_word);
if ($is_digit) $append = $is_mask ? '\d*+' : '(?!\d)';
else $append = $is_mask ? '\p{L}*+' : '(?!\p{L})';
$re_words[$is_digit ? 'digits' : 'words'][] = $re_word . $append;
}
if (array_key_exists('words', $re_words) && $re_words['words'])
{
#поиск вхождения слова:
$re_words['words'] = '(?<!\p{L}) #просмотр назад (\b не подходит и работает медленнее)
(?:' . implode(PHP_EOL . '| ', $re_words['words']) . ')
';
}
if (array_key_exists('digits', $re_words) && $re_words['digits'])
{
#поиск вхождения цифры:
$re_words['digits'] = '(?<!\d) #просмотр назад (\b не подходит и работает медленнее)
(?:' . implode(PHP_EOL . '| ', $re_words['digits']) . ')
';
}
#d(implode(PHP_EOL . '| ', $re_words));
$func_cache[$cache_id] = '~(?> #встроенный PHP, Perl, ASP код
<([\?\%]) .*? \\1>
\K
#блоки CDATA
| <\!\[CDATA\[ .*? \]\]>
\K
#MS Word тэги типа "<![if! vml]>...<![endif]>",
#условное выполнение кода для IE типа "<!--[if lt IE 7]>...<![endif]-->":
| <\! (?>--)?
\[
(?> [^\]"\']+ | "[^"]*" | \'[^\']*\' )*
\]
(?>--)?
>
\K
#комментарии
| <\!-- .*? -->
\K
#парные тэги вместе с содержимым
| <((?i:noindex|script|style|comment|button|map|iframe|frameset|object|applet))' . self::$re_attrs . '(?<!/)>
.*?
</(?i:\\2)>
\K
#парные и непарные тэги
| <[/\!]?+[a-zA-Z][a-zA-Z\d]*+' . self::$re_attrs . '>
\K
#html сущности (< > &) (+ корректно обрабатываем код типа &amp;nbsp;)
| &(?> [a-zA-Z][a-zA-Z\d]++
| \#(?> \d{1,4}+
| x[\da-fA-F]{2,4}+
)
);
\K
| ' . implode(PHP_EOL . '| ', $re_words) . '
)
~suxSX';
#d($func_cache[$cache_id]);
}
$s = preg_replace_callback($func_cache[$cache_id], function (array $m) use ($tpl)
{
return ($m[0] !== '') ? sprintf($tpl, $m[0]) : $m[0];
}, $s);
return $s;
}
/**
* Добавляет "водяные знаки" в html код.
* Дописывает "© http://domain.com/" после каждого абзаца текста,
* который не отображается в браузере, но успешно копируется вместе с текстом!
*
* @param string|null $s
* @return string|bool|null returns FALSE if error occured
*/
public static function watermark($s)
{
if (! ReflectionTypeHint::isValid()) return false;
if (is_null($s)) return $s;
return preg_replace_callback('~</(?: p> (?<!<p></p>) (?![\x00-\x20]*+</(?:td|li)>)
| td> (?<!<td></td>) [\x00-\x20]*+ </tr>
| li> (?<!<li></li>) [\x00-\x20]*+ </[ou]l>
)
~sixSX', array('self', '_watermark'), $s);
}
private static function _watermark(array $m)
{
/*
ЗАМЕЧАНИЕ
Свойство 'watermark' в CSS не существует и д.б. проигнорировано браузером (Опера "ругается" в консоли ошибок).
Попытка поместить "водяной знак" в комментарии /*...* / привела к некорректному отображению в Opera-9.27.
*/
static $i = 0, $url = null, $hash = null;
if ($url === null)
{
#вырезаем идентификатор сессии в целях усиления безопасности!
$url = 'http://' . $_SERVER['SERVER_NAME'] . URL::replace_arg($_SERVER['REQUEST_URI'], array(), $is_use_sid = false);
$hash = base_convert(md5($url), 16, 36);
}
#стили не изменять, т.к. протестировано (в декабре 2008) и корректно работает во всех современных браузерах!
return '<noindex><span class="fake invisible" style="position:absolute;display:block;width:0;height:0;text-indent:-2989px;font:normal 0 sans-serif;opacity:0.01;filter:alpha(opacity=1);watermark:' . $hash . ',' . dechex(++$i) . '"> © ' . $url . '</span></noindex>' . $m[0];
}
/**
* Удаляет лишние тэги, которые не могут быть вложены друг в друга, проверяет парность тэгов.
* Используется простой и быстрый алгоритм.
*
* ПРИМЕРЫ
* "<noindex> ... <noindex> ... </noindex> ... </noindex>" => "<noindex> ... ... ... </noindex>"
*
* ЗАМЕЧАНИЕ
* Рекомендуется использовать совместно и после вызова self::normalize_links()
*
* Яндекс и тег noindex.
* Робот Яндекса поддерживает тег noindex, который позволяет не индексировать заданные (служебные) участки текста.
* В начале служебного фрагмента поставьте — <noindex>, а в конце — </noindex>, и Яндекс не будет индексировать данный участок текста.
* Тег noindex чувствителен к вложенности!
* http://help.yandex.ru/webmaster/?id=995294
*
* @param string|array|null $s Html код
* @param array|null &$invalid_tags Возвращает массив некорректных парных тэгов, если такие есть
* @param array|null &$deleted_tags Возвращает массив удалённых тэгов, где ключами явл. тэги, а значениями кол-во > 0
* @param array $tags Эти парные тэги не м.б. вложены друг в друга (XHTML)
* Каждый элемент массива -- регулярное выражение
* @return string|bool|null returns FALSE if error occured
*/
public static function normalize_tags($s,
array &$invalid_tags = null,
array &$deleted_tags = null,
array $tags = array(
'html', 'head', 'body',
'title', 'h[1-6]',
'span', 'div',
'form', 'textarea', 'button', 'option', 'label', 'select', #формы
'strong', 'em', 'big', 'small', 'sub', 'sup', 'tt',
'[abius]', 'bdo', 'caption', 'del', 'ins',
'script', 'noscript', 'style', 'map', 'applet', 'object',
'table', 't[rhd]', #таблицы
'nobr', 'noindex', 'wiki', 'notypo', 'comment',
)
)
{
if (! ReflectionTypeHint::isValid()) return false;
if (is_null($s)) return $s;
static $_opened_tags = array();
static $_deleted_tags = array();
//static $_is_nofollow = false;
if (is_array($s) && $invalid_tags === null) #callback?
{
if ($s[0] === '' || ! isset($s[2])) return $s[0];
$t = substr($s[0], 0, 2);
if ($t === '<?' || $t === '<%' || $t === '<!') return $s[0];
$tag = strtolower($s[2]);
if (! array_key_exists($tag, $_opened_tags)) $_opened_tags[$tag] = 0;
$o =& $_opened_tags[$tag];
if ($s[1] !== '/')
{
#tag has opened
$o++;
if ($o > 1)
{
if (! array_key_exists($tag, $_deleted_tags)) $_deleted_tags[$tag] = 0;
$_deleted_tags[$tag]++;
return '';
}
/*
//DEPRECATED
if ($tag === 'a')
{
if (empty($_opened_tags['noindex']) && #не допускаем вложенности тэга <noindex> друг в друга
preg_match('~(?<![-a-z\d_])rel
[\x00-\x20\x7f]*+
=
[\x00-\x20\x7f]*+
(?:
"[^"]*? (?<![-a-z\d_])nofollow[^-a-z\d_]
| \'[^\']*? (?<![-a-z\d_])nofollow[^-a-z\d_]
| nofollow[^-a-z\d_]
)
~sxiSX', $s[0]))
{
$_is_nofollow = true;
$s[0] = '<noindex>' . $s[0];
}
}
*/
}
else
{
#tag has closed
$o--;
if ($o > 0)
{
if (! array_key_exists($tag, $_deleted_tags)) $_deleted_tags[$tag] = 0;
$_deleted_tags[$tag]++;
return '';
}
/*
//DEPRECATED
if ($tag === 'a' && $_is_nofollow)
{
$_is_nofollow = false;
$s[0] .= '</noindex>';
}
*/
}
return $s[0];
}
$s = preg_replace_callback('~(?>
<(/)?+ #1
((?i:' . implode('|', $tags) . ')) #2
(?(1)|' . self::$re_attrs . '(?<!/))
>
#встроенный PHP, Perl, ASP код
| <([?%]) .*? \\3> #3
#блоки CDATA
| <!\[CDATA\[ .*? \]\]>
#MS Word тэги типа "<![if! vml]>...<![endif]>",
#условное выполнение кода для IE типа "<!--[if lt IE 7]>...<![endif]-->"
| <! (?>--)?
\[
(?> [^\]"\']+ | "[^"]*" | \'[^\']*\' )*
\]
(?>--)?
>
#комментарии
| <!-- .*? -->
)
~sxSX', array('self', __FUNCTION__), $s);
$invalid_tags = array();
foreach ($_opened_tags as $tag => $count) if ($count !== 0) $invalid_tags[] = $tag;
$deleted_tags = $_deleted_tags;
#restore static values
$_opened_tags = array();
$_deleted_tags = array();
return $s;
}
/**
* Check to valid XHTML 1.1 Strict
* http://www.w3.org/TR/2001/REC-xhtml11-20010531/
*
* Назначение
* Проверка на XHTML позволяет придерживаться современного стандарта вёрстки веб-страниц,
* избегать грубых ошибок верстальщика (или автотипографики) и возможного "разваливания"
* дизайна сайта в браузере как следствия.
* Побочным положительным эффектом можно считать защиту от СПАМа в веб-формах с "кривым" html спамеров.
*
* Ограничения
* Этот простой парсер проверяет только синтаксис!
* Проверяется корректность вложенности пустых и парных тэгов, допустимых атрибутов.
* Логическая вложенность парных тэгов почти не проверяется.
* Так, например, нет проверки на то, что тэг <a> не может содержать другие тэги <a>.
* Не проверяется наличие обязательных аттрибутов для некоторых тэгов (например, для <img>).
* Не делается проверка на дублирующие атрибуты, когда один и тот же атрибут встречается в тэге несколько раз.
*
* Примеры использования
* echo HTML::is_xhtml('<B class=aaa><i>test</B></i><img src=""/>') ? 'OK' : 'ERROR';
* $s = '<p id="<p>">
* <img src=""/>
* 1 < 3 > 2 <!4
* <a href="#">link <!-- <!--*--> </a>
* test <i><b>bold italic</b></i>
* </p>';
* echo HTML::is_xhtml($s) ? 'OK' : 'ERROR';
*
* Замечания
* self::is_xhtml() удобно использовать совместно с Html Tidy (http://ru2.php.net/tidy)
* Функция явл. отличным учебным пособием для изучения регулярных выражений PCRE!
*
* @param string|null $s Html код
* @param bool $is_strict Строгая проверка XHTML (настоятельно рекомендуется):
* * делается проверка на разрешённые тэги из спецификации
* * имена тэгов и атрибутов д.б. только в нижнем регистре
* * значения атрибутов тэгов д.б. только в кавычках
* * символы < > в значениях атрибутов тэгов не допускаются (д.б. сущности < >)
* * символы < > за пределами тэгов не допускаются (д.б. сущности < >)
* если эти символы нужно использовать, используйте содержимое #CDATA (например, для тэгов script и style)
* * MS Word и IE (Internet Explorer) условные тэги не допускаются
* @param bool $strict_is_legacy_allow Allow tags and attributes that were already deprecated in previous versions of HTML and XHTML
* @param int|null $error_offset Возвращает смещение в байтах в случае ошибки.
* Работает надёжно только для первой вложенности тэгов.
* @param array $strict_pair_tags_extra
* @param array $strict_empty_tags_extra
* @param array $strict_attrs_extra
* @return bool|null returns FALSE if error occured
*/
public static function is_xhtml($s,
$is_strict = true,
$strict_is_legacy_allow = true,
$error_offset = null,
#дополнительные тэги и атрибуты:
array $strict_pair_tags_extra = array('nobr', 'notypo', 'wiki'),
array $strict_empty_tags_extra = array('typo', 'page'),
array $strict_attrs_extra = array(
'md5', /*'crc32', 'sha1',*/ #Text_Typograph
'time', 'speed', 'length', 'char_length', 'created', 'version', #Text_Typograph
#'if', 'blockif', #html_template DEPRECATED
)
)
{
if (! ReflectionTypeHint::isValid()) return false;
if (is_null($s)) return $s;
if (($pos = strpos($s, '<')) === false || strpos($s, '>', $pos) === false) #speed improve
{
return true; #tags are not found
}
if ($is_strict)
{
$re_attr_names = '
#Common (Core + I18N + Style + Events)
xml:space|class|id|title #Core
|dir|xml:lang #I18N
|style #Style
#|on[a-z]{3,30}+ #Events
#Events
|on(?:abort
|activate
|afterprint
|afterupdate
|beforeactivate
|beforecopy
|beforecut
|beforedeactivate
|beforeeditfocus
|beforepaste
|beforeprint
|beforeunload
|beforeupdate
|blur
|bounce
|cellchange
|change
|click
|contextmenu
|controlselect
|copy
|cut
|dataavailable
|datasetchanged
|datasetcomplete
|dblclick
|deactivate
|drag
|dragend
|dragenter
|dragleave
|dragover
|dragstart
|drop
|error
|errorupdate
|filterchange
|finish
|focus
|focusin
|focusout
|help
|keydown
|keypress
|keyup
|layoutcomplete
|load
|losecapture