-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathHtmlInputNodeProcessor.class.php
More file actions
911 lines (791 loc) · 29.8 KB
/
HtmlInputNodeProcessor.class.php
File metadata and controls
911 lines (791 loc) · 29.8 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
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
<?php
namespace wcf\system\html\input\node;
use wcf\system\bbcode\BBCodeHandler;
use wcf\system\bbcode\DomBBCodeParser;
use wcf\system\event\EventHandler;
use wcf\system\html\node\AbstractHtmlNodeProcessor;
use wcf\system\html\node\HtmlNodePlainLink;
use wcf\system\html\node\HtmlNodeUnfurlLink;
use wcf\system\html\node\IHtmlNode;
use wcf\system\html\output\node\HtmlOutputNodeProcessor;
use wcf\system\worker\AbstractWorker;
use wcf\util\DOMUtil;
use wcf\util\StringUtil;
/**
* Processes HTML nodes and handles bbcodes.
*
* @author Alexander Ebert
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @since 3.0
*/
class HtmlInputNodeProcessor extends AbstractHtmlNodeProcessor
{
/**
* list of allowed CSS class names per tag name
* @var array<array>
*/
public static $allowedClassNames = [
'figure' => ['image', 'image-style-side', 'image-style-side-left'],
'h2' => ['text-center', 'text-justify', 'text-right'],
'h3' => ['text-center', 'text-justify', 'text-right'],
'h4' => ['text-center', 'text-justify', 'text-right'],
'img' => [
// float left/right
'messageFloatObjectLeft',
'messageFloatObjectRight',
// built-in
'smiley',
'woltlabAttachment',
'woltlabSuiteMedia',
],
'li' => ['text-center', 'text-justify', 'text-right'],
'mark' => ['marker-error', 'marker-info', 'marker-success', 'marker-warning'],
'p' => ['text-center', 'text-justify', 'text-right'],
'pre' => ['woltlabHtml'],
'td' => ['text-center', 'text-justify', 'text-right'],
];
/**
* List of HTML elements that should allow for custom CSS using
* the `style`-attribute.
*
* Unfortunately, HTMLPurifier offers no *sane* way to limit this
* attribute to some elements only.
*
* @var string[]
*/
public static $allowedStyleElements = [
'span',
];
/**
* list of HTML elements that are treated as empty, that means
* they don't generate any (indirect) output at all
*
* @var string[]
*/
public static $emptyTags = [
// typical wrappers
'div',
'p',
'span',
// headlines
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
// tables
'table',
'tbody',
'thead',
'tr',
'th',
'td',
'colgroup',
'col',
// lists
'ul',
'ol',
'li',
// other
'a',
'kbd',
'woltlab-quote',
'woltlab-spoiler',
'pre',
'sub',
'sup',
'strong',
'del',
'em',
'u',
];
/**
* list of tag names that represent inline content in the HTML 5 standard
* @var string[]
*/
public static $inlineElements = [
'a',
'abbr',
'acronym',
'audio',
'b',
'bdi',
'bdo',
'big',
'br',
'button',
'canvas',
'cite',
'code',
'data',
'datalist',
'del',
'dfn',
'em',
'embed',
'i',
'iframe',
'img',
'input',
'ins',
'kbd',
'label',
'map',
'mark',
'meter',
'noscript',
'object',
'output',
'picture',
'progress',
'q',
'ruby',
's',
'samp',
'script',
'select',
'slot',
'small',
'span',
'strong',
'sub',
'sup',
'svg',
'template',
'textarea',
'time',
'u',
'tt',
'var',
'video',
'wbr',
];
/**
* @var HtmlNodePlainLink[]
*/
public $plainLinks = [];
/**
* list of embedded content grouped by type
* @var array
*/
protected $embeddedContent = [];
/**
* @inheritDoc
*/
protected $nodeInterface = IHtmlInputNode::class;
/**
* @inheritDoc
*/
public function process()
{
$this->plainLinks = [];
EventHandler::getInstance()->fireAction($this, 'beforeProcess');
// convert bbcodes to `<woltlab-metacode-marker>`
DomBBCodeParser::getInstance()->parse($this->getDocument());
// fix invalid html such as metacode markers outside of block elements
$this->fixDom();
// process metacode markers first
$this->invokeHtmlNode(new HtmlInputNodeWoltlabMetacodeMarker());
// handle static converters
$this->invokeHtmlNode(new HtmlInputNodeWoltlabMetacode());
if (MESSAGE_MAX_QUOTE_DEPTH) {
$this->enforceQuoteDepth(MESSAGE_MAX_QUOTE_DEPTH);
}
$imgNodeHandler = new HtmlInputNodeImg();
$this->invokeHtmlNode($imgNodeHandler);
$smileyCount = $imgNodeHandler->getSmileyCount();
// dynamic node handlers
$this->invokeNodeHandlers('wcf\system\html\input\node\HtmlInputNode', ['img', 'woltlab-metacode']);
// remove whitespace at the start/end of the message
$this->trim();
// detect mentions, urls, emails and smileys
$textParser = new HtmlInputNodeTextParser($this, $smileyCount);
$textParser->parse();
// handle HTML bbcode
$allowHtml = BBCodeHandler::getInstance()->isAvailableBBCode('html');
// strip invalid class names
/** @var \DOMElement $element */
foreach ($this->getXPath()->query('//*[@class]') as $element) {
$nodeName = $element->nodeName;
if (isset(self::$allowedClassNames[$nodeName])) {
if (self::$allowedClassNames[$nodeName] === '*') {
continue;
}
$classNames = \explode(' ', $element->getAttribute('class'));
$classNames = \array_filter($classNames, static function ($className) use ($allowHtml, $nodeName) {
if (!$allowHtml && $nodeName === 'pre' && $className === 'woltlabHtml') {
return false;
}
return $className && \in_array($className, self::$allowedClassNames[$nodeName]);
});
if (!empty($classNames)) {
$element->setAttribute('class', \implode(' ', $classNames));
continue;
}
}
$element->removeAttribute('class');
if ($nodeName === 'span' && $element->attributes->length === 0) {
DOMUtil::removeNode($element, true);
}
}
EventHandler::getInstance()->fireAction($this, 'beforeEmbeddedProcess');
$this->convertPlainLinks();
// extract embedded content
$this->processEmbeddedContent();
EventHandler::getInstance()->fireAction($this, 'afterProcess');
}
/**
* Enforces the maximum depth of nested quotes.
*
* @param int $depth
*/
public function enforceQuoteDepth($depth, bool $isFullQuote = false)
{
$quotes = [];
/** @var \DOMElement $quote */
foreach ($this->getDocument()->getElementsByTagName('woltlab-quote') as $quote) {
$quotes[] = $quote;
}
$checkQuotes = [];
foreach ($quotes as $quote) {
if (!$quote->parentNode) {
continue;
}
if ($depth === 0) {
DOMUtil::removeNode($quote);
} else {
$level = 0;
$parent = $quote;
while ($parent = $parent->parentNode) {
if ($parent->nodeName === 'woltlab-quote') {
$level++;
}
}
if ($level < $depth) {
continue;
}
$checkQuotes[] = $quote->parentNode;
DOMUtil::removeNode($quote);
}
}
/**
* @var \DOMElement $quote
*/
foreach ($checkQuotes as $quote) {
if ($quote->childNodes->length === 0) {
$quote->textContent = "[\u{2026}]";
}
}
// Check if the quoted message is now empty.
if ($depth === 0 && $isFullQuote && \count($quotes) > 0) {
/** @var \DOMElement $body */
$body = $this->getDocument()->getElementsByTagName('body')[0];
if ($body->childElementCount === 0) {
$p = $body->ownerDocument->createElement('p');
$p->textContent = "[\u{2026}]";
$body->appendChild($p);
}
}
}
/**
* Fixes malformed HTML with metacode markers and text being placed
* outside of paragraphs.
*/
protected function fixDom()
{
// remove or convert any <div> found
$elements = $this->getDocument()->getElementsByTagName('div');
while ($elements->length) {
$element = $elements->item(0);
if ($element->parentNode->nodeName === 'P') {
DOMUtil::removeNode($element, true);
} else {
DOMUtil::replaceElement($element, $element->ownerDocument->createElement('p'), true);
}
}
$appendToPreviousParagraph = static function (\DOMNode $node) {
$paragraph = $node;
while ($paragraph = $paragraph->previousSibling) {
if ($paragraph instanceof \DOMText) {
if (!\str_contains($paragraph->textContent, ' ') && StringUtil::trim($paragraph->textContent) === '') {
continue;
}
}
break;
}
if ($paragraph === null || $paragraph->nodeName !== 'p') {
$paragraph = $node->ownerDocument->createElement('p');
$node->parentNode->insertBefore($paragraph, $node);
}
$paragraph->appendChild($node);
return $paragraph;
};
/** @var \DOMNode $node */
$node = $this->getDocument()->getElementsByTagName('body')->item(0)->firstChild;
while ($node) {
if ($node->nodeType === \XML_ELEMENT_NODE && $node->nodeName === 'woltlab-metacode-marker') {
$node = $appendToPreviousParagraph($node);
} elseif ($node->nodeType === \XML_ELEMENT_NODE && \in_array($node->nodeName, self::$inlineElements)) {
$node = $appendToPreviousParagraph($node);
} elseif ($node->nodeType === \XML_TEXT_NODE) {
// text node contains only a line break
if ($node->textContent === "\n" || $node->textContent === "\r\n") {
// check if the previous node is a <p>, otherwise ignore this node entirely
if ($node->previousSibling === null || $node->previousSibling->nodeName !== 'p') {
$node = $node->nextSibling;
continue;
}
} else {
$textContent = StringUtil::trim($node->textContent);
// Ignore any text node that only contains whitespace.
if ($textContent === '') {
$node = $node->nextSibling;
continue;
}
}
$node = $appendToPreviousParagraph($node);
}
$node = $node->nextSibling;
}
// Remove style attributes from non-whitelisted elements.
/** @var \DOMElement $element */
foreach ($this->getXPath()->query('//*[@style]') as $element) {
if (!\in_array($element->nodeName, self::$allowedStyleElements)) {
$element->removeAttribute('style');
}
}
}
/**
* Trims leading and trailing whitespace. It will only remove text nodes containing
* just whitespaces and <p><br></p> (including any whitespace-only text nodes).
*
* It is still possible to work around this by inserting useless text formats such
* as bold to circumvent this check. The point of this method is to remove unintentional
* and/or potentially unwanted whitespace, not guarding against people being jerks.
*/
protected function trim()
{
$body = $this->getDocument()->getElementsByTagName('body')->item(0);
foreach (['firstChild', 'lastChild'] as $property) {
while ($node = $body->{$property}) {
if ($node->nodeType === \XML_TEXT_NODE) {
if (StringUtil::trim($node->textContent) === '') {
$body->removeChild($node);
} else {
break;
}
} else {
/** @var \DOMElement $node */
if ($node->nodeName === 'p') {
for ($i = 0, $length = $node->childNodes->length; $i < $length; $i++) {
$child = $node->childNodes->item($i);
if ($child->nodeType === \XML_TEXT_NODE) {
if (StringUtil::trim($child->textContent) !== '') {
// terminate for() and while()
break 2;
}
} elseif ($child->nodeName !== 'br') {
// terminate for() and while()
break 2;
}
}
$body->removeChild($node);
} else {
break;
}
}
}
}
// strip empty <p></p> (zero content, not even whitespaces)
$paragraphs = DOMUtil::getElements($this->getDocument(), 'p');
foreach ($paragraphs as $paragraph) {
if ($paragraph->childNodes->length === 0) {
DOMUtil::removeNode($paragraph);
}
}
// trim <p>...</p>
/** @var \DOMElement $paragraph */
foreach ($this->getDocument()->getElementsByTagName('p') as $paragraph) {
DOMUtil::normalize($paragraph);
// CKEditor 5 exports empty paragraphs as `<p> </p>`.
if ($paragraph->childNodes->length === 1) {
$node = $paragraph->childNodes->item(0);
if ($node->nodeType === \XML_TEXT_NODE && $node->textContent === "\u{00a0}") {
$br = $node->ownerDocument->createElement("br");
$br->setAttribute("data-cke-filler", "true");
$node->parentNode->appendChild($br);
$node->parentNode->removeChild($node);
continue;
}
}
if ($paragraph->firstChild && $paragraph->firstChild->nodeType === \XML_TEXT_NODE) {
$oldNode = $paragraph->firstChild;
$newNode = $paragraph->ownerDocument->createTextNode(
\preg_replace('/^[\p{Zs}\s]+/u', '', $oldNode->textContent)
);
$paragraph->insertBefore($newNode, $oldNode);
$paragraph->removeChild($oldNode);
}
if ($paragraph->lastChild && $paragraph->lastChild->nodeType === \XML_TEXT_NODE) {
$oldNode = $paragraph->lastChild;
$newNode = $paragraph->ownerDocument->createTextNode(
\preg_replace('/[\p{Zs}\s]+$/u', '', $oldNode->textContent)
);
$paragraph->insertBefore($newNode, $oldNode);
$paragraph->removeChild($oldNode);
}
}
// trim quotes
/** @var \DOMElement $quote */
foreach ($this->getDocument()->getElementsByTagName('woltlab-quote') as $quote) {
$removeElements = [];
for ($i = 0, $length = $quote->childNodes->length; $i < $length; $i++) {
$node = $quote->childNodes->item($i);
if ($node->nodeType === \XML_TEXT_NODE) {
continue;
}
if ($node->nodeName === 'p' && $node->childNodes->length === 1) {
$child = $node->childNodes->item(0);
if ($child->nodeType === \XML_ELEMENT_NODE && $child->nodeName === 'br') {
$removeElements[] = $node;
} else {
break;
}
} else {
break;
}
}
foreach ($removeElements as $removeElement) {
$quote->removeChild($removeElement);
}
$removeElements = [];
for ($i = $quote->childNodes->length - 1; $i >= 0; $i--) {
$node = $quote->childNodes->item($i);
if ($node->nodeType === \XML_TEXT_NODE) {
continue;
}
if ($node->nodeName === 'p' && $node->childNodes->length === 1) {
$child = $node->childNodes->item(0);
if ($child->nodeType === \XML_ELEMENT_NODE && $child->nodeName === 'br') {
$removeElements[] = $node;
} else {
break;
}
} else {
break;
}
}
foreach ($removeElements as $removeElement) {
$quote->removeChild($removeElement);
}
}
// Strip de facto empty text nodes that are the result from quirky formatting, for example:
// <p><span style="font-size: 12px"> </span></p>
/** @var \DOMElement $paragraph */
foreach ($this->getXPath()->query('//p') as $paragraph) {
$textContent = StringUtil::trim($paragraph->textContent);
if ($textContent !== '') {
continue;
}
/** @var \DOMElement $element */
foreach ($paragraph->getElementsByTagName('*') as $element) {
if (!\in_array($element->nodeName, self::$emptyTags)) {
continue 2;
}
}
// Do not strip content that contains non empty spans, such as icons.
/** @var \DOMElement $element */
foreach ($paragraph->getElementsByTagName('span') as $element) {
if ($element->getAttribute('class')) {
continue 2;
}
}
$paragraph->parentNode->removeChild($paragraph);
}
}
/**
* Checks the input html for disallowed bbcodes and returns any matches.
*
* @return string[] list of matched disallowed bbcodes
*/
public function validate()
{
$result = [];
$this->invokeNodeHandlers(
'wcf\system\html\input\node\HtmlInputNode',
[],
function (IHtmlNode $nodeHandler) use (&$result) {
$disallowed = $nodeHandler->isAllowed($this);
if ($disallowed) {
$result = \array_merge($result, $disallowed);
}
}
);
// handle custom nodes that have no dedicated handler
$customTags = [
'spoiler' => 'woltlab-spoiler',
'url' => 'a',
];
foreach ($customTags as $bbcode => $tagName) {
if (BBCodeHandler::getInstance()->isAvailableBBCode($bbcode)) {
continue;
}
if ($this->getDocument()->getElementsByTagName($tagName)->length) {
$result[] = $bbcode;
}
}
$inlineStyles = [
'color' => 'color',
'font' => 'font-family',
'size' => 'font-size',
];
foreach ($inlineStyles as $bbcode => $property) {
if (BBCodeHandler::getInstance()->isAvailableBBCode($bbcode)) {
unset($inlineStyles[$bbcode]);
}
}
if (!empty($inlineStyles)) {
/** @var \DOMElement $element */
foreach ($this->getXPath()->query('//*[@style]') as $element) {
$tmp = \array_filter(\explode(';', $element->getAttribute('style')));
foreach ($tmp as $style) {
$property = \explode(':', $style, 2)[0];
if (\in_array($property, $inlineStyles) && !\in_array($property, $result)) {
$result[] = $property;
}
}
}
}
return $result;
}
/**
* Returns the raw text content of current document.
*
* @return string raw text content
*/
public function getTextContent()
{
// cloning the body allows custom event handlers to alter the contents
// without making permanent changes to the document, avoids side-effects
$document = clone $this->getDocument();
// insert a trailing whitespace plus newline for certain elements, such as `<br>` or `<li>`
$tagNames = HtmlOutputNodeProcessor::$plainTextNewlineTags;
$tagNames[] = 'p';
$xpath = new \DOMXPath($document);
foreach ($tagNames as $tagName) {
foreach ($xpath->query("//{$tagName}") as $element) {
$newline = $document->createTextNode(" \n");
$element->parentNode->insertBefore($newline, $element->nextSibling);
DOMUtil::removeNode($element, true);
}
}
$parameters = ['body' => $document->getElementsByTagName('body')->item(0)];
EventHandler::getInstance()->fireAction($this, 'getTextContent', $parameters);
return StringUtil::trim($parameters['body']->textContent);
}
/**
* Returns true if the message appears to be empty.
*
* @return bool true if message appears to be empty
*/
public function appearsToBeEmpty()
{
if ($this->getTextContent() !== '') {
return false;
}
/** @var \DOMElement $body */
$body = $this->getDocument()->getElementsByTagName('body')->item(0);
/** @var \DOMElement $element */
foreach ($body->getElementsByTagName('*') as $element) {
if (!\in_array($element->nodeName, self::$emptyTags)) {
return false;
}
}
return true;
}
/**
* Processes embedded content.
*/
public function processEmbeddedContent()
{
$this->embeddedContent = [];
$this->parseEmbeddedContent();
}
/**
* Returns the embedded content grouped by type.
*
* @return array
*/
public function getEmbeddedContent()
{
return $this->embeddedContent;
}
/**
* Add embedded content for provided type.
*
* @param string $type type name
* @param array $data embedded content
*/
public function addEmbeddedContent($type, array $data)
{
if (isset($this->embeddedContent[$type])) {
$this->embeddedContent[$type] = \array_merge($this->embeddedContent[$type], $data);
} else {
$this->embeddedContent[$type] = $data;
}
}
/**
* Parses embedded content contained in metacode elements.
*/
protected function parseEmbeddedContent()
{
// handle `woltlab-metacode`
$elements = $this->getDocument()->getElementsByTagName('woltlab-metacode');
$metacodesByName = [];
for ($i = 0, $length = $elements->length; $i < $length; $i++) {
/** @var \DOMElement $element */
$element = $elements->item($i);
$name = $element->getAttribute('data-name');
$attributes = $this->parseAttributes($element->getAttribute('data-attributes'));
if (!isset($metacodesByName[$name])) {
$metacodesByName[$name] = [];
}
$metacodesByName[$name][] = $attributes;
}
$this->embeddedContent = $metacodesByName;
EventHandler::getInstance()->fireAction($this, 'parseEmbeddedContent');
}
/**
* Creates a new `<woltlab-metacode>` element contained in the same document
* as the provided `$node`.
*
* @param \DOMNode $node reference node used to extract the owner document
* @param string $name metacode name
* @param mixed[] $attributes list of attributes
* @return \DOMElement new metacode element
*/
public function createMetacodeElement(\DOMNode $node, $name, array $attributes)
{
$element = $node->ownerDocument->createElement('woltlab-metacode');
$element->setAttribute('data-name', $name);
$element->setAttribute('data-attributes', \base64_encode(\json_encode($attributes)));
return $element;
}
/**
* Detects links that contain nothing but their link target. Additionally, standalone links, i. e.
* those that are the only content in their line, are offered separately.
*
* @since 5.2
*/
protected function convertPlainLinks()
{
/** @var \DOMElement $link */
foreach ($this->getDocument()->getElementsByTagName('a') as $link) {
$href = $link->getAttribute('href');
if ($href !== $link->textContent) {
continue;
}
$plainLink = new HtmlNodePlainLink($link, $href);
// Check if the line appears to only contain the link text.
$parent = $link;
while ($parent->parentNode->nodeName !== 'body') {
/** @var \DOMElement $parent */
$parent = $parent->parentNode;
}
$mayContainOtherContent = false;
$linebreaks = 0;
if ($parent->nodeName === 'p' && $parent->textContent === $link->textContent) {
// The line may contain nothing but the link, exceptions include basic formatting
// and up to a single `<br>` element.
/** @var \DOMElement $element */
foreach ($parent->getElementsByTagName('*') as $element) {
if ($this->mayContainOtherContent($element, $linebreaks)) {
$mayContainOtherContent = true;
break;
}
}
if (!$mayContainOtherContent || $linebreaks <= 1) {
$this->plainLinks[] = $plainLink->setIsStandalone($parent);
continue;
}
} elseif ($parent->nodeName === 'p') {
$parentLinkElement = $link;
$nextSibling = $this->getNonEmptyNode($parentLinkElement, 'nextSibling');
$previousSibling = $this->getNonEmptyNode($parentLinkElement, 'previousSibling');
while (
$parentLinkElement->parentNode !== $parent &&
$nextSibling === null &&
$previousSibling === null
) {
$parentLinkElement = $parentLinkElement->parentNode;
\assert($parentLinkElement instanceof \DOMElement);
$nextSibling = $this->getNonEmptyNode($parentLinkElement, 'nextSibling');
$previousSibling = $this->getNonEmptyNode($parentLinkElement, 'previousSibling');
}
// Check whether the link is the only content in the line.
// To do this, we need to check whether the next/previous sibling is a `<br>' element or
// is the start/end of the paragraph.
// <p><a href="https://example.com">https://example.com</a><br>…</p>
// <p>…<br><a href="https://example.com">https://example.com</a></p>
// <p>…<br><a href="https://example.com">https://example.com</a><br>…</p>
// <p>…<br><u><b><a href="https://example.com">https://example.com</a></b></u><br>…</p>
if ($nextSibling !== null && $nextSibling->nodeName === 'br') {
$nextSibling = null;
}
if ($previousSibling !== null && $previousSibling->nodeName === 'br') {
$previousSibling = null;
}
if ($nextSibling === null && $previousSibling === null) {
$this->plainLinks[] = $plainLink->setIsStandalone($parent, false);
continue;
}
}
$this->plainLinks[] = $plainLink->setIsInline();
}
EventHandler::getInstance()->fireAction($this, 'convertPlainLinks');
$isWorkerAction = \class_exists(AbstractWorker::class, false);
if (MODULE_URL_UNFURLING && !$isWorkerAction) {
foreach ($this->plainLinks as $plainLink) {
if ($plainLink->isPristine()) {
HtmlNodeUnfurlLink::setUnfurl($plainLink);
}
}
}
}
private function getNonEmptyNode(\DOMNode $element, string $property): ?\DOMNode
{
while ($element = $element->{$property}) {
if (!DOMUtil::isEmpty($element)) {
return $element;
}
}
return null;
}
private function mayContainOtherContent(\DOMElement $element, int &$linebreaks): bool
{
switch ($element->nodeName) {
case 'br':
$linebreaks++;
break;
case 'span':
if ($element->getAttribute('class')) {
return true;
}
// `<span>` is used to hold text formatting.
break;
case 'a':
case 'b':
case 'em':
case 'i':
case 'strong':
case 'u':
// These elements are perfectly fine.
break;
default:
return true;
}
return false;
}
}