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 # On the other hand, I've been pretty careful to note with comments in the
47 # code the places where this implementation omits features of the spec or
48 # depends on the MediaWiki Sanitizer. Perhaps in the future we'll want to
49 # implement the missing pieces and make this a standalone PHP HTML5 parser.
50 # In order to do so, some sort of MediaWiki-specific API will need
51 # to be added to (a) allow the Balancer to bypass the tokenizer,
52 # and (b) support on-the-fly flattening instead of DOM node creation.
54 # [1]: https://www.mediawiki.org/wiki/Library_infrastructure_for_MediaWiki
57 * Utility constants and sets for the HTML5 tree building algorithm.
58 * Sets are associative arrays indexed first by namespace and then by
59 * lower-cased tag name.
65 const HTML_NAMESPACE
= 'http://www.w3.org/1999/xhtml';
66 const MATHML_NAMESPACE
= 'http://www.w3.org/1998/Math/MathML';
67 const SVG_NAMESPACE
= 'http://www.w3.org/2000/svg';
69 public static $unsupportedSet = [
70 self
::HTML_NAMESPACE
=> [
71 'html' => true, 'head' => true, 'body' => true, 'frameset' => true,
72 'form' => true, 'frame' => true,
73 'plaintext' => true, 'isindex' => true, 'textarea' => true,
74 'xmp' => true, 'iframe' => true, 'noembed' => true,
75 'noscript' => true, 'select' => true, 'script' => true,
80 public static $emptyElementSet = [
81 self
::HTML_NAMESPACE
=> [
82 'area' => true, 'base' => true, 'basefont' => true,
83 'bgsound' => true, 'br' => true, 'col' => true, 'command' => true,
84 'embed' => true, 'frame' => true, 'hr' => true, 'img' => true,
85 'input' => true, 'keygen' => true, 'link' => true, 'meta' => true,
86 'param' => true, 'source' => true, 'track' => true, 'wbr' => true
90 public static $headingSet = [
91 self
::HTML_NAMESPACE
=> [
92 'h1' => true, 'h2' => true, 'h3' => true,
93 'h4' => true, 'h5' => true, 'h6' => true
97 public static $specialSet = [
98 self
::HTML_NAMESPACE
=> [
99 'address' => true, 'applet' => true, 'area' => true,
100 'article' => true, 'aside' => true, 'base' => true,
101 'basefont' => true, 'bgsound' => true, 'blockquote' => true,
102 'body' => true, 'br' => true, 'button' => true, 'caption' => true,
103 'center' => true, 'col' => true, 'colgroup' => true, 'dd' => true,
104 'details' => true, 'dir' => true, 'div' => true, 'dl' => true,
105 'dt' => true, 'embed' => true, 'fieldset' => true,
106 'figcaption' => true, 'figure' => true, 'footer' => true,
107 'form' => true, 'frame' => true, 'frameset' => true, 'h1' => true,
108 'h2' => true, 'h3' => true, 'h4' => true, 'h5' => true,
109 'h6' => true, 'head' => true, 'header' => true, 'hgroup' => true,
110 'hr' => true, 'html' => true, 'iframe' => true, 'img' => true,
111 'input' => true, 'isindex' => true, 'li' => true, 'link' => true,
112 'listing' => true, 'main' => true, 'marquee' => true,
113 'menu' => true, 'menuitem' => true, 'meta' => true, 'nav' => true,
114 'noembed' => true, 'noframes' => true, 'noscript' => true,
115 'object' => true, 'ol' => true, 'p' => true, 'param' => true,
116 'plaintext' => true, 'pre' => true, 'script' => true,
117 'section' => true, 'select' => true, 'source' => true,
118 'style' => true, 'summary' => true, 'table' => true,
119 'tbody' => true, 'td' => true, 'template' => true,
120 'textarea' => true, 'tfoot' => true, 'th' => true, 'thead' => true,
121 'title' => true, 'tr' => true, 'track' => true, 'ul' => true,
122 'wbr' => true, 'xmp' => true
124 self
::SVG_NAMESPACE
=> [
125 'foreignobject' => true, 'desc' => true, 'title' => true
127 self
::MATHML_NAMESPACE
=> [
128 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
129 'mtext' => true, 'annotation-xml' => true
133 public static $addressDivPSet = [
134 self
::HTML_NAMESPACE
=> [
135 'address' => true, 'div' => true, 'p' => true
139 public static $tableSectionRowSet = [
140 self
::HTML_NAMESPACE
=> [
141 'table' => true, 'thead' => true, 'tbody' => true,
142 'tfoot' => true, 'tr' => true
146 public static $impliedEndTagsSet = [
147 self
::HTML_NAMESPACE
=> [
148 'dd' => true, 'dt' => true, 'li' => true, 'optgroup' => true,
149 'option' => true, 'p' => true, 'rb' => true, 'rp' => true,
150 'rt' => true, 'rtc' => true
154 public static $thoroughImpliedEndTagsSet = [
155 self
::HTML_NAMESPACE
=> [
156 'caption' => true, 'colgroup' => true, 'dd' => true, 'dt' => true,
157 'li' => true, 'optgroup' => true, 'option' => true, 'p' => true,
158 'rb' => true, 'rp' => true, 'rt' => true, 'rtc' => true,
159 'tbody' => true, 'td' => true, 'tfoot' => true, 'th' => true,
160 'thead' => true, 'tr' => true
164 public static $tableCellSet = [
165 self
::HTML_NAMESPACE
=> [
166 'td' => true, 'th' => true
169 public static $tableContextSet = [
170 self
::HTML_NAMESPACE
=> [
171 'table' => true, 'template' => true, 'html' => true
175 public static $tableBodyContextSet = [
176 self
::HTML_NAMESPACE
=> [
177 'tbody' => true, 'tfoot' => true, 'thead' => true,
178 'template' => true, 'html' => true
182 public static $tableRowContextSet = [
183 self
::HTML_NAMESPACE
=> [
184 'tr' => true, 'template' => true, 'html' => true
188 # OMITTED: formAssociatedSet, since we don't allow <form>
190 public static $inScopeSet = [
191 self
::HTML_NAMESPACE
=> [
192 'applet' => true, 'caption' => true, 'html' => true,
193 'marquee' => true, 'object' => true,
194 'table' => true, 'td' => true, 'template' => true,
197 self
::SVG_NAMESPACE
=> [
198 'foreignobject' => true, 'desc' => true, 'title' => true
200 self
::MATHML_NAMESPACE
=> [
201 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
202 'mtext' => true, 'annotation-xml' => true
206 private static $inListItemScopeSet = null;
207 public static function inListItemScopeSet() {
208 if ( self
::$inListItemScopeSet === null ) {
209 self
::$inListItemScopeSet = self
::$inScopeSet;
210 self
::$inListItemScopeSet[self
::HTML_NAMESPACE
]['ol'] = true;
211 self
::$inListItemScopeSet[self
::HTML_NAMESPACE
]['ul'] = true;
213 return self
::$inListItemScopeSet;
216 private static $inButtonScopeSet = null;
217 public static function inButtonScopeSet() {
218 if ( self
::$inButtonScopeSet === null ) {
219 self
::$inButtonScopeSet = self
::$inScopeSet;
220 self
::$inButtonScopeSet[self
::HTML_NAMESPACE
]['button'] = true;
222 return self
::$inButtonScopeSet;
225 public static $inTableScopeSet = [
226 self
::HTML_NAMESPACE
=> [
227 'html' => true, 'table' => true, 'template' => true
231 public static $mathmlTextIntegrationPointSet = [
232 self
::MATHML_NAMESPACE
=> [
233 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
238 public static $htmlIntegrationPointSet = [
239 self
::SVG_NAMESPACE
=> [
240 'foreignobject' => true,
246 // For tidy compatibility.
247 public static $tidyPWrapSet = [
248 self
::HTML_NAMESPACE
=> [
249 'body' => true, 'blockquote' => true,
250 // We parse with <body> as the fragment context, but the top-level
251 // element on the stack is actually <html>. We could use the
252 // "adjusted current node" everywhere to work around this, but it's
253 // easier just to add <html> to the p-wrap set.
257 public static $tidyInlineSet = [
258 self
::HTML_NAMESPACE
=> [
259 'a' => true, 'abbr' => true, 'acronym' => true, 'applet' => true,
260 'b' => true, 'basefont' => true, 'bdo' => true, 'big' => true,
261 'br' => true, 'button' => true, 'cite' => true, 'code' => true,
262 'dfn' => true, 'em' => true, 'font' => true, 'i' => true,
263 'iframe' => true, 'img' => true, 'input' => true, 'kbd' => true,
264 'label' => true, 'legend' => true, 'map' => true, 'object' => true,
265 'param' => true, 'q' => true, 'rb' => true, 'rbc' => true,
266 'rp' => true, 'rt' => true, 'rtc' => true, 'ruby' => true,
267 's' => true, 'samp' => true, 'select' => true, 'small' => true,
268 'span' => true, 'strike' => true, 'strong' => true, 'sub' => true,
269 'sup' => true, 'textarea' => true, 'tt' => true, 'u' => true,
276 * A BalanceElement is a simplified version of a DOM Node. The main
277 * difference is that we only keep BalanceElements around for nodes
278 * currently on the BalanceStack of open elements. As soon as an
279 * element is closed, with some minor exceptions relating to the
280 * tree builder "adoption agency algorithm", the element and all its
281 * children are serialized to a string using the flatten() method.
282 * This keeps our memory usage low.
287 class BalanceElement
{
289 * The namespace of the element.
290 * @var string $namespaceURI
292 public $namespaceURI;
294 * The lower-cased name of the element.
295 * @var string $localName
299 * Attributes for the element, in array form
300 * @var array $attribs
305 * Parent of this element, or the string "flat" if this element has
306 * already been flattened into its parent.
307 * @var string|null $parent
312 * An array of children of this element. Typically only the last
313 * child will be an actual BalanceElement object; the rest will
314 * be strings, representing either text nodes or flattened
315 * BalanceElement objects.
316 * @var array $children
321 * A unique string identifier for Noah's Ark purposes, lazy initialized
326 * The next active formatting element in the list, or null if this is the
327 * end of the AFE list or if the element is not in the AFE list.
332 * The previous active formatting element in the list, or null if this is
333 * the start of the list or if the element is not in the AFE list.
338 * The next element in the Noah's Ark species bucket.
343 * Make a new BalanceElement corresponding to the HTML DOM Element
344 * with the given localname, namespace, and attributes.
346 * @param string $namespaceURI The namespace of the element.
347 * @param string $localName The lowercased name of the tag.
348 * @param array $attribs Attributes of the element
350 public function __construct( $namespaceURI, $localName, array $attribs ) {
351 $this->localName
= $localName;
352 $this->namespaceURI
= $namespaceURI;
353 $this->attribs
= $attribs;
354 $this->contents
= '';
355 $this->parent
= null;
356 $this->children
= [];
360 * Remove the given child from this element.
361 * @param BalanceElement $elt
363 private function removeChild( BalanceElement
$elt ) {
364 Assert
::precondition(
365 $this->parent
!== 'flat', "Can't removeChild after flattening $this"
368 $elt->parent
=== $this, 'elt', 'must have $this as a parent'
370 $idx = array_search( $elt, $this->children
, true );
371 Assert
::parameter( $idx !== false, '$elt', 'must be a child of $this' );
373 array_splice( $this->children
, $idx, 1 );
377 * Find $a in the list of children and insert $b before it.
378 * @param BalanceElement $a
379 * @param BalanceElement|string $b
381 public function insertBefore( BalanceElement
$a, $b ) {
382 Assert
::precondition(
383 $this->parent
!== 'flat', "Can't insertBefore after flattening."
385 $idx = array_search( $a, $this->children
, true );
386 Assert
::parameter( $idx !== false, '$a', 'must be a child of $this' );
387 if ( is_string( $b ) ) {
388 array_splice( $this->children
, $idx, 0, [ $b ] );
390 Assert
::parameter( $b->parent
!== 'flat', '$b', "Can't be flat" );
391 if ( $b->parent
!== null ) {
392 $b->parent
->removeChild( $b );
394 array_splice( $this->children
, $idx, 0, [ $b ] );
400 * Append $elt to the end of the list of children.
401 * @param BalanceElement|string $elt
403 public function appendChild( $elt ) {
404 Assert
::precondition(
405 $this->parent
!== 'flat', "Can't appendChild after flattening."
407 if ( is_string( $elt ) ) {
408 array_push( $this->children
, $elt );
411 // Remove $elt from parent, if it had one.
412 if ( $elt->parent
!== null ) {
413 $elt->parent
->removeChild( $elt );
415 array_push( $this->children
, $elt );
416 $elt->parent
= $this;
420 * Transfer all of the children of $elt to $this.
421 * @param BalanceElement $elt
423 public function adoptChildren( BalanceElement
$elt ) {
424 Assert
::precondition(
425 $elt->parent
!== 'flat', "Can't adoptChildren after flattening."
427 foreach ( $elt->children
as $child ) {
428 if ( !is_string( $child ) ) {
429 // This is an optimization which avoids an O(n^2) set of
430 // array_splice operations.
431 $child->parent
= null;
433 $this->appendChild( $child );
439 * Flatten this node and all of its children into a string, as specified
440 * by the HTML serialization specification, and replace this node
441 * in its parent by that string.
445 public function flatten( $tidyCompat = false ) {
446 Assert
::parameter( $this->parent
!== null, '$this', 'must be a child' );
447 Assert
::parameter( $this->parent
!== 'flat', '$this', 'already flat' );
448 $idx = array_search( $this, $this->parent
->children
, true );
450 $idx !== false, '$this', 'must be a child of its parent'
454 foreach ( $this->children
as $elt ) {
455 if ( !is_string( $elt ) ) {
456 $elt = $elt->flatten( $tidyCompat );
458 if ( $blank && preg_match( '/[^\t\n\f\r ]/', $elt ) ) {
462 if ( $this->isHtmlNamed( 'mw:p-wrap' ) ) {
463 $this->localName
= 'p';
464 } elseif ( $blank ) {
465 // Add 'mw-empty-elt' class so elements can be hidden via CSS
466 // for compatibility with legacy tidy.
467 if ( !count( $this->attribs
) &&
468 ( $this->localName
=== 'tr' ||
$this->localName
=== 'li' )
470 $this->attribs
= [ 'class' => "mw-empty-elt" ];
474 $flat = $blank ?
'' : "{$this}";
478 $this->parent
->children
[$idx] = $flat;
479 $this->parent
= 'flat'; # for assertion checking
484 * Serialize this node and all of its children to a string, as specified
485 * by the HTML serialization specification.
487 * @return string The serialization of the BalanceElement
488 * @see https://html.spec.whatwg.org/multipage/syntax.html#serialising-html-fragments
490 public function __toString() {
492 foreach ( $this->attribs
as $name => $value ) {
493 $encValue = Sanitizer
::encodeAttribute( $value );
494 $encAttribs .= " $name=\"$encValue\"";
496 if ( !$this->isA( BalanceSets
::$emptyElementSet ) ) {
497 $out = "<{$this->localName}{$encAttribs}>";
499 foreach ( $this->children
as $elt ) {
502 $out .= "</{$this->localName}>";
504 $out = "<{$this->localName}{$encAttribs} />";
506 count( $this->children
) === 0,
507 "Empty elements shouldn't have children."
513 # Utility functions on BalanceElements.
516 * Determine if $this represents a specific HTML tag, is a member of
517 * a tag set, or is equal to another BalanceElement.
519 * @param BalanceElement|array|string $set The target BalanceElement,
520 * set (from the BalanceSets class), or string (HTML tag name).
523 public function isA( $set ) {
524 if ( $set instanceof BalanceElement
) {
525 return $this === $set;
526 } elseif ( is_array( $set ) ) {
527 return isset( $set[$this->namespaceURI
] ) &&
528 isset( $set[$this->namespaceURI
][$this->localName
] );
530 # assume this is an HTML element name.
531 return $this->isHtml() && $this->localName
=== $set;
536 * Determine if this element is an HTML element with the specified name
537 * @param string $tagName
540 public function isHtmlNamed( $tagName ) {
541 return $this->namespaceURI
=== BalanceSets
::HTML_NAMESPACE
542 && $this->localName
=== $tagName;
546 * Determine if $this represents an element in the HTML namespace.
550 public function isHtml() {
551 return $this->namespaceURI
=== BalanceSets
::HTML_NAMESPACE
;
555 * Determine if $this represents a MathML text integration point,
556 * as defined in the HTML5 specification.
559 * @see https://html.spec.whatwg.org/multipage/syntax.html#mathml-text-integration-point
561 public function isMathmlTextIntegrationPoint() {
562 return $this->isA( BalanceSets
::$mathmlTextIntegrationPointSet );
566 * Determine if $this represents an HTML integration point,
567 * as defined in the HTML5 specification.
570 * @see https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
572 public function isHtmlIntegrationPoint() {
573 if ( $this->isA( BalanceSets
::$htmlIntegrationPointSet ) ) {
577 $this->namespaceURI
=== BalanceSets
::MATHML_NAMESPACE
&&
578 $this->localName
=== 'annotation-xml' &&
579 isset( $this->attribs
['encoding'] ) &&
580 ( strcasecmp( $this->attribs
['encoding'], 'text/html' ) == 0 ||
581 strcasecmp( $this->attribs
['encoding'], 'application/xhtml+xml' ) == 0 )
589 * Get a string key for the Noah's Ark algorithm
591 public function getNoahKey() {
592 if ( $this->noahKey
=== null ) {
593 $attribs = $this->attribs
;
595 $this->noahKey
= serialize( [ $this->namespaceURI
, $this->localName
, $attribs ] );
597 return $this->noahKey
;
602 * The "stack of open elements" as defined in the HTML5 tree builder
603 * spec. This contains methods to ensure that content (start tags, text)
604 * are inserted at the correct place in the output string, and to
605 * flatten BalanceElements are they are closed to avoid holding onto
606 * a complete DOM tree for the document in memory.
608 * The stack defines a PHP iterator to traverse it in "reverse order",
609 * that is, the most-recently-added element is visited first in a
614 * @see https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements
616 class BalanceStack
implements IteratorAggregate
{
618 * Backing storage for the stack.
619 * @var array $elements
621 private $elements = [];
623 * Foster parent mode determines how nodes are inserted into the
625 * @var bool $fosterParentMode
626 * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
628 public $fosterParentMode = false;
630 * Tidy compatibility mode, determines behavior of body/blockquote
632 public $tidyCompat = false;
634 * Reference to the current element
639 * Create a new BalanceStack with a single BalanceElement on it,
640 * representing the root <html> node.
642 public function __construct() {
643 # always a root <html> element on the stack
646 new BalanceElement( BalanceSets
::HTML_NAMESPACE
, 'html', [] )
648 $this->currentNode
= $this->elements
[0];
652 * Return a string representing the output of the tree builder:
653 * all the children of the root <html> node.
656 public function getOutput() {
657 // Don't include the outer '<html>....</html>'
659 foreach ( $this->elements
[0]->children
as $elt ) {
660 $out .= is_string( $elt ) ?
$elt :
661 $elt->flatten( $this->tidyCompat
);
667 * Insert text at the appropriate place for inserting a node.
668 * @param string $value
669 * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
671 public function insertText( $value ) {
673 $this->fosterParentMode
&&
674 $this->currentNode
->isA( BalanceSets
::$tableSectionRowSet )
676 $this->fosterParent( $value );
679 $this->currentNode
->isA( BalanceSets
::$tidyPWrapSet )
681 $this->insertHTMLELement( 'mw:p-wrap', [] );
682 return $this->insertText( $value );
684 $this->currentNode
->appendChild( $value );
689 * Insert a BalanceElement at the appropriate place, pushing it
690 * on to the open elements stack.
691 * @param string $namespaceURI The element namespace
692 * @param string $tag The tag name
693 * @param string $attribs Normalized attributes, as a string.
694 * @return BalanceElement
695 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-a-foreign-element
697 public function insertForeignElement( $namespaceURI, $tag, $attribs ) {
698 return $this->insertElement(
699 new BalanceElement( $namespaceURI, $tag, $attribs )
704 * Insert an HTML element at the appropriate place, pushing it on to
705 * the open elements stack.
706 * @param string $tag The tag name
707 * @param string $attribs Normalized attributes, as a string.
708 * @return BalanceElement
709 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-an-html-element
711 public function insertHTMLElement( $tag, $attribs ) {
712 return $this->insertForeignElement(
713 BalanceSets
::HTML_NAMESPACE
, $tag, $attribs
718 * Insert an element at the appropriate place and push it on to the
719 * open elements stack.
720 * @param BalanceElement $elt
721 * @return BalanceElement
722 * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
724 public function insertElement( BalanceElement
$elt ) {
726 $this->currentNode
->isHtmlNamed( 'mw:p-wrap' ) &&
727 !$elt->isA( BalanceSets
::$tidyInlineSet )
729 // Tidy compatibility.
733 $this->fosterParentMode
&&
734 $this->currentNode
->isA( BalanceSets
::$tableSectionRowSet )
736 $elt = $this->fosterParent( $elt );
738 $this->currentNode
->appendChild( $elt );
740 Assert
::invariant( $elt->parent
!== null, "$elt must be in tree" );
741 Assert
::invariant( $elt->parent
!== 'flat', "$elt must not have been previous flattened" );
742 array_push( $this->elements
, $elt );
743 $this->currentNode
= $elt;
748 * Determine if the stack has $tag in scope.
749 * @param BalanceElement|array|string $tag
751 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
753 public function inScope( $tag ) {
754 return $this->inSpecificScope( $tag, BalanceSets
::$inScopeSet );
758 * Determine if the stack has $tag in button scope.
759 * @param BalanceElement|array|string $tag
761 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
763 public function inButtonScope( $tag ) {
764 return $this->inSpecificScope( $tag, BalanceSets
::inButtonScopeSet() );
768 * Determine if the stack has $tag in list item scope.
769 * @param BalanceElement|array|string $tag
771 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-list-item-scope
773 public function inListItemScope( $tag ) {
774 return $this->inSpecificScope( $tag, BalanceSets
::inListItemScopeSet() );
778 * Determine if the stack has $tag in table scope.
779 * @param BalanceElement|array|string $tag
781 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-table-scope
783 public function inTableScope( $tag ) {
784 return $this->inSpecificScope( $tag, BalanceSets
::$inTableScopeSet );
788 * Determine if the stack has $tag in a specific scope, $set.
789 * @param BalanceElement|array|string $tag
790 * @param BalanceElement|array|string $set
792 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-the-specific-scope
794 public function inSpecificScope( $tag, $set ) {
795 foreach ( $this as $elt ) {
796 if ( $elt->isA( $tag ) ) {
799 if ( $elt->isA( $set ) ) {
807 * Generate implied end tags.
808 * @param string $butnot
809 * @param bool $thorough True if we should generate end tags thoroughly.
810 * @see https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
812 public function generateImpliedEndTags( $butnot = null, $thorough = false ) {
813 $endTagSet = $thorough ?
814 BalanceSets
::$thoroughImpliedEndTagsSet :
815 BalanceSets
::$impliedEndTagsSet;
816 while ( $this->currentNode
) {
817 if ( $butnot !== null && $this->currentNode
->isHtmlNamed( $butnot ) ) {
820 if ( !$this->currentNode
->isA( $endTagSet ) ) {
828 * Return the adjusted current node.
830 public function adjustedCurrentNode( $fragmentContext ) {
831 return ( $fragmentContext && count( $this->elements
) === 1 ) ?
832 $fragmentContext : $this->currentNode
;
836 * Return an iterator over this stack which visits the current node
837 * first, and the root node last.
840 public function getIterator() {
841 return new ReverseArrayIterator( $this->elements
);
845 * Return the BalanceElement at the given position $idx, where
846 * position 0 represents the root element.
848 * @return BalanceElement
850 public function node( $idx ) {
851 return $this->elements
[ $idx ];
855 * Replace the element at position $idx in the BalanceStack with $elt.
857 * @param BalanceElement $elt
859 public function replaceAt( $idx, BalanceElement
$elt ) {
860 Assert
::precondition(
861 $this->elements
[$idx]->parent
!== 'flat',
862 'Replaced element should not have already been flattened.'
864 Assert
::precondition(
865 $elt->parent
!== 'flat',
866 'New element should not have already been flattened.'
868 $this->elements
[$idx] = $elt;
869 if ( $idx === count( $this->elements
) - 1 ) {
870 $this->currentNode
= $elt;
875 * Return the position of the given BalanceElement, set, or
876 * HTML tag name string in the BalanceStack.
877 * @param BalanceElement|array|string $tag
880 public function indexOf( $tag ) {
881 for ( $i = count( $this->elements
) - 1; $i >= 0; $i-- ) {
882 if ( $this->elements
[$i]->isA( $tag ) ) {
890 * Return the number of elements currently in the BalanceStack.
893 public function length() {
894 return count( $this->elements
);
898 * Remove the current node from the BalanceStack, flattening it
901 public function pop() {
902 $elt = array_pop( $this->elements
);
903 if ( count( $this->elements
) ) {
904 $this->currentNode
= $this->elements
[ count( $this->elements
) - 1 ];
906 $this->currentNode
= null;
908 if ( !$elt->isHtmlNamed( 'mw:p-wrap' ) ) {
909 $elt->flatten( $this->tidyCompat
);
914 * Remove all nodes up to and including position $idx from the
915 * BalanceStack, flattening them in the process.
918 public function popTo( $idx ) {
919 $length = count( $this->elements
);
920 for ( $length = count( $this->elements
); $length > $idx; $length-- ) {
926 * Pop elements off the stack up to and including the first
927 * element with the specified HTML tagname (or matching the given
929 * @param BalanceElement|array|string $tag
931 public function popTag( $tag ) {
932 while ( $this->currentNode
) {
933 if ( $this->currentNode
->isA( $tag ) ) {
942 * Pop elements off the stack *not including* the first element
943 * in the specified set.
944 * @param BalanceElement|array|string $set
946 public function clearToContext( $set ) {
947 // Note that we don't loop to 0. Never pop the <html> elt off.
948 for ( $length = count( $this->elements
); $length > 1; $length-- ) {
949 if ( $this->currentNode
->isA( $set ) ) {
957 * Remove the given $elt from the BalanceStack, optionally
958 * flattening it in the process.
959 * @param BalanceElement $elt The element to remove.
960 * @param bool $flatten Whether to flatten the removed element.
962 public function removeElement( BalanceElement
$elt, $flatten = true ) {
964 $elt->parent
!== 'flat',
966 '$elt should not already have been flattened.'
969 $elt->parent
->parent
!== 'flat',
971 'The parent of $elt should not already have been flattened.'
973 $idx = array_search( $elt, $this->elements
, true );
974 Assert
::parameter( $idx !== false, '$elt', 'must be in stack' );
975 array_splice( $this->elements
, $idx, 1 );
976 if ( $idx === count( $this->elements
) ) {
977 $this->currentNode
= $this->elements
[$idx - 1];
980 // serialize $elt into its parent
981 // otherwise, it will eventually serialize when the parent
982 // is serialized, we just hold onto the memory for its
983 // tree of objects a little longer.
984 $elt->flatten( $this->tidyCompat
);
986 Assert
::postcondition(
987 array_search( $elt, $this->elements
, true ) === false,
988 '$elt should no longer be in open elements stack'
993 * Find $a in the BalanceStack and insert $b after it.
994 * @param BalanceElement $a
995 * @param BalanceElement $b
997 public function insertAfter( BalanceElement
$a, BalanceElement
$b ) {
998 $idx = $this->indexOf( $a );
999 Assert
::parameter( $idx !== false, '$a', 'must be in stack' );
1000 if ( $idx === count( $this->elements
) - 1 ) {
1001 array_push( $this->elements
, $b );
1002 $this->currentNode
= $b;
1004 array_splice( $this->elements
, $idx +
1, 0, [ $b ] );
1008 # Fostering and adoption.
1011 * Foster parent the given $elt in the stack of open elements.
1012 * @param BalanceElement|string $elt
1013 * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
1015 private function fosterParent( $elt ) {
1016 $lastTable = $this->indexOf( 'table' );
1017 $lastTemplate = $this->indexOf( 'template' );
1021 if ( $lastTemplate >= 0 && ( $lastTable < 0 ||
$lastTemplate > $lastTable ) ) {
1022 $parent = $this->elements
[$lastTemplate];
1023 } elseif ( $lastTable >= 0 ) {
1024 $parent = $this->elements
[$lastTable]->parent
;
1025 # Assume all tables have parents, since we're not running scripts!
1027 $parent !== null, "All tables should have parents"
1029 $before = $this->elements
[$lastTable];
1031 $parent = $this->elements
[0]; // the `html` element.
1034 if ( $this->tidyCompat
) {
1035 if ( is_string( $elt ) ) {
1036 // We're fostering text: do we need a p-wrapper?
1037 if ( $parent->isA( BalanceSets
::$tidyPWrapSet ) ) {
1038 $this->insertHTMLElement( 'mw:p-wrap', [] );
1039 $this->insertText( $elt );
1043 // We're fostering an element; do we need to merge p-wrappers?
1044 if ( $elt->isHtmlNamed( 'mw:p-wrap' ) ) {
1046 array_search( $before, $parent->children
, true ) :
1047 count( $parent->children
);
1048 $after = $idx > 0 ?
$parent->children
[$idx - 1] : '';
1050 $after instanceof BalanceElement
&&
1051 $after->isHtmlNamed( 'mw:p-wrap' )
1053 return $after; // Re-use existing p-wrapper.
1060 $parent->insertBefore( $before, $elt );
1062 $parent->appendChild( $elt );
1068 * Run the "adoption agency algoritm" (AAA) for the given subject
1070 * @param string $tag The subject tag name.
1071 * @param BalanceActiveFormattingElements $afe The current
1072 * active formatting elements list.
1073 * @return true if the adoption agency algorithm "did something", false
1074 * if more processing is required by the caller.
1075 * @see https://html.spec.whatwg.org/multipage/syntax.html#adoption-agency-algorithm
1077 public function adoptionAgency( $tag, $afe ) {
1078 // If the current node is an HTML element whose tag name is subject,
1079 // and the current node is not in the list of active formatting
1080 // elements, then pop the current node off the stack of open
1081 // elements and abort these steps.
1083 $this->currentNode
->isHtmlNamed( $tag ) &&
1084 !$afe->isInList( $this->currentNode
)
1087 return true; // no more handling required
1090 // Let outer loop counter be zero.
1093 // Outer loop: If outer loop counter is greater than or
1094 // equal to eight, then abort these steps.
1095 while ( $outer < 8 ) {
1096 // Increment outer loop counter by one.
1099 // Let the formatting element be the last element in the list
1100 // of active formatting elements that: is between the end of
1101 // the list and the last scope marker in the list, if any, or
1102 // the start of the list otherwise, and has the same tag name
1104 $fmtelt = $afe->findElementByTag( $tag );
1106 // If there is no such node, then abort these steps and instead
1107 // act as described in the "any other end tag" entry below.
1109 return false; // false means handle by the default case
1112 // Otherwise, if there is such a node, but that node is not in
1113 // the stack of open elements, then this is a parse error;
1114 // remove the element from the list, and abort these steps.
1115 $index = $this->indexOf( $fmtelt );
1117 $afe->remove( $fmtelt );
1118 return true; // true means no more handling required
1121 // Otherwise, if there is such a node, and that node is also in
1122 // the stack of open elements, but the element is not in scope,
1123 // then this is a parse error; ignore the token, and abort
1125 if ( !$this->inScope( $fmtelt ) ) {
1129 // Let the furthest block be the topmost node in the stack of
1130 // open elements that is lower in the stack than the formatting
1131 // element, and is an element in the special category. There
1132 // might not be one.
1133 $furthestblock = null;
1134 $furthestblockindex = -1;
1135 $stacklen = $this->length();
1136 for ( $i = $index+
1; $i < $stacklen; $i++
) {
1137 if ( $this->node( $i )->isA( BalanceSets
::$specialSet ) ) {
1138 $furthestblock = $this->node( $i );
1139 $furthestblockindex = $i;
1144 // If there is no furthest block, then the UA must skip the
1145 // subsequent steps and instead just pop all the nodes from the
1146 // bottom of the stack of open elements, from the current node
1147 // up to and including the formatting element, and remove the
1148 // formatting element from the list of active formatting
1150 if ( !$furthestblock ) {
1151 $this->popTag( $fmtelt );
1152 $afe->remove( $fmtelt );
1155 // Let the common ancestor be the element immediately above
1156 // the formatting element in the stack of open elements.
1157 $ancestor = $this->node( $index-1 );
1159 // Let a bookmark note the position of the formatting
1160 // element in the list of active formatting elements
1161 // relative to the elements on either side of it in the
1163 $BOOKMARK = new BalanceElement( '[bookmark]', '[bookmark]', [] );
1164 $afe->insertAfter( $fmtelt, $BOOKMARK );
1166 // Let node and last node be the furthest block.
1167 $node = $furthestblock;
1168 $lastnode = $furthestblock;
1169 $nodeindex = $furthestblockindex;
1172 // Let inner loop counter be zero.
1177 // Increment inner loop counter by one.
1180 // Let node be the element immediately above node in
1181 // the stack of open elements, or if node is no longer
1182 // in the stack of open elements (e.g. because it got
1183 // removed by this algorithm), the element that was
1184 // immediately above node in the stack of open elements
1185 // before node was removed.
1186 $node = $this->node( --$nodeindex );
1188 // If node is the formatting element, then go
1189 // to the next step in the overall algorithm.
1190 if ( $node === $fmtelt ) break;
1192 // If the inner loop counter is greater than three and node
1193 // is in the list of active formatting elements, then remove
1194 // node from the list of active formatting elements.
1195 $isAFE = $afe->isInList( $node );
1196 if ( $inner > 3 && $isAFE ) {
1197 $afe->remove( $node );
1201 // If node is not in the list of active formatting
1202 // elements, then remove node from the stack of open
1203 // elements and then go back to the step labeled inner
1206 // Don't flatten here, since we're about to relocate
1207 // parts of this $node.
1208 $this->removeElement( $node, false );
1212 // Create an element for the token for which the
1213 // element node was created with common ancestor as
1214 // the intended parent, replace the entry for node
1215 // in the list of active formatting elements with an
1216 // entry for the new element, replace the entry for
1217 // node in the stack of open elements with an entry for
1218 // the new element, and let node be the new element.
1219 $newelt = new BalanceElement(
1220 $node->namespaceURI
, $node->localName
, $node->attribs
);
1221 $afe->replace( $node, $newelt );
1222 $this->replaceAt( $nodeindex, $newelt );
1225 // If last node is the furthest block, then move the
1226 // aforementioned bookmark to be immediately after the
1227 // new node in the list of active formatting elements.
1228 if ( $lastnode === $furthestblock ) {
1229 $afe->remove( $BOOKMARK );
1230 $afe->insertAfter( $newelt, $BOOKMARK );
1233 // Insert last node into node, first removing it from
1234 // its previous parent node if any.
1235 $node->appendChild( $lastnode );
1237 // Let last node be node.
1241 // If the common ancestor node is a table, tbody, tfoot,
1242 // thead, or tr element, then, foster parent whatever last
1243 // node ended up being in the previous step, first removing
1244 // it from its previous parent node if any.
1246 $this->fosterParentMode
&&
1247 $ancestor->isA( BalanceSets
::$tableSectionRowSet )
1249 $this->fosterParent( $lastnode );
1251 // Otherwise, append whatever last node ended up being in
1252 // the previous step to the common ancestor node, first
1253 // removing it from its previous parent node if any.
1254 $ancestor->appendChild( $lastnode );
1257 // Create an element for the token for which the
1258 // formatting element was created, with furthest block
1259 // as the intended parent.
1260 $newelt2 = new BalanceElement(
1261 $fmtelt->namespaceURI
, $fmtelt->localName
, $fmtelt->attribs
);
1263 // Take all of the child nodes of the furthest block and
1264 // append them to the element created in the last step.
1265 $newelt2->adoptChildren( $furthestblock );
1267 // Append that new element to the furthest block.
1268 $furthestblock->appendChild( $newelt2 );
1270 // Remove the formatting element from the list of active
1271 // formatting elements, and insert the new element into the
1272 // list of active formatting elements at the position of
1273 // the aforementioned bookmark.
1274 $afe->remove( $fmtelt );
1275 $afe->replace( $BOOKMARK, $newelt2 );
1277 // Remove the formatting element from the stack of open
1278 // elements, and insert the new element into the stack of
1279 // open elements immediately below the position of the
1280 // furthest block in that stack.
1281 $this->removeElement( $fmtelt );
1282 $this->insertAfter( $furthestblock, $newelt2 );
1290 * Return the contents of the open elements stack as a string for
1294 public function __toString() {
1296 foreach ( $this->elements
as $elt ) {
1297 array_push( $r, $elt->localName
);
1299 return implode( $r, ' ' );
1304 * A pseudo-element used as a marker in the list of active formatting elements
1309 class BalanceMarker
{
1315 * The list of active formatting elements, which is used to handle
1316 * mis-nested formatting element tags in the HTML5 tree builder
1321 * @see https://html.spec.whatwg.org/multipage/syntax.html#list-of-active-formatting-elements
1323 class BalanceActiveFormattingElements
{
1324 /** The last (most recent) element in the list */
1327 /** The first (least recent) element in the list */
1331 * An array of arrays representing the population of elements in each bucket
1332 * according to the Noah's Ark clause. The outer array is stack-like, with each
1333 * integer-indexed element representing a segment of the list, bounded by
1334 * markers. The first element represents the segment of the list before the
1337 * The inner arrays are indexed by "Noah key", which is a string which uniquely
1338 * identifies each bucket according to the rules in the spec. The value in
1339 * the inner array is the first (least recently inserted) element in the bucket,
1340 * and subsequent members of the bucket can be found by iterating through the
1341 * singly-linked list via $node->nextNoah.
1343 * This is optimised for the most common case of inserting into a bucket
1344 * with zero members, and deleting a bucket containing one member. In the
1345 * worst case, iteration through the list is still O(1) in the document
1346 * size, since each bucket can have at most 3 members.
1348 private $noahTableStack = [ [] ];
1350 public function __destruct() {
1351 for ( $node = $this->head
; $node; $node = $next ) {
1352 $next = $node->nextAFE
;
1353 $node->prevAFE
= $node->nextAFE
= $node->nextNoah
= null;
1355 $this->head
= $this->tail
= $this->noahTableStack
= null;
1358 public function insertMarker() {
1359 $elt = new BalanceMarker
;
1360 if ( $this->tail
) {
1361 $this->tail
->nextAFE
= $elt;
1362 $elt->prevAFE
= $this->tail
;
1367 $this->noahTableStack
[] = [];
1371 * Follow the steps required when the spec requires us to "push onto the
1372 * list of active formatting elements".
1373 * @param BalanceElement $elt
1375 public function push( BalanceElement
$elt ) {
1376 // Must not be in the list already
1377 if ( $elt->prevAFE
!== null ||
$this->head
=== $elt ) {
1378 throw new ParameterAssertionException( '$elt',
1379 'Cannot insert a node into the AFE list twice' );
1382 // "Noah's Ark clause" -- if there are already three copies of
1383 // this element before we encounter a marker, then drop the last
1385 $noahKey = $elt->getNoahKey();
1386 $table =& $this->noahTableStack
[ count( $this->noahTableStack
) - 1 ];
1387 if ( !isset( $table[$noahKey] ) ) {
1388 $table[$noahKey] = $elt;
1391 $head = $tail = $table[$noahKey];
1392 while ( $tail->nextNoah
) {
1393 $tail = $tail->nextNoah
;
1396 if ( $count >= 3 ) {
1397 $this->remove( $head );
1399 $tail->nextNoah
= $elt;
1401 // Add to the main AFE list
1402 if ( $this->tail
) {
1403 $this->tail
->nextAFE
= $elt;
1404 $elt->prevAFE
= $this->tail
;
1412 * Follow the steps required when the spec asks us to "clear the list of
1413 * active formatting elements up to the last marker".
1415 public function clearToMarker() {
1416 // Iterate back through the list starting from the tail
1417 $tail = $this->tail
;
1418 while ( $tail && !( $tail instanceof BalanceMarker
) ) {
1419 // Unlink the element
1420 $prev = $tail->prevAFE
;
1421 $tail->prevAFE
= null;
1423 $prev->nextAFE
= null;
1425 $tail->nextNoah
= null;
1428 // If we finished on a marker, unlink it and pop it off the Noah table stack
1430 $prev = $tail->prevAFE
;
1432 $prev->nextAFE
= null;
1435 array_pop( $this->noahTableStack
);
1437 // No marker: wipe the top-level Noah table (which is the only one)
1438 $this->noahTableStack
[0] = [];
1440 // If we removed all the elements, clear the head pointer
1444 $this->tail
= $tail;
1448 * Find and return the last element with the specified tag between the
1449 * end of the list and the last marker on the list.
1450 * Used when parsing <a> "in body mode".
1452 public function findElementByTag( $tag ) {
1454 while ( $elt && !( $elt instanceof BalanceMarker
) ) {
1455 if ( $elt->localName
=== $tag ) {
1458 $elt = $elt->prevAFE
;
1464 * Determine whether an element is in the list of formatting elements.
1467 public function isInList( BalanceElement
$elt ) {
1468 return $this->head
=== $elt ||
$elt->prevAFE
;
1472 * Find the element $elt in the list and remove it.
1473 * Used when parsing <a> in body mode.
1475 public function remove( BalanceElement
$elt ) {
1476 if ( $this->head
!== $elt && !$elt->prevAFE
) {
1477 throw new ParameterAssertionException( '$elt',
1478 "Attempted to remove an element which is not in the AFE list" );
1480 // Update head and tail pointers
1481 if ( $this->head
=== $elt ) {
1482 $this->head
= $elt->nextAFE
;
1484 if ( $this->tail
=== $elt ) {
1485 $this->tail
= $elt->prevAFE
;
1487 // Update previous element
1488 if ( $elt->prevAFE
) {
1489 $elt->prevAFE
->nextAFE
= $elt->nextAFE
;
1491 // Update next element
1492 if ( $elt->nextAFE
) {
1493 $elt->nextAFE
->prevAFE
= $elt->prevAFE
;
1495 // Clear pointers so that isInList() etc. will work
1496 $elt->prevAFE
= $elt->nextAFE
= null;
1498 $this->removeFromNoahList( $elt );
1501 private function addToNoahList( BalanceElement
$elt ) {
1502 $noahKey = $elt->getNoahKey();
1503 $table =& $this->noahTableStack
[ count( $this->noahTableStack
) - 1 ];
1504 if ( !isset( $table[$noahKey] ) ) {
1505 $table[$noahKey] = $elt;
1507 $tail = $table[$noahKey];
1508 while ( $tail->nextNoah
) {
1509 $tail = $tail->nextNoah
;
1511 $tail->nextNoah
= $elt;
1515 private function removeFromNoahList( BalanceElement
$elt ) {
1516 $table =& $this->noahTableStack
[ count( $this->noahTableStack
) - 1 ];
1517 $key = $elt->getNoahKey();
1518 $noahElt = $table[$key];
1519 if ( $noahElt === $elt ) {
1520 if ( $noahElt->nextNoah
) {
1521 $table[$key] = $noahElt->nextNoah
;
1522 $noahElt->nextNoah
= null;
1524 unset( $table[$key] );
1528 $prevNoahElt = $noahElt;
1529 $noahElt = $prevNoahElt->nextNoah
;
1530 if ( $noahElt === $elt ) {
1532 $prevNoahElt->nextNoah
= $elt->nextNoah
;
1533 $elt->nextNoah
= null;
1536 } while ( $noahElt );
1541 * Find element $a in the list and replace it with element $b
1543 public function replace( BalanceElement
$a, BalanceElement
$b ) {
1544 if ( $this->head
!== $a && !$a->prevAFE
) {
1545 throw new ParameterAssertionException( '$a',
1546 "Attempted to replace an element which is not in the AFE list" );
1548 // Update head and tail pointers
1549 if ( $this->head
=== $a ) {
1552 if ( $this->tail
=== $a ) {
1555 // Update previous element
1556 if ( $a->prevAFE
) {
1557 $a->prevAFE
->nextAFE
= $b;
1559 // Update next element
1560 if ( $a->nextAFE
) {
1561 $a->nextAFE
->prevAFE
= $b;
1563 $b->prevAFE
= $a->prevAFE
;
1564 $b->nextAFE
= $a->nextAFE
;
1565 $a->nextAFE
= $a->prevAFE
= null;
1567 $this->removeFromNoahList( $a );
1568 $this->addToNoahList( $b );
1572 * Find $a in the list and insert $b after it.
1574 public function insertAfter( BalanceElement
$a, BalanceElement
$b ) {
1575 if ( $this->head
!== $a && !$a->prevAFE
) {
1576 throw new ParameterAssertionException( '$a',
1577 "Attempted to insert after an element which is not in the AFE list" );
1579 if ( $this->tail
=== $a ) {
1582 if ( $a->nextAFE
) {
1583 $a->nextAFE
->prevAFE
= $b;
1585 $b->nextAFE
= $a->nextAFE
;
1588 $this->addToNoahList( $b );
1591 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
1593 * Reconstruct the active formatting elements.
1594 * @param BalanceStack $stack The open elements stack
1595 * @see https://html.spec.whatwg.org/multipage/syntax.html#reconstruct-the-active-formatting-elements
1597 // @codingStandardsIgnoreEnd
1598 public function reconstruct( $stack ) {
1599 $entry = $this->tail
;
1600 // If there are no entries in the list of active formatting elements,
1601 // then there is nothing to reconstruct
1605 // If the last is a marker, do nothing.
1606 if ( $entry instanceof BalanceMarker
) {
1609 // Or if it is an open element, do nothing.
1610 if ( $stack->indexOf( $entry ) >= 0 ) {
1614 // Loop backward through the list until we find a marker or an
1616 while ( $entry->prevAFE
) {
1617 $entry = $entry->prevAFE
;
1618 if ( $entry instanceof BalanceMarker ||
$stack->indexOf( $entry ) >= 0 ) {
1623 // Now loop forward, starting from the element after the current one (or
1624 // the first element if we didn't find a marker or open element),
1625 // recreating formatting elements and pushing them back onto the list
1626 // of open elements.
1627 if ( $entry->prevAFE
) {
1628 $entry = $entry->nextAFE
;
1631 $newElement = $stack->insertHTMLElement(
1634 $this->replace( $entry, $newElement );
1635 $entry = $newElement->nextAFE
;
1640 * Get a string representation of the AFE list, for debugging
1642 public function __toString() {
1645 for ( $node = $this->head
; $node; $prev = $node, $node = $node->nextAFE
) {
1646 if ( $node instanceof BalanceMarker
) {
1650 $s .= $node->localName
. '#' . substr( md5( spl_object_hash( $node ) ), 0, 8 );
1651 if ( $node->nextNoah
) {
1652 $s .= " (noah sibling: {$node->nextNoah->localName}#" .
1653 substr( md5( spl_object_hash( $node->nextNoah
) ), 0, 8 ) .
1656 if ( $node->nextAFE
&& $node->nextAFE
->prevAFE
!== $node ) {
1657 $s .= " (reverse link is wrong!)";
1661 if ( $prev !== $this->tail
) {
1662 $s .= "(tail pointer is wrong!)\n";
1669 * An implementation of the tree building portion of the HTML5 parsing
1672 * This is used to balance and tidy output so that the result can
1673 * always be cleanly serialized/deserialized by an HTML5 parser. It
1674 * does *not* guarantee "conforming" output -- the HTML5 spec contains
1675 * a number of constraints which are not enforced by the HTML5 parsing
1676 * process. But the result will be free of gross errors: misnested or
1677 * unclosed tags, for example, and will be unchanged by spec-complient
1678 * parsing followed by serialization.
1680 * The tree building stage is structured as a state machine.
1681 * When comparing the implementation to
1682 * https://www.w3.org/TR/html5/syntax.html#tree-construction
1683 * note that each state is implemented as a function with a
1684 * name ending in `Mode` (because the HTML spec refers to them
1685 * as insertion modes). The current insertion mode is held by
1686 * the $parseMode property.
1688 * The following simplifications have been made:
1689 * - We handle body content only (ie, we start `in body`.)
1690 * - The document is never in "quirks mode".
1691 * - All occurrences of < and > have been entity escaped, so we
1692 * can parse tags by simply splitting on those two characters.
1693 * Similarly, all attributes have been "cleaned" and are double-quoted
1695 * - All comments and null characters are assumed to have been removed.
1696 * - We don't alter linefeeds after <pre>/<listing>.
1697 * - The following elements are disallowed: <html>, <head>, <body>, <frameset>,
1698 * <form>, <frame>, <plaintext>, <isindex>, <textarea>, <xmp>, <iframe>,
1699 * <noembed>, <noscript>, <select>, <script>, <title>. As a result,
1700 * further simplifications can be made:
1701 * - `frameset-ok` is not tracked.
1702 * - `form element pointer` is not tracked.
1703 * - `head element pointer` is not tracked (but presumed non-null)
1704 * - Tokenizer has only a single mode.
1706 * We generally mark places where we omit cases from the spec due to
1707 * disallowed elements with a comment: `# OMITTED: <element-name>`.
1709 * The HTML spec keeps a flag during the parsing process to track
1710 * whether or not a "parse error" has been encountered. We don't
1711 * bother to track that flag, we just implement the error-handling
1712 * process as specified.
1716 * @see https://html.spec.whatwg.org/multipage/syntax.html#tree-construction
1720 private $bitsIterator;
1721 private $allowedHtmlElements;
1725 private $tidyCompat;
1727 private $textIntegrationMode = false;
1728 private $pendingTableText;
1729 private $originalInsertionMode;
1730 private $fragmentContext;
1733 * Create a new Balancer.
1734 * @param array $config Balancer configuration. Includes:
1735 * 'strict' : boolean, defaults to false.
1736 * When true, enforces syntactic constraints on input:
1737 * all non-tag '<' must be escaped, all attributes must be
1738 * separated by a single space and double-quoted. This is
1739 * consistent with the output of the Sanitizer.
1740 * 'allowedHtmlElements' : array, defaults to null.
1741 * When present, the keys of this associative array give
1742 * the acceptable HTML tag names. When not present, no
1743 * tag sanitization is done.
1744 * 'tidyCompat' : boolean, defaults to false.
1745 * When true, the serialization algorithm is tweaked to
1746 * provide historical compatibility with the old "tidy"
1747 * program: <p>-wrapping is done to the children of
1748 * <body> and <blockquote> elements, and empty elements
1751 public function __construct( array $config = [] ) {
1752 $config = $config +
[
1754 'allowedHtmlElements' => null,
1755 'tidyCompat' => false,
1757 $this->allowedHtmlElements
= $config['allowedHtmlElements'];
1758 $this->strict
= $config['strict'];
1759 $this->tidyCompat
= $config['tidyCompat'];
1760 if ( $this->allowedHtmlElements
!== null ) {
1762 $bad = array_uintersect_assoc(
1763 $this->allowedHtmlElements
,
1764 BalanceSets
::$unsupportedSet[BalanceSets
::HTML_NAMESPACE
],
1765 function( $a, $b ) {
1766 // Ignore the values (just intersect the keys) by saying
1767 // all values are equal to each other.
1771 if ( count( $bad ) > 0 ) {
1772 $badstr = implode( array_keys( $bad ), ',' );
1773 throw new ParameterAssertionException(
1775 'Balance attempted with sanitization including ' .
1776 "unsupported elements: {$badstr}"
1783 * Return a balanced HTML string for the HTML fragment given by $text,
1784 * subject to the caveats listed in the class description. The result
1785 * will typically be idempotent -- that is, rebalancing the output
1786 * would result in no change.
1788 * @param string $text The markup to be balanced
1789 * @param callable $processingCallback Callback to do any variable or
1790 * parameter replacements in HTML attributes values
1791 * @param array|bool $processingArgs Arguments for the processing callback
1792 * @return string The balanced markup
1794 public function balance( $text, $processingCallback = null, $processingArgs = [] ) {
1795 $this->parseMode
= 'inBodyMode';
1796 $this->bitsIterator
= new ExplodeIterator( '<', $text );
1797 $this->afe
= new BalanceActiveFormattingElements();
1798 $this->stack
= new BalanceStack();
1799 $this->stack
->tidyCompat
= $this->tidyCompat
;
1800 $this->processingCallback
= $processingCallback;
1801 $this->processingArgs
= $processingArgs;
1803 # The stack is constructed with an <html> element already on it.
1804 # Set this up as a fragment parsed with <body> as the context.
1805 $this->fragmentContext
=
1806 new BalanceElement( BalanceSets
::HTML_NAMESPACE
, 'body', [] );
1807 $this->resetInsertionMode();
1809 // First element is text not tag
1810 $x = $this->bitsIterator
->current();
1811 $this->bitsIterator
->next();
1812 $this->insertToken( 'text', str_replace( '>', '>', $x ) );
1813 // Now process each tag.
1814 while ( $this->bitsIterator
->valid() ) {
1817 $this->insertToken( 'eof', null );
1818 $result = $this->stack
->getOutput();
1819 // Free memory before returning.
1820 $this->bitsIterator
= null;
1822 $this->stack
= null;
1823 $this->fragmentContext
= null;
1828 * Pass a token to the tree builder. The $token will be one of the
1829 * strings "tag", "endtag", or "text".
1831 private function insertToken( $token, $value, $attribs = null, $selfclose = false ) {
1832 // validate tags against $unsupportedSet
1833 if ( $token === 'tag' ||
$token === 'endtag' ) {
1834 if ( isset( BalanceSets
::$unsupportedSet[BalanceSets
::HTML_NAMESPACE
][$value] ) ) {
1835 # As described in "simplifications" above, these tags are
1836 # not supported in the balancer.
1839 "Unsupported $token <$value> found."
1843 } elseif ( $token === 'text' && $value === '' ) {
1844 # Don't actually inject the empty string as a text token.
1847 // Some hoops we have to jump through
1848 $adjusted = $this->stack
->adjustedCurrentNode( $this->fragmentContext
);
1852 $this->stack
->length() === 0 ||
1853 $adjusted->isHtml() ||
1857 } elseif ( $adjusted->isMathmlTextIntegrationPoint() ) {
1858 if ( $token === 'text' ) {
1862 $value !== 'mglyph' && $value !== 'malignmark'
1867 $adjusted->namespaceURI
=== BalanceSets
::MATHML_NAMESPACE
&&
1868 $adjusted->localName
=== 'annotation-xml' &&
1869 $token === 'tag' && $value === 'svg'
1873 $adjusted->isHtmlIntegrationPoint() &&
1874 ( $token === 'tag' ||
$token === 'text' )
1879 return $this->insertForeignToken( $token, $value, $attribs, $selfclose );
1881 $func = $this->parseMode
;
1882 return $this->$func( $token, $value, $attribs, $selfclose );
1886 private function insertForeignToken( $token, $value, $attribs = null, $selfclose = false ) {
1887 if ( $token === 'text' ) {
1888 $this->stack
->insertText( $value );
1890 } elseif ( $token === 'tag' ) {
1893 if ( isset( $attribs['color'] )
1894 ||
isset( $attribs['face'] )
1895 ||
isset( $attribs['size'] )
1899 /* otherwise, fall through */
1944 if ( $this->fragmentContext
) {
1948 $this->stack
->pop();
1949 $node = $this->stack
->currentNode
;
1951 $node->isMathmlTextIntegrationPoint() ||
1952 $node->isHtmlIntegrationPoint() ||
1958 return $this->insertToken( $token, $value, $attribs, $selfclose );
1960 // "Any other start tag"
1961 $adjusted = ( $this->fragmentContext
&& $this->stack
->length()===1 ) ?
1962 $this->fragmentContext
: $this->stack
->currentNode
;
1963 $this->stack
->insertForeignElement(
1964 $adjusted->namespaceURI
, $value, $attribs
1967 $this->stack
->pop();
1970 } elseif ( $token === 'endtag' ) {
1972 foreach ( $this->stack
as $i => $node ) {
1973 if ( $node->isHtml() && !$first ) {
1974 // process the end tag as HTML
1975 $func = $this->parseMode
;
1976 return $this->$func( $token, $value, $attribs, $selfclose );
1977 } elseif ( $i === 0 ) {
1979 } elseif ( $node->localName
=== $value ) {
1980 $this->stack
->popTag( $node );
1989 * Grab the next "token" from $bitsIterator. This is either a open/close
1990 * tag or text, depending on whether the Sanitizer approves.
1992 private function advance() {
1993 $x = $this->bitsIterator
->current();
1994 $this->bitsIterator
->next();
1996 # $slash: Does the current element start with a '/'?
1997 # $t: Current element name
1998 # $attribStr: String between element name and >
1999 # $brace: Ending '>' or '/>'
2000 # $rest: Everything until the next element from the $bitsIterator
2001 if ( preg_match( Sanitizer
::ELEMENT_BITS_REGEX
, $x, $regs ) ) {
2002 list( /* $qbar */, $slash, $t, $attribStr, $brace, $rest ) = $regs;
2003 $t = strtolower( $t );
2004 if ( $this->strict
) {
2005 /* Verify that attributes are all properly double-quoted */
2008 '/^( [:_A-Z0-9][-.:_A-Z0-9]*="[^"]*")*[ ]*$/i', $attribStr
2010 "Bad attribute string found"
2015 !$this->strict
, "< found which does not start a valid tag"
2017 $slash = $t = $attribStr = $brace = $rest = null;
2020 $sanitize = $this->allowedHtmlElements
!== null;
2022 $goodtag = $t && isset( $this->allowedHtmlElements
[$t] );
2025 if ( is_callable( $this->processingCallback
) ) {
2026 call_user_func_array( $this->processingCallback
, [ &$attribStr, $this->processingArgs
] );
2029 $goodtag = Sanitizer
::validateTag( $attribStr, $t );
2034 $attribs = Sanitizer
::decodeTagAttributes( $attribStr );
2035 $attribs = Sanitizer
::validateTagAttributes( $attribs, $t );
2037 $attribs = Sanitizer
::decodeTagAttributes( $attribStr );
2039 $goodtag = $this->insertToken(
2040 $slash ?
'endtag' : 'tag', $t, $attribs, $brace === '/>'
2044 $rest = str_replace( '>', '>', $rest );
2045 $this->insertToken( 'text', str_replace( '>', '>', $rest ) );
2047 # bad tag; serialize entire thing as text.
2048 $this->insertToken( 'text', '<' . str_replace( '>', '>', $x ) );
2052 private function switchMode( $mode ) {
2054 substr( $mode, -4 )==='Mode', '$mode', 'should end in Mode'
2056 $oldMode = $this->parseMode
;
2057 $this->parseMode
= $mode;
2061 private function switchModeAndReprocess( $mode, $token, $value, $attribs, $selfclose ) {
2062 $this->switchMode( $mode );
2063 return $this->insertToken( $token, $value, $attribs, $selfclose );
2066 private function resetInsertionMode() {
2068 foreach ( $this->stack
as $i => $node ) {
2071 if ( $this->fragmentContext
) {
2072 $node = $this->fragmentContext
;
2075 if ( $node->isHtml() ) {
2076 switch ( $node->localName
) {
2080 $stacklen = $this->stack->length();
2081 for ( $j = $i + 1; $j < $stacklen-1; $j++ ) {
2082 $ancestor = $this->stack->node( $stacklen-$j-1 );
2083 if ( $ancestor->isHtmlNamed( 'template' ) ) {
2086 if ( $ancestor->isHtmlNamed( 'table' ) ) {
2087 $this->switchMode( 'inSelectInTableMode' );
2091 $this->switchMode( 'inSelectMode' );
2095 $this->switchMode( 'inRowMode' );
2100 $this->switchMode( 'inTableBodyMode' );
2103 $this->switchMode( 'inCaptionMode' );
2106 $this->switchMode( 'inColumnGroupMode' );
2109 $this->switchMode( 'inTableMode' );
2113 array_slice( $this->templateInsertionModes
, -1 )[0]
2117 $this->switchMode( 'inBodyMode' );
2119 # OMITTED: <frameset>
2125 if ( $node->isA( BalanceSets
::$tableCellSet ) ) {
2126 $this->switchMode( 'inCellMode' );
2133 $this->switchMode( 'inBodyMode' );
2139 private function stopParsing() {
2140 # Most of the spec methods are inapplicable, other than step 2:
2141 # "pop all the nodes off the stack of open elements".
2142 # We're going to keep the top-most <html> element on the stack, though.
2144 # Clear the AFE list first, otherwise the element objects will stay live
2145 # during serialization, potentially using O(N^2) memory. Note that
2146 # popping the stack will never result in reconstructing the active
2147 # formatting elements.
2149 $this->stack
->popTo( 1 );
2152 private function parseRawText( $value, $attribs = null ) {
2153 $this->stack
->insertHTMLElement( $value, $attribs );
2154 // XXX switch tokenizer to rawtext state?
2155 $this->originalInsertionMode
= $this->switchMode( 'inTextMode' );
2159 private function inTextMode( $token, $value, $attribs = null, $selfclose = false ) {
2160 if ( $token === 'text' ) {
2161 $this->stack
->insertText( $value );
2163 } elseif ( $token === 'eof' ) {
2164 $this->stack
->pop();
2165 return $this->switchModeAndReprocess(
2166 $this->originalInsertionMode
, $token, $value, $attribs, $selfclose
2168 } elseif ( $token === 'endtag' ) {
2169 $this->stack
->pop();
2170 $this->switchMode( $this->originalInsertionMode
);
2176 private function inHeadMode( $token, $value, $attribs = null, $selfclose = false ) {
2177 if ( $token === 'text' ) {
2178 if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
2179 $this->stack
->insertText( $matches[0] );
2180 $value = substr( $value, strlen( $matches[0] ) );
2182 if ( strlen( $value ) === 0 ) {
2183 return true; // All text handled.
2185 // Fall through to handle non-whitespace below.
2186 } elseif ( $token === 'tag' ) {
2189 # OMITTED: in a full HTML parser, this might change the encoding.
2196 $this->stack
->insertHTMLElement( $value, $attribs );
2197 $this->stack
->pop();
2200 # OMITTED: <noscript>
2203 return $this->parseRawText( $value, $attribs );
2206 $this->stack
->insertHTMLElement( $value, $attribs );
2207 $this->afe
->insertMarker();
2208 # OMITTED: frameset_ok
2209 $this->switchMode( 'inTemplateMode' );
2210 $this->templateInsertionModes
[] = $this->parseMode
;
2214 } elseif ( $token === 'endtag' ) {
2220 break; // handle at the bottom of the function
2222 if ( $this->stack
->indexOf( $value ) < 0 ) {
2223 return true; // Ignore the token.
2225 $this->stack
->generateImpliedEndTags( null, true /* thorough */ );
2226 $this->stack
->popTag( $value );
2227 $this->afe
->clearToMarker();
2228 array_pop( $this->templateInsertionModes
);
2229 $this->resetInsertionMode();
2232 // ignore any other end tag
2237 // If not handled above
2238 $this->inHeadMode( 'endtag', 'head' ); // synthetic </head>
2239 // Then redo this one
2240 return $this->insertToken( $token, $value, $attribs, $selfclose );
2243 private function inBodyMode( $token, $value, $attribs = null, $selfclose = false ) {
2244 if ( $token === 'text' ) {
2245 $this->afe
->reconstruct( $this->stack
);
2246 $this->stack
->insertText( $value );
2248 } elseif ( $token === 'eof' ) {
2249 if ( !empty( $this->templateInsertionModes
) ) {
2250 return $this->inTemplateMode( $token, $value, $attribs, $selfclose );
2252 $this->stopParsing();
2254 } elseif ( $token === 'tag' ) {
2267 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2269 # OMITTED: <frameset>
2295 if ( $this->stack
->inButtonScope( 'p' ) ) {
2296 $this->inBodyMode( 'endtag', 'p' );
2298 $this->stack
->insertHTMLElement( $value, $attribs );
2307 if ( $this->stack
->inButtonScope( 'p' ) ) {
2308 $this->inBodyMode( 'endtag', 'p' );
2310 if ( $this->stack
->currentNode
->isA( BalanceSets
::$headingSet ) ) {
2311 $this->stack
->pop();
2313 $this->stack
->insertHTMLElement( $value, $attribs );
2318 if ( $this->stack
->inButtonScope( 'p' ) ) {
2319 $this->inBodyMode( 'endtag', 'p' );
2321 $this->stack
->insertHTMLElement( $value, $attribs );
2322 # As described in "simplifications" above:
2323 # 1. We don't touch the next token, even if it's a linefeed.
2324 # 2. OMITTED: frameset_ok
2330 # OMITTED: frameset_ok
2331 foreach ( $this->stack
as $node ) {
2332 if ( $node->isHtmlNamed( 'li' ) ) {
2333 $this->inBodyMode( 'endtag', 'li' );
2337 $node->isA( BalanceSets
::$specialSet ) &&
2338 !$node->isA( BalanceSets
::$addressDivPSet )
2343 if ( $this->stack
->inButtonScope( 'p' ) ) {
2344 $this->inBodyMode( 'endtag', 'p' );
2346 $this->stack
->insertHTMLElement( $value, $attribs );
2351 # OMITTED: frameset_ok
2352 foreach ( $this->stack
as $node ) {
2353 if ( $node->isHtmlNamed( 'dd' ) ) {
2354 $this->inBodyMode( 'endtag', 'dd' );
2357 if ( $node->isHtmlNamed( 'dt' ) ) {
2358 $this->inBodyMode( 'endtag', 'dt' );
2362 $node->isA( BalanceSets
::$specialSet ) &&
2363 !$node->isA( BalanceSets
::$addressDivPSet )
2368 if ( $this->stack
->inButtonScope( 'p' ) ) {
2369 $this->inBodyMode( 'endtag', 'p' );
2371 $this->stack
->insertHTMLElement( $value, $attribs );
2374 # OMITTED: <plaintext>
2377 if ( $this->stack
->inScope( 'button' ) ) {
2378 $this->inBodyMode( 'endtag', 'button' );
2379 return $this->insertToken( $token, $value, $attribs, $selfclose );
2381 $this->afe
->reconstruct( $this->stack
);
2382 $this->stack
->insertHTMLElement( $value, $attribs );
2386 $activeElement = $this->afe
->findElementByTag( 'a' );
2387 if ( $activeElement ) {
2388 $this->inBodyMode( 'endtag', 'a' );
2389 if ( $this->afe
->isInList( $activeElement ) ) {
2390 $this->afe
->remove( $activeElement );
2391 // Don't flatten here, since when we fall
2392 // through below we might foster parent
2393 // the new <a> tag inside this one.
2394 $this->stack
->removeElement( $activeElement, false );
2410 $this->afe
->reconstruct( $this->stack
);
2411 $this->afe
->push( $this->stack
->insertHTMLElement( $value, $attribs ), $attribs );
2415 $this->afe
->reconstruct( $this->stack
);
2416 if ( $this->stack
->inScope( 'nobr' ) ) {
2417 $this->inBodyMode( 'endtag', 'nobr' );
2418 $this->afe
->reconstruct( $this->stack
);
2420 $this->afe
->push( $this->stack
->insertHTMLElement( $value, $attribs ), $attribs );
2426 $this->afe
->reconstruct( $this->stack
);
2427 $this->stack
->insertHTMLElement( $value, $attribs );
2428 $this->afe
->insertMarker();
2429 # OMITTED: frameset_ok
2433 # The document is never in "quirks mode"; see simplifications
2435 if ( $this->stack
->inButtonScope( 'p' ) ) {
2436 $this->inBodyMode( 'endtag', 'p' );
2438 $this->stack
->insertHTMLElement( $value, $attribs );
2439 # OMITTED: frameset_ok
2440 $this->switchMode( 'inTableMode' );
2449 $this->afe
->reconstruct( $this->stack
);
2450 $this->stack
->insertHTMLElement( $value, $attribs );
2451 $this->stack
->pop();
2452 # OMITTED: frameset_ok
2456 $this->afe
->reconstruct( $this->stack
);
2457 $this->stack
->insertHTMLElement( $value, $attribs );
2458 $this->stack
->pop();
2459 # OMITTED: frameset_ok
2460 # (hence we don't need to examine the tag's "type" attribute)
2467 $this->stack
->insertHTMLElement( $value, $attribs );
2468 $this->stack
->pop();
2472 if ( $this->stack
->inButtonScope( 'p' ) ) {
2473 $this->inBodyMode( 'endtag', 'p' );
2475 $this->stack
->insertHTMLElement( $value, $attribs );
2476 $this->stack
->pop();
2481 return $this->inBodyMode( $token, 'img', $attribs, $selfclose );
2483 # OMITTED: <isindex>
2484 # OMITTED: <textarea>
2487 # OMITTED: <noembed>
2488 # OMITTED: <noscript>
2493 $this->afe->reconstruct( $this->stack );
2494 $this->stack->insertHTMLElement( $value, $attribs );
2495 switch ( $this->parseMode ) {
2497 case 'inCaptionMode':
2498 case 'inTableBodyMode':
2501 $this->switchMode( 'inSelectInTableMode' );
2504 $this->switchMode( 'inSelectMode' );
2511 if ( $this->stack
->currentNode
->isHtmlNamed( 'option' ) ) {
2512 $this->inBodyMode( 'endtag', 'option' );
2514 $this->afe
->reconstruct( $this->stack
);
2515 $this->stack
->insertHTMLElement( $value, $attribs );
2520 if ( $this->stack
->inScope( 'ruby' ) ) {
2521 $this->stack
->generateImpliedEndTags();
2523 $this->stack
->insertHTMLElement( $value, $attribs );
2528 if ( $this->stack
->inScope( 'ruby' ) ) {
2529 $this->stack
->generateImpliedEndTags( 'rtc' );
2531 $this->stack
->insertHTMLElement( $value, $attribs );
2535 $this->afe
->reconstruct( $this->stack
);
2536 # We skip the spec's "adjust MathML attributes" and
2537 # "adjust foreign attributes" steps, since the browser will
2538 # do this later when it parses the output and it doesn't affect
2540 $this->stack
->insertForeignElement(
2541 BalanceSets
::MATHML_NAMESPACE
, $value, $attribs
2544 # emit explicit </math> tag.
2545 $this->stack
->pop();
2550 $this->afe
->reconstruct( $this->stack
);
2551 # We skip the spec's "adjust SVG attributes" and
2552 # "adjust foreign attributes" steps, since the browser will
2553 # do this later when it parses the output and it doesn't affect
2555 $this->stack
->insertForeignElement(
2556 BalanceSets
::SVG_NAMESPACE
, $value, $attribs
2559 # emit explicit </svg> tag.
2560 $this->stack
->pop();
2575 // Ignore table tags if we're not inTableMode
2579 // Handle any other start tag here
2580 $this->afe
->reconstruct( $this->stack
);
2581 $this->stack
->insertHTMLElement( $value, $attribs );
2583 } elseif ( $token === 'endtag' ) {
2585 # </body>,</html> are unsupported.
2588 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2616 // Ignore if there is not a matching open tag
2617 if ( !$this->stack
->inScope( $value ) ) {
2620 $this->stack
->generateImpliedEndTags();
2621 $this->stack
->popTag( $value );
2627 if ( !$this->stack
->inButtonScope( 'p' ) ) {
2628 $this->inBodyMode( 'tag', 'p', [] );
2629 return $this->insertToken( $token, $value, $attribs, $selfclose );
2631 $this->stack
->generateImpliedEndTags( $value );
2632 $this->stack
->popTag( $value );
2636 if ( !$this->stack
->inListItemScope( $value ) ) {
2637 return true; # ignore
2639 $this->stack
->generateImpliedEndTags( $value );
2640 $this->stack
->popTag( $value );
2645 if ( !$this->stack
->inScope( $value ) ) {
2646 return true; # ignore
2648 $this->stack
->generateImpliedEndTags( $value );
2649 $this->stack
->popTag( $value );
2658 if ( !$this->stack
->inScope( BalanceSets
::$headingSet ) ) {
2661 $this->stack
->generateImpliedEndTags();
2662 $this->stack
->popTag( BalanceSets
::$headingSet );
2666 # Take a deep breath, then:
2683 if ( $this->stack
->adoptionAgency( $value, $this->afe
) ) {
2684 return true; # If we did something, we're done.
2686 break; # Go to the "any other end tag" case.
2691 if ( !$this->stack
->inScope( $value ) ) {
2692 return true; # ignore
2694 $this->stack
->generateImpliedEndTags();
2695 $this->stack
->popTag( $value );
2696 $this->afe
->clearToMarker();
2700 # Turn </br> into <br>
2701 return $this->inBodyMode( 'tag', $value, [] );
2704 // Any other end tag goes here
2705 foreach ( $this->stack
as $i => $node ) {
2706 if ( $node->isHtmlNamed( $value ) ) {
2707 $this->stack
->generateImpliedEndTags( $value );
2708 $this->stack
->popTo( $i ); # including $i
2710 } elseif ( $node->isA( BalanceSets
::$specialSet ) ) {
2711 return true; // ignore this close token.
2716 Assert
::invariant( false, "Bad token type: $token" );
2720 private function inTableMode( $token, $value, $attribs = null, $selfclose = false ) {
2721 if ( $token === 'text' ) {
2722 if ( $this->textIntegrationMode
) {
2723 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
2724 } elseif ( $this->stack
->currentNode
->isA( BalanceSets
::$tableSectionRowSet ) ) {
2725 $this->pendingTableText
= '';
2726 $this->originalInsertionMode
= $this->parseMode
;
2727 return $this->switchModeAndReprocess( 'inTableTextMode', $token, $value, $attribs, $selfclose );
2729 // fall through to default case.
2730 } elseif ( $token === 'eof' ) {
2731 $this->stopParsing();
2733 } elseif ( $token === 'tag' ) {
2736 $this->afe
->insertMarker();
2737 $this->stack
->insertHTMLElement( $value, $attribs );
2738 $this->switchMode( 'inCaptionMode' );
2741 $this->stack
->clearToContext( BalanceSets
::$tableContextSet );
2742 $this->stack
->insertHTMLElement( $value, $attribs );
2743 $this->switchMode( 'inColumnGroupMode' );
2746 $this->inTableMode( 'tag', 'colgroup', [] );
2747 return $this->insertToken( $token, $value, $attribs, $selfclose );
2751 $this->stack
->clearToContext( BalanceSets
::$tableContextSet );
2752 $this->stack
->insertHTMLElement( $value, $attribs );
2753 $this->switchMode( 'inTableBodyMode' );
2758 $this->inTableMode( 'tag', 'tbody', [] );
2759 return $this->insertToken( $token, $value, $attribs, $selfclose );
2761 if ( !$this->stack
->inTableScope( $value ) ) {
2762 return true; // Ignore this tag.
2764 $this->inTableMode( 'endtag', $value );
2765 return $this->insertToken( $token, $value, $attribs, $selfclose );
2770 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2773 if ( !isset( $attribs['type'] ) ||
strcasecmp( $attribs['type'], 'hidden' ) !== 0 ) {
2774 break; // Handle this as "everything else"
2776 $this->stack
->insertHTMLElement( $value, $attribs );
2777 $this->stack
->pop();
2782 // Fall through for "anything else" clause.
2783 } elseif ( $token === 'endtag' ) {
2786 if ( !$this->stack
->inTableScope( $value ) ) {
2787 return true; // Ignore.
2789 $this->stack
->popTag( $value );
2790 $this->resetInsertionMode();
2803 return true; // Ignore the token.
2805 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2807 // Fall through for "anything else" clause.
2809 // This is the "anything else" case:
2810 $this->stack
->fosterParentMode
= true;
2811 $this->inBodyMode( $token, $value, $attribs, $selfclose );
2812 $this->stack
->fosterParentMode
= false;
2816 private function inTableTextMode( $token, $value, $attribs = null, $selfclose = false ) {
2817 if ( $token === 'text' ) {
2818 $this->pendingTableText
.= $value;
2822 $text = $this->pendingTableText
;
2823 $this->pendingTableText
= '';
2824 if ( preg_match( '/[^\x09\x0A\x0C\x0D\x20]/', $text ) ) {
2825 // This should match the "anything else" case inTableMode
2826 $this->stack
->fosterParentMode
= true;
2827 $this->inBodyMode( 'text', $text );
2828 $this->stack
->fosterParentMode
= false;
2830 // Pending text is just whitespace.
2831 $this->stack
->insertText( $text );
2833 return $this->switchModeAndReprocess(
2834 $this->originalInsertionMode
, $token, $value, $attribs, $selfclose
2838 // helper for inCaptionMode
2839 private function endCaption() {
2840 if ( !$this->stack
->inTableScope( 'caption' ) ) {
2843 $this->stack
->generateImpliedEndTags();
2844 $this->stack
->popTag( 'caption' );
2845 $this->afe
->clearToMarker();
2846 $this->switchMode( 'inTableMode' );
2850 private function inCaptionMode( $token, $value, $attribs = null, $selfclose = false ) {
2851 if ( $token === 'tag' ) {
2862 if ( $this->endCaption() ) {
2863 $this->insertToken( $token, $value, $attribs, $selfclose );
2867 // Fall through to "anything else" case.
2868 } elseif ( $token === 'endtag' ) {
2871 $this->endCaption();
2874 if ( $this->endCaption() ) {
2875 $this->insertToken( $token, $value, $attribs, $selfclose );
2891 // Fall through to "anything else" case.
2893 // The Anything Else case
2894 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
2897 private function inColumnGroupMode( $token, $value, $attribs = null, $selfclose = false ) {
2898 if ( $token === 'text' ) {
2899 if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
2900 $this->stack
->insertText( $matches[0] );
2901 $value = substr( $value, strlen( $matches[0] ) );
2903 if ( strlen( $value ) === 0 ) {
2904 return true; // All text handled.
2906 // Fall through to handle non-whitespace below.
2907 } elseif ( $token === 'tag' ) {
2911 $this->stack
->insertHTMLElement( $value, $attribs );
2912 $this->stack
->pop();
2915 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2917 // Fall through for "anything else".
2918 } elseif ( $token === 'endtag' ) {
2921 if ( !$this->stack
->currentNode
->isHtmlNamed( 'colgroup' ) ) {
2922 return true; // Ignore the token.
2924 $this->stack
->pop();
2925 $this->switchMode( 'inTableMode' );
2928 return true; // Ignore the token.
2930 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2932 // Fall through for "anything else".
2933 } elseif ( $token === 'eof' ) {
2934 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
2938 if ( !$this->stack
->currentNode
->isHtmlNamed( 'colgroup' ) ) {
2939 return true; // Ignore the token.
2941 $this->inColumnGroupMode( 'endtag', 'colgroup' );
2942 return $this->insertToken( $token, $value, $attribs, $selfclose );
2945 // Helper function for inTableBodyMode
2946 private function endSection() {
2948 $this->stack
->inTableScope( 'tbody' ) ||
2949 $this->stack
->inTableScope( 'thead' ) ||
2950 $this->stack
->inTableScope( 'tfoot' )
2954 $this->stack
->clearToContext( BalanceSets
::$tableBodyContextSet );
2955 $this->stack
->pop();
2956 $this->switchMode( 'inTableMode' );
2959 private function inTableBodyMode( $token, $value, $attribs = null, $selfclose = false ) {
2960 if ( $token === 'tag' ) {
2963 $this->stack
->clearToContext( BalanceSets
::$tableBodyContextSet );
2964 $this->stack
->insertHTMLElement( $value, $attribs );
2965 $this->switchMode( 'inRowMode' );
2969 $this->inTableBodyMode( 'tag', 'tr', [] );
2970 $this->insertToken( $token, $value, $attribs, $selfclose );
2978 if ( $this->endSection() ) {
2979 $this->insertToken( $token, $value, $attribs, $selfclose );
2983 } elseif ( $token === 'endtag' ) {
2986 if ( $this->endSection() ) {
2987 $this->insertToken( $token, $value, $attribs, $selfclose );
2993 if ( $this->stack
->inTableScope( $value ) ) {
2994 $this->endSection();
3005 return true; // Ignore the token.
3009 return $this->inTableMode( $token, $value, $attribs, $selfclose );
3012 // Helper function for inRowMode
3013 private function endRow() {
3014 if ( !$this->stack
->inTableScope( 'tr' ) ) {
3017 $this->stack
->clearToContext( BalanceSets
::$tableRowContextSet );
3018 $this->stack
->pop();
3019 $this->switchMode( 'inTableBodyMode' );
3022 private function inRowMode( $token, $value, $attribs = null, $selfclose = false ) {
3023 if ( $token === 'tag' ) {
3027 $this->stack
->clearToContext( BalanceSets
::$tableRowContextSet );
3028 $this->stack
->insertHTMLElement( $value, $attribs );
3029 $this->switchMode( 'inCellMode' );
3030 $this->afe
->insertMarker();
3039 if ( $this->endRow() ) {
3040 $this->insertToken( $token, $value, $attribs, $selfclose );
3044 } elseif ( $token === 'endtag' ) {
3050 if ( $this->endRow() ) {
3051 $this->insertToken( $token, $value, $attribs, $selfclose );
3058 $this->stack
->inTableScope( $value ) &&
3061 $this->insertToken( $token, $value, $attribs, $selfclose );
3071 return true; // Ignore the token.
3075 return $this->inTableMode( $token, $value, $attribs, $selfclose );
3078 // Helper for inCellMode
3079 private function endCell() {
3080 if ( $this->stack
->inTableScope( 'td' ) ) {
3081 $this->inCellMode( 'endtag', 'td' );
3083 } elseif ( $this->stack
->inTableScope( 'th' ) ) {
3084 $this->inCellMode( 'endtag', 'th' );
3090 private function inCellMode( $token, $value, $attribs = null, $selfclose = false ) {
3091 if ( $token === 'tag' ) {
3102 if ( $this->endCell() ) {
3103 $this->insertToken( $token, $value, $attribs, $selfclose );
3107 } elseif ( $token === 'endtag' ) {
3111 if ( $this->stack
->inTableScope( $value ) ) {
3112 $this->stack
->generateImpliedEndTags();
3113 $this->stack
->popTag( $value );
3114 $this->afe
->clearToMarker();
3115 $this->switchMode( 'inRowMode' );
3130 if ( $this->stack
->inTableScope( $value ) ) {
3131 $this->stack
->generateImpliedEndTags();
3132 $this->stack
->popTag( BalanceSets
::$tableCellSet );
3133 $this->afe
->clearToMarker();
3134 $this->switchMode( 'inRowMode' );
3135 $this->insertToken( $token, $value, $attribs, $selfclose );
3141 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
3146 private function inSelectMode( $token, $value, $attribs = null, $selfclose = false ) {
3147 Assert::invariant( false, 'Unimplemented' );
3150 private function inSelectInTableMode( $token, $value, $attribs = null, $selfclose = false ) {
3151 Assert::invariant( false, 'Unimplemented' );
3155 private function inTemplateMode( $token, $value, $attribs = null, $selfclose = false ) {
3156 if ( $token === 'text' ) {
3157 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
3158 } elseif ( $token === 'eof' ) {
3159 if ( $this->stack
->indexOf( 'template' ) < 0 ) {
3160 $this->stopParsing();
3162 $this->stack
->popTag( 'template' );
3163 $this->afe
->clearToMarker();
3164 array_pop( $this->templateInsertionModes
);
3165 $this->resetInsertionMode();
3166 $this->insertToken( $token, $value, $attribs, $selfclose );
3169 } elseif ( $token === 'tag' ) {
3181 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
3188 return $this->switchModeAndReprocess(
3189 'inTableMode', $token, $value, $attribs, $selfclose
3193 return $this->switchModeAndReprocess(
3194 'inColumnGroupMode', $token, $value, $attribs, $selfclose
3198 return $this->switchModeAndReprocess(
3199 'inTableBodyMode', $token, $value, $attribs, $selfclose
3204 return $this->switchModeAndReprocess(
3205 'inRowMode', $token, $value, $attribs, $selfclose
3208 return $this->switchModeAndReprocess(
3209 'inBodyMode', $token, $value, $attribs, $selfclose
3211 } elseif ( $token === 'endtag' ) {
3214 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
3218 Assert
::invariant( false, "Bad token type: $token" );