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,
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, 'li' => true, 'link' => true,
123 'listing' => true, 'main' => true, 'marquee' => true,
124 'menu' => 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,
160 'menuitem' => true, 'optgroup' => true,
161 'option' => true, 'p' => true, 'rb' => true, 'rp' => true,
162 'rt' => true, 'rtc' => true
166 public static $thoroughImpliedEndTagsSet = [
167 self
::HTML_NAMESPACE
=> [
168 'caption' => true, 'colgroup' => true, 'dd' => true, 'dt' => true,
169 'li' => true, 'optgroup' => true, 'option' => true, 'p' => true,
170 'rb' => true, 'rp' => true, 'rt' => true, 'rtc' => true,
171 'tbody' => true, 'td' => true, 'tfoot' => true, 'th' => true,
172 'thead' => true, 'tr' => true
176 public static $tableCellSet = [
177 self
::HTML_NAMESPACE
=> [
178 'td' => true, 'th' => true
181 public static $tableContextSet = [
182 self
::HTML_NAMESPACE
=> [
183 'table' => true, 'template' => true, 'html' => true
187 public static $tableBodyContextSet = [
188 self
::HTML_NAMESPACE
=> [
189 'tbody' => true, 'tfoot' => true, 'thead' => true,
190 'template' => true, 'html' => true
194 public static $tableRowContextSet = [
195 self
::HTML_NAMESPACE
=> [
196 'tr' => true, 'template' => true, 'html' => true
200 // See https://html.spec.whatwg.org/multipage/forms.html#form-associated-element
201 public static $formAssociatedSet = [
202 self
::HTML_NAMESPACE
=> [
203 'button' => true, 'fieldset' => true, 'input' => true,
204 'keygen' => true, 'object' => true, 'output' => true,
205 'select' => true, 'textarea' => true, 'img' => true
209 public static $inScopeSet = [
210 self
::HTML_NAMESPACE
=> [
211 'applet' => true, 'caption' => true, 'html' => true,
212 'marquee' => true, 'object' => true,
213 'table' => true, 'td' => true, 'template' => true,
216 self
::SVG_NAMESPACE
=> [
217 'foreignobject' => true, 'desc' => true, 'title' => true
219 self
::MATHML_NAMESPACE
=> [
220 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
221 'mtext' => true, 'annotation-xml' => true
225 private static $inListItemScopeSet = null;
226 public static function inListItemScopeSet() {
227 if ( self
::$inListItemScopeSet === null ) {
228 self
::$inListItemScopeSet = self
::$inScopeSet;
229 self
::$inListItemScopeSet[self
::HTML_NAMESPACE
]['ol'] = true;
230 self
::$inListItemScopeSet[self
::HTML_NAMESPACE
]['ul'] = true;
232 return self
::$inListItemScopeSet;
235 private static $inButtonScopeSet = null;
236 public static function inButtonScopeSet() {
237 if ( self
::$inButtonScopeSet === null ) {
238 self
::$inButtonScopeSet = self
::$inScopeSet;
239 self
::$inButtonScopeSet[self
::HTML_NAMESPACE
]['button'] = true;
241 return self
::$inButtonScopeSet;
244 public static $inTableScopeSet = [
245 self
::HTML_NAMESPACE
=> [
246 'html' => true, 'table' => true, 'template' => true
250 public static $inInvertedSelectScopeSet = [
251 self
::HTML_NAMESPACE
=> [
252 'option' => true, 'optgroup' => true
256 public static $mathmlTextIntegrationPointSet = [
257 self
::MATHML_NAMESPACE
=> [
258 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
263 public static $htmlIntegrationPointSet = [
264 self
::SVG_NAMESPACE
=> [
265 'foreignobject' => true,
271 // For tidy compatibility.
272 public static $tidyPWrapSet = [
273 self
::HTML_NAMESPACE
=> [
274 'body' => true, 'blockquote' => true,
275 // We parse with <body> as the fragment context, but the top-level
276 // element on the stack is actually <html>. We could use the
277 // "adjusted current node" everywhere to work around this, but it's
278 // easier just to add <html> to the p-wrap set.
282 public static $tidyInlineSet = [
283 self
::HTML_NAMESPACE
=> [
284 'a' => true, 'abbr' => true, 'acronym' => true, 'applet' => true,
285 'b' => true, 'basefont' => true, 'bdo' => true, 'big' => true,
286 'br' => true, 'button' => true, 'cite' => true, 'code' => true,
287 'dfn' => true, 'em' => true, 'font' => true, 'i' => true,
288 'iframe' => true, 'img' => true, 'input' => true, 'kbd' => true,
289 'label' => true, 'legend' => true, 'map' => true, 'object' => true,
290 'param' => true, 'q' => true, 'rb' => true, 'rbc' => true,
291 'rp' => true, 'rt' => true, 'rtc' => true, 'ruby' => true,
292 's' => true, 'samp' => true, 'select' => true, 'small' => true,
293 'span' => true, 'strike' => true, 'strong' => true, 'sub' => true,
294 'sup' => true, 'textarea' => true, 'tt' => true, 'u' => true,
301 * A BalanceElement is a simplified version of a DOM Node. The main
302 * difference is that we only keep BalanceElements around for nodes
303 * currently on the BalanceStack of open elements. As soon as an
304 * element is closed, with some minor exceptions relating to the
305 * tree builder "adoption agency algorithm", the element and all its
306 * children are serialized to a string using the flatten() method.
307 * This keeps our memory usage low.
312 class BalanceElement
{
314 * The namespace of the element.
315 * @var string $namespaceURI
317 public $namespaceURI;
319 * The lower-cased name of the element.
320 * @var string $localName
324 * Attributes for the element, in array form
325 * @var array $attribs
330 * Parent of this element, or the string "flat" if this element has
331 * already been flattened into its parent.
332 * @var BalanceElement|string|null $parent
337 * An array of children of this element. Typically only the last
338 * child will be an actual BalanceElement object; the rest will
339 * be strings, representing either text nodes or flattened
340 * BalanceElement objects.
341 * @var BalanceElement[]|string[] $children
346 * A unique string identifier for Noah's Ark purposes, lazy initialized
351 * The next active formatting element in the list, or null if this is the
352 * end of the AFE list or if the element is not in the AFE list.
357 * The previous active formatting element in the list, or null if this is
358 * the start of the list or if the element is not in the AFE list.
363 * The next element in the Noah's Ark species bucket.
368 * Make a new BalanceElement corresponding to the HTML DOM Element
369 * with the given localname, namespace, and attributes.
371 * @param string $namespaceURI The namespace of the element.
372 * @param string $localName The lowercased name of the tag.
373 * @param array $attribs Attributes of the element
375 public function __construct( $namespaceURI, $localName, array $attribs ) {
376 $this->localName
= $localName;
377 $this->namespaceURI
= $namespaceURI;
378 $this->attribs
= $attribs;
379 $this->contents
= '';
380 $this->parent
= null;
381 $this->children
= [];
385 * Remove the given child from this element.
386 * @param BalanceElement $elt
388 private function removeChild( BalanceElement
$elt ) {
389 Assert
::precondition(
390 $this->parent
!== 'flat', "Can't removeChild after flattening $this"
393 $elt->parent
=== $this, 'elt', 'must have $this as a parent'
395 $idx = array_search( $elt, $this->children
, true );
396 Assert
::parameter( $idx !== false, '$elt', 'must be a child of $this' );
398 array_splice( $this->children
, $idx, 1 );
402 * Find $a in the list of children and insert $b before it.
403 * @param BalanceElement $a
404 * @param BalanceElement|string $b
406 public function insertBefore( BalanceElement
$a, $b ) {
407 Assert
::precondition(
408 $this->parent
!== 'flat', "Can't insertBefore after flattening."
410 $idx = array_search( $a, $this->children
, true );
411 Assert
::parameter( $idx !== false, '$a', 'must be a child of $this' );
412 if ( is_string( $b ) ) {
413 array_splice( $this->children
, $idx, 0, [ $b ] );
415 Assert
::parameter( $b->parent
!== 'flat', '$b', "Can't be flat" );
416 if ( $b->parent
!== null ) {
417 $b->parent
->removeChild( $b );
419 array_splice( $this->children
, $idx, 0, [ $b ] );
425 * Append $elt to the end of the list of children.
426 * @param BalanceElement|string $elt
428 public function appendChild( $elt ) {
429 Assert
::precondition(
430 $this->parent
!== 'flat', "Can't appendChild after flattening."
432 if ( is_string( $elt ) ) {
433 array_push( $this->children
, $elt );
436 // Remove $elt from parent, if it had one.
437 if ( $elt->parent
!== null ) {
438 $elt->parent
->removeChild( $elt );
440 array_push( $this->children
, $elt );
441 $elt->parent
= $this;
445 * Transfer all of the children of $elt to $this.
446 * @param BalanceElement $elt
448 public function adoptChildren( BalanceElement
$elt ) {
449 Assert
::precondition(
450 $elt->parent
!== 'flat', "Can't adoptChildren after flattening."
452 foreach ( $elt->children
as $child ) {
453 if ( !is_string( $child ) ) {
454 // This is an optimization which avoids an O(n^2) set of
455 // array_splice operations.
456 $child->parent
= null;
458 $this->appendChild( $child );
464 * Flatten this node and all of its children into a string, as specified
465 * by the HTML serialization specification, and replace this node
466 * in its parent by that string.
468 * @param array $config Balancer configuration; see Balancer::__construct().
473 public function flatten( array $config ) {
474 Assert
::parameter( $this->parent
!== null, '$this', 'must be a child' );
475 Assert
::parameter( $this->parent
!== 'flat', '$this', 'already flat' );
476 $idx = array_search( $this, $this->parent
->children
, true );
478 $idx !== false, '$this', 'must be a child of its parent'
480 $tidyCompat = $config['tidyCompat'];
483 foreach ( $this->children
as $elt ) {
484 if ( !is_string( $elt ) ) {
485 $elt = $elt->flatten( $config );
487 if ( $blank && preg_match( '/[^\t\n\f\r ]/', $elt ) ) {
491 if ( $this->isHtmlNamed( 'mw:p-wrap' ) ) {
492 $this->localName
= 'p';
493 } elseif ( $blank ) {
494 // Add 'mw-empty-elt' class so elements can be hidden via CSS
495 // for compatibility with legacy tidy.
496 if ( !count( $this->attribs
) &&
497 ( $this->localName
=== 'tr' ||
$this->localName
=== 'li' )
499 $this->attribs
= [ 'class' => "mw-empty-elt" ];
503 $this->isA( BalanceSets
::$extraLinefeedSet ) &&
504 count( $this->children
) > 0 &&
505 substr( $this->children
[0], 0, 1 ) == "\n"
507 // Double the linefeed after pre/listing/textarea
508 // according to the (old) HTML5 fragment serialization
509 // algorithm (see https://github.com/whatwg/html/issues/944)
510 // to ensure this will round-trip.
511 array_unshift( $this->children
, "\n" );
513 $flat = $blank ?
'' : "{$this}";
517 $this->parent
->children
[$idx] = $flat;
518 $this->parent
= 'flat'; // for assertion checking
523 * Serialize this node and all of its children to a string, as specified
524 * by the HTML serialization specification.
526 * @return string The serialization of the BalanceElement
527 * @see https://html.spec.whatwg.org/multipage/syntax.html#serialising-html-fragments
529 public function __toString() {
531 foreach ( $this->attribs
as $name => $value ) {
532 $encValue = Sanitizer
::encodeAttribute( $value );
533 $encAttribs .= " $name=\"$encValue\"";
535 if ( !$this->isA( BalanceSets
::$emptyElementSet ) ) {
536 $out = "<{$this->localName}{$encAttribs}>";
537 $len = strlen( $out );
539 foreach ( $this->children
as $elt ) {
542 $out .= "</{$this->localName}>";
544 $out = "<{$this->localName}{$encAttribs} />";
546 count( $this->children
) === 0,
547 "Empty elements shouldn't have children."
553 // Utility functions on BalanceElements.
556 * Determine if $this represents a specific HTML tag, is a member of
557 * a tag set, or is equal to another BalanceElement.
559 * @param BalanceElement|array|string $set The target BalanceElement,
560 * set (from the BalanceSets class), or string (HTML tag name).
563 public function isA( $set ) {
564 if ( $set instanceof BalanceElement
) {
565 return $this === $set;
566 } elseif ( is_array( $set ) ) {
567 return isset( $set[$this->namespaceURI
] ) &&
568 isset( $set[$this->namespaceURI
][$this->localName
] );
570 // assume this is an HTML element name.
571 return $this->isHtml() && $this->localName
=== $set;
576 * Determine if this element is an HTML element with the specified name
577 * @param string $tagName
580 public function isHtmlNamed( $tagName ) {
581 return $this->namespaceURI
=== BalanceSets
::HTML_NAMESPACE
582 && $this->localName
=== $tagName;
586 * Determine if $this represents an element in the HTML namespace.
590 public function isHtml() {
591 return $this->namespaceURI
=== BalanceSets
::HTML_NAMESPACE
;
595 * Determine if $this represents a MathML text integration point,
596 * as defined in the HTML5 specification.
599 * @see https://html.spec.whatwg.org/multipage/syntax.html#mathml-text-integration-point
601 public function isMathmlTextIntegrationPoint() {
602 return $this->isA( BalanceSets
::$mathmlTextIntegrationPointSet );
606 * Determine if $this represents an HTML integration point,
607 * as defined in the HTML5 specification.
610 * @see https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
612 public function isHtmlIntegrationPoint() {
613 if ( $this->isA( BalanceSets
::$htmlIntegrationPointSet ) ) {
617 $this->namespaceURI
=== BalanceSets
::MATHML_NAMESPACE
&&
618 $this->localName
=== 'annotation-xml' &&
619 isset( $this->attribs
['encoding'] ) &&
620 ( strcasecmp( $this->attribs
['encoding'], 'text/html' ) == 0 ||
621 strcasecmp( $this->attribs
['encoding'], 'application/xhtml+xml' ) == 0 )
629 * Get a string key for the Noah's Ark algorithm
632 public function getNoahKey() {
633 if ( $this->noahKey
=== null ) {
634 $attribs = $this->attribs
;
636 $this->noahKey
= serialize( [ $this->namespaceURI
, $this->localName
, $attribs ] );
638 return $this->noahKey
;
643 * The "stack of open elements" as defined in the HTML5 tree builder
644 * spec. This contains methods to ensure that content (start tags, text)
645 * are inserted at the correct place in the output string, and to
646 * flatten BalanceElements are they are closed to avoid holding onto
647 * a complete DOM tree for the document in memory.
649 * The stack defines a PHP iterator to traverse it in "reverse order",
650 * that is, the most-recently-added element is visited first in a
655 * @see https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements
657 class BalanceStack
implements IteratorAggregate
{
659 * Backing storage for the stack.
660 * @var BalanceElement[] $elements
662 private $elements = [];
664 * Foster parent mode determines how nodes are inserted into the
666 * @var bool $fosterParentMode
667 * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
669 public $fosterParentMode = false;
671 * Configuration options governing flattening.
673 * @see Balancer::__construct()
677 * Reference to the current element
682 * Create a new BalanceStack with a single BalanceElement on it,
683 * representing the root <html> node.
684 * @param array $config Balancer configuration; see Balancer::_construct().
686 public function __construct( array $config ) {
687 // always a root <html> element on the stack
690 new BalanceElement( BalanceSets
::HTML_NAMESPACE
, 'html', [] )
692 $this->currentNode
= $this->elements
[0];
693 $this->config
= $config;
697 * Return a string representing the output of the tree builder:
698 * all the children of the root <html> node.
701 public function getOutput() {
702 // Don't include the outer '<html>....</html>'
704 foreach ( $this->elements
[0]->children
as $elt ) {
705 $out .= is_string( $elt ) ?
$elt :
706 $elt->flatten( $this->config
);
712 * Insert a comment at the appropriate place for inserting a node.
713 * @param string $value Content of the comment.
715 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-a-comment
717 public function insertComment( $value ) {
718 // Just another type of text node, except for tidy p-wrapping.
719 return $this->insertText( '<!--' . $value . '-->', true );
723 * Insert text at the appropriate place for inserting a node.
724 * @param string $value
725 * @param bool $isComment
727 * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
729 public function insertText( $value, $isComment = false ) {
731 $this->fosterParentMode
&&
732 $this->currentNode
->isA( BalanceSets
::$tableSectionRowSet )
734 $this->fosterParent( $value );
736 $this->config
['tidyCompat'] && !$isComment &&
737 $this->currentNode
->isA( BalanceSets
::$tidyPWrapSet )
739 $this->insertHTMLElement( 'mw:p-wrap', [] );
740 return $this->insertText( $value );
742 $this->currentNode
->appendChild( $value );
747 * Insert a BalanceElement at the appropriate place, pushing it
748 * on to the open elements stack.
749 * @param string $namespaceURI The element namespace
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-a-foreign-element
755 public function insertForeignElement( $namespaceURI, $tag, $attribs ) {
756 return $this->insertElement(
757 new BalanceElement( $namespaceURI, $tag, $attribs )
762 * Insert an HTML element at the appropriate place, pushing it on to
763 * the open elements stack.
764 * @param string $tag The tag name
765 * @param string $attribs Normalized attributes, as a string.
766 * @return BalanceElement
767 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-an-html-element
769 public function insertHTMLElement( $tag, $attribs ) {
770 return $this->insertForeignElement(
771 BalanceSets
::HTML_NAMESPACE
, $tag, $attribs
776 * Insert an element at the appropriate place and push it on to the
777 * open elements stack.
778 * @param BalanceElement $elt
779 * @return BalanceElement
780 * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
782 public function insertElement( BalanceElement
$elt ) {
784 $this->currentNode
->isHtmlNamed( 'mw:p-wrap' ) &&
785 !$elt->isA( BalanceSets
::$tidyInlineSet )
787 // Tidy compatibility.
791 $this->fosterParentMode
&&
792 $this->currentNode
->isA( BalanceSets
::$tableSectionRowSet )
794 $elt = $this->fosterParent( $elt );
796 $this->currentNode
->appendChild( $elt );
798 Assert
::invariant( $elt->parent
!== null, "$elt must be in tree" );
799 Assert
::invariant( $elt->parent
!== 'flat', "$elt must not have been previous flattened" );
800 array_push( $this->elements
, $elt );
801 $this->currentNode
= $elt;
806 * Determine if the stack has $tag in scope.
807 * @param BalanceElement|array|string $tag
809 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
811 public function inScope( $tag ) {
812 return $this->inSpecificScope( $tag, BalanceSets
::$inScopeSet );
816 * Determine if the stack has $tag in button scope.
817 * @param BalanceElement|array|string $tag
819 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
821 public function inButtonScope( $tag ) {
822 return $this->inSpecificScope( $tag, BalanceSets
::inButtonScopeSet() );
826 * Determine if the stack has $tag in list item scope.
827 * @param BalanceElement|array|string $tag
829 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-list-item-scope
831 public function inListItemScope( $tag ) {
832 return $this->inSpecificScope( $tag, BalanceSets
::inListItemScopeSet() );
836 * Determine if the stack has $tag in table scope.
837 * @param BalanceElement|array|string $tag
839 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-table-scope
841 public function inTableScope( $tag ) {
842 return $this->inSpecificScope( $tag, BalanceSets
::$inTableScopeSet );
846 * Determine if the stack has $tag in select scope.
847 * @param BalanceElement|array|string $tag
849 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-select-scope
851 public function inSelectScope( $tag ) {
852 // Can't use inSpecificScope to implement this, since it involves
853 // *inverting* a set of tags. Implement manually.
854 foreach ( $this as $elt ) {
855 if ( $elt->isA( $tag ) ) {
858 if ( !$elt->isA( BalanceSets
::$inInvertedSelectScopeSet ) ) {
866 * Determine if the stack has $tag in a specific scope, $set.
867 * @param BalanceElement|array|string $tag
868 * @param BalanceElement|array|string $set
870 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-the-specific-scope
872 public function inSpecificScope( $tag, $set ) {
873 foreach ( $this as $elt ) {
874 if ( $elt->isA( $tag ) ) {
877 if ( $elt->isA( $set ) ) {
885 * Generate implied end tags.
886 * @param string $butnot
887 * @param bool $thorough True if we should generate end tags thoroughly.
888 * @see https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
890 public function generateImpliedEndTags( $butnot = null, $thorough = false ) {
891 $endTagSet = $thorough ?
892 BalanceSets
::$thoroughImpliedEndTagsSet :
893 BalanceSets
::$impliedEndTagsSet;
894 while ( $this->currentNode
) {
895 if ( $butnot !== null && $this->currentNode
->isHtmlNamed( $butnot ) ) {
898 if ( !$this->currentNode
->isA( $endTagSet ) ) {
906 * Return the adjusted current node.
907 * @param string $fragmentContext
910 public function adjustedCurrentNode( $fragmentContext ) {
911 return ( $fragmentContext && count( $this->elements
) === 1 ) ?
912 $fragmentContext : $this->currentNode
;
916 * Return an iterator over this stack which visits the current node
917 * first, and the root node last.
920 public function getIterator() {
921 return new ReverseArrayIterator( $this->elements
);
925 * Return the BalanceElement at the given position $idx, where
926 * position 0 represents the root element.
928 * @return BalanceElement
930 public function node( $idx ) {
931 return $this->elements
[ $idx ];
935 * Replace the element at position $idx in the BalanceStack with $elt.
937 * @param BalanceElement $elt
939 public function replaceAt( $idx, BalanceElement
$elt ) {
940 Assert
::precondition(
941 $this->elements
[$idx]->parent
!== 'flat',
942 'Replaced element should not have already been flattened.'
944 Assert
::precondition(
945 $elt->parent
!== 'flat',
946 'New element should not have already been flattened.'
948 $this->elements
[$idx] = $elt;
949 if ( $idx === count( $this->elements
) - 1 ) {
950 $this->currentNode
= $elt;
955 * Return the position of the given BalanceElement, set, or
956 * HTML tag name string in the BalanceStack.
957 * @param BalanceElement|array|string $tag
960 public function indexOf( $tag ) {
961 for ( $i = count( $this->elements
) - 1; $i >= 0; $i-- ) {
962 if ( $this->elements
[$i]->isA( $tag ) ) {
970 * Return the number of elements currently in the BalanceStack.
973 public function length() {
974 return count( $this->elements
);
978 * Remove the current node from the BalanceStack, flattening it
981 public function pop() {
982 $elt = array_pop( $this->elements
);
983 if ( count( $this->elements
) ) {
984 $this->currentNode
= $this->elements
[ count( $this->elements
) - 1 ];
986 $this->currentNode
= null;
988 if ( !$elt->isHtmlNamed( 'mw:p-wrap' ) ) {
989 $elt->flatten( $this->config
);
994 * Remove all nodes up to and including position $idx from the
995 * BalanceStack, flattening them in the process.
998 public function popTo( $idx ) {
999 for ( $length = count( $this->elements
); $length > $idx; $length-- ) {
1005 * Pop elements off the stack up to and including the first
1006 * element with the specified HTML tagname (or matching the given
1008 * @param BalanceElement|array|string $tag
1010 public function popTag( $tag ) {
1011 while ( $this->currentNode
) {
1012 if ( $this->currentNode
->isA( $tag ) ) {
1021 * Pop elements off the stack *not including* the first element
1022 * in the specified set.
1023 * @param BalanceElement|array|string $set
1025 public function clearToContext( $set ) {
1026 // Note that we don't loop to 0. Never pop the <html> elt off.
1027 for ( $length = count( $this->elements
); $length > 1; $length-- ) {
1028 if ( $this->currentNode
->isA( $set ) ) {
1036 * Remove the given $elt from the BalanceStack, optionally
1037 * flattening it in the process.
1038 * @param BalanceElement $elt The element to remove.
1039 * @param bool $flatten Whether to flatten the removed element.
1041 public function removeElement( BalanceElement
$elt, $flatten = true ) {
1043 $elt->parent
!== 'flat',
1045 '$elt should not already have been flattened.'
1048 $elt->parent
->parent
!== 'flat',
1050 'The parent of $elt should not already have been flattened.'
1052 $idx = array_search( $elt, $this->elements
, true );
1053 Assert
::parameter( $idx !== false, '$elt', 'must be in stack' );
1054 array_splice( $this->elements
, $idx, 1 );
1055 if ( $idx === count( $this->elements
) ) {
1056 $this->currentNode
= $this->elements
[$idx - 1];
1059 // serialize $elt into its parent
1060 // otherwise, it will eventually serialize when the parent
1061 // is serialized, we just hold onto the memory for its
1062 // tree of objects a little longer.
1063 $elt->flatten( $this->config
);
1065 Assert
::postcondition(
1066 array_search( $elt, $this->elements
, true ) === false,
1067 '$elt should no longer be in open elements stack'
1072 * Find $a in the BalanceStack and insert $b after it.
1073 * @param BalanceElement $a
1074 * @param BalanceElement $b
1076 public function insertAfter( BalanceElement
$a, BalanceElement
$b ) {
1077 $idx = $this->indexOf( $a );
1078 Assert
::parameter( $idx !== false, '$a', 'must be in stack' );
1079 if ( $idx === count( $this->elements
) - 1 ) {
1080 array_push( $this->elements
, $b );
1081 $this->currentNode
= $b;
1083 array_splice( $this->elements
, $idx +
1, 0, [ $b ] );
1087 // Fostering and adoption.
1090 * Foster parent the given $elt in the stack of open elements.
1091 * @param BalanceElement|string $elt
1092 * @return BalanceElement|string
1094 * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
1096 private function fosterParent( $elt ) {
1097 $lastTable = $this->indexOf( 'table' );
1098 $lastTemplate = $this->indexOf( 'template' );
1102 if ( $lastTemplate >= 0 && ( $lastTable < 0 ||
$lastTemplate > $lastTable ) ) {
1103 $parent = $this->elements
[$lastTemplate];
1104 } elseif ( $lastTable >= 0 ) {
1105 $parent = $this->elements
[$lastTable]->parent
;
1106 // Assume all tables have parents, since we're not running scripts!
1108 $parent !== null, "All tables should have parents"
1110 $before = $this->elements
[$lastTable];
1112 $parent = $this->elements
[0]; // the `html` element.
1115 if ( $this->config
['tidyCompat'] ) {
1116 if ( is_string( $elt ) ) {
1117 // We're fostering text: do we need a p-wrapper?
1118 if ( $parent->isA( BalanceSets
::$tidyPWrapSet ) ) {
1119 $this->insertHTMLElement( 'mw:p-wrap', [] );
1120 $this->insertText( $elt );
1124 // We're fostering an element; do we need to merge p-wrappers?
1125 if ( $elt->isHtmlNamed( 'mw:p-wrap' ) ) {
1127 array_search( $before, $parent->children
, true ) :
1128 count( $parent->children
);
1129 $after = $idx > 0 ?
$parent->children
[$idx - 1] : '';
1131 $after instanceof BalanceElement
&&
1132 $after->isHtmlNamed( 'mw:p-wrap' )
1134 return $after; // Re-use existing p-wrapper.
1141 $parent->insertBefore( $before, $elt );
1143 $parent->appendChild( $elt );
1149 * Run the "adoption agency algoritm" (AAA) for the given subject
1151 * @param string $tag The subject tag name.
1152 * @param BalanceActiveFormattingElements $afe The current
1153 * active formatting elements list.
1154 * @return true if the adoption agency algorithm "did something", false
1155 * if more processing is required by the caller.
1156 * @see https://html.spec.whatwg.org/multipage/syntax.html#adoption-agency-algorithm
1158 public function adoptionAgency( $tag, $afe ) {
1159 // If the current node is an HTML element whose tag name is subject,
1160 // and the current node is not in the list of active formatting
1161 // elements, then pop the current node off the stack of open
1162 // elements and abort these steps.
1164 $this->currentNode
->isHtmlNamed( $tag ) &&
1165 !$afe->isInList( $this->currentNode
)
1168 return true; // no more handling required
1171 // Outer loop: If outer loop counter is greater than or
1172 // equal to eight, then abort these steps.
1173 for ( $outer = 0; $outer < 8; $outer++
) {
1174 // Let the formatting element be the last element in the list
1175 // of active formatting elements that: is between the end of
1176 // the list and the last scope marker in the list, if any, or
1177 // the start of the list otherwise, and has the same tag name
1179 $fmtElt = $afe->findElementByTag( $tag );
1181 // If there is no such node, then abort these steps and instead
1182 // act as described in the "any other end tag" entry below.
1184 return false; // false means handle by the default case
1187 // Otherwise, if there is such a node, but that node is not in
1188 // the stack of open elements, then this is a parse error;
1189 // remove the element from the list, and abort these steps.
1190 $index = $this->indexOf( $fmtElt );
1192 $afe->remove( $fmtElt );
1193 return true; // true means no more handling required
1196 // Otherwise, if there is such a node, and that node is also in
1197 // the stack of open elements, but the element is not in scope,
1198 // then this is a parse error; ignore the token, and abort
1200 if ( !$this->inScope( $fmtElt ) ) {
1204 // Let the furthest block be the topmost node in the stack of
1205 // open elements that is lower in the stack than the formatting
1206 // element, and is an element in the special category. There
1207 // might not be one.
1208 $furthestBlock = null;
1209 $furthestBlockIndex = -1;
1210 $stackLength = $this->length();
1211 for ( $i = $index +
1; $i < $stackLength; $i++
) {
1212 if ( $this->node( $i )->isA( BalanceSets
::$specialSet ) ) {
1213 $furthestBlock = $this->node( $i );
1214 $furthestBlockIndex = $i;
1219 // If there is no furthest block, then the UA must skip the
1220 // subsequent steps and instead just pop all the nodes from the
1221 // bottom of the stack of open elements, from the current node
1222 // up to and including the formatting element, and remove the
1223 // formatting element from the list of active formatting
1225 if ( !$furthestBlock ) {
1226 $this->popTag( $fmtElt );
1227 $afe->remove( $fmtElt );
1231 // Let the common ancestor be the element immediately above
1232 // the formatting element in the stack of open elements.
1233 $ancestor = $this->node( $index - 1 );
1235 // Let a bookmark note the position of the formatting
1236 // element in the list of active formatting elements
1237 // relative to the elements on either side of it in the
1239 $BOOKMARK = new BalanceElement( '[bookmark]', '[bookmark]', [] );
1240 $afe->insertAfter( $fmtElt, $BOOKMARK );
1242 // Let node and last node be the furthest block.
1243 $node = $furthestBlock;
1244 $lastNode = $furthestBlock;
1245 $nodeIndex = $furthestBlockIndex;
1249 for ( $inner = 1; true; $inner++
) {
1250 // Let node be the element immediately above node in
1251 // the stack of open elements, or if node is no longer
1252 // in the stack of open elements (e.g. because it got
1253 // removed by this algorithm), the element that was
1254 // immediately above node in the stack of open elements
1255 // before node was removed.
1256 $node = $this->node( --$nodeIndex );
1258 // If node is the formatting element, then go
1259 // to the next step in the overall algorithm.
1260 if ( $node === $fmtElt ) break;
1262 // If the inner loop counter is greater than three and node
1263 // is in the list of active formatting elements, then remove
1264 // node from the list of active formatting elements.
1265 $isAFE = $afe->isInList( $node );
1266 if ( $inner > 3 && $isAFE ) {
1267 $afe->remove( $node );
1271 // If node is not in the list of active formatting
1272 // elements, then remove node from the stack of open
1273 // elements and then go back to the step labeled inner
1276 // Don't flatten here, since we're about to relocate
1277 // parts of this $node.
1278 $this->removeElement( $node, false );
1282 // Create an element for the token for which the
1283 // element node was created with common ancestor as
1284 // the intended parent, replace the entry for node
1285 // in the list of active formatting elements with an
1286 // entry for the new element, replace the entry for
1287 // node in the stack of open elements with an entry for
1288 // the new element, and let node be the new element.
1289 $newElt = new BalanceElement(
1290 $node->namespaceURI
, $node->localName
, $node->attribs
);
1291 $afe->replace( $node, $newElt );
1292 $this->replaceAt( $nodeIndex, $newElt );
1295 // If last node is the furthest block, then move the
1296 // aforementioned bookmark to be immediately after the
1297 // new node in the list of active formatting elements.
1298 if ( $lastNode === $furthestBlock ) {
1299 $afe->remove( $BOOKMARK );
1300 $afe->insertAfter( $newElt, $BOOKMARK );
1303 // Insert last node into node, first removing it from
1304 // its previous parent node if any.
1305 $node->appendChild( $lastNode );
1307 // Let last node be node.
1311 // If the common ancestor node is a table, tbody, tfoot,
1312 // thead, or tr element, then, foster parent whatever last
1313 // node ended up being in the previous step, first removing
1314 // it from its previous parent node if any.
1316 $this->fosterParentMode
&&
1317 $ancestor->isA( BalanceSets
::$tableSectionRowSet )
1319 $this->fosterParent( $lastNode );
1321 // Otherwise, append whatever last node ended up being in
1322 // the previous step to the common ancestor node, first
1323 // removing it from its previous parent node if any.
1324 $ancestor->appendChild( $lastNode );
1327 // Create an element for the token for which the
1328 // formatting element was created, with furthest block
1329 // as the intended parent.
1330 $newElt2 = new BalanceElement(
1331 $fmtElt->namespaceURI
, $fmtElt->localName
, $fmtElt->attribs
);
1333 // Take all of the child nodes of the furthest block and
1334 // append them to the element created in the last step.
1335 $newElt2->adoptChildren( $furthestBlock );
1337 // Append that new element to the furthest block.
1338 $furthestBlock->appendChild( $newElt2 );
1340 // Remove the formatting element from the list of active
1341 // formatting elements, and insert the new element into the
1342 // list of active formatting elements at the position of
1343 // the aforementioned bookmark.
1344 $afe->remove( $fmtElt );
1345 $afe->replace( $BOOKMARK, $newElt2 );
1347 // Remove the formatting element from the stack of open
1348 // elements, and insert the new element into the stack of
1349 // open elements immediately below the position of the
1350 // furthest block in that stack.
1351 $this->removeElement( $fmtElt );
1352 $this->insertAfter( $furthestBlock, $newElt2 );
1359 * Return the contents of the open elements stack as a string for
1363 public function __toString() {
1365 foreach ( $this->elements
as $elt ) {
1366 array_push( $r, $elt->localName
);
1368 return implode( $r, ' ' );
1373 * A pseudo-element used as a marker in the list of active formatting elements
1378 class BalanceMarker
{
1384 * The list of active formatting elements, which is used to handle
1385 * mis-nested formatting element tags in the HTML5 tree builder
1390 * @see https://html.spec.whatwg.org/multipage/syntax.html#list-of-active-formatting-elements
1392 class BalanceActiveFormattingElements
{
1393 /** The last (most recent) element in the list */
1396 /** The first (least recent) element in the list */
1400 * An array of arrays representing the population of elements in each bucket
1401 * according to the Noah's Ark clause. The outer array is stack-like, with each
1402 * integer-indexed element representing a segment of the list, bounded by
1403 * markers. The first element represents the segment of the list before the
1406 * The inner arrays are indexed by "Noah key", which is a string which uniquely
1407 * identifies each bucket according to the rules in the spec. The value in
1408 * the inner array is the first (least recently inserted) element in the bucket,
1409 * and subsequent members of the bucket can be found by iterating through the
1410 * singly-linked list via $node->nextNoah.
1412 * This is optimised for the most common case of inserting into a bucket
1413 * with zero members, and deleting a bucket containing one member. In the
1414 * worst case, iteration through the list is still O(1) in the document
1415 * size, since each bucket can have at most 3 members.
1417 private $noahTableStack = [ [] ];
1419 public function __destruct() {
1421 for ( $node = $this->head
; $node; $node = $next ) {
1422 $next = $node->nextAFE
;
1423 $node->prevAFE
= $node->nextAFE
= $node->nextNoah
= null;
1425 $this->head
= $this->tail
= $this->noahTableStack
= null;
1428 public function insertMarker() {
1429 $elt = new BalanceMarker
;
1430 if ( $this->tail
) {
1431 $this->tail
->nextAFE
= $elt;
1432 $elt->prevAFE
= $this->tail
;
1437 $this->noahTableStack
[] = [];
1441 * Follow the steps required when the spec requires us to "push onto the
1442 * list of active formatting elements".
1443 * @param BalanceElement $elt
1445 public function push( BalanceElement
$elt ) {
1446 // Must not be in the list already
1447 if ( $elt->prevAFE
!== null ||
$this->head
=== $elt ) {
1448 throw new ParameterAssertionException( '$elt',
1449 'Cannot insert a node into the AFE list twice' );
1452 // "Noah's Ark clause" -- if there are already three copies of
1453 // this element before we encounter a marker, then drop the last
1455 $noahKey = $elt->getNoahKey();
1456 $table =& $this->noahTableStack
[ count( $this->noahTableStack
) - 1 ];
1457 if ( !isset( $table[$noahKey] ) ) {
1458 $table[$noahKey] = $elt;
1461 $head = $tail = $table[$noahKey];
1462 while ( $tail->nextNoah
) {
1463 $tail = $tail->nextNoah
;
1466 if ( $count >= 3 ) {
1467 $this->remove( $head );
1469 $tail->nextNoah
= $elt;
1471 // Add to the main AFE list
1472 if ( $this->tail
) {
1473 $this->tail
->nextAFE
= $elt;
1474 $elt->prevAFE
= $this->tail
;
1482 * Follow the steps required when the spec asks us to "clear the list of
1483 * active formatting elements up to the last marker".
1485 public function clearToMarker() {
1486 // Iterate back through the list starting from the tail
1487 $tail = $this->tail
;
1488 while ( $tail && !( $tail instanceof BalanceMarker
) ) {
1489 // Unlink the element
1490 $prev = $tail->prevAFE
;
1491 $tail->prevAFE
= null;
1493 $prev->nextAFE
= null;
1495 $tail->nextNoah
= null;
1498 // If we finished on a marker, unlink it and pop it off the Noah table stack
1500 $prev = $tail->prevAFE
;
1502 $prev->nextAFE
= null;
1505 array_pop( $this->noahTableStack
);
1507 // No marker: wipe the top-level Noah table (which is the only one)
1508 $this->noahTableStack
[0] = [];
1510 // If we removed all the elements, clear the head pointer
1514 $this->tail
= $tail;
1518 * Find and return the last element with the specified tag between the
1519 * end of the list and the last marker on the list.
1520 * Used when parsing <a> "in body mode".
1521 * @param string $tag
1524 public function findElementByTag( $tag ) {
1526 while ( $elt && !( $elt instanceof BalanceMarker
) ) {
1527 if ( $elt->localName
=== $tag ) {
1530 $elt = $elt->prevAFE
;
1536 * Determine whether an element is in the list of formatting elements.
1537 * @param BalanceElement $elt
1540 public function isInList( BalanceElement
$elt ) {
1541 return $this->head
=== $elt ||
$elt->prevAFE
;
1545 * Find the element $elt in the list and remove it.
1546 * Used when parsing <a> in body mode.
1548 * @param BalanceElement $elt
1550 public function remove( BalanceElement
$elt ) {
1551 if ( $this->head
!== $elt && !$elt->prevAFE
) {
1552 throw new ParameterAssertionException( '$elt',
1553 "Attempted to remove an element which is not in the AFE list" );
1555 // Update head and tail pointers
1556 if ( $this->head
=== $elt ) {
1557 $this->head
= $elt->nextAFE
;
1559 if ( $this->tail
=== $elt ) {
1560 $this->tail
= $elt->prevAFE
;
1562 // Update previous element
1563 if ( $elt->prevAFE
) {
1564 $elt->prevAFE
->nextAFE
= $elt->nextAFE
;
1566 // Update next element
1567 if ( $elt->nextAFE
) {
1568 $elt->nextAFE
->prevAFE
= $elt->prevAFE
;
1570 // Clear pointers so that isInList() etc. will work
1571 $elt->prevAFE
= $elt->nextAFE
= null;
1573 $this->removeFromNoahList( $elt );
1576 private function addToNoahList( BalanceElement
$elt ) {
1577 $noahKey = $elt->getNoahKey();
1578 $table =& $this->noahTableStack
[ count( $this->noahTableStack
) - 1 ];
1579 if ( !isset( $table[$noahKey] ) ) {
1580 $table[$noahKey] = $elt;
1582 $tail = $table[$noahKey];
1583 while ( $tail->nextNoah
) {
1584 $tail = $tail->nextNoah
;
1586 $tail->nextNoah
= $elt;
1590 private function removeFromNoahList( BalanceElement
$elt ) {
1591 $table =& $this->noahTableStack
[ count( $this->noahTableStack
) - 1 ];
1592 $key = $elt->getNoahKey();
1593 $noahElt = $table[$key];
1594 if ( $noahElt === $elt ) {
1595 if ( $noahElt->nextNoah
) {
1596 $table[$key] = $noahElt->nextNoah
;
1597 $noahElt->nextNoah
= null;
1599 unset( $table[$key] );
1603 $prevNoahElt = $noahElt;
1604 $noahElt = $prevNoahElt->nextNoah
;
1605 if ( $noahElt === $elt ) {
1607 $prevNoahElt->nextNoah
= $elt->nextNoah
;
1608 $elt->nextNoah
= null;
1611 } while ( $noahElt );
1616 * Find element $a in the list and replace it with element $b
1618 * @param BalanceElement $a
1619 * @param BalanceElement $b
1621 public function replace( BalanceElement
$a, BalanceElement
$b ) {
1622 if ( $this->head
!== $a && !$a->prevAFE
) {
1623 throw new ParameterAssertionException( '$a',
1624 "Attempted to replace an element which is not in the AFE list" );
1626 // Update head and tail pointers
1627 if ( $this->head
=== $a ) {
1630 if ( $this->tail
=== $a ) {
1633 // Update previous element
1634 if ( $a->prevAFE
) {
1635 $a->prevAFE
->nextAFE
= $b;
1637 // Update next element
1638 if ( $a->nextAFE
) {
1639 $a->nextAFE
->prevAFE
= $b;
1641 $b->prevAFE
= $a->prevAFE
;
1642 $b->nextAFE
= $a->nextAFE
;
1643 $a->nextAFE
= $a->prevAFE
= null;
1645 $this->removeFromNoahList( $a );
1646 $this->addToNoahList( $b );
1650 * Find $a in the list and insert $b after it.
1652 * @param BalanceElement $a
1653 * @param BalanceElement $b
1655 public function insertAfter( BalanceElement
$a, BalanceElement
$b ) {
1656 if ( $this->head
!== $a && !$a->prevAFE
) {
1657 throw new ParameterAssertionException( '$a',
1658 "Attempted to insert after an element which is not in the AFE list" );
1660 if ( $this->tail
=== $a ) {
1663 if ( $a->nextAFE
) {
1664 $a->nextAFE
->prevAFE
= $b;
1666 $b->nextAFE
= $a->nextAFE
;
1669 $this->addToNoahList( $b );
1673 * Reconstruct the active formatting elements.
1674 * @param BalanceStack $stack The open elements stack
1675 * @see https://html.spec.whatwg.org/multipage/syntax.html#reconstruct-the-active-formatting-elements
1677 public function reconstruct( $stack ) {
1678 $entry = $this->tail
;
1679 // If there are no entries in the list of active formatting elements,
1680 // then there is nothing to reconstruct
1684 // If the last is a marker, do nothing.
1685 if ( $entry instanceof BalanceMarker
) {
1688 // Or if it is an open element, do nothing.
1689 if ( $stack->indexOf( $entry ) >= 0 ) {
1693 // Loop backward through the list until we find a marker or an
1696 while ( $entry->prevAFE
) {
1697 $entry = $entry->prevAFE
;
1698 if ( $entry instanceof BalanceMarker ||
$stack->indexOf( $entry ) >= 0 ) {
1704 // Now loop forward, starting from the element after the current one (or
1705 // the first element if we didn't find a marker or open element),
1706 // recreating formatting elements and pushing them back onto the list
1707 // of open elements.
1709 $entry = $entry->nextAFE
;
1712 $newElement = $stack->insertHTMLElement(
1715 $this->replace( $entry, $newElement );
1716 $entry = $newElement->nextAFE
;
1721 * Get a string representation of the AFE list, for debugging
1723 public function __toString() {
1726 for ( $node = $this->head
; $node; $prev = $node, $node = $node->nextAFE
) {
1727 if ( $node instanceof BalanceMarker
) {
1731 $s .= $node->localName
. '#' . substr( md5( spl_object_hash( $node ) ), 0, 8 );
1732 if ( $node->nextNoah
) {
1733 $s .= " (noah sibling: {$node->nextNoah->localName}#" .
1734 substr( md5( spl_object_hash( $node->nextNoah
) ), 0, 8 ) .
1737 if ( $node->nextAFE
&& $node->nextAFE
->prevAFE
!== $node ) {
1738 $s .= " (reverse link is wrong!)";
1742 if ( $prev !== $this->tail
) {
1743 $s .= "(tail pointer is wrong!)\n";
1750 * An implementation of the tree building portion of the HTML5 parsing
1753 * This is used to balance and tidy output so that the result can
1754 * always be cleanly serialized/deserialized by an HTML5 parser. It
1755 * does *not* guarantee "conforming" output -- the HTML5 spec contains
1756 * a number of constraints which are not enforced by the HTML5 parsing
1757 * process. But the result will be free of gross errors: misnested or
1758 * unclosed tags, for example, and will be unchanged by spec-complient
1759 * parsing followed by serialization.
1761 * The tree building stage is structured as a state machine.
1762 * When comparing the implementation to
1763 * https://www.w3.org/TR/html5/syntax.html#tree-construction
1764 * note that each state is implemented as a function with a
1765 * name ending in `Mode` (because the HTML spec refers to them
1766 * as insertion modes). The current insertion mode is held by
1767 * the $parseMode property.
1769 * The following simplifications have been made:
1770 * - We handle body content only (ie, we start `in body`.)
1771 * - The document is never in "quirks mode".
1772 * - All occurrences of < and > have been entity escaped, so we
1773 * can parse tags by simply splitting on those two characters.
1774 * (This also simplifies the handling of < inside <textarea>.)
1775 * The character < must not appear inside comments.
1776 * Similarly, all attributes have been "cleaned" and are double-quoted
1778 * - All null characters are assumed to have been removed.
1779 * - The following elements are disallowed: <html>, <head>, <body>, <frameset>,
1780 * <frame>, <plaintext>, <xmp>, <iframe>,
1781 * <noembed>, <noscript>, <script>, <title>. As a result,
1782 * further simplifications can be made:
1783 * - `frameset-ok` is not tracked.
1784 * - `head element pointer` is not tracked (but presumed non-null)
1785 * - Tokenizer has only a single mode. (<textarea> wants RCDATA and
1786 * <style>/<noframes> want RAWTEXT modes which we only loosely emulate.)
1788 * We generally mark places where we omit cases from the spec due to
1789 * disallowed elements with a comment: `// OMITTED: <element-name>`.
1791 * The HTML spec keeps a flag during the parsing process to track
1792 * whether or not a "parse error" has been encountered. We don't
1793 * bother to track that flag, we just implement the error-handling
1794 * process as specified.
1798 * @see https://html.spec.whatwg.org/multipage/syntax.html#tree-construction
1802 /** @var \Iterator */
1803 private $bitsIterator;
1804 private $allowedHtmlElements;
1805 /** @var BalanceActiveFormattingElements */
1807 /** @var BalanceStack */
1810 private $allowComments;
1813 private $textIntegrationMode;
1814 private $pendingTableText;
1815 private $originalInsertionMode;
1816 private $fragmentContext;
1817 private $formElementPointer;
1818 private $ignoreLinefeed;
1822 /** @var callable|null */
1823 private $processingCallback;
1825 private $processingArgs;
1828 * Valid HTML5 comments.
1829 * Regex borrowed from Tim Starling's "remex-html" project.
1831 const VALID_COMMENT_REGEX
= "~ !--
1832 ( # 1. Comment match detector
1833 > | -> | # Invalid short close
1834 ( # 2. Comment contents
1844 ( # 3. Comment close
1845 --> | # Normal close
1846 --!> | # Comment end bang
1847 ( # 4. Indicate matches requiring EOF
1848 --! | # EOF in comment end bang state
1849 -- | # EOF in comment end state
1850 - | # EOF in comment end dash state
1851 (?#nothing) # EOF in comment state
1855 ([^<]*) \z # 5. Non-tag text after the comment
1859 * Create a new Balancer.
1860 * @param array $config Balancer configuration. Includes:
1861 * 'strict' : boolean, defaults to false.
1862 * When true, enforces syntactic constraints on input:
1863 * all non-tag '<' must be escaped, all attributes must be
1864 * separated by a single space and double-quoted. This is
1865 * consistent with the output of the Sanitizer.
1866 * 'allowedHtmlElements' : array, defaults to null.
1867 * When present, the keys of this associative array give
1868 * the acceptable HTML tag names. When not present, no
1869 * tag sanitization is done.
1870 * 'tidyCompat' : boolean, defaults to false.
1871 * When true, the serialization algorithm is tweaked to
1872 * provide historical compatibility with the old "tidy"
1873 * program: <p>-wrapping is done to the children of
1874 * <body> and <blockquote> elements, and empty elements
1875 * are removed. The <pre>/<listing>/<textarea> serialization
1876 * is also tweaked to allow lossless round trips.
1877 * (See: https://github.com/whatwg/html/issues/944)
1878 * 'allowComments': boolean, defaults to true.
1879 * When true, allows HTML comments in the input.
1880 * The Sanitizer generally strips all comments, so if you
1881 * are running on sanitized output you can set this to
1882 * false to get a bit more performance.
1884 public function __construct( array $config = [] ) {
1885 $this->config
= $config = $config +
[
1887 'allowedHtmlElements' => null,
1888 'tidyCompat' => false,
1889 'allowComments' => true,
1891 $this->allowedHtmlElements
= $config['allowedHtmlElements'];
1892 $this->strict
= $config['strict'];
1893 $this->allowComments
= $config['allowComments'];
1894 if ( $this->allowedHtmlElements
!== null ) {
1896 $bad = array_uintersect_assoc(
1897 $this->allowedHtmlElements
,
1898 BalanceSets
::$unsupportedSet[BalanceSets
::HTML_NAMESPACE
],
1899 function ( $a, $b ) {
1900 // Ignore the values (just intersect the keys) by saying
1901 // all values are equal to each other.
1905 if ( count( $bad ) > 0 ) {
1906 $badstr = implode( array_keys( $bad ), ',' );
1907 throw new ParameterAssertionException(
1909 'Balance attempted with sanitization including ' .
1910 "unsupported elements: {$badstr}"
1917 * Return a balanced HTML string for the HTML fragment given by $text,
1918 * subject to the caveats listed in the class description. The result
1919 * will typically be idempotent -- that is, rebalancing the output
1920 * would result in no change.
1922 * @param string $text The markup to be balanced
1923 * @param callable $processingCallback Callback to do any variable or
1924 * parameter replacements in HTML attributes values
1925 * @param array|bool $processingArgs Arguments for the processing callback
1926 * @return string The balanced markup
1928 public function balance( $text, $processingCallback = null, $processingArgs = [] ) {
1929 $this->parseMode
= 'inBodyMode';
1930 $this->bitsIterator
= new ExplodeIterator( '<', $text );
1931 $this->afe
= new BalanceActiveFormattingElements();
1932 $this->stack
= new BalanceStack( $this->config
);
1933 $this->processingCallback
= $processingCallback;
1934 $this->processingArgs
= $processingArgs;
1936 $this->textIntegrationMode
=
1937 $this->ignoreLinefeed
=
1939 $this->inRAWTEXT
= false;
1941 // The stack is constructed with an <html> element already on it.
1942 // Set this up as a fragment parsed with <body> as the context.
1943 $this->fragmentContext
=
1944 new BalanceElement( BalanceSets
::HTML_NAMESPACE
, 'body', [] );
1945 $this->resetInsertionMode();
1946 $this->formElementPointer
= null;
1947 for ( $e = $this->fragmentContext
; $e != null; $e = $e->parent
) {
1948 if ( $e->isHtmlNamed( 'form' ) ) {
1949 $this->formElementPointer
= $e;
1954 // First element is text not tag
1955 $x = $this->bitsIterator
->current();
1956 $this->bitsIterator
->next();
1957 $this->insertToken( 'text', str_replace( '>', '>', $x ) );
1958 // Now process each tag.
1959 while ( $this->bitsIterator
->valid() ) {
1962 $this->insertToken( 'eof', null );
1963 $result = $this->stack
->getOutput();
1964 // Free memory before returning.
1965 $this->bitsIterator
= null;
1967 $this->stack
= null;
1968 $this->fragmentContext
= null;
1969 $this->formElementPointer
= null;
1974 * Pass a token to the tree builder. The $token will be one of the
1975 * strings "tag", "endtag", or "text".
1977 private function insertToken( $token, $value, $attribs = null, $selfClose = false ) {
1978 // validate tags against $unsupportedSet
1979 if ( $token === 'tag' ||
$token === 'endtag' ) {
1980 if ( isset( BalanceSets
::$unsupportedSet[BalanceSets
::HTML_NAMESPACE
][$value] ) ) {
1981 // As described in "simplifications" above, these tags are
1982 // not supported in the balancer.
1985 "Unsupported $token <$value> found."
1989 } elseif ( $token === 'text' && $value === '' ) {
1990 // Don't actually inject the empty string as a text token.
1993 // Support pre/listing/textarea by suppressing initial linefeed
1994 if ( $this->ignoreLinefeed
) {
1995 $this->ignoreLinefeed
= false;
1996 if ( $token === 'text' ) {
1997 if ( $value[0] === "\n" ) {
1998 if ( $value === "\n" ) {
1999 // Nothing would be left, don't inject the empty string.
2002 $value = substr( $value, 1 );
2006 // Some hoops we have to jump through
2007 $adjusted = $this->stack
->adjustedCurrentNode( $this->fragmentContext
);
2009 // The spec calls this the "tree construction dispatcher".
2012 $this->stack
->length() === 0 ||
2013 $adjusted->isHtml() ||
2017 } elseif ( $adjusted->isMathmlTextIntegrationPoint() ) {
2018 if ( $token === 'text' ) {
2022 $value !== 'mglyph' && $value !== 'malignmark'
2027 $adjusted->namespaceURI
=== BalanceSets
::MATHML_NAMESPACE
&&
2028 $adjusted->localName
=== 'annotation-xml' &&
2029 $token === 'tag' && $value === 'svg'
2033 $adjusted->isHtmlIntegrationPoint() &&
2034 ( $token === 'tag' ||
$token === 'text' )
2039 return $this->insertForeignToken( $token, $value, $attribs, $selfClose );
2041 $func = $this->parseMode
;
2042 return $this->$func( $token, $value, $attribs, $selfClose );
2046 private function insertForeignToken( $token, $value, $attribs = null, $selfClose = false ) {
2047 if ( $token === 'text' ) {
2048 $this->stack
->insertText( $value );
2050 } elseif ( $token === 'comment' ) {
2051 $this->stack
->insertComment( $value );
2053 } elseif ( $token === 'tag' ) {
2056 if ( isset( $attribs['color'] )
2057 ||
isset( $attribs['face'] )
2058 ||
isset( $attribs['size'] )
2062 // otherwise, fall through
2107 if ( $this->fragmentContext
) {
2111 $this->stack
->pop();
2112 $node = $this->stack
->currentNode
;
2114 $node->isMathmlTextIntegrationPoint() ||
2115 $node->isHtmlIntegrationPoint() ||
2121 return $this->insertToken( $token, $value, $attribs, $selfClose );
2123 // "Any other start tag"
2124 $adjusted = ( $this->fragmentContext
&& $this->stack
->length() === 1 ) ?
2125 $this->fragmentContext
: $this->stack
->currentNode
;
2126 $this->stack
->insertForeignElement(
2127 $adjusted->namespaceURI
, $value, $attribs
2130 $this->stack
->pop();
2133 } elseif ( $token === 'endtag' ) {
2135 foreach ( $this->stack
as $i => $node ) {
2136 if ( $node->isHtml() && !$first ) {
2137 // process the end tag as HTML
2138 $func = $this->parseMode
;
2139 return $this->$func( $token, $value, $attribs, $selfClose );
2140 } elseif ( $i === 0 ) {
2142 } elseif ( $node->localName
=== $value ) {
2143 $this->stack
->popTag( $node );
2152 * Grab the next "token" from $bitsIterator. This is either a open/close
2153 * tag or text or a comment, depending on whether the Sanitizer approves.
2155 private function advance() {
2156 $x = $this->bitsIterator
->current();
2157 $this->bitsIterator
->next();
2159 // Handle comments. These won't be generated by mediawiki (they
2160 // are stripped in the Sanitizer) but may be generated by extensions.
2162 $this->allowComments
&&
2163 !( $this->inRCDATA ||
$this->inRAWTEXT
) &&
2164 preg_match( self
::VALID_COMMENT_REGEX
, $x, $regs, PREG_OFFSET_CAPTURE
) &&
2165 // verify EOF condition where necessary
2166 ( $regs[4][1] < 0 ||
!$this->bitsIterator
->valid() )
2168 $contents = $regs[2][0];
2169 $rest = $regs[5][0];
2170 $this->insertToken( 'comment', $contents );
2171 $this->insertToken( 'text', str_replace( '>', '>', $rest ) );
2174 // $slash: Does the current element start with a '/'?
2175 // $t: Current element name
2176 // $attribStr: String between element name and >
2177 // $brace: Ending '>' or '/>'
2178 // $rest: Everything until the next element from the $bitsIterator
2179 if ( preg_match( Sanitizer
::ELEMENT_BITS_REGEX
, $x, $regs ) ) {
2180 list( /* $qbar */, $slash, $t, $attribStr, $brace, $rest ) = $regs;
2181 $t = strtolower( $t );
2182 if ( $this->strict
) {
2183 // Verify that attributes are all properly double-quoted
2186 '/^( [:_A-Z0-9][-.:_A-Z0-9]*="[^"]*")*[ ]*$/i', $attribStr
2188 "Bad attribute string found"
2193 !$this->strict
, "< found which does not start a valid tag"
2195 $slash = $t = $attribStr = $brace = $rest = null;
2198 if ( $this->inRCDATA
) {
2199 if ( $slash && $t === $this->inRCDATA
) {
2200 $this->inRCDATA
= false;
2202 // No tags allowed; this emulates the "rcdata" tokenizer mode.
2206 if ( $this->inRAWTEXT
) {
2207 if ( $slash && $t === $this->inRAWTEXT
) {
2208 $this->inRAWTEXT
= false;
2210 // No tags allowed, no entity-escaping done.
2214 $sanitize = $this->allowedHtmlElements
!== null;
2216 $goodTag = $t && isset( $this->allowedHtmlElements
[$t] );
2219 if ( is_callable( $this->processingCallback
) ) {
2220 call_user_func_array( $this->processingCallback
, [ &$attribStr, $this->processingArgs
] );
2223 $goodTag = Sanitizer
::validateTag( $attribStr, $t );
2228 $attribs = Sanitizer
::decodeTagAttributes( $attribStr );
2229 $attribs = Sanitizer
::validateTagAttributes( $attribs, $t );
2231 $attribs = Sanitizer
::decodeTagAttributes( $attribStr );
2233 $goodTag = $this->insertToken(
2234 $slash ?
'endtag' : 'tag', $t, $attribs, $brace === '/>'
2238 $rest = str_replace( '>', '>', $rest );
2239 $this->insertToken( 'text', str_replace( '>', '>', $rest ) );
2240 } elseif ( $this->inRAWTEXT
) {
2241 $this->insertToken( 'text', "<$x" );
2243 // bad tag; serialize entire thing as text.
2244 $this->insertToken( 'text', '<' . str_replace( '>', '>', $x ) );
2248 private function switchMode( $mode ) {
2250 substr( $mode, -4 ) === 'Mode', '$mode', 'should end in Mode'
2252 $oldMode = $this->parseMode
;
2253 $this->parseMode
= $mode;
2257 private function switchModeAndReprocess( $mode, $token, $value, $attribs, $selfClose ) {
2258 $this->switchMode( $mode );
2259 return $this->insertToken( $token, $value, $attribs, $selfClose );
2262 private function resetInsertionMode() {
2264 foreach ( $this->stack
as $i => $node ) {
2267 if ( $this->fragmentContext
) {
2268 $node = $this->fragmentContext
;
2271 if ( $node->isHtml() ) {
2272 switch ( $node->localName
) {
2274 $stackLength = $this->stack
->length();
2275 for ( $j = $i +
1; $j < $stackLength - 1; $j++
) {
2276 $ancestor = $this->stack
->node( $stackLength - $j - 1 );
2277 if ( $ancestor->isHtmlNamed( 'template' ) ) {
2280 if ( $ancestor->isHtmlNamed( 'table' ) ) {
2281 $this->switchMode( 'inSelectInTableMode' );
2285 $this->switchMode( 'inSelectMode' );
2288 $this->switchMode( 'inRowMode' );
2293 $this->switchMode( 'inTableBodyMode' );
2296 $this->switchMode( 'inCaptionMode' );
2299 $this->switchMode( 'inColumnGroupMode' );
2302 $this->switchMode( 'inTableMode' );
2306 array_slice( $this->templateInsertionModes
, -1 )[0]
2310 $this->switchMode( 'inBodyMode' );
2312 // OMITTED: <frameset>
2318 if ( $node->isA( BalanceSets
::$tableCellSet ) ) {
2319 $this->switchMode( 'inCellMode' );
2326 $this->switchMode( 'inBodyMode' );
2332 private function stopParsing() {
2333 // Most of the spec methods are inapplicable, other than step 2:
2334 // "pop all the nodes off the stack of open elements".
2335 // We're going to keep the top-most <html> element on the stack, though.
2337 // Clear the AFE list first, otherwise the element objects will stay live
2338 // during serialization, potentially using O(N^2) memory. Note that
2339 // popping the stack will never result in reconstructing the active
2340 // formatting elements.
2342 $this->stack
->popTo( 1 );
2345 private function parseRawText( $value, $attribs = null ) {
2346 $this->stack
->insertHTMLElement( $value, $attribs );
2347 $this->inRAWTEXT
= $value;
2348 $this->originalInsertionMode
= $this->switchMode( 'inTextMode' );
2352 private function inTextMode( $token, $value, $attribs = null, $selfClose = false ) {
2353 if ( $token === 'text' ) {
2354 $this->stack
->insertText( $value );
2356 } elseif ( $token === 'eof' ) {
2357 $this->stack
->pop();
2358 return $this->switchModeAndReprocess(
2359 $this->originalInsertionMode
, $token, $value, $attribs, $selfClose
2361 } elseif ( $token === 'endtag' ) {
2362 $this->stack
->pop();
2363 $this->switchMode( $this->originalInsertionMode
);
2369 private function inHeadMode( $token, $value, $attribs = null, $selfClose = false ) {
2370 if ( $token === 'text' ) {
2371 if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
2372 $this->stack
->insertText( $matches[0] );
2373 $value = substr( $value, strlen( $matches[0] ) );
2375 if ( strlen( $value ) === 0 ) {
2376 return true; // All text handled.
2378 // Fall through to handle non-whitespace below.
2379 } elseif ( $token === 'tag' ) {
2382 // OMITTED: in a full HTML parser, this might change the encoding.
2389 $this->stack
->insertHTMLElement( $value, $attribs );
2390 $this->stack
->pop();
2393 // OMITTED: <noscript>
2396 return $this->parseRawText( $value, $attribs );
2397 // OMITTED: <script>
2399 $this->stack
->insertHTMLElement( $value, $attribs );
2400 $this->afe
->insertMarker();
2401 // OMITTED: frameset_ok
2402 $this->switchMode( 'inTemplateMode' );
2403 $this->templateInsertionModes
[] = $this->parseMode
;
2407 } elseif ( $token === 'endtag' ) {
2413 break; // handle at the bottom of the function
2415 if ( $this->stack
->indexOf( $value ) < 0 ) {
2416 return true; // Ignore the token.
2418 $this->stack
->generateImpliedEndTags( null, true /* thorough */ );
2419 $this->stack
->popTag( $value );
2420 $this->afe
->clearToMarker();
2421 array_pop( $this->templateInsertionModes
);
2422 $this->resetInsertionMode();
2425 // ignore any other end tag
2428 } elseif ( $token === 'comment' ) {
2429 $this->stack
->insertComment( $value );
2433 // If not handled above
2434 $this->inHeadMode( 'endtag', 'head' ); // synthetic </head>
2435 // Then redo this one
2436 return $this->insertToken( $token, $value, $attribs, $selfClose );
2439 private function inBodyMode( $token, $value, $attribs = null, $selfClose = false ) {
2440 if ( $token === 'text' ) {
2441 $this->afe
->reconstruct( $this->stack
);
2442 $this->stack
->insertText( $value );
2444 } elseif ( $token === 'eof' ) {
2445 if ( !empty( $this->templateInsertionModes
) ) {
2446 return $this->inTemplateMode( $token, $value, $attribs, $selfClose );
2448 $this->stopParsing();
2450 } elseif ( $token === 'tag' ) {
2459 // OMITTED: <script>
2463 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
2465 // OMITTED: <frameset>
2490 if ( $this->stack
->inButtonScope( 'p' ) ) {
2491 $this->inBodyMode( 'endtag', 'p' );
2493 $this->stack
->insertHTMLElement( $value, $attribs );
2497 if ( $this->stack
->inButtonScope( "p" ) ) {
2498 $this->inBodyMode( 'endtag', 'p' );
2500 if ( $this->stack
->currentNode
->isHtmlNamed( 'menuitem' ) ) {
2501 $this->stack
->pop();
2503 $this->stack
->insertHTMLElement( $value, $attribs );
2512 if ( $this->stack
->inButtonScope( 'p' ) ) {
2513 $this->inBodyMode( 'endtag', 'p' );
2515 if ( $this->stack
->currentNode
->isA( BalanceSets
::$headingSet ) ) {
2516 $this->stack
->pop();
2518 $this->stack
->insertHTMLElement( $value, $attribs );
2523 if ( $this->stack
->inButtonScope( 'p' ) ) {
2524 $this->inBodyMode( 'endtag', 'p' );
2526 $this->stack
->insertHTMLElement( $value, $attribs );
2527 $this->ignoreLinefeed
= true;
2528 // OMITTED: frameset_ok
2533 $this->formElementPointer
&&
2534 $this->stack
->indexOf( 'template' ) < 0
2536 return true; // in a form, not in a template.
2538 if ( $this->stack
->inButtonScope( "p" ) ) {
2539 $this->inBodyMode( 'endtag', 'p' );
2541 $elt = $this->stack
->insertHTMLElement( $value, $attribs );
2542 if ( $this->stack
->indexOf( 'template' ) < 0 ) {
2543 $this->formElementPointer
= $elt;
2548 // OMITTED: frameset_ok
2549 foreach ( $this->stack
as $node ) {
2550 if ( $node->isHtmlNamed( 'li' ) ) {
2551 $this->inBodyMode( 'endtag', 'li' );
2555 $node->isA( BalanceSets
::$specialSet ) &&
2556 !$node->isA( BalanceSets
::$addressDivPSet )
2561 if ( $this->stack
->inButtonScope( 'p' ) ) {
2562 $this->inBodyMode( 'endtag', 'p' );
2564 $this->stack
->insertHTMLElement( $value, $attribs );
2569 // OMITTED: frameset_ok
2570 foreach ( $this->stack
as $node ) {
2571 if ( $node->isHtmlNamed( 'dd' ) ) {
2572 $this->inBodyMode( 'endtag', 'dd' );
2575 if ( $node->isHtmlNamed( 'dt' ) ) {
2576 $this->inBodyMode( 'endtag', 'dt' );
2580 $node->isA( BalanceSets
::$specialSet ) &&
2581 !$node->isA( BalanceSets
::$addressDivPSet )
2586 if ( $this->stack
->inButtonScope( 'p' ) ) {
2587 $this->inBodyMode( 'endtag', 'p' );
2589 $this->stack
->insertHTMLElement( $value, $attribs );
2592 // OMITTED: <plaintext>
2595 if ( $this->stack
->inScope( 'button' ) ) {
2596 $this->inBodyMode( 'endtag', 'button' );
2597 return $this->insertToken( $token, $value, $attribs, $selfClose );
2599 $this->afe
->reconstruct( $this->stack
);
2600 $this->stack
->insertHTMLElement( $value, $attribs );
2604 $activeElement = $this->afe
->findElementByTag( 'a' );
2605 if ( $activeElement ) {
2606 $this->inBodyMode( 'endtag', 'a' );
2607 if ( $this->afe
->isInList( $activeElement ) ) {
2608 $this->afe
->remove( $activeElement );
2609 // Don't flatten here, since when we fall
2610 // through below we might foster parent
2611 // the new <a> tag inside this one.
2612 $this->stack
->removeElement( $activeElement, false );
2628 $this->afe
->reconstruct( $this->stack
);
2629 $this->afe
->push( $this->stack
->insertHTMLElement( $value, $attribs ) );
2633 $this->afe
->reconstruct( $this->stack
);
2634 if ( $this->stack
->inScope( 'nobr' ) ) {
2635 $this->inBodyMode( 'endtag', 'nobr' );
2636 $this->afe
->reconstruct( $this->stack
);
2638 $this->afe
->push( $this->stack
->insertHTMLElement( $value, $attribs ) );
2644 $this->afe
->reconstruct( $this->stack
);
2645 $this->stack
->insertHTMLElement( $value, $attribs );
2646 $this->afe
->insertMarker();
2647 // OMITTED: frameset_ok
2651 // The document is never in "quirks mode"; see simplifications
2653 if ( $this->stack
->inButtonScope( 'p' ) ) {
2654 $this->inBodyMode( 'endtag', 'p' );
2656 $this->stack
->insertHTMLElement( $value, $attribs );
2657 // OMITTED: frameset_ok
2658 $this->switchMode( 'inTableMode' );
2667 $this->afe
->reconstruct( $this->stack
);
2668 $this->stack
->insertHTMLElement( $value, $attribs );
2669 $this->stack
->pop();
2670 // OMITTED: frameset_ok
2674 $this->afe
->reconstruct( $this->stack
);
2675 $this->stack
->insertHTMLElement( $value, $attribs );
2676 $this->stack
->pop();
2677 // OMITTED: frameset_ok
2678 // (hence we don't need to examine the tag's "type" attribute)
2684 $this->stack
->insertHTMLElement( $value, $attribs );
2685 $this->stack
->pop();
2689 if ( $this->stack
->inButtonScope( 'p' ) ) {
2690 $this->inBodyMode( 'endtag', 'p' );
2692 if ( $this->stack
->currentNode
->isHtmlNamed( 'menuitem' ) ) {
2693 $this->stack
->pop();
2695 $this->stack
->insertHTMLElement( $value, $attribs );
2696 $this->stack
->pop();
2701 return $this->inBodyMode( $token, 'img', $attribs, $selfClose );
2704 $this->stack
->insertHTMLElement( $value, $attribs );
2705 $this->ignoreLinefeed
= true;
2706 $this->inRCDATA
= $value; // emulate rcdata tokenizer mode
2707 // OMITTED: frameset_ok
2711 // OMITTED: <iframe>
2712 // OMITTED: <noembed>
2713 // OMITTED: <noscript>
2716 $this->afe
->reconstruct( $this->stack
);
2717 $this->stack
->insertHTMLElement( $value, $attribs );
2718 switch ( $this->parseMode
) {
2720 case 'inCaptionMode':
2721 case 'inTableBodyMode':
2724 $this->switchMode( 'inSelectInTableMode' );
2727 $this->switchMode( 'inSelectMode' );
2733 if ( $this->stack
->currentNode
->isHtmlNamed( 'option' ) ) {
2734 $this->inBodyMode( 'endtag', 'option' );
2736 $this->afe
->reconstruct( $this->stack
);
2737 $this->stack
->insertHTMLElement( $value, $attribs );
2741 if ( $this->stack
->currentNode
->isHtmlNamed( 'menuitem' ) ) {
2742 $this->stack
->pop();
2744 $this->afe
->reconstruct( $this->stack
);
2745 $this->stack
->insertHTMLElement( $value, $attribs );
2750 if ( $this->stack
->inScope( 'ruby' ) ) {
2751 $this->stack
->generateImpliedEndTags();
2753 $this->stack
->insertHTMLElement( $value, $attribs );
2758 if ( $this->stack
->inScope( 'ruby' ) ) {
2759 $this->stack
->generateImpliedEndTags( 'rtc' );
2761 $this->stack
->insertHTMLElement( $value, $attribs );
2765 $this->afe
->reconstruct( $this->stack
);
2766 // We skip the spec's "adjust MathML attributes" and
2767 // "adjust foreign attributes" steps, since the browser will
2768 // do this later when it parses the output and it doesn't affect
2770 $this->stack
->insertForeignElement(
2771 BalanceSets
::MATHML_NAMESPACE
, $value, $attribs
2774 // emit explicit </math> tag.
2775 $this->stack
->pop();
2780 $this->afe
->reconstruct( $this->stack
);
2781 // We skip the spec's "adjust SVG attributes" and
2782 // "adjust foreign attributes" steps, since the browser will
2783 // do this later when it parses the output and it doesn't affect
2785 $this->stack
->insertForeignElement(
2786 BalanceSets
::SVG_NAMESPACE
, $value, $attribs
2789 // emit explicit </svg> tag.
2790 $this->stack
->pop();
2805 // Ignore table tags if we're not inTableMode
2809 // Handle any other start tag here
2810 $this->afe
->reconstruct( $this->stack
);
2811 $this->stack
->insertHTMLElement( $value, $attribs );
2813 } elseif ( $token === 'endtag' ) {
2815 // </body>,</html> are unsupported.
2818 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
2846 // Ignore if there is not a matching open tag
2847 if ( !$this->stack
->inScope( $value ) ) {
2850 $this->stack
->generateImpliedEndTags();
2851 $this->stack
->popTag( $value );
2855 if ( $this->stack
->indexOf( 'template' ) < 0 ) {
2856 $openform = $this->formElementPointer
;
2857 $this->formElementPointer
= null;
2858 if ( !$openform ||
!$this->stack
->inScope( $openform ) ) {
2861 $this->stack
->generateImpliedEndTags();
2862 // Don't flatten yet if we're removing a <form> element
2863 // out-of-order. (eg. `<form><div></form>`)
2864 $flatten = ( $this->stack
->currentNode
=== $openform );
2865 $this->stack
->removeElement( $openform, $flatten );
2867 if ( !$this->stack
->inScope( 'form' ) ) {
2870 $this->stack
->generateImpliedEndTags();
2871 $this->stack
->popTag( 'form' );
2876 if ( !$this->stack
->inButtonScope( 'p' ) ) {
2877 $this->inBodyMode( 'tag', 'p', [] );
2878 return $this->insertToken( $token, $value, $attribs, $selfClose );
2880 $this->stack
->generateImpliedEndTags( $value );
2881 $this->stack
->popTag( $value );
2885 if ( !$this->stack
->inListItemScope( $value ) ) {
2886 return true; // ignore
2888 $this->stack
->generateImpliedEndTags( $value );
2889 $this->stack
->popTag( $value );
2894 if ( !$this->stack
->inScope( $value ) ) {
2895 return true; // ignore
2897 $this->stack
->generateImpliedEndTags( $value );
2898 $this->stack
->popTag( $value );
2907 if ( !$this->stack
->inScope( BalanceSets
::$headingSet ) ) {
2908 return true; // ignore
2910 $this->stack
->generateImpliedEndTags();
2911 $this->stack
->popTag( BalanceSets
::$headingSet );
2915 // Take a deep breath, then:
2932 if ( $this->stack
->adoptionAgency( $value, $this->afe
) ) {
2933 return true; // If we did something, we're done.
2935 break; // Go to the "any other end tag" case.
2940 if ( !$this->stack
->inScope( $value ) ) {
2941 return true; // ignore
2943 $this->stack
->generateImpliedEndTags();
2944 $this->stack
->popTag( $value );
2945 $this->afe
->clearToMarker();
2949 // Turn </br> into <br>
2950 return $this->inBodyMode( 'tag', $value, [] );
2953 // Any other end tag goes here
2954 foreach ( $this->stack
as $i => $node ) {
2955 if ( $node->isHtmlNamed( $value ) ) {
2956 $this->stack
->generateImpliedEndTags( $value );
2957 $this->stack
->popTo( $i ); // including $i
2959 } elseif ( $node->isA( BalanceSets
::$specialSet ) ) {
2960 return true; // ignore this close token.
2964 } elseif ( $token === 'comment' ) {
2965 $this->stack
->insertComment( $value );
2968 Assert
::invariant( false, "Bad token type: $token" );
2972 private function inTableMode( $token, $value, $attribs = null, $selfClose = false ) {
2973 if ( $token === 'text' ) {
2974 if ( $this->textIntegrationMode
) {
2975 return $this->inBodyMode( $token, $value, $attribs, $selfClose );
2976 } elseif ( $this->stack
->currentNode
->isA( BalanceSets
::$tableSectionRowSet ) ) {
2977 $this->pendingTableText
= '';
2978 $this->originalInsertionMode
= $this->parseMode
;
2979 return $this->switchModeAndReprocess( 'inTableTextMode',
2980 $token, $value, $attribs, $selfClose );
2982 // fall through to default case.
2983 } elseif ( $token === 'eof' ) {
2984 $this->stopParsing();
2986 } elseif ( $token === 'tag' ) {
2989 $this->afe
->insertMarker();
2990 $this->stack
->insertHTMLElement( $value, $attribs );
2991 $this->switchMode( 'inCaptionMode' );
2994 $this->stack
->clearToContext( BalanceSets
::$tableContextSet );
2995 $this->stack
->insertHTMLElement( $value, $attribs );
2996 $this->switchMode( 'inColumnGroupMode' );
2999 $this->inTableMode( 'tag', 'colgroup', [] );
3000 return $this->insertToken( $token, $value, $attribs, $selfClose );
3004 $this->stack
->clearToContext( BalanceSets
::$tableContextSet );
3005 $this->stack
->insertHTMLElement( $value, $attribs );
3006 $this->switchMode( 'inTableBodyMode' );
3011 $this->inTableMode( 'tag', 'tbody', [] );
3012 return $this->insertToken( $token, $value, $attribs, $selfClose );
3014 if ( !$this->stack
->inTableScope( $value ) ) {
3015 return true; // Ignore this tag.
3017 $this->inTableMode( 'endtag', $value );
3018 return $this->insertToken( $token, $value, $attribs, $selfClose );
3021 // OMITTED: <script>
3023 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
3026 if ( !isset( $attribs['type'] ) ||
strcasecmp( $attribs['type'], 'hidden' ) !== 0 ) {
3027 break; // Handle this as "everything else"
3029 $this->stack
->insertHTMLElement( $value, $attribs );
3030 $this->stack
->pop();
3035 $this->formElementPointer ||
3036 $this->stack
->indexOf( 'template' ) >= 0
3038 return true; // ignore this token
3040 $this->formElementPointer
=
3041 $this->stack
->insertHTMLElement( $value, $attribs );
3042 $this->stack
->popTag( $this->formElementPointer
);
3045 // Fall through for "anything else" clause.
3046 } elseif ( $token === 'endtag' ) {
3049 if ( !$this->stack
->inTableScope( $value ) ) {
3050 return true; // Ignore.
3052 $this->stack
->popTag( $value );
3053 $this->resetInsertionMode();
3066 return true; // Ignore the token.
3068 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
3070 // Fall through for "anything else" clause.
3071 } elseif ( $token === 'comment' ) {
3072 $this->stack
->insertComment( $value );
3075 // This is the "anything else" case:
3076 $this->stack
->fosterParentMode
= true;
3077 $this->inBodyMode( $token, $value, $attribs, $selfClose );
3078 $this->stack
->fosterParentMode
= false;
3082 private function inTableTextMode( $token, $value, $attribs = null, $selfClose = false ) {
3083 if ( $token === 'text' ) {
3084 $this->pendingTableText
.= $value;
3088 $text = $this->pendingTableText
;
3089 $this->pendingTableText
= '';
3090 if ( preg_match( '/[^\x09\x0A\x0C\x0D\x20]/', $text ) ) {
3091 // This should match the "anything else" case inTableMode
3092 $this->stack
->fosterParentMode
= true;
3093 $this->inBodyMode( 'text', $text );
3094 $this->stack
->fosterParentMode
= false;
3096 // Pending text is just whitespace.
3097 $this->stack
->insertText( $text );
3099 return $this->switchModeAndReprocess(
3100 $this->originalInsertionMode
, $token, $value, $attribs, $selfClose
3104 // helper for inCaptionMode
3105 private function endCaption() {
3106 if ( !$this->stack
->inTableScope( 'caption' ) ) {
3109 $this->stack
->generateImpliedEndTags();
3110 $this->stack
->popTag( 'caption' );
3111 $this->afe
->clearToMarker();
3112 $this->switchMode( 'inTableMode' );
3116 private function inCaptionMode( $token, $value, $attribs = null, $selfClose = false ) {
3117 if ( $token === 'tag' ) {
3128 if ( $this->endCaption() ) {
3129 $this->insertToken( $token, $value, $attribs, $selfClose );
3133 // Fall through to "anything else" case.
3134 } elseif ( $token === 'endtag' ) {
3137 $this->endCaption();
3140 if ( $this->endCaption() ) {
3141 $this->insertToken( $token, $value, $attribs, $selfClose );
3157 // Fall through to "anything else" case.
3159 // The Anything Else case
3160 return $this->inBodyMode( $token, $value, $attribs, $selfClose );
3163 private function inColumnGroupMode( $token, $value, $attribs = null, $selfClose = false ) {
3164 if ( $token === 'text' ) {
3165 if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
3166 $this->stack
->insertText( $matches[0] );
3167 $value = substr( $value, strlen( $matches[0] ) );
3169 if ( strlen( $value ) === 0 ) {
3170 return true; // All text handled.
3172 // Fall through to handle non-whitespace below.
3173 } elseif ( $token === 'tag' ) {
3177 $this->stack
->insertHTMLElement( $value, $attribs );
3178 $this->stack
->pop();
3181 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
3183 // Fall through for "anything else".
3184 } elseif ( $token === 'endtag' ) {
3187 if ( !$this->stack
->currentNode
->isHtmlNamed( 'colgroup' ) ) {
3188 return true; // Ignore the token.
3190 $this->stack
->pop();
3191 $this->switchMode( 'inTableMode' );
3194 return true; // Ignore the token.
3196 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
3198 // Fall through for "anything else".
3199 } elseif ( $token === 'eof' ) {
3200 return $this->inBodyMode( $token, $value, $attribs, $selfClose );
3201 } elseif ( $token === 'comment' ) {
3202 $this->stack
->insertComment( $value );
3207 if ( !$this->stack
->currentNode
->isHtmlNamed( 'colgroup' ) ) {
3208 return true; // Ignore the token.
3210 $this->inColumnGroupMode( 'endtag', 'colgroup' );
3211 return $this->insertToken( $token, $value, $attribs, $selfClose );
3214 // Helper function for inTableBodyMode
3215 private function endSection() {
3217 $this->stack
->inTableScope( 'tbody' ) ||
3218 $this->stack
->inTableScope( 'thead' ) ||
3219 $this->stack
->inTableScope( 'tfoot' )
3223 $this->stack
->clearToContext( BalanceSets
::$tableBodyContextSet );
3224 $this->stack
->pop();
3225 $this->switchMode( 'inTableMode' );
3228 private function inTableBodyMode( $token, $value, $attribs = null, $selfClose = false ) {
3229 if ( $token === 'tag' ) {
3232 $this->stack
->clearToContext( BalanceSets
::$tableBodyContextSet );
3233 $this->stack
->insertHTMLElement( $value, $attribs );
3234 $this->switchMode( 'inRowMode' );
3238 $this->inTableBodyMode( 'tag', 'tr', [] );
3239 $this->insertToken( $token, $value, $attribs, $selfClose );
3247 if ( $this->endSection() ) {
3248 $this->insertToken( $token, $value, $attribs, $selfClose );
3252 } elseif ( $token === 'endtag' ) {
3255 if ( $this->endSection() ) {
3256 $this->insertToken( $token, $value, $attribs, $selfClose );
3262 if ( $this->stack
->inTableScope( $value ) ) {
3263 $this->endSection();
3274 return true; // Ignore the token.
3278 return $this->inTableMode( $token, $value, $attribs, $selfClose );
3281 // Helper function for inRowMode
3282 private function endRow() {
3283 if ( !$this->stack
->inTableScope( 'tr' ) ) {
3286 $this->stack
->clearToContext( BalanceSets
::$tableRowContextSet );
3287 $this->stack
->pop();
3288 $this->switchMode( 'inTableBodyMode' );
3291 private function inRowMode( $token, $value, $attribs = null, $selfClose = false ) {
3292 if ( $token === 'tag' ) {
3296 $this->stack
->clearToContext( BalanceSets
::$tableRowContextSet );
3297 $this->stack
->insertHTMLElement( $value, $attribs );
3298 $this->switchMode( 'inCellMode' );
3299 $this->afe
->insertMarker();
3308 if ( $this->endRow() ) {
3309 $this->insertToken( $token, $value, $attribs, $selfClose );
3313 } elseif ( $token === 'endtag' ) {
3319 if ( $this->endRow() ) {
3320 $this->insertToken( $token, $value, $attribs, $selfClose );
3327 $this->stack
->inTableScope( $value ) &&
3330 $this->insertToken( $token, $value, $attribs, $selfClose );
3340 return true; // Ignore the token.
3344 return $this->inTableMode( $token, $value, $attribs, $selfClose );
3347 // Helper for inCellMode
3348 private function endCell() {
3349 if ( $this->stack
->inTableScope( 'td' ) ) {
3350 $this->inCellMode( 'endtag', 'td' );
3352 } elseif ( $this->stack
->inTableScope( 'th' ) ) {
3353 $this->inCellMode( 'endtag', 'th' );
3359 private function inCellMode( $token, $value, $attribs = null, $selfClose = false ) {
3360 if ( $token === 'tag' ) {
3371 if ( $this->endCell() ) {
3372 $this->insertToken( $token, $value, $attribs, $selfClose );
3376 } elseif ( $token === 'endtag' ) {
3380 if ( $this->stack
->inTableScope( $value ) ) {
3381 $this->stack
->generateImpliedEndTags();
3382 $this->stack
->popTag( $value );
3383 $this->afe
->clearToMarker();
3384 $this->switchMode( 'inRowMode' );
3399 if ( $this->stack
->inTableScope( $value ) ) {
3400 $this->stack
->generateImpliedEndTags();
3401 $this->stack
->popTag( BalanceSets
::$tableCellSet );
3402 $this->afe
->clearToMarker();
3403 $this->switchMode( 'inRowMode' );
3404 $this->insertToken( $token, $value, $attribs, $selfClose );
3410 return $this->inBodyMode( $token, $value, $attribs, $selfClose );
3413 private function inSelectMode( $token, $value, $attribs = null, $selfClose = false ) {
3414 if ( $token === 'text' ) {
3415 $this->stack
->insertText( $value );
3417 } elseif ( $token === 'eof' ) {
3418 return $this->inBodyMode( $token, $value, $attribs, $selfClose );
3419 } elseif ( $token === 'tag' ) {
3423 if ( $this->stack
->currentNode
->isHtmlNamed( 'option' ) ) {
3424 $this->stack
->pop();
3426 $this->stack
->insertHTMLElement( $value, $attribs );
3429 if ( $this->stack
->currentNode
->isHtmlNamed( 'option' ) ) {
3430 $this->stack
->pop();
3432 if ( $this->stack
->currentNode
->isHtmlNamed( 'optgroup' ) ) {
3433 $this->stack
->pop();
3435 $this->stack
->insertHTMLElement( $value, $attribs );
3438 $this->inSelectMode( 'endtag', $value ); // treat it like endtag
3443 if ( !$this->stack
->inSelectScope( 'select' ) ) {
3444 return true; // ignore token (fragment case)
3446 $this->inSelectMode( 'endtag', 'select' );
3447 return $this->insertToken( $token, $value, $attribs, $selfClose );
3450 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
3452 } elseif ( $token === 'endtag' ) {
3456 $this->stack
->currentNode
->isHtmlNamed( 'option' ) &&
3457 $this->stack
->length() >= 2 &&
3458 $this->stack
->node( $this->stack
->length() - 2 )->isHtmlNamed( 'optgroup' )
3460 $this->stack
->pop();
3462 if ( $this->stack
->currentNode
->isHtmlNamed( 'optgroup' ) ) {
3463 $this->stack
->pop();
3467 if ( $this->stack
->currentNode
->isHtmlNamed( 'option' ) ) {
3468 $this->stack
->pop();
3472 if ( !$this->stack
->inSelectScope( $value ) ) {
3473 return true; // fragment case
3475 $this->stack
->popTag( $value );
3476 $this->resetInsertionMode();
3479 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
3481 } elseif ( $token === 'comment' ) {
3482 $this->stack
->insertComment( $value );
3485 // anything else: just ignore the token
3489 private function inSelectInTableMode( $token, $value, $attribs = null, $selfClose = false ) {
3499 if ( $token === 'tag' ) {
3500 $this->inSelectInTableMode( 'endtag', 'select' );
3501 return $this->insertToken( $token, $value, $attribs, $selfClose );
3502 } elseif ( $token === 'endtag' ) {
3503 if ( $this->stack
->inTableScope( $value ) ) {
3504 $this->inSelectInTableMode( 'endtag', 'select' );
3505 return $this->insertToken( $token, $value, $attribs, $selfClose );
3511 return $this->inSelectMode( $token, $value, $attribs, $selfClose );
3514 private function inTemplateMode( $token, $value, $attribs = null, $selfClose = false ) {
3515 if ( $token === 'text' ||
$token === 'comment' ) {
3516 return $this->inBodyMode( $token, $value, $attribs, $selfClose );
3517 } elseif ( $token === 'eof' ) {
3518 if ( $this->stack
->indexOf( 'template' ) < 0 ) {
3519 $this->stopParsing();
3521 $this->stack
->popTag( 'template' );
3522 $this->afe
->clearToMarker();
3523 array_pop( $this->templateInsertionModes
);
3524 $this->resetInsertionMode();
3525 $this->insertToken( $token, $value, $attribs, $selfClose );
3528 } elseif ( $token === 'tag' ) {
3536 // OMITTED: <script>
3540 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
3547 return $this->switchModeAndReprocess(
3548 'inTableMode', $token, $value, $attribs, $selfClose
3552 return $this->switchModeAndReprocess(
3553 'inColumnGroupMode', $token, $value, $attribs, $selfClose
3557 return $this->switchModeAndReprocess(
3558 'inTableBodyMode', $token, $value, $attribs, $selfClose
3563 return $this->switchModeAndReprocess(
3564 'inRowMode', $token, $value, $attribs, $selfClose
3567 return $this->switchModeAndReprocess(
3568 'inBodyMode', $token, $value, $attribs, $selfClose
3570 } elseif ( $token === 'endtag' ) {
3573 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
3577 Assert
::invariant( false, "Bad token type: $token" );