Debian Codegraph @

vendor/wikimedia/parsoid/src/Utils/DOMUtils.php

raw
1 <?php
2 declare( strict_types = 1 );
3
4 namespace Wikimedia\Parsoid\Utils;
5
6 use Wikimedia\Assert\Assert;
7 use Wikimedia\Parsoid\Core\ClientError;
8 use Wikimedia\Parsoid\DOM\Comment;
9 use Wikimedia\Parsoid\DOM\Document;
10 use Wikimedia\Parsoid\DOM\DocumentFragment;
11 use Wikimedia\Parsoid\DOM\Element;
12 use Wikimedia\Parsoid\DOM\Node;
13 use Wikimedia\Parsoid\DOM\Text;
14 use Wikimedia\Parsoid\Wikitext\Consts;
15 use Wikimedia\Parsoid\Wt2Html\TreeBuilder\DOMBuilder;
16 use Wikimedia\Parsoid\Wt2Html\XMLSerializer;
17 use Wikimedia\RemexHtml\Tokenizer\Tokenizer;
18 use Wikimedia\RemexHtml\TreeBuilder\Dispatcher;
19 use Wikimedia\RemexHtml\TreeBuilder\TreeBuilder;
20
21 /**
22 * DOM utilities for querying the DOM. This is largely independent of Parsoid
23 * although some Parsoid details (TokenUtils, inline content version)
24 * have snuck in.
25 */
26 class DOMUtils {
27
28 /**
29 * Parse HTML, return the tree.
30 *
31 * @param string $html
32 * @param bool $validateXMLNames
33 * @return Document
34 */
35 public static function parseHTML(
36 string $html, bool $validateXMLNames = false
37 ): Document {
38 if ( !preg_match( '/^<(?:!doctype|html|body)/i', $html ) ) {
39 // Make sure that we parse fragments in the body. Otherwise comments,
40 // link and meta tags end up outside the html element or in the head
41 // elements.
42 $html = '<body>' . $html;
43 }
44
45 $domBuilder = new DOMBuilder; // our DOMBuilder, not remex's
46 $treeBuilder = new TreeBuilder( $domBuilder, [ 'ignoreErrors' => true ] );
47 $dispatcher = new Dispatcher( $treeBuilder );
48 $tokenizer = new Tokenizer( $dispatcher, $html, [ 'ignoreErrors' => true ] );
49 $tokenizer->execute( [] );
50 if ( $validateXMLNames && $domBuilder->isCoerced() ) {
51 throw new ClientError( 'Encountered a name invalid in XML.' );
52 }
53 $frag = $domBuilder->getFragment();
54 '@phan-var Document $frag'; // @var Document $frag
55 return $frag;
56 }
57
58 /**
59 * This is a simplified version of the DOMTraverser.
60 * Consider using that before making this more complex.
61 *
62 * FIXME: Move to DOMTraverser OR create a new class?
63 * @param Node $node
64 * @param callable $handler
65 * @param mixed ...$args
66 */
67 public static function visitDOM( Node $node, callable $handler, ...$args ): void {
68 $handler( $node, ...$args );
69 $node = $node->firstChild;
70 while ( $node ) {
71 $next = $node->nextSibling;
72 self::visitDOM( $node, $handler, ...$args );
73 $node = $next;
74 }
75 }
76
77 /**
78 * Move 'from'.childNodes to 'to' adding them before 'beforeNode'
79 * If 'beforeNode' is null, the nodes are appended at the end.
80 * @param Node $from Source node. Children will be removed.
81 * @param Node $to Destination node. Children of $from will be added here
82 * @param ?Node $beforeNode Add the children before this node.
83 */
84 public static function migrateChildren(
85 Node $from, Node $to, ?Node $beforeNode = null
86 ): void {
87 while ( $from->firstChild ) {
88 $to->insertBefore( $from->firstChild, $beforeNode );
89 }
90 }
91
92 /**
93 * Copy 'from'.childNodes to 'to' adding them before 'beforeNode'
94 * 'from' and 'to' belong to different documents.
95 *
96 * If 'beforeNode' is null, the nodes are appended at the end.
97 * @param Node $from
98 * @param Node $to
99 * @param ?Node $beforeNode
100 */
101 public static function migrateChildrenBetweenDocs(
102 Node $from, Node $to, ?Node $beforeNode = null
103 ): void {
104 $n = $from->firstChild;
105 $destDoc = $to->ownerDocument;
106 while ( $n ) {
107 $to->insertBefore( $destDoc->importNode( $n, true ), $beforeNode );
108 $n = $n->nextSibling;
109 }
110 }
111
112 // phpcs doesn't like @phan-assert...
113 // phpcs:disable MediaWiki.Commenting.FunctionAnnotations.UnrecognizedAnnotation
114
115 /**
116 * Assert that this is a DOM element node.
117 * This is primarily to help phan analyze variable types.
118 * @phan-assert Element $node
119 * @param ?Node $node
120 * @return bool Always returns true
121 * @phan-assert Element $node
122 */
123 public static function assertElt( ?Node $node ): bool {
124 Assert::invariant( $node instanceof Element, "Expected an element" );
125 return true;
126 }
127
128 /**
129 * @param ?Node $node
130 * @return bool
131 */
132 public static function isRemexBlockNode( ?Node $node ): bool {
133 return $node instanceof Element &&
134 !isset( Consts::$HTML['OnlyInlineElements'][DOMCompat::nodeName( $node )] ) &&
135 // This is a superset of \\MediaWiki\Tidy\RemexCompatMunger::$metadataElements
136 !self::isMetaDataTag( $node );
137 }
138
139 /**
140 * @param ?Node $node
141 * @return bool
142 */
143 public static function isWikitextBlockNode( ?Node $node ): bool {
144 return $node && TokenUtils::isWikitextBlockTag( DOMCompat::nodeName( $node ) );
145 }
146
147 /**
148 * Determine whether this is a formatting DOM element.
149 * @param ?Node $node
150 * @return bool
151 */
152 public static function isFormattingElt( ?Node $node ): bool {
153 return $node && isset( Consts::$HTML['FormattingTags'][DOMCompat::nodeName( $node )] );
154 }
155
156 /**
157 * Determine whether this is a quote DOM element.
158 * @param ?Node $node
159 * @return bool
160 */
161 public static function isQuoteElt( ?Node $node ): bool {
162 return $node && isset( Consts::$WTQuoteTags[DOMCompat::nodeName( $node )] );
163 }
164
165 /**
166 * Determine whether this is the <body> DOM element.
167 * @param ?Node $node
168 * @return bool
169 */
170 public static function isBody( ?Node $node ): bool {
171 return $node && DOMCompat::nodeName( $node ) === 'body';
172 }
173
174 /**
175 * Determine whether this is a removed DOM node but Node object yet
176 * @param ?Node $node
177 * @return bool
178 */
179 public static function isRemoved( ?Node $node ): bool {
180 return !$node || !isset( $node->nodeType );
181 }
182
183 /**
184 * Build path from a node to the root of the document.
185 *
186 * @param Node $node
187 * @return Node[] Path including all nodes from $node to the root of the document
188 */
189 public static function pathToRoot( Node $node ): array {
190 $path = [];
191 do {
192 $path[] = $node;
193 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
194 } while ( $node = $node->parentNode );
195 return $path;
196 }
197
198 /**
199 * Compute the edge length of the path from $node to the root.
200 * Root document is at depth 0, <html> at 1, <body> at 2.
201 * @param Node $node
202 * @return int
203 */
204 public static function nodeDepth( Node $node ): int {
205 $edges = 0;
206 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
207 while ( $node = $node->parentNode ) {
208 $edges++;
209 }
210 return $edges;
211 }
212
213 /**
214 * Build path from a node to its passed-in sibling.
215 * Return will not include the passed-in sibling.
216 *
217 * @param Node $node
218 * @param Node $sibling
219 * @param bool $left indicates whether to go backwards, use previousSibling instead of nextSibling.
220 * @return Node[]
221 */
222 public static function pathToSibling( Node $node, Node $sibling, bool $left ): array {
223 $path = [];
224 while ( $node && $node !== $sibling ) {
225 $path[] = $node;
226 $node = $left ? $node->previousSibling : $node->nextSibling;
227 }
228 return $path;
229 }
230
231 /**
232 * Check whether a node `n1` comes before another node `n2` in
233 * their parent's children list.
234 *
235 * @param Node $n1 The node you expect to come first.
236 * @param Node $n2 Expected later sibling.
237 * @return bool
238 */
239 public static function inSiblingOrder( Node $n1, Node $n2 ): bool {
240 while ( $n1 && $n1 !== $n2 ) {
241 $n1 = $n1->nextSibling;
242 }
243 return $n1 !== null;
244 }
245
246 /**
247 * Check that a node 'n1' is an ancestor of another node 'n2' in
248 * the DOM. Returns true if n1 === n2.
249 * $n1 is the suspected ancestor.
250 * $n2 The suspected descendant.
251 *
252 * @param Node $n1
253 * @param Node $n2
254 * @return bool
255 */
256 public static function isAncestorOf( Node $n1, Node $n2 ): bool {
257 while ( $n2 && $n2 !== $n1 ) {
258 $n2 = $n2->parentNode;
259 }
260 return $n2 !== null;
261 }
262
263 /**
264 * Find an ancestor of $node with nodeName $name.
265 *
266 * @param Node $node
267 * @param string $name
268 * @return ?Element
269 */
270 public static function findAncestorOfName( Node $node, string $name ): ?Element {
271 $node = $node->parentNode;
272 while ( $node && DOMCompat::nodeName( $node ) !== $name ) {
273 $node = $node->parentNode;
274 }
275 '@phan-var Element $node'; // @var Element $node
276 return $node;
277 }
278
279 /**
280 * Check whether $node has $name or has an ancestor named $name.
281 *
282 * @param Node $node
283 * @param string $name
284 * @return bool
285 */
286 public static function hasNameOrHasAncestorOfName( Node $node, string $name ): bool {
287 return DOMCompat::nodeName( $node ) === $name || self::findAncestorOfName( $node, $name ) !== null;
288 }
289
290 /**
291 * Determine whether the node matches the given nodeName and attribute value.
292 * Returns true if node name matches and the attribute equals "typeof"
293 *
294 * @param Node $n The node to test
295 * @param string $name The expected nodeName of $n
296 * @param string $typeRe Regular expression matching the expected value of
297 * `typeof` attribute.
298 * @return ?string The matching `typeof` value, or `null` if there is
299 * no match.
300 */
301 public static function matchNameAndTypeOf( Node $n, string $name, string $typeRe ): ?string {
302 return DOMCompat::nodeName( $n ) === $name ? self::matchTypeOf( $n, $typeRe ) : null;
303 }
304
305 /**
306 * Determine whether the node matches the given nodeName and typeof
307 * attribute value; the typeof is given as string.
308 *
309 * @param Node $n
310 * @param string $name node name to test for
311 * @param string $type Expected value of "typeof" attribute (literal string)
312 * @return bool True if the node matches.
313 */
314 public static function hasNameAndTypeOf( Node $n, string $name, string $type ): bool {
315 return self::matchNameAndTypeOf(
316 $n, $name, '/^' . preg_quote( $type, '/' ) . '$/'
317 ) !== null;
318 }
319
320 /**
321 * Determine whether the node matches the given `typeof` attribute value.
322 *
323 * @param Node $n The node to test
324 * @param string $typeRe Regular expression matching the expected value of
325 * the `typeof` attribute.
326 * @return ?string The matching `typeof` value, or `null` if there is
327 * no match.
328 */
329 public static function matchTypeOf( Node $n, string $typeRe ): ?string {
330 return self::matchMultivalAttr( $n, 'typeof', $typeRe );
331 }
332
333 /**
334 * Determine whether the node matches the given `rel` attribute value.
335 *
336 * @param Node $n The node to test
337 * @param string $relRe Regular expression matching the expected value of
338 * the `rel` attribute.
339 * @return ?string The matching `rel` value, or `null` if there is
340 * no match.
341 */
342 public static function matchRel( Node $n, string $relRe ): ?string {
343 return self::matchMultivalAttr( $n, 'rel', $relRe );
344 }
345
346 /**
347 * Determine whether the node matches the given multivalue attribute value.
348 *
349 * @param Node $n The node to test
350 * @param string $attrName the attribute to test (typically 'rel' or 'typeof')
351 * @param string $valueRe Regular expression matching the expected value of
352 * the attribute.
353 * @return ?string The matching attribute value, or `null` if there is
354 * no match.
355 */
356 private static function matchMultivalAttr( Node $n, string $attrName, string $valueRe ): ?string {
357 if ( !( $n instanceof Element ) ) {
358 return null;
359 }
360 $attrValue = DOMCompat::getAttribute( $n, $attrName );
361 if ( $attrValue === null || $attrValue === '' ) {
362 return null;
363 }
364 foreach ( explode( ' ', $attrValue ) as $ty ) {
365 if ( $ty === '' ) {
366 continue;
367 }
368 $count = preg_match( $valueRe, $ty );
369 Assert::invariant( $count !== false, "Bad regexp" );
370 if ( $count ) {
371 return $ty;
372 }
373 }
374 return null;
375 }
376
377 /**
378 * Determine whether the node matches the given typeof attribute value.
379 *
380 * @param Node $n
381 * @param string $type Expected value of "typeof" attribute, as a literal
382 * string.
383 * @return bool True if the node matches.
384 */
385 public static function hasTypeOf( Node $n, string $type ): bool {
386 return self::hasValueInMultivalAttr( $n, 'typeof', $type );
387 }
388
389 /**
390 * Determine whether the node matches the given rel attribute value.
391 *
392 * @param Node $n
393 * @param string $rel Expected value of "rel" attribute, as a literal string.
394 * @return bool True if the node matches.
395 */
396 public static function hasRel( Node $n, string $rel ): bool {
397 return self::hasValueInMultivalAttr( $n, 'rel', $rel );
398 }
399
400 /**
401 * @param Element $element
402 * @param string $regex Partial regular expression, e.g. "foo|bar"
403 * @return bool
404 */
405 public static function hasClass( Element $element, string $regex ): bool {
406 $value = DOMCompat::getAttribute( $element, 'class' );
407 return (bool)preg_match( '{(?<=^|\s)' . $regex . '(?=\s|$)}', $value ?? '' );
408 }
409
410 /**
411 * Determine whether the node matches the given attribute value for a multivalued attribute
412 * @param Node $n
413 * @param string $attrName name of the attribute to check (typically 'typeof', 'rel')
414 * @param string $value Expected value of $attrName" attribute, as a literal string.
415 * @return bool True if the node matches
416 */
417 private static function hasValueInMultivalAttr( Node $n, string $attrName, string $value ): bool {
418 // fast path
419 if ( !( $n instanceof Element ) ) {
420 return false;
421 }
422 $attrValue = DOMCompat::getAttribute( $n, $attrName );
423 if ( $attrValue === null || $attrValue === '' ) {
424 return false;
425 }
426 if ( $attrValue === $value ) {
427 return true;
428 }
429 // fallback
430 return in_array( $value, explode( ' ', $attrValue ), true );
431 }
432
433 /**
434 * Add a type to the typeof attribute. This method should almost always
435 * be used instead of `setAttribute`, to ensure we don't overwrite existing
436 * typeof information.
437 *
438 * @param Element $node node
439 * @param string $type type
440 * @param bool $prepend If true, adds value to start, rather than end.
441 * Use of this option in new code is discouraged.
442 */
443 public static function addTypeOf( Element $node, string $type, bool $prepend = false ): void {
444 self::addValueToMultivalAttr( $node, 'typeof', $type, $prepend );
445 }
446
447 /**
448 * Add a type to the rel attribute. This method should almost always
449 * be used instead of `setAttribute`, to ensure we don't overwrite existing
450 * rel information.
451 *
452 * @param Element $node node
453 * @param string $rel type
454 */
455 public static function addRel( Element $node, string $rel ): void {
456 self::addValueToMultivalAttr( $node, 'rel', $rel );
457 }
458
459 /**
460 * Add an element to a multivalue attribute (typeof, rel). This method should almost always
461 * be used instead of `setAttribute`, to ensure we don't overwrite existing
462 * multivalue information.
463 *
464 * @param Element $node
465 * @param string $attr
466 * @param string $value
467 * @param bool $prepend If true, adds value to start, rather than end
468 */
469 private static function addValueToMultivalAttr(
470 Element $node, string $attr, string $value, bool $prepend = false
471 ): void {
472 $value = trim( $value );
473 if ( $value === '' ) {
474 return;
475 }
476 $oldValue = DOMCompat::getAttribute( $node, $attr );
477 if ( $oldValue !== null && trim( $oldValue ) !== '' ) {
478 $values = explode( ' ', trim( $oldValue ) );
479 if ( in_array( $value, $values, true ) ) {
480 return;
481 }
482 $value = $prepend ? "$value $oldValue" : "$oldValue $value";
483 }
484 $node->setAttribute( $attr, $value );
485 }
486
487 /**
488 * Remove a value from a multiple-valued attribute.
489 *
490 * @param Element $node node
491 * @param string $attr The attribute name
492 * @param string $value The value to remove
493 */
494 private static function removeValueFromMultivalAttr(
495 Element $node, string $attr, string $value
496 ): void {
497 $oldValue = DOMCompat::getAttribute( $node, $attr );
498 if ( $oldValue !== null && $oldValue !== '' ) {
499 $value = trim( $value );
500 $types = array_diff( explode( ' ', $oldValue ), [ $value ] );
501 if ( count( $types ) > 0 ) {
502 $node->setAttribute( $attr, implode( ' ', $types ) );
503 } else {
504 $node->removeAttribute( $attr );
505 }
506 }
507 }
508
509 /**
510 * Remove a type from the typeof attribute.
511 *
512 * @param Element $node node
513 * @param string $type type
514 */
515 public static function removeTypeOf( Element $node, string $type ): void {
516 self::removeValueFromMultivalAttr( $node, 'typeof', $type );
517 }
518
519 /**
520 * Remove a type from the rel attribute.
521 *
522 * @param Element $node node
523 * @param string $rel rel
524 */
525 public static function removeRel( Element $node, string $rel ): void {
526 self::removeValueFromMultivalAttr( $node, 'rel', $rel );
527 }
528
529 /**
530 * Check whether `node` is in a fosterable position.
531 *
532 * @param ?Node $n
533 * @return bool
534 */
535 public static function isFosterablePosition( ?Node $n ): bool {
536 return $n && isset( Consts::$HTML['FosterablePosition'][DOMCompat::nodeName( $n->parentNode )] );
537 }
538
539 /**
540 * Check whether `node` is a heading.
541 *
542 * @param ?Node $n
543 * @return bool
544 */
545 public static function isHeading( ?Node $n ): bool {
546 return $n && preg_match( '/^h[1-6]$/D', DOMCompat::nodeName( $n ) );
547 }
548
549 /**
550 * Check whether `node` is a list.
551 *
552 * @param ?Node $n
553 * @return bool
554 */
555 public static function isList( ?Node $n ): bool {
556 return $n && isset( Consts::$HTML['ListTags'][DOMCompat::nodeName( $n )] );
557 }
558
559 /**
560 * Check whether `node` is a list item.
561 *
562 * @param ?Node $n
563 * @return bool
564 */
565 public static function isListItem( ?Node $n ): bool {
566 return $n && isset( Consts::$HTML['ListItemTags'][DOMCompat::nodeName( $n )] );
567 }
568
569 /**
570 * Check whether `node` is a list or list item.
571 *
572 * @param ?Node $n
573 * @return bool
574 */
575 public static function isListOrListItem( ?Node $n ): bool {
576 return self::isList( $n ) || self::isListItem( $n );
577 }
578
579 /**
580 * Check whether `node` is nestee in a list item.
581 *
582 * @param ?Node $n
583 * @return bool
584 */
585 public static function isNestedInListItem( ?Node $n ): bool {
586 $parentNode = $n->parentNode;
587 while ( $parentNode ) {
588 if ( self::isListItem( $parentNode ) ) {
589 return true;
590 }
591 $parentNode = $parentNode->parentNode;
592 }
593 return false;
594 }
595
596 /**
597 * Check whether `node` is a nested list or a list item.
598 *
599 * @param ?Node $n
600 * @return bool
601 */
602 public static function isNestedListOrListItem( ?Node $n ): bool {
603 return self::isListOrListItem( $n ) && self::isNestedInListItem( $n );
604 }
605
606 /**
607 * Check a node to see whether it's a meta with some typeof.
608 *
609 * @param Node $n
610 * @param string $type
611 * @return bool
612 */
613 public static function isMarkerMeta( Node $n, string $type ): bool {
614 return self::hasNameAndTypeOf( $n, 'meta', $type );
615 }
616
617 /**
618 * Check whether a node has any children that are elements.
619 *
620 * @param Node $node
621 * @return bool
622 */
623 public static function hasElementChild( Node $node ): bool {
624 for ( $child = $node->firstChild; $child; $child = $child->nextSibling ) {
625 if ( $child instanceof Element ) {
626 return true;
627 }
628 }
629 return false;
630 }
631
632 /**
633 * Check if a node has a block-level element descendant.
634 *
635 * @param Node $node
636 * @return bool
637 */
638 public static function hasBlockElementDescendant( Node $node ): bool {
639 for ( $child = $node->firstChild; $child; $child = $child->nextSibling ) {
640 if ( $child instanceof Element &&
641 ( self::isWikitextBlockNode( $child ) || // Is a block-level node
642 self::hasBlockElementDescendant( $child ) ) // or has a block-level child or grandchild or..
643 ) {
644 return true;
645 }
646 }
647 return false;
648 }
649
650 /**
651 * Is a node representing inter-element whitespace?
652 *
653 * @param ?Node $node
654 * @return bool
655 */
656 public static function isIEW( ?Node $node ): bool {
657 // ws-only
658 return $node instanceof Text && preg_match( '/^\s*$/D', $node->nodeValue );
659 }
660
661 /**
662 * Is a node a document fragment?
663 *
664 * @param ?Node $node
665 * @return bool
666 */
667 public static function isDocumentFragment( ?Node $node ): bool {
668 return $node && $node->nodeType === XML_DOCUMENT_FRAG_NODE;
669 }
670
671 /**
672 * Is a node at the top?
673 *
674 * @param ?Node $node
675 * @return bool
676 */
677 public static function atTheTop( ?Node $node ): bool {
678 return self::isDocumentFragment( $node ) || self::isBody( $node );
679 }
680
681 /**
682 * Are all children of this node text or comment nodes?
683 *
684 * @param Node $node
685 * @return bool
686 */
687 public static function allChildrenAreTextOrComments( Node $node ): bool {
688 $child = $node->firstChild;
689 while ( $child ) {
690 if ( !( $child instanceof Text || $child instanceof Comment ) ) {
691 return false;
692 }
693 $child = $child->nextSibling;
694 }
695 return true;
696 }
697
698 /**
699 * Check if the dom-subtree rooted at node has an element with tag name 'tagName'
700 * By default, the root node is not checked.
701 *
702 * @param Node $node The DOM node whose tree should be checked
703 * @param string $tagName Tag name to look for
704 * @param bool $checkRoot Should the root be checked?
705 * @return bool
706 */
707 public static function treeHasElement( Node $node, string $tagName, bool $checkRoot = false ): bool {
708 if ( $checkRoot && DOMCompat::nodeName( $node ) === $tagName ) {
709 return true;
710 }
711
712 $node = $node->firstChild;
713 while ( $node ) {
714 if ( $node instanceof Element ) {
715 if ( self::treeHasElement( $node, $tagName, true ) ) {
716 return true;
717 }
718 }
719 $node = $node->nextSibling;
720 }
721 return false;
722 }
723
724 /**
725 * Is node a table tag (table, tbody, td, tr, etc.)?
726 *
727 * @param Node $node
728 * @return bool
729 */
730 public static function isTableTag( Node $node ): bool {
731 return isset( Consts::$HTML['TableTags'][DOMCompat::nodeName( $node )] );
732 }
733
734 /**
735 * Returns a media element nested in `node`
736 *
737 * @param Element $node
738 * @return Element|null
739 */
740 public static function selectMediaElt( Element $node ): ?Element {
741 return DOMCompat::querySelector( $node, 'img, video, audio' );
742 }
743
744 /**
745 * Extract http-equiv headers from the HTML, including content-language and
746 * vary headers, if present
747 *
748 * @param Document $doc
749 * @return array<string,string>
750 */
751 public static function findHttpEquivHeaders( Document $doc ): array {
752 $elts = DOMCompat::querySelectorAll( $doc, 'meta[http-equiv][content]' );
753 $r = [];
754 foreach ( $elts as $el ) {
755 $r[strtolower(
756 DOMCompat::getAttribute( $el, 'http-equiv' )
757 )] = DOMCompat::getAttribute( $el, 'content' );
758 }
759 return $r;
760 }
761
762 /**
763 * Add or replace http-equiv headers in the HTML <head>.
764 * This is used for content-language and vary headers, among possible
765 * others.
766 * @param Document $doc The HTML document to update
767 * @param array<string,string|string[]> $headers An array mapping HTTP
768 * header names (which are case-insensitive) to new values. If an
769 * array of values is provided, they will be joined with commas.
770 */
771 public static function addHttpEquivHeaders( Document $doc, array $headers ): void {
772 foreach ( $headers as $key => $value ) {
773 if ( is_array( $value ) ) {
774 $value = implode( ',', $value );
775 }
776 // HTTP header names are case-insensitive; hence the "i" suffix
777 // on this selector query.
778 $el = DOMCompat::querySelector( $doc, "meta[http-equiv=\"{$key}\"i]" );
779 if ( !$el ) {
780 // This also ensures there is a <head> element.
781 $el = self::appendToHead( $doc, 'meta', [ 'http-equiv' => $key ] );
782 }
783 $el->setAttribute( 'content', $value );
784
785 }
786 }
787
788 /**
789 * @param Document $doc
790 * @return string|null
791 */
792 public static function extractInlinedContentVersion( Document $doc ): ?string {
793 $el = DOMCompat::querySelector( $doc,
794 'meta[property="mw:htmlVersion"], meta[property="mw:html:version"]' );
795 return $el ? DOMCompat::getAttribute( $el, 'content' ) : null;
796 }
797
798 /**
799 * Add attributes to a node element.
800 *
801 * @param Element $elt element
802 * @param array $attrs attributes
803 */
804 public static function addAttributes( Element $elt, array $attrs ): void {
805 foreach ( $attrs as $key => $value ) {
806 if ( $value !== null ) {
807 if ( $key === 'id' ) {
808 DOMCompat::setIdAttribute( $elt, $value );
809 } else {
810 $elt->setAttribute( $key, $value );
811 }
812 }
813 }
814 }
815
816 /**
817 * Create an element in the document head with the given attrs.
818 * Creates the head element in the document if needed.
819 *
820 * @param Document $document
821 * @param string $tagName
822 * @param array $attrs
823 * @return Element The newly-appended Element
824 */
825 public static function appendToHead( Document $document, string $tagName, array $attrs = [] ): Element {
826 $elt = $document->createElement( $tagName );
827 self::addAttributes( $elt, $attrs );
828 $head = DOMCompat::getHead( $document );
829 if ( !$head ) {
830 $head = $document->createElement( 'head' );
831 $document->documentElement->insertBefore(
832 $head, DOMCompat::getBody( $document )
833 );
834 }
835 $head->appendChild( $elt );
836 return $elt;
837 }
838
839 /**
840 * innerHTML and outerHTML are not defined on DocumentFragment.
841 *
842 * Defined similarly to DOMCompat::getInnerHTML()
843 *
844 * @param DocumentFragment $frag
845 * @return string
846 */
847 public static function getFragmentInnerHTML(
848 DocumentFragment $frag
849 ): string {
850 return XMLSerializer::serialize(
851 $frag, [ 'innerXML' => true ]
852 )['html'];
853 }
854
855 /**
856 * innerHTML and outerHTML are not defined on DocumentFragment.
857 * @see DOMCompat::setInnerHTML() for the Element version
858 *
859 * @param DocumentFragment $frag
860 * @param string $html
861 */
862 public static function setFragmentInnerHTML(
863 DocumentFragment $frag, string $html
864 ): void {
865 // FIXME: This should be an HTML5 template element
866 $body = $frag->ownerDocument->createElement( 'body' );
867 DOMCompat::setInnerHTML( $body, $html );
868 self::migrateChildren( $body, $frag );
869 }
870
871 /**
872 * @param Document $doc
873 * @param string $html
874 * @return DocumentFragment
875 */
876 public static function parseHTMLToFragment(
877 Document $doc, string $html
878 ): DocumentFragment {
879 $frag = $doc->createDocumentFragment();
880 self::setFragmentInnerHTML( $frag, $html );
881 return $frag;
882 }
883
884 /**
885 * @param Node $node
886 * @return bool
887 */
888 public static function isRawTextElement( Node $node ): bool {
889 return isset( Consts::$HTML['RawTextElements'][DOMCompat::nodeName( $node )] );
890 }
891
892 /**
893 * Is 'n' a block tag, or does the subtree rooted at 'n' have a block tag
894 * in it?
895 *
896 * @param Node $n
897 * @return bool
898 */
899 public static function hasBlockTag( Node $n ): bool {
900 if ( self::isRemexBlockNode( $n ) ) {
901 return true;
902 }
903 $c = $n->firstChild;
904 while ( $c ) {
905 if ( self::hasBlockTag( $c ) ) {
906 return true;
907 }
908 $c = $c->nextSibling;
909 }
910 return false;
911 }
912
913 /**
914 * Get an associative array of attributes, suitable for serialization.
915 *
916 * Add the xmlns attribute if available, to workaround PHP's surprising
917 * behavior with the xmlns attribute: HTML is *not* an XML document,
918 * but various parts of PHP (including our misnamed XMLSerializer) pretend
919 * that it is, sort of.
920 *
921 * @param Element $element
922 * @return array<string,string>
923 * @see https://phabricator.wikimedia.org/T235295
924 */
925 public static function attributes( Element $element ): array {
926 $result = [];
927 // The 'xmlns' attribute is "invisible" T235295
928 $xmlns = DOMCompat::getAttribute( $element, 'xmlns' );
929 if ( $xmlns !== null ) {
930 $result['xmlns'] = $xmlns;
931 }
932 foreach ( $element->attributes as $attr ) {
933 $result[$attr->name] = $attr->value;
934 }
935 return $result;
936 }
937
938 /**
939 * @param Element $node
940 * @return bool
941 */
942 public static function isMetaDataTag( Element $node ): bool {
943 return isset( Consts::$HTML['MetaDataTags'][DOMCompat::nodeName( $node )] );
944 }
945
946 /**
947 * Strip a paragraph wrapper, if any, before parsing HTML to DOM
948 */
949 public static function stripPWrapper( string $ret ): string {
950 return preg_replace( '#(^<p>)|(\n</p>(' . Utils::COMMENT_REGEXP_FRAGMENT . '|\s)*$)#D', '', $ret );
951 }
952 }