3 * An implementation of the tree building portion of the HTML5 parsing
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
24 * @author C. Scott Ananian, 2016
26 namespace MediaWiki\Tidy
;
28 use Wikimedia\Assert\Assert
;
29 use Wikimedia\Assert\ParameterAssertionException
;
31 use \IteratorAggregate
;
32 use \ReverseArrayIterator
;
35 # A note for future librarization[1] -- this file is a good candidate
36 # for splitting into an independent library, except that it is currently
37 # highly optimized for MediaWiki use. It only implements the portions
38 # of the HTML5 tree builder used by tags supported by MediaWiki, and
39 # does not contain a true tokenizer pass, instead relying on
40 # comment stripping, attribute normalization, and escaping done by
41 # the MediaWiki Sanitizer. It also deliberately avoids building
42 # a true DOM in memory, instead serializing elements to an output string
43 # as soon as possible (usually as soon as the tag is closed) to reduce
44 # its memory footprint.
46 # We've been gradually lifting some of these restrictions to handle
47 # non-sanitized output generated by extensions, but we shortcut the tokenizer
48 # for speed (primarily by splitting on `<`) and so rely on syntactic
51 # On the other hand, I've been pretty careful to note with comments in the
52 # code the places where this implementation omits features of the spec or
53 # depends on the MediaWiki Sanitizer. Perhaps in the future we'll want to
54 # implement the missing pieces and make this a standalone PHP HTML5 parser.
55 # In order to do so, some sort of MediaWiki-specific API will need
56 # to be added to (a) allow the Balancer to bypass the tokenizer,
57 # and (b) support on-the-fly flattening instead of DOM node creation.
59 # [1]: https://www.mediawiki.org/wiki/Library_infrastructure_for_MediaWiki
62 * Utility constants and sets for the HTML5 tree building algorithm.
63 * Sets are associative arrays indexed first by namespace and then by
64 * lower-cased tag name.
70 const HTML_NAMESPACE
= 'http://www.w3.org/1999/xhtml';
71 const MATHML_NAMESPACE
= 'http://www.w3.org/1998/Math/MathML';
72 const SVG_NAMESPACE
= 'http://www.w3.org/2000/svg';
74 public static $unsupportedSet = [
75 self
::HTML_NAMESPACE
=> [
76 'html' => true, 'head' => true, 'body' => true, 'frameset' => true,
78 'plaintext' => true, 'isindex' => true,
79 'xmp' => true, 'iframe' => true, 'noembed' => true,
80 'noscript' => true, 'script' => true,
85 public static $emptyElementSet = [
86 self
::HTML_NAMESPACE
=> [
87 'area' => true, 'base' => true, 'basefont' => true,
88 'bgsound' => true, 'br' => true, 'col' => true, 'command' => true,
89 'embed' => true, 'frame' => true, 'hr' => true, 'img' => true,
90 'input' => true, 'keygen' => true, 'link' => true, 'meta' => true,
91 'param' => true, 'source' => true, 'track' => true, 'wbr' => true
95 public static $extraLinefeedSet = [
96 self
::HTML_NAMESPACE
=> [
97 'pre' => true, 'textarea' => true, 'listing' => true,
101 public static $headingSet = [
102 self
::HTML_NAMESPACE
=> [
103 'h1' => true, 'h2' => true, 'h3' => true,
104 'h4' => true, 'h5' => true, 'h6' => true
108 public static $specialSet = [
109 self
::HTML_NAMESPACE
=> [
110 'address' => true, 'applet' => true, 'area' => true,
111 'article' => true, 'aside' => true, 'base' => true,
112 'basefont' => true, 'bgsound' => true, 'blockquote' => true,
113 'body' => true, 'br' => true, 'button' => true, 'caption' => true,
114 'center' => true, 'col' => true, 'colgroup' => true, 'dd' => true,
115 'details' => true, 'dir' => true, 'div' => true, 'dl' => true,
116 'dt' => true, 'embed' => true, 'fieldset' => true,
117 'figcaption' => true, 'figure' => true, 'footer' => true,
118 'form' => true, 'frame' => true, 'frameset' => true, 'h1' => true,
119 'h2' => true, 'h3' => true, 'h4' => true, 'h5' => true,
120 'h6' => true, 'head' => true, 'header' => true, 'hgroup' => true,
121 'hr' => true, 'html' => true, 'iframe' => true, 'img' => true,
122 'input' => true, 'isindex' => true, 'li' => true, 'link' => true,
123 'listing' => true, 'main' => true, 'marquee' => true,
124 'menu' => true, 'menuitem' => true, 'meta' => true, 'nav' => true,
125 'noembed' => true, 'noframes' => true, 'noscript' => true,
126 'object' => true, 'ol' => true, 'p' => true, 'param' => true,
127 'plaintext' => true, 'pre' => true, 'script' => true,
128 'section' => true, 'select' => true, 'source' => true,
129 'style' => true, 'summary' => true, 'table' => true,
130 'tbody' => true, 'td' => true, 'template' => true,
131 'textarea' => true, 'tfoot' => true, 'th' => true, 'thead' => true,
132 'title' => true, 'tr' => true, 'track' => true, 'ul' => true,
133 'wbr' => true, 'xmp' => true
135 self
::SVG_NAMESPACE
=> [
136 'foreignobject' => true, 'desc' => true, 'title' => true
138 self
::MATHML_NAMESPACE
=> [
139 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
140 'mtext' => true, 'annotation-xml' => true
144 public static $addressDivPSet = [
145 self
::HTML_NAMESPACE
=> [
146 'address' => true, 'div' => true, 'p' => true
150 public static $tableSectionRowSet = [
151 self
::HTML_NAMESPACE
=> [
152 'table' => true, 'thead' => true, 'tbody' => true,
153 'tfoot' => true, 'tr' => true
157 public static $impliedEndTagsSet = [
158 self
::HTML_NAMESPACE
=> [
159 'dd' => true, 'dt' => true, 'li' => true, 'optgroup' => true,
160 'option' => true, 'p' => true, 'rb' => true, 'rp' => true,
161 'rt' => true, 'rtc' => true
165 public static $thoroughImpliedEndTagsSet = [
166 self
::HTML_NAMESPACE
=> [
167 'caption' => true, 'colgroup' => true, 'dd' => true, 'dt' => true,
168 'li' => true, 'optgroup' => true, 'option' => true, 'p' => true,
169 'rb' => true, 'rp' => true, 'rt' => true, 'rtc' => true,
170 'tbody' => true, 'td' => true, 'tfoot' => true, 'th' => true,
171 'thead' => true, 'tr' => true
175 public static $tableCellSet = [
176 self
::HTML_NAMESPACE
=> [
177 'td' => true, 'th' => true
180 public static $tableContextSet = [
181 self
::HTML_NAMESPACE
=> [
182 'table' => true, 'template' => true, 'html' => true
186 public static $tableBodyContextSet = [
187 self
::HTML_NAMESPACE
=> [
188 'tbody' => true, 'tfoot' => true, 'thead' => true,
189 'template' => true, 'html' => true
193 public static $tableRowContextSet = [
194 self
::HTML_NAMESPACE
=> [
195 'tr' => true, 'template' => true, 'html' => true
199 // See https://html.spec.whatwg.org/multipage/forms.html#form-associated-element
200 public static $formAssociatedSet = [
201 self
::HTML_NAMESPACE
=> [
202 'button' => true, 'fieldset' => true, 'input' => true,
203 'keygen' => true, 'object' => true, 'output' => true,
204 'select' => true, 'textarea' => true, 'img' => true
208 public static $inScopeSet = [
209 self
::HTML_NAMESPACE
=> [
210 'applet' => true, 'caption' => true, 'html' => true,
211 'marquee' => true, 'object' => true,
212 'table' => true, 'td' => true, 'template' => true,
215 self
::SVG_NAMESPACE
=> [
216 'foreignobject' => true, 'desc' => true, 'title' => true
218 self
::MATHML_NAMESPACE
=> [
219 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
220 'mtext' => true, 'annotation-xml' => true
224 private static $inListItemScopeSet = null;
225 public static function inListItemScopeSet() {
226 if ( self
::$inListItemScopeSet === null ) {
227 self
::$inListItemScopeSet = self
::$inScopeSet;
228 self
::$inListItemScopeSet[self
::HTML_NAMESPACE
]['ol'] = true;
229 self
::$inListItemScopeSet[self
::HTML_NAMESPACE
]['ul'] = true;
231 return self
::$inListItemScopeSet;
234 private static $inButtonScopeSet = null;
235 public static function inButtonScopeSet() {
236 if ( self
::$inButtonScopeSet === null ) {
237 self
::$inButtonScopeSet = self
::$inScopeSet;
238 self
::$inButtonScopeSet[self
::HTML_NAMESPACE
]['button'] = true;
240 return self
::$inButtonScopeSet;
243 public static $inTableScopeSet = [
244 self
::HTML_NAMESPACE
=> [
245 'html' => true, 'table' => true, 'template' => true
249 public static $inInvertedSelectScopeSet = [
250 self
::HTML_NAMESPACE
=> [
251 'option' => true, 'optgroup' => true
255 public static $mathmlTextIntegrationPointSet = [
256 self
::MATHML_NAMESPACE
=> [
257 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
262 public static $htmlIntegrationPointSet = [
263 self
::SVG_NAMESPACE
=> [
264 'foreignobject' => true,
270 // For tidy compatibility.
271 public static $tidyPWrapSet = [
272 self
::HTML_NAMESPACE
=> [
273 'body' => true, 'blockquote' => true,
274 // We parse with <body> as the fragment context, but the top-level
275 // element on the stack is actually <html>. We could use the
276 // "adjusted current node" everywhere to work around this, but it's
277 // easier just to add <html> to the p-wrap set.
281 public static $tidyInlineSet = [
282 self
::HTML_NAMESPACE
=> [
283 'a' => true, 'abbr' => true, 'acronym' => true, 'applet' => true,
284 'b' => true, 'basefont' => true, 'bdo' => true, 'big' => true,
285 'br' => true, 'button' => true, 'cite' => true, 'code' => true,
286 'dfn' => true, 'em' => true, 'font' => true, 'i' => true,
287 'iframe' => true, 'img' => true, 'input' => true, 'kbd' => true,
288 'label' => true, 'legend' => true, 'map' => true, 'object' => true,
289 'param' => true, 'q' => true, 'rb' => true, 'rbc' => true,
290 'rp' => true, 'rt' => true, 'rtc' => true, 'ruby' => true,
291 's' => true, 'samp' => true, 'select' => true, 'small' => true,
292 'span' => true, 'strike' => true, 'strong' => true, 'sub' => true,
293 'sup' => true, 'textarea' => true, 'tt' => true, 'u' => true,
300 * A BalanceElement is a simplified version of a DOM Node. The main
301 * difference is that we only keep BalanceElements around for nodes
302 * currently on the BalanceStack of open elements. As soon as an
303 * element is closed, with some minor exceptions relating to the
304 * tree builder "adoption agency algorithm", the element and all its
305 * children are serialized to a string using the flatten() method.
306 * This keeps our memory usage low.
311 class BalanceElement
{
313 * The namespace of the element.
314 * @var string $namespaceURI
316 public $namespaceURI;
318 * The lower-cased name of the element.
319 * @var string $localName
323 * Attributes for the element, in array form
324 * @var array $attribs
329 * Parent of this element, or the string "flat" if this element has
330 * already been flattened into its parent.
331 * @var string|null $parent
336 * An array of children of this element. Typically only the last
337 * child will be an actual BalanceElement object; the rest will
338 * be strings, representing either text nodes or flattened
339 * BalanceElement objects.
340 * @var array $children
345 * A unique string identifier for Noah's Ark purposes, lazy initialized
350 * The next active formatting element in the list, or null if this is the
351 * end of the AFE list or if the element is not in the AFE list.
356 * The previous active formatting element in the list, or null if this is
357 * the start of the list or if the element is not in the AFE list.
362 * The next element in the Noah's Ark species bucket.
367 * Make a new BalanceElement corresponding to the HTML DOM Element
368 * with the given localname, namespace, and attributes.
370 * @param string $namespaceURI The namespace of the element.
371 * @param string $localName The lowercased name of the tag.
372 * @param array $attribs Attributes of the element
374 public function __construct( $namespaceURI, $localName, array $attribs ) {
375 $this->localName
= $localName;
376 $this->namespaceURI
= $namespaceURI;
377 $this->attribs
= $attribs;
378 $this->contents
= '';
379 $this->parent
= null;
380 $this->children
= [];
384 * Remove the given child from this element.
385 * @param BalanceElement $elt
387 private function removeChild( BalanceElement
$elt ) {
388 Assert
::precondition(
389 $this->parent
!== 'flat', "Can't removeChild after flattening $this"
392 $elt->parent
=== $this, 'elt', 'must have $this as a parent'
394 $idx = array_search( $elt, $this->children
, true );
395 Assert
::parameter( $idx !== false, '$elt', 'must be a child of $this' );
397 array_splice( $this->children
, $idx, 1 );
401 * Find $a in the list of children and insert $b before it.
402 * @param BalanceElement $a
403 * @param BalanceElement|string $b
405 public function insertBefore( BalanceElement
$a, $b ) {
406 Assert
::precondition(
407 $this->parent
!== 'flat', "Can't insertBefore after flattening."
409 $idx = array_search( $a, $this->children
, true );
410 Assert
::parameter( $idx !== false, '$a', 'must be a child of $this' );
411 if ( is_string( $b ) ) {
412 array_splice( $this->children
, $idx, 0, [ $b ] );
414 Assert
::parameter( $b->parent
!== 'flat', '$b', "Can't be flat" );
415 if ( $b->parent
!== null ) {
416 $b->parent
->removeChild( $b );
418 array_splice( $this->children
, $idx, 0, [ $b ] );
424 * Append $elt to the end of the list of children.
425 * @param BalanceElement|string $elt
427 public function appendChild( $elt ) {
428 Assert
::precondition(
429 $this->parent
!== 'flat', "Can't appendChild after flattening."
431 if ( is_string( $elt ) ) {
432 array_push( $this->children
, $elt );
435 // Remove $elt from parent, if it had one.
436 if ( $elt->parent
!== null ) {
437 $elt->parent
->removeChild( $elt );
439 array_push( $this->children
, $elt );
440 $elt->parent
= $this;
444 * Transfer all of the children of $elt to $this.
445 * @param BalanceElement $elt
447 public function adoptChildren( BalanceElement
$elt ) {
448 Assert
::precondition(
449 $elt->parent
!== 'flat', "Can't adoptChildren after flattening."
451 foreach ( $elt->children
as $child ) {
452 if ( !is_string( $child ) ) {
453 // This is an optimization which avoids an O(n^2) set of
454 // array_splice operations.
455 $child->parent
= null;
457 $this->appendChild( $child );
463 * Flatten this node and all of its children into a string, as specified
464 * by the HTML serialization specification, and replace this node
465 * in its parent by that string.
469 public function flatten( $tidyCompat = false ) {
470 Assert
::parameter( $this->parent
!== null, '$this', 'must be a child' );
471 Assert
::parameter( $this->parent
!== 'flat', '$this', 'already flat' );
472 $idx = array_search( $this, $this->parent
->children
, true );
474 $idx !== false, '$this', 'must be a child of its parent'
478 foreach ( $this->children
as $elt ) {
479 if ( !is_string( $elt ) ) {
480 $elt = $elt->flatten( $tidyCompat );
482 if ( $blank && preg_match( '/[^\t\n\f\r ]/', $elt ) ) {
486 if ( $this->isHtmlNamed( 'mw:p-wrap' ) ) {
487 $this->localName
= 'p';
488 } elseif ( $blank ) {
489 // Add 'mw-empty-elt' class so elements can be hidden via CSS
490 // for compatibility with legacy tidy.
491 if ( !count( $this->attribs
) &&
492 ( $this->localName
=== 'tr' ||
$this->localName
=== 'li' )
494 $this->attribs
= [ 'class' => "mw-empty-elt" ];
498 $flat = $blank ?
'' : "{$this}";
502 $this->parent
->children
[$idx] = $flat;
503 $this->parent
= 'flat'; # for assertion checking
508 * Serialize this node and all of its children to a string, as specified
509 * by the HTML serialization specification.
511 * @return string The serialization of the BalanceElement
512 * @see https://html.spec.whatwg.org/multipage/syntax.html#serialising-html-fragments
514 public function __toString() {
516 foreach ( $this->attribs
as $name => $value ) {
517 $encValue = Sanitizer
::encodeAttribute( $value );
518 $encAttribs .= " $name=\"$encValue\"";
520 if ( !$this->isA( BalanceSets
::$emptyElementSet ) ) {
521 $out = "<{$this->localName}{$encAttribs}>";
522 $len = strlen( $out );
524 foreach ( $this->children
as $elt ) {
527 $out .= "</{$this->localName}>";
529 $this->isA( BalanceSets
::$extraLinefeedSet ) &&
532 // Double the linefeed after pre/listing/textarea
533 // according to the HTML5 fragment serialization algorithm.
534 $out = substr( $out, 0, $len +
1 ) .
535 substr( $out, $len );
538 $out = "<{$this->localName}{$encAttribs} />";
540 count( $this->children
) === 0,
541 "Empty elements shouldn't have children."
547 # Utility functions on BalanceElements.
550 * Determine if $this represents a specific HTML tag, is a member of
551 * a tag set, or is equal to another BalanceElement.
553 * @param BalanceElement|array|string $set The target BalanceElement,
554 * set (from the BalanceSets class), or string (HTML tag name).
557 public function isA( $set ) {
558 if ( $set instanceof BalanceElement
) {
559 return $this === $set;
560 } elseif ( is_array( $set ) ) {
561 return isset( $set[$this->namespaceURI
] ) &&
562 isset( $set[$this->namespaceURI
][$this->localName
] );
564 # assume this is an HTML element name.
565 return $this->isHtml() && $this->localName
=== $set;
570 * Determine if this element is an HTML element with the specified name
571 * @param string $tagName
574 public function isHtmlNamed( $tagName ) {
575 return $this->namespaceURI
=== BalanceSets
::HTML_NAMESPACE
576 && $this->localName
=== $tagName;
580 * Determine if $this represents an element in the HTML namespace.
584 public function isHtml() {
585 return $this->namespaceURI
=== BalanceSets
::HTML_NAMESPACE
;
589 * Determine if $this represents a MathML text integration point,
590 * as defined in the HTML5 specification.
593 * @see https://html.spec.whatwg.org/multipage/syntax.html#mathml-text-integration-point
595 public function isMathmlTextIntegrationPoint() {
596 return $this->isA( BalanceSets
::$mathmlTextIntegrationPointSet );
600 * Determine if $this represents an HTML integration point,
601 * as defined in the HTML5 specification.
604 * @see https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
606 public function isHtmlIntegrationPoint() {
607 if ( $this->isA( BalanceSets
::$htmlIntegrationPointSet ) ) {
611 $this->namespaceURI
=== BalanceSets
::MATHML_NAMESPACE
&&
612 $this->localName
=== 'annotation-xml' &&
613 isset( $this->attribs
['encoding'] ) &&
614 ( strcasecmp( $this->attribs
['encoding'], 'text/html' ) == 0 ||
615 strcasecmp( $this->attribs
['encoding'], 'application/xhtml+xml' ) == 0 )
623 * Get a string key for the Noah's Ark algorithm
625 public function getNoahKey() {
626 if ( $this->noahKey
=== null ) {
627 $attribs = $this->attribs
;
629 $this->noahKey
= serialize( [ $this->namespaceURI
, $this->localName
, $attribs ] );
631 return $this->noahKey
;
636 * The "stack of open elements" as defined in the HTML5 tree builder
637 * spec. This contains methods to ensure that content (start tags, text)
638 * are inserted at the correct place in the output string, and to
639 * flatten BalanceElements are they are closed to avoid holding onto
640 * a complete DOM tree for the document in memory.
642 * The stack defines a PHP iterator to traverse it in "reverse order",
643 * that is, the most-recently-added element is visited first in a
648 * @see https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements
650 class BalanceStack
implements IteratorAggregate
{
652 * Backing storage for the stack.
653 * @var array $elements
655 private $elements = [];
657 * Foster parent mode determines how nodes are inserted into the
659 * @var bool $fosterParentMode
660 * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
662 public $fosterParentMode = false;
664 * Tidy compatibility mode, determines behavior of body/blockquote
666 public $tidyCompat = false;
668 * Reference to the current element
673 * Create a new BalanceStack with a single BalanceElement on it,
674 * representing the root <html> node.
676 public function __construct() {
677 # always a root <html> element on the stack
680 new BalanceElement( BalanceSets
::HTML_NAMESPACE
, 'html', [] )
682 $this->currentNode
= $this->elements
[0];
686 * Return a string representing the output of the tree builder:
687 * all the children of the root <html> node.
690 public function getOutput() {
691 // Don't include the outer '<html>....</html>'
693 foreach ( $this->elements
[0]->children
as $elt ) {
694 $out .= is_string( $elt ) ?
$elt :
695 $elt->flatten( $this->tidyCompat
);
701 * Insert a comment at the appropriate place for inserting a node.
702 * @param string $value Content of the comment.
703 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-a-comment
705 public function insertComment( $value ) {
706 // Just another type of text node, except for tidy p-wrapping.
707 return $this->insertText( '<!--' . $value . '-->', true );
711 * Insert text at the appropriate place for inserting a node.
712 * @param string $value
713 * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
715 public function insertText( $value, $isComment = false ) {
717 $this->fosterParentMode
&&
718 $this->currentNode
->isA( BalanceSets
::$tableSectionRowSet )
720 $this->fosterParent( $value );
722 $this->tidyCompat
&& !$isComment &&
723 $this->currentNode
->isA( BalanceSets
::$tidyPWrapSet )
725 $this->insertHTMLELement( 'mw:p-wrap', [] );
726 return $this->insertText( $value );
728 $this->currentNode
->appendChild( $value );
733 * Insert a BalanceElement at the appropriate place, pushing it
734 * on to the open elements stack.
735 * @param string $namespaceURI The element namespace
736 * @param string $tag The tag name
737 * @param string $attribs Normalized attributes, as a string.
738 * @return BalanceElement
739 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-a-foreign-element
741 public function insertForeignElement( $namespaceURI, $tag, $attribs ) {
742 return $this->insertElement(
743 new BalanceElement( $namespaceURI, $tag, $attribs )
748 * Insert an HTML element at the appropriate place, pushing it on to
749 * the open elements stack.
750 * @param string $tag The tag name
751 * @param string $attribs Normalized attributes, as a string.
752 * @return BalanceElement
753 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-an-html-element
755 public function insertHTMLElement( $tag, $attribs ) {
756 return $this->insertForeignElement(
757 BalanceSets
::HTML_NAMESPACE
, $tag, $attribs
762 * Insert an element at the appropriate place and push it on to the
763 * open elements stack.
764 * @param BalanceElement $elt
765 * @return BalanceElement
766 * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
768 public function insertElement( BalanceElement
$elt ) {
770 $this->currentNode
->isHtmlNamed( 'mw:p-wrap' ) &&
771 !$elt->isA( BalanceSets
::$tidyInlineSet )
773 // Tidy compatibility.
777 $this->fosterParentMode
&&
778 $this->currentNode
->isA( BalanceSets
::$tableSectionRowSet )
780 $elt = $this->fosterParent( $elt );
782 $this->currentNode
->appendChild( $elt );
784 Assert
::invariant( $elt->parent
!== null, "$elt must be in tree" );
785 Assert
::invariant( $elt->parent
!== 'flat', "$elt must not have been previous flattened" );
786 array_push( $this->elements
, $elt );
787 $this->currentNode
= $elt;
792 * Determine if the stack has $tag in scope.
793 * @param BalanceElement|array|string $tag
795 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
797 public function inScope( $tag ) {
798 return $this->inSpecificScope( $tag, BalanceSets
::$inScopeSet );
802 * Determine if the stack has $tag in button scope.
803 * @param BalanceElement|array|string $tag
805 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
807 public function inButtonScope( $tag ) {
808 return $this->inSpecificScope( $tag, BalanceSets
::inButtonScopeSet() );
812 * Determine if the stack has $tag in list item scope.
813 * @param BalanceElement|array|string $tag
815 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-list-item-scope
817 public function inListItemScope( $tag ) {
818 return $this->inSpecificScope( $tag, BalanceSets
::inListItemScopeSet() );
822 * Determine if the stack has $tag in table scope.
823 * @param BalanceElement|array|string $tag
825 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-table-scope
827 public function inTableScope( $tag ) {
828 return $this->inSpecificScope( $tag, BalanceSets
::$inTableScopeSet );
832 * Determine if the stack has $tag in select scope.
833 * @param BalanceElement|array|string $tag
835 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-select-scope
837 public function inSelectScope( $tag ) {
838 // Can't use inSpecificScope to implement this, since it involves
839 // *inverting* a set of tags. Implement manually.
840 foreach ( $this as $elt ) {
841 if ( $elt->isA( $tag ) ) {
844 if ( !$elt->isA( BalanceSets
::$inInvertedSelectScopeSet ) ) {
852 * Determine if the stack has $tag in a specific scope, $set.
853 * @param BalanceElement|array|string $tag
854 * @param BalanceElement|array|string $set
856 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-the-specific-scope
858 public function inSpecificScope( $tag, $set ) {
859 foreach ( $this as $elt ) {
860 if ( $elt->isA( $tag ) ) {
863 if ( $elt->isA( $set ) ) {
871 * Generate implied end tags.
872 * @param string $butnot
873 * @param bool $thorough True if we should generate end tags thoroughly.
874 * @see https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
876 public function generateImpliedEndTags( $butnot = null, $thorough = false ) {
877 $endTagSet = $thorough ?
878 BalanceSets
::$thoroughImpliedEndTagsSet :
879 BalanceSets
::$impliedEndTagsSet;
880 while ( $this->currentNode
) {
881 if ( $butnot !== null && $this->currentNode
->isHtmlNamed( $butnot ) ) {
884 if ( !$this->currentNode
->isA( $endTagSet ) ) {
892 * Return the adjusted current node.
894 public function adjustedCurrentNode( $fragmentContext ) {
895 return ( $fragmentContext && count( $this->elements
) === 1 ) ?
896 $fragmentContext : $this->currentNode
;
900 * Return an iterator over this stack which visits the current node
901 * first, and the root node last.
904 public function getIterator() {
905 return new ReverseArrayIterator( $this->elements
);
909 * Return the BalanceElement at the given position $idx, where
910 * position 0 represents the root element.
912 * @return BalanceElement
914 public function node( $idx ) {
915 return $this->elements
[ $idx ];
919 * Replace the element at position $idx in the BalanceStack with $elt.
921 * @param BalanceElement $elt
923 public function replaceAt( $idx, BalanceElement
$elt ) {
924 Assert
::precondition(
925 $this->elements
[$idx]->parent
!== 'flat',
926 'Replaced element should not have already been flattened.'
928 Assert
::precondition(
929 $elt->parent
!== 'flat',
930 'New element should not have already been flattened.'
932 $this->elements
[$idx] = $elt;
933 if ( $idx === count( $this->elements
) - 1 ) {
934 $this->currentNode
= $elt;
939 * Return the position of the given BalanceElement, set, or
940 * HTML tag name string in the BalanceStack.
941 * @param BalanceElement|array|string $tag
944 public function indexOf( $tag ) {
945 for ( $i = count( $this->elements
) - 1; $i >= 0; $i-- ) {
946 if ( $this->elements
[$i]->isA( $tag ) ) {
954 * Return the number of elements currently in the BalanceStack.
957 public function length() {
958 return count( $this->elements
);
962 * Remove the current node from the BalanceStack, flattening it
965 public function pop() {
966 $elt = array_pop( $this->elements
);
967 if ( count( $this->elements
) ) {
968 $this->currentNode
= $this->elements
[ count( $this->elements
) - 1 ];
970 $this->currentNode
= null;
972 if ( !$elt->isHtmlNamed( 'mw:p-wrap' ) ) {
973 $elt->flatten( $this->tidyCompat
);
978 * Remove all nodes up to and including position $idx from the
979 * BalanceStack, flattening them in the process.
982 public function popTo( $idx ) {
983 $length = count( $this->elements
);
984 for ( $length = count( $this->elements
); $length > $idx; $length-- ) {
990 * Pop elements off the stack up to and including the first
991 * element with the specified HTML tagname (or matching the given
993 * @param BalanceElement|array|string $tag
995 public function popTag( $tag ) {
996 while ( $this->currentNode
) {
997 if ( $this->currentNode
->isA( $tag ) ) {
1006 * Pop elements off the stack *not including* the first element
1007 * in the specified set.
1008 * @param BalanceElement|array|string $set
1010 public function clearToContext( $set ) {
1011 // Note that we don't loop to 0. Never pop the <html> elt off.
1012 for ( $length = count( $this->elements
); $length > 1; $length-- ) {
1013 if ( $this->currentNode
->isA( $set ) ) {
1021 * Remove the given $elt from the BalanceStack, optionally
1022 * flattening it in the process.
1023 * @param BalanceElement $elt The element to remove.
1024 * @param bool $flatten Whether to flatten the removed element.
1026 public function removeElement( BalanceElement
$elt, $flatten = true ) {
1028 $elt->parent
!== 'flat',
1030 '$elt should not already have been flattened.'
1033 $elt->parent
->parent
!== 'flat',
1035 'The parent of $elt should not already have been flattened.'
1037 $idx = array_search( $elt, $this->elements
, true );
1038 Assert
::parameter( $idx !== false, '$elt', 'must be in stack' );
1039 array_splice( $this->elements
, $idx, 1 );
1040 if ( $idx === count( $this->elements
) ) {
1041 $this->currentNode
= $this->elements
[$idx - 1];
1044 // serialize $elt into its parent
1045 // otherwise, it will eventually serialize when the parent
1046 // is serialized, we just hold onto the memory for its
1047 // tree of objects a little longer.
1048 $elt->flatten( $this->tidyCompat
);
1050 Assert
::postcondition(
1051 array_search( $elt, $this->elements
, true ) === false,
1052 '$elt should no longer be in open elements stack'
1057 * Find $a in the BalanceStack and insert $b after it.
1058 * @param BalanceElement $a
1059 * @param BalanceElement $b
1061 public function insertAfter( BalanceElement
$a, BalanceElement
$b ) {
1062 $idx = $this->indexOf( $a );
1063 Assert
::parameter( $idx !== false, '$a', 'must be in stack' );
1064 if ( $idx === count( $this->elements
) - 1 ) {
1065 array_push( $this->elements
, $b );
1066 $this->currentNode
= $b;
1068 array_splice( $this->elements
, $idx +
1, 0, [ $b ] );
1072 # Fostering and adoption.
1075 * Foster parent the given $elt in the stack of open elements.
1076 * @param BalanceElement|string $elt
1077 * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
1079 private function fosterParent( $elt ) {
1080 $lastTable = $this->indexOf( 'table' );
1081 $lastTemplate = $this->indexOf( 'template' );
1085 if ( $lastTemplate >= 0 && ( $lastTable < 0 ||
$lastTemplate > $lastTable ) ) {
1086 $parent = $this->elements
[$lastTemplate];
1087 } elseif ( $lastTable >= 0 ) {
1088 $parent = $this->elements
[$lastTable]->parent
;
1089 # Assume all tables have parents, since we're not running scripts!
1091 $parent !== null, "All tables should have parents"
1093 $before = $this->elements
[$lastTable];
1095 $parent = $this->elements
[0]; // the `html` element.
1098 if ( $this->tidyCompat
) {
1099 if ( is_string( $elt ) ) {
1100 // We're fostering text: do we need a p-wrapper?
1101 if ( $parent->isA( BalanceSets
::$tidyPWrapSet ) ) {
1102 $this->insertHTMLElement( 'mw:p-wrap', [] );
1103 $this->insertText( $elt );
1107 // We're fostering an element; do we need to merge p-wrappers?
1108 if ( $elt->isHtmlNamed( 'mw:p-wrap' ) ) {
1110 array_search( $before, $parent->children
, true ) :
1111 count( $parent->children
);
1112 $after = $idx > 0 ?
$parent->children
[$idx - 1] : '';
1114 $after instanceof BalanceElement
&&
1115 $after->isHtmlNamed( 'mw:p-wrap' )
1117 return $after; // Re-use existing p-wrapper.
1124 $parent->insertBefore( $before, $elt );
1126 $parent->appendChild( $elt );
1132 * Run the "adoption agency algoritm" (AAA) for the given subject
1134 * @param string $tag The subject tag name.
1135 * @param BalanceActiveFormattingElements $afe The current
1136 * active formatting elements list.
1137 * @return true if the adoption agency algorithm "did something", false
1138 * if more processing is required by the caller.
1139 * @see https://html.spec.whatwg.org/multipage/syntax.html#adoption-agency-algorithm
1141 public function adoptionAgency( $tag, $afe ) {
1142 // If the current node is an HTML element whose tag name is subject,
1143 // and the current node is not in the list of active formatting
1144 // elements, then pop the current node off the stack of open
1145 // elements and abort these steps.
1147 $this->currentNode
->isHtmlNamed( $tag ) &&
1148 !$afe->isInList( $this->currentNode
)
1151 return true; // no more handling required
1154 // Let outer loop counter be zero.
1157 // Outer loop: If outer loop counter is greater than or
1158 // equal to eight, then abort these steps.
1159 while ( $outer < 8 ) {
1160 // Increment outer loop counter by one.
1163 // Let the formatting element be the last element in the list
1164 // of active formatting elements that: is between the end of
1165 // the list and the last scope marker in the list, if any, or
1166 // the start of the list otherwise, and has the same tag name
1168 $fmtelt = $afe->findElementByTag( $tag );
1170 // If there is no such node, then abort these steps and instead
1171 // act as described in the "any other end tag" entry below.
1173 return false; // false means handle by the default case
1176 // Otherwise, if there is such a node, but that node is not in
1177 // the stack of open elements, then this is a parse error;
1178 // remove the element from the list, and abort these steps.
1179 $index = $this->indexOf( $fmtelt );
1181 $afe->remove( $fmtelt );
1182 return true; // true means no more handling required
1185 // Otherwise, if there is such a node, and that node is also in
1186 // the stack of open elements, but the element is not in scope,
1187 // then this is a parse error; ignore the token, and abort
1189 if ( !$this->inScope( $fmtelt ) ) {
1193 // Let the furthest block be the topmost node in the stack of
1194 // open elements that is lower in the stack than the formatting
1195 // element, and is an element in the special category. There
1196 // might not be one.
1197 $furthestblock = null;
1198 $furthestblockindex = -1;
1199 $stacklen = $this->length();
1200 for ( $i = $index+
1; $i < $stacklen; $i++
) {
1201 if ( $this->node( $i )->isA( BalanceSets
::$specialSet ) ) {
1202 $furthestblock = $this->node( $i );
1203 $furthestblockindex = $i;
1208 // If there is no furthest block, then the UA must skip the
1209 // subsequent steps and instead just pop all the nodes from the
1210 // bottom of the stack of open elements, from the current node
1211 // up to and including the formatting element, and remove the
1212 // formatting element from the list of active formatting
1214 if ( !$furthestblock ) {
1215 $this->popTag( $fmtelt );
1216 $afe->remove( $fmtelt );
1219 // Let the common ancestor be the element immediately above
1220 // the formatting element in the stack of open elements.
1221 $ancestor = $this->node( $index-1 );
1223 // Let a bookmark note the position of the formatting
1224 // element in the list of active formatting elements
1225 // relative to the elements on either side of it in the
1227 $BOOKMARK = new BalanceElement( '[bookmark]', '[bookmark]', [] );
1228 $afe->insertAfter( $fmtelt, $BOOKMARK );
1230 // Let node and last node be the furthest block.
1231 $node = $furthestblock;
1232 $lastnode = $furthestblock;
1233 $nodeindex = $furthestblockindex;
1236 // Let inner loop counter be zero.
1241 // Increment inner loop counter by one.
1244 // Let node be the element immediately above node in
1245 // the stack of open elements, or if node is no longer
1246 // in the stack of open elements (e.g. because it got
1247 // removed by this algorithm), the element that was
1248 // immediately above node in the stack of open elements
1249 // before node was removed.
1250 $node = $this->node( --$nodeindex );
1252 // If node is the formatting element, then go
1253 // to the next step in the overall algorithm.
1254 if ( $node === $fmtelt ) break;
1256 // If the inner loop counter is greater than three and node
1257 // is in the list of active formatting elements, then remove
1258 // node from the list of active formatting elements.
1259 $isAFE = $afe->isInList( $node );
1260 if ( $inner > 3 && $isAFE ) {
1261 $afe->remove( $node );
1265 // If node is not in the list of active formatting
1266 // elements, then remove node from the stack of open
1267 // elements and then go back to the step labeled inner
1270 // Don't flatten here, since we're about to relocate
1271 // parts of this $node.
1272 $this->removeElement( $node, false );
1276 // Create an element for the token for which the
1277 // element node was created with common ancestor as
1278 // the intended parent, replace the entry for node
1279 // in the list of active formatting elements with an
1280 // entry for the new element, replace the entry for
1281 // node in the stack of open elements with an entry for
1282 // the new element, and let node be the new element.
1283 $newelt = new BalanceElement(
1284 $node->namespaceURI
, $node->localName
, $node->attribs
);
1285 $afe->replace( $node, $newelt );
1286 $this->replaceAt( $nodeindex, $newelt );
1289 // If last node is the furthest block, then move the
1290 // aforementioned bookmark to be immediately after the
1291 // new node in the list of active formatting elements.
1292 if ( $lastnode === $furthestblock ) {
1293 $afe->remove( $BOOKMARK );
1294 $afe->insertAfter( $newelt, $BOOKMARK );
1297 // Insert last node into node, first removing it from
1298 // its previous parent node if any.
1299 $node->appendChild( $lastnode );
1301 // Let last node be node.
1305 // If the common ancestor node is a table, tbody, tfoot,
1306 // thead, or tr element, then, foster parent whatever last
1307 // node ended up being in the previous step, first removing
1308 // it from its previous parent node if any.
1310 $this->fosterParentMode
&&
1311 $ancestor->isA( BalanceSets
::$tableSectionRowSet )
1313 $this->fosterParent( $lastnode );
1315 // Otherwise, append whatever last node ended up being in
1316 // the previous step to the common ancestor node, first
1317 // removing it from its previous parent node if any.
1318 $ancestor->appendChild( $lastnode );
1321 // Create an element for the token for which the
1322 // formatting element was created, with furthest block
1323 // as the intended parent.
1324 $newelt2 = new BalanceElement(
1325 $fmtelt->namespaceURI
, $fmtelt->localName
, $fmtelt->attribs
);
1327 // Take all of the child nodes of the furthest block and
1328 // append them to the element created in the last step.
1329 $newelt2->adoptChildren( $furthestblock );
1331 // Append that new element to the furthest block.
1332 $furthestblock->appendChild( $newelt2 );
1334 // Remove the formatting element from the list of active
1335 // formatting elements, and insert the new element into the
1336 // list of active formatting elements at the position of
1337 // the aforementioned bookmark.
1338 $afe->remove( $fmtelt );
1339 $afe->replace( $BOOKMARK, $newelt2 );
1341 // Remove the formatting element from the stack of open
1342 // elements, and insert the new element into the stack of
1343 // open elements immediately below the position of the
1344 // furthest block in that stack.
1345 $this->removeElement( $fmtelt );
1346 $this->insertAfter( $furthestblock, $newelt2 );
1354 * Return the contents of the open elements stack as a string for
1358 public function __toString() {
1360 foreach ( $this->elements
as $elt ) {
1361 array_push( $r, $elt->localName
);
1363 return implode( $r, ' ' );
1368 * A pseudo-element used as a marker in the list of active formatting elements
1373 class BalanceMarker
{
1379 * The list of active formatting elements, which is used to handle
1380 * mis-nested formatting element tags in the HTML5 tree builder
1385 * @see https://html.spec.whatwg.org/multipage/syntax.html#list-of-active-formatting-elements
1387 class BalanceActiveFormattingElements
{
1388 /** The last (most recent) element in the list */
1391 /** The first (least recent) element in the list */
1395 * An array of arrays representing the population of elements in each bucket
1396 * according to the Noah's Ark clause. The outer array is stack-like, with each
1397 * integer-indexed element representing a segment of the list, bounded by
1398 * markers. The first element represents the segment of the list before the
1401 * The inner arrays are indexed by "Noah key", which is a string which uniquely
1402 * identifies each bucket according to the rules in the spec. The value in
1403 * the inner array is the first (least recently inserted) element in the bucket,
1404 * and subsequent members of the bucket can be found by iterating through the
1405 * singly-linked list via $node->nextNoah.
1407 * This is optimised for the most common case of inserting into a bucket
1408 * with zero members, and deleting a bucket containing one member. In the
1409 * worst case, iteration through the list is still O(1) in the document
1410 * size, since each bucket can have at most 3 members.
1412 private $noahTableStack = [ [] ];
1414 public function __destruct() {
1415 for ( $node = $this->head
; $node; $node = $next ) {
1416 $next = $node->nextAFE
;
1417 $node->prevAFE
= $node->nextAFE
= $node->nextNoah
= null;
1419 $this->head
= $this->tail
= $this->noahTableStack
= null;
1422 public function insertMarker() {
1423 $elt = new BalanceMarker
;
1424 if ( $this->tail
) {
1425 $this->tail
->nextAFE
= $elt;
1426 $elt->prevAFE
= $this->tail
;
1431 $this->noahTableStack
[] = [];
1435 * Follow the steps required when the spec requires us to "push onto the
1436 * list of active formatting elements".
1437 * @param BalanceElement $elt
1439 public function push( BalanceElement
$elt ) {
1440 // Must not be in the list already
1441 if ( $elt->prevAFE
!== null ||
$this->head
=== $elt ) {
1442 throw new ParameterAssertionException( '$elt',
1443 'Cannot insert a node into the AFE list twice' );
1446 // "Noah's Ark clause" -- if there are already three copies of
1447 // this element before we encounter a marker, then drop the last
1449 $noahKey = $elt->getNoahKey();
1450 $table =& $this->noahTableStack
[ count( $this->noahTableStack
) - 1 ];
1451 if ( !isset( $table[$noahKey] ) ) {
1452 $table[$noahKey] = $elt;
1455 $head = $tail = $table[$noahKey];
1456 while ( $tail->nextNoah
) {
1457 $tail = $tail->nextNoah
;
1460 if ( $count >= 3 ) {
1461 $this->remove( $head );
1463 $tail->nextNoah
= $elt;
1465 // Add to the main AFE list
1466 if ( $this->tail
) {
1467 $this->tail
->nextAFE
= $elt;
1468 $elt->prevAFE
= $this->tail
;
1476 * Follow the steps required when the spec asks us to "clear the list of
1477 * active formatting elements up to the last marker".
1479 public function clearToMarker() {
1480 // Iterate back through the list starting from the tail
1481 $tail = $this->tail
;
1482 while ( $tail && !( $tail instanceof BalanceMarker
) ) {
1483 // Unlink the element
1484 $prev = $tail->prevAFE
;
1485 $tail->prevAFE
= null;
1487 $prev->nextAFE
= null;
1489 $tail->nextNoah
= null;
1492 // If we finished on a marker, unlink it and pop it off the Noah table stack
1494 $prev = $tail->prevAFE
;
1496 $prev->nextAFE
= null;
1499 array_pop( $this->noahTableStack
);
1501 // No marker: wipe the top-level Noah table (which is the only one)
1502 $this->noahTableStack
[0] = [];
1504 // If we removed all the elements, clear the head pointer
1508 $this->tail
= $tail;
1512 * Find and return the last element with the specified tag between the
1513 * end of the list and the last marker on the list.
1514 * Used when parsing <a> "in body mode".
1516 public function findElementByTag( $tag ) {
1518 while ( $elt && !( $elt instanceof BalanceMarker
) ) {
1519 if ( $elt->localName
=== $tag ) {
1522 $elt = $elt->prevAFE
;
1528 * Determine whether an element is in the list of formatting elements.
1531 public function isInList( BalanceElement
$elt ) {
1532 return $this->head
=== $elt ||
$elt->prevAFE
;
1536 * Find the element $elt in the list and remove it.
1537 * Used when parsing <a> in body mode.
1539 public function remove( BalanceElement
$elt ) {
1540 if ( $this->head
!== $elt && !$elt->prevAFE
) {
1541 throw new ParameterAssertionException( '$elt',
1542 "Attempted to remove an element which is not in the AFE list" );
1544 // Update head and tail pointers
1545 if ( $this->head
=== $elt ) {
1546 $this->head
= $elt->nextAFE
;
1548 if ( $this->tail
=== $elt ) {
1549 $this->tail
= $elt->prevAFE
;
1551 // Update previous element
1552 if ( $elt->prevAFE
) {
1553 $elt->prevAFE
->nextAFE
= $elt->nextAFE
;
1555 // Update next element
1556 if ( $elt->nextAFE
) {
1557 $elt->nextAFE
->prevAFE
= $elt->prevAFE
;
1559 // Clear pointers so that isInList() etc. will work
1560 $elt->prevAFE
= $elt->nextAFE
= null;
1562 $this->removeFromNoahList( $elt );
1565 private function addToNoahList( BalanceElement
$elt ) {
1566 $noahKey = $elt->getNoahKey();
1567 $table =& $this->noahTableStack
[ count( $this->noahTableStack
) - 1 ];
1568 if ( !isset( $table[$noahKey] ) ) {
1569 $table[$noahKey] = $elt;
1571 $tail = $table[$noahKey];
1572 while ( $tail->nextNoah
) {
1573 $tail = $tail->nextNoah
;
1575 $tail->nextNoah
= $elt;
1579 private function removeFromNoahList( BalanceElement
$elt ) {
1580 $table =& $this->noahTableStack
[ count( $this->noahTableStack
) - 1 ];
1581 $key = $elt->getNoahKey();
1582 $noahElt = $table[$key];
1583 if ( $noahElt === $elt ) {
1584 if ( $noahElt->nextNoah
) {
1585 $table[$key] = $noahElt->nextNoah
;
1586 $noahElt->nextNoah
= null;
1588 unset( $table[$key] );
1592 $prevNoahElt = $noahElt;
1593 $noahElt = $prevNoahElt->nextNoah
;
1594 if ( $noahElt === $elt ) {
1596 $prevNoahElt->nextNoah
= $elt->nextNoah
;
1597 $elt->nextNoah
= null;
1600 } while ( $noahElt );
1605 * Find element $a in the list and replace it with element $b
1607 public function replace( BalanceElement
$a, BalanceElement
$b ) {
1608 if ( $this->head
!== $a && !$a->prevAFE
) {
1609 throw new ParameterAssertionException( '$a',
1610 "Attempted to replace an element which is not in the AFE list" );
1612 // Update head and tail pointers
1613 if ( $this->head
=== $a ) {
1616 if ( $this->tail
=== $a ) {
1619 // Update previous element
1620 if ( $a->prevAFE
) {
1621 $a->prevAFE
->nextAFE
= $b;
1623 // Update next element
1624 if ( $a->nextAFE
) {
1625 $a->nextAFE
->prevAFE
= $b;
1627 $b->prevAFE
= $a->prevAFE
;
1628 $b->nextAFE
= $a->nextAFE
;
1629 $a->nextAFE
= $a->prevAFE
= null;
1631 $this->removeFromNoahList( $a );
1632 $this->addToNoahList( $b );
1636 * Find $a in the list and insert $b after it.
1638 public function insertAfter( BalanceElement
$a, BalanceElement
$b ) {
1639 if ( $this->head
!== $a && !$a->prevAFE
) {
1640 throw new ParameterAssertionException( '$a',
1641 "Attempted to insert after an element which is not in the AFE list" );
1643 if ( $this->tail
=== $a ) {
1646 if ( $a->nextAFE
) {
1647 $a->nextAFE
->prevAFE
= $b;
1649 $b->nextAFE
= $a->nextAFE
;
1652 $this->addToNoahList( $b );
1655 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
1657 * Reconstruct the active formatting elements.
1658 * @param BalanceStack $stack The open elements stack
1659 * @see https://html.spec.whatwg.org/multipage/syntax.html#reconstruct-the-active-formatting-elements
1661 // @codingStandardsIgnoreEnd
1662 public function reconstruct( $stack ) {
1663 $entry = $this->tail
;
1664 // If there are no entries in the list of active formatting elements,
1665 // then there is nothing to reconstruct
1669 // If the last is a marker, do nothing.
1670 if ( $entry instanceof BalanceMarker
) {
1673 // Or if it is an open element, do nothing.
1674 if ( $stack->indexOf( $entry ) >= 0 ) {
1678 // Loop backward through the list until we find a marker or an
1681 while ( $entry->prevAFE
) {
1682 $entry = $entry->prevAFE
;
1683 if ( $entry instanceof BalanceMarker ||
$stack->indexOf( $entry ) >= 0 ) {
1689 // Now loop forward, starting from the element after the current one (or
1690 // the first element if we didn't find a marker or open element),
1691 // recreating formatting elements and pushing them back onto the list
1692 // of open elements.
1694 $entry = $entry->nextAFE
;
1697 $newElement = $stack->insertHTMLElement(
1700 $this->replace( $entry, $newElement );
1701 $entry = $newElement->nextAFE
;
1706 * Get a string representation of the AFE list, for debugging
1708 public function __toString() {
1711 for ( $node = $this->head
; $node; $prev = $node, $node = $node->nextAFE
) {
1712 if ( $node instanceof BalanceMarker
) {
1716 $s .= $node->localName
. '#' . substr( md5( spl_object_hash( $node ) ), 0, 8 );
1717 if ( $node->nextNoah
) {
1718 $s .= " (noah sibling: {$node->nextNoah->localName}#" .
1719 substr( md5( spl_object_hash( $node->nextNoah
) ), 0, 8 ) .
1722 if ( $node->nextAFE
&& $node->nextAFE
->prevAFE
!== $node ) {
1723 $s .= " (reverse link is wrong!)";
1727 if ( $prev !== $this->tail
) {
1728 $s .= "(tail pointer is wrong!)\n";
1735 * An implementation of the tree building portion of the HTML5 parsing
1738 * This is used to balance and tidy output so that the result can
1739 * always be cleanly serialized/deserialized by an HTML5 parser. It
1740 * does *not* guarantee "conforming" output -- the HTML5 spec contains
1741 * a number of constraints which are not enforced by the HTML5 parsing
1742 * process. But the result will be free of gross errors: misnested or
1743 * unclosed tags, for example, and will be unchanged by spec-complient
1744 * parsing followed by serialization.
1746 * The tree building stage is structured as a state machine.
1747 * When comparing the implementation to
1748 * https://www.w3.org/TR/html5/syntax.html#tree-construction
1749 * note that each state is implemented as a function with a
1750 * name ending in `Mode` (because the HTML spec refers to them
1751 * as insertion modes). The current insertion mode is held by
1752 * the $parseMode property.
1754 * The following simplifications have been made:
1755 * - We handle body content only (ie, we start `in body`.)
1756 * - The document is never in "quirks mode".
1757 * - All occurrences of < and > have been entity escaped, so we
1758 * can parse tags by simply splitting on those two characters.
1759 * (This also simplifies the handling of < inside <textarea>.)
1760 * The character < must not appear inside comments.
1761 * Similarly, all attributes have been "cleaned" and are double-quoted
1763 * - All null characters are assumed to have been removed.
1764 * - The following elements are disallowed: <html>, <head>, <body>, <frameset>,
1765 * <frame>, <plaintext>, <isindex>, <xmp>, <iframe>,
1766 * <noembed>, <noscript>, <script>, <title>. As a result,
1767 * further simplifications can be made:
1768 * - `frameset-ok` is not tracked.
1769 * - `head element pointer` is not tracked (but presumed non-null)
1770 * - Tokenizer has only a single mode. (<textarea> wants RCDATA and
1771 * <style>/<noframes> want RAWTEXT modes which we only loosely emulate.)
1773 * We generally mark places where we omit cases from the spec due to
1774 * disallowed elements with a comment: `# OMITTED: <element-name>`.
1776 * The HTML spec keeps a flag during the parsing process to track
1777 * whether or not a "parse error" has been encountered. We don't
1778 * bother to track that flag, we just implement the error-handling
1779 * process as specified.
1783 * @see https://html.spec.whatwg.org/multipage/syntax.html#tree-construction
1787 private $bitsIterator;
1788 private $allowedHtmlElements;
1792 private $tidyCompat;
1793 private $allowComments;
1795 private $textIntegrationMode;
1796 private $pendingTableText;
1797 private $originalInsertionMode;
1798 private $fragmentContext;
1799 private $formElementPointer;
1800 private $ignoreLinefeed;
1805 * Valid HTML5 comments.
1806 * Regex borrowed from Tim Starling's "remex-html" project.
1808 const VALID_COMMENT_REGEX
= "~ !--
1809 ( # 1. Comment match detector
1810 > | -> | # Invalid short close
1811 ( # 2. Comment contents
1821 ( # 3. Comment close
1822 --> | # Normal close
1823 --!> | # Comment end bang
1824 ( # 4. Indicate matches requiring EOF
1825 --! | # EOF in comment end bang state
1826 -- | # EOF in comment end state
1827 - | # EOF in comment end dash state
1828 # EOF in comment state
1832 ([^<]*) \z # 5. Non-tag text after the comment
1836 * Create a new Balancer.
1837 * @param array $config Balancer configuration. Includes:
1838 * 'strict' : boolean, defaults to false.
1839 * When true, enforces syntactic constraints on input:
1840 * all non-tag '<' must be escaped, all attributes must be
1841 * separated by a single space and double-quoted. This is
1842 * consistent with the output of the Sanitizer.
1843 * 'allowedHtmlElements' : array, defaults to null.
1844 * When present, the keys of this associative array give
1845 * the acceptable HTML tag names. When not present, no
1846 * tag sanitization is done.
1847 * 'tidyCompat' : boolean, defaults to false.
1848 * When true, the serialization algorithm is tweaked to
1849 * provide historical compatibility with the old "tidy"
1850 * program: <p>-wrapping is done to the children of
1851 * <body> and <blockquote> elements, and empty elements
1853 * 'allowComments': boolean, defaults to true.
1854 * When true, allows HTML comments in the input.
1855 * The Sanitizer generally strips all comments, so if you
1856 * are running on sanitized output you can set this to
1857 * false to get a bit more performance.
1859 public function __construct( array $config = [] ) {
1860 $config = $config +
[
1862 'allowedHtmlElements' => null,
1863 'tidyCompat' => false,
1864 'allowComments' => true,
1866 $this->allowedHtmlElements
= $config['allowedHtmlElements'];
1867 $this->strict
= $config['strict'];
1868 $this->tidyCompat
= $config['tidyCompat'];
1869 $this->allowComments
= $config['allowComments'];
1870 if ( $this->allowedHtmlElements
!== null ) {
1872 $bad = array_uintersect_assoc(
1873 $this->allowedHtmlElements
,
1874 BalanceSets
::$unsupportedSet[BalanceSets
::HTML_NAMESPACE
],
1875 function( $a, $b ) {
1876 // Ignore the values (just intersect the keys) by saying
1877 // all values are equal to each other.
1881 if ( count( $bad ) > 0 ) {
1882 $badstr = implode( array_keys( $bad ), ',' );
1883 throw new ParameterAssertionException(
1885 'Balance attempted with sanitization including ' .
1886 "unsupported elements: {$badstr}"
1893 * Return a balanced HTML string for the HTML fragment given by $text,
1894 * subject to the caveats listed in the class description. The result
1895 * will typically be idempotent -- that is, rebalancing the output
1896 * would result in no change.
1898 * @param string $text The markup to be balanced
1899 * @param callable $processingCallback Callback to do any variable or
1900 * parameter replacements in HTML attributes values
1901 * @param array|bool $processingArgs Arguments for the processing callback
1902 * @return string The balanced markup
1904 public function balance( $text, $processingCallback = null, $processingArgs = [] ) {
1905 $this->parseMode
= 'inBodyMode';
1906 $this->bitsIterator
= new ExplodeIterator( '<', $text );
1907 $this->afe
= new BalanceActiveFormattingElements();
1908 $this->stack
= new BalanceStack();
1909 $this->stack
->tidyCompat
= $this->tidyCompat
;
1910 $this->processingCallback
= $processingCallback;
1911 $this->processingArgs
= $processingArgs;
1913 $this->textIntegrationMode
=
1914 $this->ignoreLinefeed
=
1916 $this->inRAWTEXT
= false;
1918 # The stack is constructed with an <html> element already on it.
1919 # Set this up as a fragment parsed with <body> as the context.
1920 $this->fragmentContext
=
1921 new BalanceElement( BalanceSets
::HTML_NAMESPACE
, 'body', [] );
1922 $this->resetInsertionMode();
1923 $this->formElementPointer
= null;
1924 for ( $e = $this->fragmentContext
; $e != null; $e = $e->parent
) {
1925 if ( $e->isHtmlNamed( 'form' ) ) {
1926 $this->formElementPointer
= $e;
1931 // First element is text not tag
1932 $x = $this->bitsIterator
->current();
1933 $this->bitsIterator
->next();
1934 $this->insertToken( 'text', str_replace( '>', '>', $x ) );
1935 // Now process each tag.
1936 while ( $this->bitsIterator
->valid() ) {
1939 $this->insertToken( 'eof', null );
1940 $result = $this->stack
->getOutput();
1941 // Free memory before returning.
1942 $this->bitsIterator
= null;
1944 $this->stack
= null;
1945 $this->fragmentContext
= null;
1946 $this->formElementPointer
= null;
1951 * Pass a token to the tree builder. The $token will be one of the
1952 * strings "tag", "endtag", or "text".
1954 private function insertToken( $token, $value, $attribs = null, $selfclose = false ) {
1955 // validate tags against $unsupportedSet
1956 if ( $token === 'tag' ||
$token === 'endtag' ) {
1957 if ( isset( BalanceSets
::$unsupportedSet[BalanceSets
::HTML_NAMESPACE
][$value] ) ) {
1958 # As described in "simplifications" above, these tags are
1959 # not supported in the balancer.
1962 "Unsupported $token <$value> found."
1966 } elseif ( $token === 'text' && $value === '' ) {
1967 # Don't actually inject the empty string as a text token.
1970 // Support pre/listing/textarea by suppressing initial linefeed
1971 if ( $this->ignoreLinefeed
) {
1972 $this->ignoreLinefeed
= false;
1973 if ( $token === 'text' ) {
1974 if ( $value[0] === "\n" ) {
1975 if ( $value === "\n" ) {
1976 # Nothing would be left, don't inject the empty string.
1979 $value = substr( $value, 1 );
1983 // Some hoops we have to jump through
1984 $adjusted = $this->stack
->adjustedCurrentNode( $this->fragmentContext
);
1988 $this->stack
->length() === 0 ||
1989 $adjusted->isHtml() ||
1993 } elseif ( $adjusted->isMathmlTextIntegrationPoint() ) {
1994 if ( $token === 'text' ) {
1998 $value !== 'mglyph' && $value !== 'malignmark'
2003 $adjusted->namespaceURI
=== BalanceSets
::MATHML_NAMESPACE
&&
2004 $adjusted->localName
=== 'annotation-xml' &&
2005 $token === 'tag' && $value === 'svg'
2009 $adjusted->isHtmlIntegrationPoint() &&
2010 ( $token === 'tag' ||
$token === 'text' )
2015 return $this->insertForeignToken( $token, $value, $attribs, $selfclose );
2017 $func = $this->parseMode
;
2018 return $this->$func( $token, $value, $attribs, $selfclose );
2022 private function insertForeignToken( $token, $value, $attribs = null, $selfclose = false ) {
2023 if ( $token === 'text' ) {
2024 $this->stack
->insertText( $value );
2026 } elseif ( $token === 'tag' ) {
2029 if ( isset( $attribs['color'] )
2030 ||
isset( $attribs['face'] )
2031 ||
isset( $attribs['size'] )
2035 /* otherwise, fall through */
2080 if ( $this->fragmentContext
) {
2084 $this->stack
->pop();
2085 $node = $this->stack
->currentNode
;
2087 $node->isMathmlTextIntegrationPoint() ||
2088 $node->isHtmlIntegrationPoint() ||
2094 return $this->insertToken( $token, $value, $attribs, $selfclose );
2096 // "Any other start tag"
2097 $adjusted = ( $this->fragmentContext
&& $this->stack
->length()===1 ) ?
2098 $this->fragmentContext
: $this->stack
->currentNode
;
2099 $this->stack
->insertForeignElement(
2100 $adjusted->namespaceURI
, $value, $attribs
2103 $this->stack
->pop();
2106 } elseif ( $token === 'endtag' ) {
2108 foreach ( $this->stack
as $i => $node ) {
2109 if ( $node->isHtml() && !$first ) {
2110 // process the end tag as HTML
2111 $func = $this->parseMode
;
2112 return $this->$func( $token, $value, $attribs, $selfclose );
2113 } elseif ( $i === 0 ) {
2115 } elseif ( $node->localName
=== $value ) {
2116 $this->stack
->popTag( $node );
2125 * Grab the next "token" from $bitsIterator. This is either a open/close
2126 * tag or text or a comment, depending on whether the Sanitizer approves.
2128 private function advance() {
2129 $x = $this->bitsIterator
->current();
2130 $this->bitsIterator
->next();
2132 # Handle comments. These won't be generated by mediawiki (they
2133 # are stripped in the Sanitizer) but may be generated by extensions.
2135 $this->allowComments
&&
2136 !( $this->inRCDATA ||
$this->inRAWTEXT
) &&
2137 preg_match( Balancer
::VALID_COMMENT_REGEX
, $x, $regs, PREG_OFFSET_CAPTURE
) &&
2138 /* verify EOF condition where necessary */
2139 ( $regs[4][1] < 0 ||
!$this->bitsIterator
->valid() )
2141 $contents = $regs[2][0];
2142 $rest = $regs[5][0];
2143 $this->insertToken( 'comment', $contents );
2144 $this->insertToken( 'text', str_replace( '>', '>', $rest ) );
2147 # $slash: Does the current element start with a '/'?
2148 # $t: Current element name
2149 # $attribStr: String between element name and >
2150 # $brace: Ending '>' or '/>'
2151 # $rest: Everything until the next element from the $bitsIterator
2152 if ( preg_match( Sanitizer
::ELEMENT_BITS_REGEX
, $x, $regs ) ) {
2153 list( /* $qbar */, $slash, $t, $attribStr, $brace, $rest ) = $regs;
2154 $t = strtolower( $t );
2155 if ( $this->strict
) {
2156 /* Verify that attributes are all properly double-quoted */
2159 '/^( [:_A-Z0-9][-.:_A-Z0-9]*="[^"]*")*[ ]*$/i', $attribStr
2161 "Bad attribute string found"
2166 !$this->strict
, "< found which does not start a valid tag"
2168 $slash = $t = $attribStr = $brace = $rest = null;
2171 if ( $this->inRCDATA
) {
2172 if ( $slash && $t === $this->inRCDATA
) {
2173 $this->inRCDATA
= false;
2175 // No tags allowed; this emulates the "rcdata" tokenizer mode.
2179 if ( $this->inRAWTEXT
) {
2180 if ( $slash && $t === $this->inRAWTEXT
) {
2181 $this->inRAWTEXT
= false;
2183 // No tags allowed, no entity-escaping done.
2187 $sanitize = $this->allowedHtmlElements
!== null;
2189 $goodtag = $t && isset( $this->allowedHtmlElements
[$t] );
2192 if ( is_callable( $this->processingCallback
) ) {
2193 call_user_func_array( $this->processingCallback
, [ &$attribStr, $this->processingArgs
] );
2196 $goodtag = Sanitizer
::validateTag( $attribStr, $t );
2201 $attribs = Sanitizer
::decodeTagAttributes( $attribStr );
2202 $attribs = Sanitizer
::validateTagAttributes( $attribs, $t );
2204 $attribs = Sanitizer
::decodeTagAttributes( $attribStr );
2206 $goodtag = $this->insertToken(
2207 $slash ?
'endtag' : 'tag', $t, $attribs, $brace === '/>'
2211 $rest = str_replace( '>', '>', $rest );
2212 $this->insertToken( 'text', str_replace( '>', '>', $rest ) );
2213 } elseif ( $this->inRAWTEXT
) {
2214 $this->insertToken( 'text', "<$x" );
2216 # bad tag; serialize entire thing as text.
2217 $this->insertToken( 'text', '<' . str_replace( '>', '>', $x ) );
2221 private function switchMode( $mode ) {
2223 substr( $mode, -4 )==='Mode', '$mode', 'should end in Mode'
2225 $oldMode = $this->parseMode
;
2226 $this->parseMode
= $mode;
2230 private function switchModeAndReprocess( $mode, $token, $value, $attribs, $selfclose ) {
2231 $this->switchMode( $mode );
2232 return $this->insertToken( $token, $value, $attribs, $selfclose );
2235 private function resetInsertionMode() {
2237 foreach ( $this->stack
as $i => $node ) {
2240 if ( $this->fragmentContext
) {
2241 $node = $this->fragmentContext
;
2244 if ( $node->isHtml() ) {
2245 switch ( $node->localName
) {
2247 $stacklen = $this->stack
->length();
2248 for ( $j = $i +
1; $j < $stacklen-1; $j++
) {
2249 $ancestor = $this->stack
->node( $stacklen-$j-1 );
2250 if ( $ancestor->isHtmlNamed( 'template' ) ) {
2253 if ( $ancestor->isHtmlNamed( 'table' ) ) {
2254 $this->switchMode( 'inSelectInTableMode' );
2258 $this->switchMode( 'inSelectMode' );
2261 $this->switchMode( 'inRowMode' );
2266 $this->switchMode( 'inTableBodyMode' );
2269 $this->switchMode( 'inCaptionMode' );
2272 $this->switchMode( 'inColumnGroupMode' );
2275 $this->switchMode( 'inTableMode' );
2279 array_slice( $this->templateInsertionModes
, -1 )[0]
2283 $this->switchMode( 'inBodyMode' );
2285 # OMITTED: <frameset>
2291 if ( $node->isA( BalanceSets
::$tableCellSet ) ) {
2292 $this->switchMode( 'inCellMode' );
2299 $this->switchMode( 'inBodyMode' );
2305 private function stopParsing() {
2306 # Most of the spec methods are inapplicable, other than step 2:
2307 # "pop all the nodes off the stack of open elements".
2308 # We're going to keep the top-most <html> element on the stack, though.
2310 # Clear the AFE list first, otherwise the element objects will stay live
2311 # during serialization, potentially using O(N^2) memory. Note that
2312 # popping the stack will never result in reconstructing the active
2313 # formatting elements.
2315 $this->stack
->popTo( 1 );
2318 private function parseRawText( $value, $attribs = null ) {
2319 $this->stack
->insertHTMLElement( $value, $attribs );
2320 $this->inRAWTEXT
= $value;
2321 $this->originalInsertionMode
= $this->switchMode( 'inTextMode' );
2325 private function inTextMode( $token, $value, $attribs = null, $selfclose = false ) {
2326 if ( $token === 'text' ) {
2327 $this->stack
->insertText( $value );
2329 } elseif ( $token === 'eof' ) {
2330 $this->stack
->pop();
2331 return $this->switchModeAndReprocess(
2332 $this->originalInsertionMode
, $token, $value, $attribs, $selfclose
2334 } elseif ( $token === 'endtag' ) {
2335 $this->stack
->pop();
2336 $this->switchMode( $this->originalInsertionMode
);
2342 private function inHeadMode( $token, $value, $attribs = null, $selfclose = false ) {
2343 if ( $token === 'text' ) {
2344 if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
2345 $this->stack
->insertText( $matches[0] );
2346 $value = substr( $value, strlen( $matches[0] ) );
2348 if ( strlen( $value ) === 0 ) {
2349 return true; // All text handled.
2351 // Fall through to handle non-whitespace below.
2352 } elseif ( $token === 'tag' ) {
2355 # OMITTED: in a full HTML parser, this might change the encoding.
2362 $this->stack
->insertHTMLElement( $value, $attribs );
2363 $this->stack
->pop();
2366 # OMITTED: <noscript>
2369 return $this->parseRawText( $value, $attribs );
2372 $this->stack
->insertHTMLElement( $value, $attribs );
2373 $this->afe
->insertMarker();
2374 # OMITTED: frameset_ok
2375 $this->switchMode( 'inTemplateMode' );
2376 $this->templateInsertionModes
[] = $this->parseMode
;
2380 } elseif ( $token === 'endtag' ) {
2386 break; // handle at the bottom of the function
2388 if ( $this->stack
->indexOf( $value ) < 0 ) {
2389 return true; // Ignore the token.
2391 $this->stack
->generateImpliedEndTags( null, true /* thorough */ );
2392 $this->stack
->popTag( $value );
2393 $this->afe
->clearToMarker();
2394 array_pop( $this->templateInsertionModes
);
2395 $this->resetInsertionMode();
2398 // ignore any other end tag
2401 } elseif ( $token === 'comment' ) {
2402 $this->stack
->insertComment( $value );
2406 // If not handled above
2407 $this->inHeadMode( 'endtag', 'head' ); // synthetic </head>
2408 // Then redo this one
2409 return $this->insertToken( $token, $value, $attribs, $selfclose );
2412 private function inBodyMode( $token, $value, $attribs = null, $selfclose = false ) {
2413 if ( $token === 'text' ) {
2414 $this->afe
->reconstruct( $this->stack
);
2415 $this->stack
->insertText( $value );
2417 } elseif ( $token === 'eof' ) {
2418 if ( !empty( $this->templateInsertionModes
) ) {
2419 return $this->inTemplateMode( $token, $value, $attribs, $selfclose );
2421 $this->stopParsing();
2423 } elseif ( $token === 'tag' ) {
2436 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2438 # OMITTED: <frameset>
2464 if ( $this->stack
->inButtonScope( 'p' ) ) {
2465 $this->inBodyMode( 'endtag', 'p' );
2467 $this->stack
->insertHTMLElement( $value, $attribs );
2476 if ( $this->stack
->inButtonScope( 'p' ) ) {
2477 $this->inBodyMode( 'endtag', 'p' );
2479 if ( $this->stack
->currentNode
->isA( BalanceSets
::$headingSet ) ) {
2480 $this->stack
->pop();
2482 $this->stack
->insertHTMLElement( $value, $attribs );
2487 if ( $this->stack
->inButtonScope( 'p' ) ) {
2488 $this->inBodyMode( 'endtag', 'p' );
2490 $this->stack
->insertHTMLElement( $value, $attribs );
2491 $this->ignoreLinefeed
= true;
2492 # OMITTED: frameset_ok
2497 $this->formElementPointer
&&
2498 $this->stack
->indexOf( 'template' ) < 0
2500 return true; // in a form, not in a template.
2502 if ( $this->stack
->inButtonScope( "p" ) ) {
2503 $this->inBodyMode( 'endtag', 'p' );
2505 $elt = $this->stack
->insertHTMLElement( $value, $attribs );
2506 if ( $this->stack
->indexOf( 'template' ) < 0 ) {
2507 $this->formElementPointer
= $elt;
2512 # OMITTED: frameset_ok
2513 foreach ( $this->stack
as $node ) {
2514 if ( $node->isHtmlNamed( 'li' ) ) {
2515 $this->inBodyMode( 'endtag', 'li' );
2519 $node->isA( BalanceSets
::$specialSet ) &&
2520 !$node->isA( BalanceSets
::$addressDivPSet )
2525 if ( $this->stack
->inButtonScope( 'p' ) ) {
2526 $this->inBodyMode( 'endtag', 'p' );
2528 $this->stack
->insertHTMLElement( $value, $attribs );
2533 # OMITTED: frameset_ok
2534 foreach ( $this->stack
as $node ) {
2535 if ( $node->isHtmlNamed( 'dd' ) ) {
2536 $this->inBodyMode( 'endtag', 'dd' );
2539 if ( $node->isHtmlNamed( 'dt' ) ) {
2540 $this->inBodyMode( 'endtag', 'dt' );
2544 $node->isA( BalanceSets
::$specialSet ) &&
2545 !$node->isA( BalanceSets
::$addressDivPSet )
2550 if ( $this->stack
->inButtonScope( 'p' ) ) {
2551 $this->inBodyMode( 'endtag', 'p' );
2553 $this->stack
->insertHTMLElement( $value, $attribs );
2556 # OMITTED: <plaintext>
2559 if ( $this->stack
->inScope( 'button' ) ) {
2560 $this->inBodyMode( 'endtag', 'button' );
2561 return $this->insertToken( $token, $value, $attribs, $selfclose );
2563 $this->afe
->reconstruct( $this->stack
);
2564 $this->stack
->insertHTMLElement( $value, $attribs );
2568 $activeElement = $this->afe
->findElementByTag( 'a' );
2569 if ( $activeElement ) {
2570 $this->inBodyMode( 'endtag', 'a' );
2571 if ( $this->afe
->isInList( $activeElement ) ) {
2572 $this->afe
->remove( $activeElement );
2573 // Don't flatten here, since when we fall
2574 // through below we might foster parent
2575 // the new <a> tag inside this one.
2576 $this->stack
->removeElement( $activeElement, false );
2592 $this->afe
->reconstruct( $this->stack
);
2593 $this->afe
->push( $this->stack
->insertHTMLElement( $value, $attribs ), $attribs );
2597 $this->afe
->reconstruct( $this->stack
);
2598 if ( $this->stack
->inScope( 'nobr' ) ) {
2599 $this->inBodyMode( 'endtag', 'nobr' );
2600 $this->afe
->reconstruct( $this->stack
);
2602 $this->afe
->push( $this->stack
->insertHTMLElement( $value, $attribs ), $attribs );
2608 $this->afe
->reconstruct( $this->stack
);
2609 $this->stack
->insertHTMLElement( $value, $attribs );
2610 $this->afe
->insertMarker();
2611 # OMITTED: frameset_ok
2615 # The document is never in "quirks mode"; see simplifications
2617 if ( $this->stack
->inButtonScope( 'p' ) ) {
2618 $this->inBodyMode( 'endtag', 'p' );
2620 $this->stack
->insertHTMLElement( $value, $attribs );
2621 # OMITTED: frameset_ok
2622 $this->switchMode( 'inTableMode' );
2631 $this->afe
->reconstruct( $this->stack
);
2632 $this->stack
->insertHTMLElement( $value, $attribs );
2633 $this->stack
->pop();
2634 # OMITTED: frameset_ok
2638 $this->afe
->reconstruct( $this->stack
);
2639 $this->stack
->insertHTMLElement( $value, $attribs );
2640 $this->stack
->pop();
2641 # OMITTED: frameset_ok
2642 # (hence we don't need to examine the tag's "type" attribute)
2649 $this->stack
->insertHTMLElement( $value, $attribs );
2650 $this->stack
->pop();
2654 if ( $this->stack
->inButtonScope( 'p' ) ) {
2655 $this->inBodyMode( 'endtag', 'p' );
2657 $this->stack
->insertHTMLElement( $value, $attribs );
2658 $this->stack
->pop();
2663 return $this->inBodyMode( $token, 'img', $attribs, $selfclose );
2665 # OMITTED: <isindex>
2668 $this->stack
->insertHTMLElement( $value, $attribs );
2669 $this->ignoreLinefeed
= true;
2670 $this->inRCDATA
= $value; // emulate rcdata tokenizer mode
2671 # OMITTED: frameset_ok
2676 # OMITTED: <noembed>
2677 # OMITTED: <noscript>
2680 $this->afe
->reconstruct( $this->stack
);
2681 $this->stack
->insertHTMLElement( $value, $attribs );
2682 switch ( $this->parseMode
) {
2684 case 'inCaptionMode':
2685 case 'inTableBodyMode':
2688 $this->switchMode( 'inSelectInTableMode' );
2691 $this->switchMode( 'inSelectMode' );
2697 if ( $this->stack
->currentNode
->isHtmlNamed( 'option' ) ) {
2698 $this->inBodyMode( 'endtag', 'option' );
2700 $this->afe
->reconstruct( $this->stack
);
2701 $this->stack
->insertHTMLElement( $value, $attribs );
2706 if ( $this->stack
->inScope( 'ruby' ) ) {
2707 $this->stack
->generateImpliedEndTags();
2709 $this->stack
->insertHTMLElement( $value, $attribs );
2714 if ( $this->stack
->inScope( 'ruby' ) ) {
2715 $this->stack
->generateImpliedEndTags( 'rtc' );
2717 $this->stack
->insertHTMLElement( $value, $attribs );
2721 $this->afe
->reconstruct( $this->stack
);
2722 # We skip the spec's "adjust MathML attributes" and
2723 # "adjust foreign attributes" steps, since the browser will
2724 # do this later when it parses the output and it doesn't affect
2726 $this->stack
->insertForeignElement(
2727 BalanceSets
::MATHML_NAMESPACE
, $value, $attribs
2730 # emit explicit </math> tag.
2731 $this->stack
->pop();
2736 $this->afe
->reconstruct( $this->stack
);
2737 # We skip the spec's "adjust SVG attributes" and
2738 # "adjust foreign attributes" steps, since the browser will
2739 # do this later when it parses the output and it doesn't affect
2741 $this->stack
->insertForeignElement(
2742 BalanceSets
::SVG_NAMESPACE
, $value, $attribs
2745 # emit explicit </svg> tag.
2746 $this->stack
->pop();
2761 // Ignore table tags if we're not inTableMode
2765 // Handle any other start tag here
2766 $this->afe
->reconstruct( $this->stack
);
2767 $this->stack
->insertHTMLElement( $value, $attribs );
2769 } elseif ( $token === 'endtag' ) {
2771 # </body>,</html> are unsupported.
2774 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2802 // Ignore if there is not a matching open tag
2803 if ( !$this->stack
->inScope( $value ) ) {
2806 $this->stack
->generateImpliedEndTags();
2807 $this->stack
->popTag( $value );
2811 if ( $this->stack
->indexOf( 'template' ) < 0 ) {
2812 $openform = $this->formElementPointer
;
2813 $this->formElementPointer
= null;
2814 if ( !$openform ||
!$this->stack
->inScope( $openform ) ) {
2817 $this->stack
->generateImpliedEndTags();
2818 // Don't flatten yet if we're removing a <form> element
2819 // out-of-order. (eg. `<form><div></form>`)
2820 $flatten = ( $this->stack
->currentNode
=== $openform );
2821 $this->stack
->removeElement( $openform, $flatten );
2823 if ( !$this->stack
->inScope( 'form' ) ) {
2826 $this->stack
->generateImpliedEndTags();
2827 $this->stack
->popTag( 'form' );
2832 if ( !$this->stack
->inButtonScope( 'p' ) ) {
2833 $this->inBodyMode( 'tag', 'p', [] );
2834 return $this->insertToken( $token, $value, $attribs, $selfclose );
2836 $this->stack
->generateImpliedEndTags( $value );
2837 $this->stack
->popTag( $value );
2841 if ( !$this->stack
->inListItemScope( $value ) ) {
2842 return true; # ignore
2844 $this->stack
->generateImpliedEndTags( $value );
2845 $this->stack
->popTag( $value );
2850 if ( !$this->stack
->inScope( $value ) ) {
2851 return true; # ignore
2853 $this->stack
->generateImpliedEndTags( $value );
2854 $this->stack
->popTag( $value );
2863 if ( !$this->stack
->inScope( BalanceSets
::$headingSet ) ) {
2864 return true; # ignore
2866 $this->stack
->generateImpliedEndTags();
2867 $this->stack
->popTag( BalanceSets
::$headingSet );
2871 # Take a deep breath, then:
2888 if ( $this->stack
->adoptionAgency( $value, $this->afe
) ) {
2889 return true; # If we did something, we're done.
2891 break; # Go to the "any other end tag" case.
2896 if ( !$this->stack
->inScope( $value ) ) {
2897 return true; # ignore
2899 $this->stack
->generateImpliedEndTags();
2900 $this->stack
->popTag( $value );
2901 $this->afe
->clearToMarker();
2905 # Turn </br> into <br>
2906 return $this->inBodyMode( 'tag', $value, [] );
2909 // Any other end tag goes here
2910 foreach ( $this->stack
as $i => $node ) {
2911 if ( $node->isHtmlNamed( $value ) ) {
2912 $this->stack
->generateImpliedEndTags( $value );
2913 $this->stack
->popTo( $i ); # including $i
2915 } elseif ( $node->isA( BalanceSets
::$specialSet ) ) {
2916 return true; // ignore this close token.
2920 } elseif ( $token === 'comment' ) {
2921 $this->stack
->insertComment( $value );
2924 Assert
::invariant( false, "Bad token type: $token" );
2928 private function inTableMode( $token, $value, $attribs = null, $selfclose = false ) {
2929 if ( $token === 'text' ) {
2930 if ( $this->textIntegrationMode
) {
2931 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
2932 } elseif ( $this->stack
->currentNode
->isA( BalanceSets
::$tableSectionRowSet ) ) {
2933 $this->pendingTableText
= '';
2934 $this->originalInsertionMode
= $this->parseMode
;
2935 return $this->switchModeAndReprocess( 'inTableTextMode', $token, $value, $attribs, $selfclose );
2937 // fall through to default case.
2938 } elseif ( $token === 'eof' ) {
2939 $this->stopParsing();
2941 } elseif ( $token === 'tag' ) {
2944 $this->afe
->insertMarker();
2945 $this->stack
->insertHTMLElement( $value, $attribs );
2946 $this->switchMode( 'inCaptionMode' );
2949 $this->stack
->clearToContext( BalanceSets
::$tableContextSet );
2950 $this->stack
->insertHTMLElement( $value, $attribs );
2951 $this->switchMode( 'inColumnGroupMode' );
2954 $this->inTableMode( 'tag', 'colgroup', [] );
2955 return $this->insertToken( $token, $value, $attribs, $selfclose );
2959 $this->stack
->clearToContext( BalanceSets
::$tableContextSet );
2960 $this->stack
->insertHTMLElement( $value, $attribs );
2961 $this->switchMode( 'inTableBodyMode' );
2966 $this->inTableMode( 'tag', 'tbody', [] );
2967 return $this->insertToken( $token, $value, $attribs, $selfclose );
2969 if ( !$this->stack
->inTableScope( $value ) ) {
2970 return true; // Ignore this tag.
2972 $this->inTableMode( 'endtag', $value );
2973 return $this->insertToken( $token, $value, $attribs, $selfclose );
2978 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2981 if ( !isset( $attribs['type'] ) ||
strcasecmp( $attribs['type'], 'hidden' ) !== 0 ) {
2982 break; // Handle this as "everything else"
2984 $this->stack
->insertHTMLElement( $value, $attribs );
2985 $this->stack
->pop();
2990 $this->formElementPointer ||
2991 $this->stack
->indexOf( 'template' ) >= 0
2993 return true; // ignore this token
2995 $this->formElementPointer
=
2996 $this->stack
->insertHTMLElement( $value, $attribs );
2997 $this->stack
->popTag( $this->formElementPointer
);
3000 // Fall through for "anything else" clause.
3001 } elseif ( $token === 'endtag' ) {
3004 if ( !$this->stack
->inTableScope( $value ) ) {
3005 return true; // Ignore.
3007 $this->stack
->popTag( $value );
3008 $this->resetInsertionMode();
3021 return true; // Ignore the token.
3023 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
3025 // Fall through for "anything else" clause.
3026 } elseif ( $token === 'comment' ) {
3027 $this->stack
->insertComment( $value );
3030 // This is the "anything else" case:
3031 $this->stack
->fosterParentMode
= true;
3032 $this->inBodyMode( $token, $value, $attribs, $selfclose );
3033 $this->stack
->fosterParentMode
= false;
3037 private function inTableTextMode( $token, $value, $attribs = null, $selfclose = false ) {
3038 if ( $token === 'text' ) {
3039 $this->pendingTableText
.= $value;
3043 $text = $this->pendingTableText
;
3044 $this->pendingTableText
= '';
3045 if ( preg_match( '/[^\x09\x0A\x0C\x0D\x20]/', $text ) ) {
3046 // This should match the "anything else" case inTableMode
3047 $this->stack
->fosterParentMode
= true;
3048 $this->inBodyMode( 'text', $text );
3049 $this->stack
->fosterParentMode
= false;
3051 // Pending text is just whitespace.
3052 $this->stack
->insertText( $text );
3054 return $this->switchModeAndReprocess(
3055 $this->originalInsertionMode
, $token, $value, $attribs, $selfclose
3059 // helper for inCaptionMode
3060 private function endCaption() {
3061 if ( !$this->stack
->inTableScope( 'caption' ) ) {
3064 $this->stack
->generateImpliedEndTags();
3065 $this->stack
->popTag( 'caption' );
3066 $this->afe
->clearToMarker();
3067 $this->switchMode( 'inTableMode' );
3071 private function inCaptionMode( $token, $value, $attribs = null, $selfclose = false ) {
3072 if ( $token === 'tag' ) {
3083 if ( $this->endCaption() ) {
3084 $this->insertToken( $token, $value, $attribs, $selfclose );
3088 // Fall through to "anything else" case.
3089 } elseif ( $token === 'endtag' ) {
3092 $this->endCaption();
3095 if ( $this->endCaption() ) {
3096 $this->insertToken( $token, $value, $attribs, $selfclose );
3112 // Fall through to "anything else" case.
3114 // The Anything Else case
3115 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
3118 private function inColumnGroupMode( $token, $value, $attribs = null, $selfclose = false ) {
3119 if ( $token === 'text' ) {
3120 if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
3121 $this->stack
->insertText( $matches[0] );
3122 $value = substr( $value, strlen( $matches[0] ) );
3124 if ( strlen( $value ) === 0 ) {
3125 return true; // All text handled.
3127 // Fall through to handle non-whitespace below.
3128 } elseif ( $token === 'tag' ) {
3132 $this->stack
->insertHTMLElement( $value, $attribs );
3133 $this->stack
->pop();
3136 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
3138 // Fall through for "anything else".
3139 } elseif ( $token === 'endtag' ) {
3142 if ( !$this->stack
->currentNode
->isHtmlNamed( 'colgroup' ) ) {
3143 return true; // Ignore the token.
3145 $this->stack
->pop();
3146 $this->switchMode( 'inTableMode' );
3149 return true; // Ignore the token.
3151 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
3153 // Fall through for "anything else".
3154 } elseif ( $token === 'eof' ) {
3155 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
3156 } elseif ( $token === 'comment' ) {
3157 $this->stack
->insertComment( $value );
3162 if ( !$this->stack
->currentNode
->isHtmlNamed( 'colgroup' ) ) {
3163 return true; // Ignore the token.
3165 $this->inColumnGroupMode( 'endtag', 'colgroup' );
3166 return $this->insertToken( $token, $value, $attribs, $selfclose );
3169 // Helper function for inTableBodyMode
3170 private function endSection() {
3172 $this->stack
->inTableScope( 'tbody' ) ||
3173 $this->stack
->inTableScope( 'thead' ) ||
3174 $this->stack
->inTableScope( 'tfoot' )
3178 $this->stack
->clearToContext( BalanceSets
::$tableBodyContextSet );
3179 $this->stack
->pop();
3180 $this->switchMode( 'inTableMode' );
3183 private function inTableBodyMode( $token, $value, $attribs = null, $selfclose = false ) {
3184 if ( $token === 'tag' ) {
3187 $this->stack
->clearToContext( BalanceSets
::$tableBodyContextSet );
3188 $this->stack
->insertHTMLElement( $value, $attribs );
3189 $this->switchMode( 'inRowMode' );
3193 $this->inTableBodyMode( 'tag', 'tr', [] );
3194 $this->insertToken( $token, $value, $attribs, $selfclose );
3202 if ( $this->endSection() ) {
3203 $this->insertToken( $token, $value, $attribs, $selfclose );
3207 } elseif ( $token === 'endtag' ) {
3210 if ( $this->endSection() ) {
3211 $this->insertToken( $token, $value, $attribs, $selfclose );
3217 if ( $this->stack
->inTableScope( $value ) ) {
3218 $this->endSection();
3229 return true; // Ignore the token.
3233 return $this->inTableMode( $token, $value, $attribs, $selfclose );
3236 // Helper function for inRowMode
3237 private function endRow() {
3238 if ( !$this->stack
->inTableScope( 'tr' ) ) {
3241 $this->stack
->clearToContext( BalanceSets
::$tableRowContextSet );
3242 $this->stack
->pop();
3243 $this->switchMode( 'inTableBodyMode' );
3246 private function inRowMode( $token, $value, $attribs = null, $selfclose = false ) {
3247 if ( $token === 'tag' ) {
3251 $this->stack
->clearToContext( BalanceSets
::$tableRowContextSet );
3252 $this->stack
->insertHTMLElement( $value, $attribs );
3253 $this->switchMode( 'inCellMode' );
3254 $this->afe
->insertMarker();
3263 if ( $this->endRow() ) {
3264 $this->insertToken( $token, $value, $attribs, $selfclose );
3268 } elseif ( $token === 'endtag' ) {
3274 if ( $this->endRow() ) {
3275 $this->insertToken( $token, $value, $attribs, $selfclose );
3282 $this->stack
->inTableScope( $value ) &&
3285 $this->insertToken( $token, $value, $attribs, $selfclose );
3295 return true; // Ignore the token.
3299 return $this->inTableMode( $token, $value, $attribs, $selfclose );
3302 // Helper for inCellMode
3303 private function endCell() {
3304 if ( $this->stack
->inTableScope( 'td' ) ) {
3305 $this->inCellMode( 'endtag', 'td' );
3307 } elseif ( $this->stack
->inTableScope( 'th' ) ) {
3308 $this->inCellMode( 'endtag', 'th' );
3314 private function inCellMode( $token, $value, $attribs = null, $selfclose = false ) {
3315 if ( $token === 'tag' ) {
3326 if ( $this->endCell() ) {
3327 $this->insertToken( $token, $value, $attribs, $selfclose );
3331 } elseif ( $token === 'endtag' ) {
3335 if ( $this->stack
->inTableScope( $value ) ) {
3336 $this->stack
->generateImpliedEndTags();
3337 $this->stack
->popTag( $value );
3338 $this->afe
->clearToMarker();
3339 $this->switchMode( 'inRowMode' );
3354 if ( $this->stack
->inTableScope( $value ) ) {
3355 $this->stack
->generateImpliedEndTags();
3356 $this->stack
->popTag( BalanceSets
::$tableCellSet );
3357 $this->afe
->clearToMarker();
3358 $this->switchMode( 'inRowMode' );
3359 $this->insertToken( $token, $value, $attribs, $selfclose );
3365 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
3368 private function inSelectMode( $token, $value, $attribs = null, $selfclose = false ) {
3369 if ( $token === 'text' ) {
3370 $this->stack
->insertText( $value );
3372 } elseif ( $token === 'eof' ) {
3373 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
3374 } elseif ( $token === 'tag' ) {
3378 if ( $this->stack
->currentNode
->isHtmlNamed( 'option' ) ) {
3379 $this->stack
->pop();
3381 $this->stack
->insertHTMLElement( $value, $attribs );
3384 if ( $this->stack
->currentNode
->isHtmlNamed( 'option' ) ) {
3385 $this->stack
->pop();
3387 if ( $this->stack
->currentNode
->isHtmlNamed( 'optgroup' ) ) {
3388 $this->stack
->pop();
3390 $this->stack
->insertHTMLElement( $value, $attribs );
3393 $this->inSelectMode( 'endtag', $value ); // treat it like endtag
3398 if ( !$this->stack
->inSelectScope( 'select' ) ) {
3399 return true; // ignore token (fragment case)
3401 $this->inSelectMode( 'endtag', 'select' );
3402 return $this->insertToken( $token, $value, $attribs, $selfclose );
3405 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
3407 } elseif ( $token === 'endtag' ) {
3411 $this->stack
->currentNode
->isHtmlNamed( 'option' ) &&
3412 $this->stack
->length() >= 2 &&
3413 $this->stack
->node( $this->stack
->length() - 2 )->isHtmlNamed( 'optgroup' )
3415 $this->stack
->pop();
3417 if ( $this->stack
->currentNode
->isHtmlNamed( 'optgroup' ) ) {
3418 $this->stack
->pop();
3422 if ( $this->stack
->currentNode
->isHtmlNamed( 'option' ) ) {
3423 $this->stack
->pop();
3427 if ( !$this->stack
->inSelectScope( $value ) ) {
3428 return true; // fragment case
3430 $this->stack
->popTag( $value );
3431 $this->resetInsertionMode();
3434 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
3436 } elseif ( $token === 'comment' ) {
3437 $this->stack
->insertComment( $value );
3440 // anything else: just ignore the token
3444 private function inSelectInTableMode( $token, $value, $attribs = null, $selfclose = false ) {
3454 if ( $token === 'tag' ) {
3455 $this->inSelectInTableMode( 'endtag', 'select' );
3456 return $this->insertToken( $token, $value, $attribs, $selfclose );
3457 } elseif ( $token === 'endtag' ) {
3458 if ( $this->stack
->inTableScope( $value ) ) {
3459 $this->inSelectInTableMode( 'endtag', 'select' );
3460 return $this->insertToken( $token, $value, $attribs, $selfclose );
3466 return $this->inSelectMode( $token, $value, $attribs, $selfclose );
3469 private function inTemplateMode( $token, $value, $attribs = null, $selfclose = false ) {
3470 if ( $token === 'text' ||
$token === 'comment' ) {
3471 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
3472 } elseif ( $token === 'eof' ) {
3473 if ( $this->stack
->indexOf( 'template' ) < 0 ) {
3474 $this->stopParsing();
3476 $this->stack
->popTag( 'template' );
3477 $this->afe
->clearToMarker();
3478 array_pop( $this->templateInsertionModes
);
3479 $this->resetInsertionMode();
3480 $this->insertToken( $token, $value, $attribs, $selfclose );
3483 } elseif ( $token === 'tag' ) {
3495 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
3502 return $this->switchModeAndReprocess(
3503 'inTableMode', $token, $value, $attribs, $selfclose
3507 return $this->switchModeAndReprocess(
3508 'inColumnGroupMode', $token, $value, $attribs, $selfclose
3512 return $this->switchModeAndReprocess(
3513 'inTableBodyMode', $token, $value, $attribs, $selfclose
3518 return $this->switchModeAndReprocess(
3519 'inRowMode', $token, $value, $attribs, $selfclose
3522 return $this->switchModeAndReprocess(
3523 'inBodyMode', $token, $value, $attribs, $selfclose
3525 } elseif ( $token === 'endtag' ) {
3528 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
3532 Assert
::invariant( false, "Bad token type: $token" );