Html.php
18.5 KB
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
<?php
/**
* @package Regular Labs Library
* @version 18.2.10140
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2018 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
namespace RegularLabs\Library;
defined('_JEXEC') or die;
use DOMDocument;
/**
* Class Html
* @package RegularLabs\Library
*/
class Html
{
/**
* Convert content saved in a WYSIWYG editor to plain text (like removing html tags)
*
* @param $string
*
* @return string
*/
public static function convertWysiwygToPlainText($string)
{
// replace chr style enters with normal enters
$string = str_replace([chr(194) . chr(160), ' ', ' '], ' ', $string);
// replace linebreak tags with normal linebreaks (paragraphs, enters, etc).
$enter_tags = ['p', 'br'];
$regex = '</?((' . implode(')|(', $enter_tags) . '))+[^>]*?>\n?';
$string = RegEx::replace($regex, " \n", $string);
// replace indent characters with spaces
$string = RegEx::replace('<img [^>]*/sourcerer/images/tab\.png[^>]*>', ' ', $string);
// strip all other tags
$regex = '<(/?\w+((\s+\w+(\s*=\s*(?:".*?"|\'.*?\'|[^\'">\s]+))?)+\s*|\s*)/?)>';
$string = RegEx::replace($regex, '', $string);
// reset htmlentities
$string = StringHelper::html_entity_decoder($string);
// convert protected html entities &_...; -> &...;
$string = RegEx::replace('&_([a-z0-9\#]+?);', '&\1;', $string);
return $string;
}
/**
* Extract the <body>...</body> part from an entire html output string
*
* @param string $html
*
* @return array
*/
public static function getBody($html)
{
if (strpos($html, '<body') === false || strpos($html, '</body>') === false)
{
return ['', $html, ''];
}
// Force string to UTF-8
$html = StringHelper::convertToUtf8($html);
$html_split = explode('<body', $html, 2);
$pre = $html_split[0];
$body = '<body' . $html_split[1];
$body_split = explode('</body>', $body);
$post = array_pop($body_split);
$body = implode('</body>', $body_split) . '</body>';
return [$pre, $body, $post];
}
/**
* Search the string for the start and end searches and split the string in a pre, body and post part
* This is used to be able to do replacements on the body part, which will be lighter than doing it on the entire string
*
* @param string $string
* @param array $start_searches
* @param array $end_searches
* @param int $start_offset
* @param null $end_offset
*
* @return array
*/
public static function getContentContainingSearches($string, $start_searches = [], $end_searches = [], $start_offset = 1000, $end_offset = null)
{
// String is too short to split and search through
if (strlen($string) < 2000)
{
return ['', $string, ''];
}
$end_offset = is_null($end_offset) ? $start_offset : $end_offset;
$found = false;
$start_split = strlen($string);
foreach ($start_searches as $search)
{
$pos = strpos($string, $search);
if ($pos === false)
{
continue;
}
$start_split = min($start_split, $pos);
$found = true;
}
// No searches are found
if ( ! $found)
{
return [$string, '', ''];
}
// String is too short to split
if (strlen($string) < ($start_offset + $end_offset + 1000))
{
return ['', $string, ''];
}
$start_split = max($start_split - $start_offset, 0);
$pre = substr($string, 0, $start_split);
$string = substr($string, $start_split);
self::fixBrokenTagsByPreString($pre, $string);
if (empty($end_searches))
{
$end_searches = $start_searches;
}
$end_split = 0;
$found = false;
foreach ($end_searches as $search)
{
$pos = strrpos($string, $search);
if ($pos === false)
{
continue;
}
$end_split = max($end_split, $pos + strlen($search));
$found = true;
}
// No end split is found, so don't split remainder
if ( ! $found)
{
return [$pre, $string, ''];
}
$end_split = min($end_split + $end_offset, strlen($string));
$post = substr($string, $end_split);
$string = substr($string, 0, $end_split);
self::fixBrokenTagsByPostString($post, $string);
return [$pre, $string, $post];
}
/**
* Check if string contains block elements
*
* @param string $string
*
* @return string
*/
public static function containsBlockElements($string)
{
return RegEx::match('</?(' . implode('|', self::getBlockElements()) . ')(?: [^>]*)?>', $string);
}
/**
* Fix broken/invalid html syntax in a string
*
* @param string $string
*
* @return string
*/
public static function fix($string)
{
if ( ! self::containsBlockElements($string))
{
return $string;
}
// Convert utf8 characters to html entities
if (function_exists('mb_convert_encoding'))
{
$string = mb_convert_encoding($string, 'html-entities', 'utf-8');
}
$string = self::protectSpecialCode($string);
$string = self::convertDivsInsideInlineElementsToSpans($string);
$string = self::removeParagraphsAroundBlockElements($string);
$string = self::removeInlineElementsAroundBlockElements($string);
$string = self::fixParagraphsAroundParagraphElements($string);
$string = class_exists('DOMDocument')
? self::fixUsingDOMDocument($string)
: self::fixUsingCustomFixer($string);
$string = self::unprotectSpecialCode($string);
// Convert html entities back to utf8 characters
if (function_exists('mb_convert_encoding'))
{
// Make sure < and > don't get converted
$string = str_replace(['<', '>'], ['&lt;', '&gt;'], $string);
$string = mb_convert_encoding($string, 'utf-8', 'html-entities');
}
$string = self::removeParagraphsAroundComments($string);
return $string;
}
/**
* Fix broken/invalid html syntax in an array of strings
*
* @param array $array
*
* @return array
*/
public static function fixArray($array)
{
$splitter = ':|:';
$string = self::fix(implode($splitter, $array));
$parts = self::removeEmptyTags(explode($splitter, $string));
// use original keys but new values
return array_combine(array_keys($array), $parts);
}
/**
* Removes empty tags which span concatenating parts in the array
*
* @param array $array
*
* @return array
*/
public static function removeEmptyTags($array)
{
$splitter = ':|:';
$comments = '(?:\s*<\!--.*?-->\s*)*';
$string = implode($splitter, $array);
$string = RegEx::replace(
'<([a-z][a-z0-9]*)(?: [^>]*)?>\s*(' . $comments . RegEx::quote($splitter) . $comments . ')\s*</\1>',
'\2',
$string
);
return explode($splitter, $string);
}
/**
* Fix broken/invalid html syntax in a string using php DOMDocument functionality
*
* @param string $string
*
* @return mixed
*/
private static function fixUsingDOMDocument($string)
{
$doc = new DOMDocument;
$doc->substituteEntities = false;
// Add temporary surrounding div
$string = '<div>' . $string . '</div>';
@$doc->loadHTML($string);
$string = $doc->saveHTML();
// Remove html document structures
$string = RegEx::replace('^<[^>]*>(.*?)<html>.*?(?:<head>(.*)</head>.*?)?<body>(.*)</body>.*?$', '\1\2\3', $string);
// Remove temporary surrounding div
$string = RegEx::replace('^\s*<div>(.*)</div>\s*$', '\1', $string);
// Remove leading/trailing empty paragraph
$string = RegEx::replace('(^\s*<div>\s*</div>|<div>\s*</div>\s*$)', '', $string);
// Remove leading/trailing empty paragraph
$string = RegEx::replace('(^\s*<p(?: [^>]*)?>\s*</p>|<p(?: [^>]*)?>\s*</p>\s*$)', '', $string);
return $string;
}
/**
* Fix broken/invalid html syntax in a string using custom code as an alternative to php DOMDocument functionality
*
* @param string $string
*
* @return string
*/
private static function fixUsingCustomFixer($string)
{
$block_regex = '<(' . implode('|', self::getBlockElementsNoDiv()) . ')[\s>]';
$string = RegEx::replace('(' . $block_regex . ')', '[:SPLIT-BLOCK:]\1', $string);
$parts = explode('[:SPLIT-BLOCK:]', $string);
foreach ($parts as $i => &$part)
{
if ( ! RegEx::match('^' . $block_regex, $part, $type))
{
continue;
}
$type = strtolower($type[1]);
// remove endings of other block elements
$part = RegEx::replace('</(?:' . implode('|', self::getBlockElementsNoDiv($type)) . ')>', '', $part);
if (strpos($part, '</' . $type . '>') !== false)
{
continue;
}
// Add ending tag once
$part = RegEx::replaceOnce('(\s*)$', '</' . $type . '>\1', $part);
// Remove empty block tags
$part = RegEx::replace('^<' . $type . '(?: [^>]*)?>\s*</' . $type . '>', '', $part);
}
return implode('', $parts);
}
/**
* Removes complete html tag pairs from the concatenated parts
*
* @param array $parts
* @param array $elements
*
* @return array
*/
public static function cleanSurroundingTags($parts, $elements = ['p', 'span'])
{
$breaks = '(?:(?:<br ?/?>|<\!--.*?-->|:\|:)\s*)*';
$keys = array_keys($parts);
$string = implode(':|:', $parts);
// Remove empty tags
$regex = '<(' . implode('|', $elements) . ')(?: [^>]*)?>\s*(' . $breaks . ')<\/\1>\s*';
while (RegEx::match($regex, $string, $match))
{
$string = str_replace($match[0], $match[2], $string);
}
// Remove paragraphs around block elements
$block_elements = [
'p', 'div',
'table', 'tr', 'td', 'thead', 'tfoot',
'h[1-6]',
];
$block_elements = '(' . implode('|', $block_elements) . ')';
$regex = '(<p(?: [^>]*)?>)(\s*' . $breaks . ')(<' . $block_elements . '(?: [^>]*)?>)';
while (RegEx::match($regex, $string, $match))
{
if ($match[4] == 'p')
{
$match[3] = $match[1] . $match[3];
self::combinePTags($match[3]);
}
$string = str_replace($match[0], $match[2] . $match[3], $string);
}
$regex = '(</' . $block_elements . '>\s*' . $breaks . ')</p>';
while (RegEx::match($regex, $string, $match))
{
$string = str_replace($match[0], $match[1], $string);
}
$parts = explode(':|:', $string);
$new_tags = [];
foreach ($parts as $key => $val)
{
$key = isset($keys[$key]) ? $keys[$key] : $key;
$new_tags[$key] = $val;
}
return $new_tags;
}
/**
* Remove <p> tags around block elements
*
* @param string $string
*
* @return mixed
*/
private static function removeParagraphsAroundBlockElements($string)
{
if (strpos($string, '</p>') == false)
{
return $string;
}
$string = RegEx::replace(
'<p(?: [^>]*)?>\s*'
. '((?:<\!--.*?-->\s*)*</?(?:' . implode('|', self::getBlockElements()) . ')' . '(?: [^>]*)?>)',
'\1',
$string
);
$string = RegEx::replace(
'(</?(?:' . implode('|', self::getBlockElements()) . ')' . '(?: [^>]*)?>(?:\s*<\!--.*?-->)*)'
. '(?:\s*</p>)',
'\1',
$string
);
return $string;
}
/**
* Remove <p> tags around comments
*
* @param string $string
*
* @return mixed
*/
private static function removeParagraphsAroundComments($string)
{
if (strpos($string, '</p>') == false)
{
return $string;
}
$string = RegEx::replace(
'(?:<p(?: [^>]*)?>\s*)'
. '(<\!--.*?-->)'
. '(?:\s*</p>)',
'\1',
$string
);
return $string;
}
/**
* Fix <p> tags around other <p> elements
*
* @param string $string
*
* @return mixed
*/
private static function fixParagraphsAroundParagraphElements($string)
{
if (strpos($string, '</p>') == false)
{
return $string;
}
$parts = explode('</p>', $string);
$ending = '</p>' . array_pop($parts);
foreach ($parts as &$part)
{
if (strpos($part, '<p>') === false && strpos($part, '<p ') === false)
{
$part = '<p>' . $part;
continue;
}
$part = RegEx::replace(
'(<p(?: [^>]*)?>.*?)(<p(?: [^>]*)?>)',
'\1</p>\2',
$part
);
}
return implode('</p>', $parts) . $ending;
}
/*
* Remove empty tags
*
* @param string $string
* @param array $elements
*
* @return mixed
*/
public static function removeEmptyTagPairs($string, $elements = ['p', 'span'])
{
$breaks = '(?:(?:<br ?/?>|<\!--.*?-->)\s*)*';
$regex = '<(' . implode('|', $elements) . ')(?: [^>]*)?>\s*(' . $breaks . ')<\/\1>\s*';
while (RegEx::match($regex, $string, $match))
{
$string = str_replace($match[0], $match[2], $string);
}
return $string;
}
/**
* Convert <div> tags inside inline elements to <span> tags
*
* @param string $string
*
* @return mixed
*/
private static function convertDivsInsideInlineElementsToSpans($string)
{
if (strpos($string, '</div>') == false)
{
return $string;
}
// Ignore block elements inside anchors
$regex = '<(' . implode('|', self::getInlineElementsNoAnchor()) . ')(?: [^>]*)?>.*?</\1>';
RegEx::matchAll($regex, $string, $matches, '', PREG_PATTERN_ORDER);
if (empty($matches))
{
return $string;
}
$matches = array_unique($matches[0]);
$searches = [];
$replacements = [];
foreach ($matches as $match)
{
if (strpos($match, '</div>') === false)
{
continue;
}
$searches[] = $match;
$replacements[] = str_replace(
['<div>', '<div ', '</div>'],
['<span>', '<span ', '</span>'],
$match
);
}
if (empty($searches))
{
return $string;
}
return str_replace($matches, $replacements, $string);
}
/**
* Combine duplicate <p> tags
* input: <p class="aaa" a="1"><!-- ... --><p class="bbb" b="2">
* output: <p class="aaa bbb" a="1" b="2"><!-- ... -->
*
* @param $string
*/
public static function combinePTags(&$string)
{
if (empty($string))
{
return;
}
$p_start_tag = '<p(?: [^>]*)?>';
$optional_tags = '\s*(?:<\!-- [^>]*-->| |&\#160;)*\s*';
RegEx::matchAll('(' . $p_start_tag . ')(' . $optional_tags . ')(' . $p_start_tag . ')', $string, $tags);
if (empty($tags))
{
return;
}
foreach ($tags as $tag)
{
$string = str_replace($tag[0], $tag[2] . HtmlTag::combine($tag[1], $tag[3]), $string);
}
}
/**
* Remove inline elements around block elements
*
* @param string $string
*
* @return mixed
*/
public static function removeInlineElementsAroundBlockElements($string)
{
$string = RegEx::replace(
'(?:<(?:' . implode('|', self::getInlineElementsNoAnchor()) . ')(?: [^>]*)?>\s*)'
. '(</?(?:' . implode('|', self::getBlockElements()) . ')(?: [^>]*)?>)',
'\1',
$string
);
$string = RegEx::replace(
'(</?(?:' . implode('|', self::getBlockElements()) . ')(?: [^>]*)?>)'
. '(?:\s*</(?:' . implode('|', self::getInlineElementsNoAnchor()) . ')>)',
'\1',
$string
);
return $string;
}
/**
* Return an array of block element names, optionally without any of the names given $exclude
*
* @param array $exclude
*
* @return array
*/
public static function getBlockElements($exclude = [])
{
if ( ! is_array($exclude))
{
$exclude = [$exclude];
}
$elements = [
'div', 'p', 'pre',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
];
$elements = array_diff($elements, $exclude);
$elements = implode(',', $elements);
$elements = str_replace('h1,h2,h3,h4,h5,h6', 'h[1-6]', $elements);
$elements = explode(',', $elements);
return $elements;
}
/**
* Return an array of inline element names, optionally without any of the names given $exclude
*
* @param array $exclude
*
* @return array
*/
public static function getInlineElements($exclude = [])
{
if ( ! is_array($exclude))
{
$exclude = [$exclude];
}
$elements = [
'span', 'code', 'a',
'strong', 'b', 'em', 'i', 'u', 'big', 'small', 'font',
];
return array_diff($elements, $exclude);
}
/**
* Return an array of block element names, without divs and any of the names given $exclude
*
* @param array $exclude
*
* @return array
*/
public static function getBlockElementsNoDiv($exclude = [])
{
return array_diff(self::getBlockElements($exclude), ['div']);
}
/**
* Return an array of block element names, without anchors (a) and any of the names given $exclude
*
* @param array $exclude
*
* @return array
*/
public static function getInlineElementsNoAnchor($exclude = [])
{
return array_diff(self::getInlineElements($exclude), ['a']);
}
/**
* Protect plugin style tags and php
*
* @param $string
*
* @return mixed
*/
private static function protectSpecialCode($string)
{
// Protect PHP code
Protect::protectByRegex($string, '(<|<)\?php\s.*?\?(>|>)');
// Protect {...} tags
Protect::protectByRegex($string, '\{[a-z0-9].*?\}');
// Protect [...] tags
Protect::protectByRegex($string, '\[[a-z0-9].*?\]');
// Protect scripts
Protect::protectByRegex($string, '<script[^>]*>.*?</script>');
// Protect css
Protect::protectByRegex($string, '<style[^>]*>.*?</style>');
Protect::convertProtectionToHtmlSafe($string);
return $string;
}
/**
* Unprotect protected tags
*
* @param $string
*
* @return mixed
*/
private static function unprotectSpecialCode($string)
{
Protect::unprotectHtmlSafe($string);
return $string;
}
/**
* Prevents broken html tags at the end of $pre (other half at beginning of $string)
* It will move the broken part to the beginning of $string to complete it
*
* @param $pre
* @param $string
*/
private static function fixBrokenTagsByPreString(&$pre, &$string)
{
if ( ! RegEx::match('<(\![^>]*|/?[a-z][^>]*(="[^"]*)?)$', $pre, $match))
{
return;
}
$pre = substr($pre, 0, strlen($pre) - strlen($match[0]));
$string = $match[0] . $string;
}
/**
* Prevents broken html tags at the beginning of $pre (other half at end of $string)
* It will move the broken part to the end of $string to complete it
*
* @param $post
* @param $string
*/
private static function fixBrokenTagsByPostString(&$post, &$string)
{
if ( ! RegEx::match('<(\![^>]*|/?[a-z][^>]*(="[^"]*)?)$', $string, $match))
{
return;
}
if ( ! RegEx::match('^[^>]*>', $post, $match))
{
return;
}
$post = substr($post, strlen($match[0]));
$string .= $match[0];
}
/**
* Removes html tags from string
*
* @param string $string
*
* @return string
*/
public static function removeHtmlTags($string)
{
// remove pagenavcounter
$string = RegEx::replace('(<div class="pagenavcounter">.*?</div>)', ' ', $string);
// remove pagenavbar
$string = RegEx::replace('(<div class="pagenavbar">(<div>.*?</div>)*</div>)', ' ', $string);
// remove inline scripts
$string = RegEx::replace('(<script[^a-z0-9].*?</script>)', ' ', $string);
$string = RegEx::replace('(<noscript[^a-z0-9].*?</noscript>)', ' ', $string);
// remove inline styles
$string = RegEx::replace('(<style[^a-z0-9].*?</style>)', ' ', $string);
// remove other tags
$string = RegEx::replace('(</?[a-z][a-z0-9]?.*?>)', ' ', $string);
// remove double whitespace
$string = trim(RegEx::replace('(\s)[ ]+', '\1', $string));
return $string;
}
}