3 * An implementation of the tree building portion of the HTML5 parsing
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
24 * @author C. Scott Ananian, 2016
26 namespace MediaWiki\Tidy
;
28 use Wikimedia\Assert\Assert
;
29 use Wikimedia\Assert\ParameterAssertionException
;
31 use \IteratorAggregate
;
32 use \ReverseArrayIterator
;
35 // A note for future librarization[1] -- this file is a good candidate
36 // for splitting into an independent library, except that it is currently
37 // highly optimized for MediaWiki use. It only implements the portions
38 // of the HTML5 tree builder used by tags supported by MediaWiki, and
39 // does not contain a true tokenizer pass, instead relying on
40 // comment stripping, attribute normalization, and escaping done by
41 // the MediaWiki Sanitizer. It also deliberately avoids building
42 // a true DOM in memory, instead serializing elements to an output string
43 // as soon as possible (usually as soon as the tag is closed) to reduce
44 // its memory footprint.
46 // We've been gradually lifting some of these restrictions to handle
47 // non-sanitized output generated by extensions, but we shortcut the tokenizer
48 // for speed (primarily by splitting on `<`) and so rely on syntactic
51 // On the other hand, I've been pretty careful to note with comments in the
52 // code the places where this implementation omits features of the spec or
53 // depends on the MediaWiki Sanitizer. Perhaps in the future we'll want to
54 // implement the missing pieces and make this a standalone PHP HTML5 parser.
55 // In order to do so, some sort of MediaWiki-specific API will need
56 // to be added to (a) allow the Balancer to bypass the tokenizer,
57 // and (b) support on-the-fly flattening instead of DOM node creation.
59 // [1]: https://www.mediawiki.org/wiki/Library_infrastructure_for_MediaWiki
62 * Utility constants and sets for the HTML5 tree building algorithm.
63 * Sets are associative arrays indexed first by namespace and then by
64 * lower-cased tag name.
70 const HTML_NAMESPACE
= 'http://www.w3.org/1999/xhtml';
71 const MATHML_NAMESPACE
= 'http://www.w3.org/1998/Math/MathML';
72 const SVG_NAMESPACE
= 'http://www.w3.org/2000/svg';
74 public static $unsupportedSet = [
75 self
::HTML_NAMESPACE
=> [
76 'html' => true, 'head' => true, 'body' => true, 'frameset' => true,
78 'plaintext' => true, 'isindex' => true,
79 'xmp' => true, 'iframe' => true, 'noembed' => true,
80 'noscript' => true, 'script' => true,
85 public static $emptyElementSet = [
86 self
::HTML_NAMESPACE
=> [
87 'area' => true, 'base' => true, 'basefont' => true,
88 'bgsound' => true, 'br' => true, 'col' => true, 'command' => true,
89 'embed' => true, 'frame' => true, 'hr' => true, 'img' => true,
90 'input' => true, 'keygen' => true, 'link' => true, 'meta' => true,
91 'param' => true, 'source' => true, 'track' => true, 'wbr' => true
95 public static $extraLinefeedSet = [
96 self
::HTML_NAMESPACE
=> [
97 'pre' => true, 'textarea' => true, 'listing' => true,
101 public static $headingSet = [
102 self
::HTML_NAMESPACE
=> [
103 'h1' => true, 'h2' => true, 'h3' => true,
104 'h4' => true, 'h5' => true, 'h6' => true
108 public static $specialSet = [
109 self
::HTML_NAMESPACE
=> [
110 'address' => true, 'applet' => true, 'area' => true,
111 'article' => true, 'aside' => true, 'base' => true,
112 'basefont' => true, 'bgsound' => true, 'blockquote' => true,
113 'body' => true, 'br' => true, 'button' => true, 'caption' => true,
114 'center' => true, 'col' => true, 'colgroup' => true, 'dd' => true,
115 'details' => true, 'dir' => true, 'div' => true, 'dl' => true,
116 'dt' => true, 'embed' => true, 'fieldset' => true,
117 'figcaption' => true, 'figure' => true, 'footer' => true,
118 'form' => true, 'frame' => true, 'frameset' => true, 'h1' => true,
119 'h2' => true, 'h3' => true, 'h4' => true, 'h5' => true,
120 'h6' => true, 'head' => true, 'header' => true, 'hgroup' => true,
121 'hr' => true, 'html' => true, 'iframe' => true, 'img' => true,
122 'input' => true, 'isindex' => true, 'li' => true, 'link' => true,
123 'listing' => true, 'main' => true, 'marquee' => true,
124 'menu' => true, 'menuitem' => true, 'meta' => true, 'nav' => true,
125 'noembed' => true, 'noframes' => true, 'noscript' => true,
126 'object' => true, 'ol' => true, 'p' => true, 'param' => true,
127 'plaintext' => true, 'pre' => true, 'script' => true,
128 'section' => true, 'select' => true, 'source' => true,
129 'style' => true, 'summary' => true, 'table' => true,
130 'tbody' => true, 'td' => true, 'template' => true,
131 'textarea' => true, 'tfoot' => true, 'th' => true, 'thead' => true,
132 'title' => true, 'tr' => true, 'track' => true, 'ul' => true,
133 'wbr' => true, 'xmp' => true
135 self
::SVG_NAMESPACE
=> [
136 'foreignobject' => true, 'desc' => true, 'title' => true
138 self
::MATHML_NAMESPACE
=> [
139 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
140 'mtext' => true, 'annotation-xml' => true
144 public static $addressDivPSet = [
145 self
::HTML_NAMESPACE
=> [
146 'address' => true, 'div' => true, 'p' => true
150 public static $tableSectionRowSet = [
151 self
::HTML_NAMESPACE
=> [
152 'table' => true, 'thead' => true, 'tbody' => true,
153 'tfoot' => true, 'tr' => true
157 public static $impliedEndTagsSet = [
158 self
::HTML_NAMESPACE
=> [
159 'dd' => true, 'dt' => true, 'li' => true, 'optgroup' => true,
160 'option' => true, 'p' => true, 'rb' => true, 'rp' => true,
161 'rt' => true, 'rtc' => true
165 public static $thoroughImpliedEndTagsSet = [
166 self
::HTML_NAMESPACE
=> [
167 'caption' => true, 'colgroup' => true, 'dd' => true, 'dt' => true,
168 'li' => true, 'optgroup' => true, 'option' => true, 'p' => true,
169 'rb' => true, 'rp' => true, 'rt' => true, 'rtc' => true,
170 'tbody' => true, 'td' => true, 'tfoot' => true, 'th' => true,
171 'thead' => true, 'tr' => true
175 public static $tableCellSet = [
176 self
::HTML_NAMESPACE
=> [
177 'td' => true, 'th' => true
180 public static $tableContextSet = [
181 self
::HTML_NAMESPACE
=> [
182 'table' => true, 'template' => true, 'html' => true
186 public static $tableBodyContextSet = [
187 self
::HTML_NAMESPACE
=> [
188 'tbody' => true, 'tfoot' => true, 'thead' => true,
189 'template' => true, 'html' => true
193 public static $tableRowContextSet = [
194 self
::HTML_NAMESPACE
=> [
195 'tr' => true, 'template' => true, 'html' => true
199 // See https://html.spec.whatwg.org/multipage/forms.html#form-associated-element
200 public static $formAssociatedSet = [
201 self
::HTML_NAMESPACE
=> [
202 'button' => true, 'fieldset' => true, 'input' => true,
203 'keygen' => true, 'object' => true, 'output' => true,
204 'select' => true, 'textarea' => true, 'img' => true
208 public static $inScopeSet = [
209 self
::HTML_NAMESPACE
=> [
210 'applet' => true, 'caption' => true, 'html' => true,
211 'marquee' => true, 'object' => true,
212 'table' => true, 'td' => true, 'template' => true,
215 self
::SVG_NAMESPACE
=> [
216 'foreignobject' => true, 'desc' => true, 'title' => true
218 self
::MATHML_NAMESPACE
=> [
219 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
220 'mtext' => true, 'annotation-xml' => true
224 private static $inListItemScopeSet = null;
225 public static function inListItemScopeSet() {
226 if ( self
::$inListItemScopeSet === null ) {
227 self
::$inListItemScopeSet = self
::$inScopeSet;
228 self
::$inListItemScopeSet[self
::HTML_NAMESPACE
]['ol'] = true;
229 self
::$inListItemScopeSet[self
::HTML_NAMESPACE
]['ul'] = true;
231 return self
::$inListItemScopeSet;
234 private static $inButtonScopeSet = null;
235 public static function inButtonScopeSet() {
236 if ( self
::$inButtonScopeSet === null ) {
237 self
::$inButtonScopeSet = self
::$inScopeSet;
238 self
::$inButtonScopeSet[self
::HTML_NAMESPACE
]['button'] = true;
240 return self
::$inButtonScopeSet;
243 public static $inTableScopeSet = [
244 self
::HTML_NAMESPACE
=> [
245 'html' => true, 'table' => true, 'template' => true
249 public static $inInvertedSelectScopeSet = [
250 self
::HTML_NAMESPACE
=> [
251 'option' => true, 'optgroup' => true
255 public static $mathmlTextIntegrationPointSet = [
256 self
::MATHML_NAMESPACE
=> [
257 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
262 public static $htmlIntegrationPointSet = [
263 self
::SVG_NAMESPACE
=> [
264 'foreignobject' => true,
270 // For tidy compatibility.
271 public static $tidyPWrapSet = [
272 self
::HTML_NAMESPACE
=> [
273 'body' => true, 'blockquote' => true,
274 // We parse with <body> as the fragment context, but the top-level
275 // element on the stack is actually <html>. We could use the
276 // "adjusted current node" everywhere to work around this, but it's
277 // easier just to add <html> to the p-wrap set.
281 public static $tidyInlineSet = [
282 self
::HTML_NAMESPACE
=> [
283 'a' => true, 'abbr' => true, 'acronym' => true, 'applet' => true,
284 'b' => true, 'basefont' => true, 'bdo' => true, 'big' => true,
285 'br' => true, 'button' => true, 'cite' => true, 'code' => true,
286 'dfn' => true, 'em' => true, 'font' => true, 'i' => true,
287 'iframe' => true, 'img' => true, 'input' => true, 'kbd' => true,
288 'label' => true, 'legend' => true, 'map' => true, 'object' => true,
289 'param' => true, 'q' => true, 'rb' => true, 'rbc' => true,
290 'rp' => true, 'rt' => true, 'rtc' => true, 'ruby' => true,
291 's' => true, 'samp' => true, 'select' => true, 'small' => true,
292 'span' => true, 'strike' => true, 'strong' => true, 'sub' => true,
293 'sup' => true, 'textarea' => true, 'tt' => true, 'u' => true,
300 * A BalanceElement is a simplified version of a DOM Node. The main
301 * difference is that we only keep BalanceElements around for nodes
302 * currently on the BalanceStack of open elements. As soon as an
303 * element is closed, with some minor exceptions relating to the
304 * tree builder "adoption agency algorithm", the element and all its
305 * children are serialized to a string using the flatten() method.
306 * This keeps our memory usage low.
311 class BalanceElement
{
313 * The namespace of the element.
314 * @var string $namespaceURI
316 public $namespaceURI;
318 * The lower-cased name of the element.
319 * @var string $localName
323 * Attributes for the element, in array form
324 * @var array $attribs
329 * Parent of this element, or the string "flat" if this element has
330 * already been flattened into its parent.
331 * @var BalanceElement|string|null $parent
336 * An array of children of this element. Typically only the last
337 * child will be an actual BalanceElement object; the rest will
338 * be strings, representing either text nodes or flattened
339 * BalanceElement objects.
340 * @var BalanceElement[]|string[] $children
345 * A unique string identifier for Noah's Ark purposes, lazy initialized
350 * The next active formatting element in the list, or null if this is the
351 * end of the AFE list or if the element is not in the AFE list.
356 * The previous active formatting element in the list, or null if this is
357 * the start of the list or if the element is not in the AFE list.
362 * The next element in the Noah's Ark species bucket.
367 * Make a new BalanceElement corresponding to the HTML DOM Element
368 * with the given localname, namespace, and attributes.
370 * @param string $namespaceURI The namespace of the element.
371 * @param string $localName The lowercased name of the tag.
372 * @param array $attribs Attributes of the element
374 public function __construct( $namespaceURI, $localName, array $attribs ) {
375 $this->localName
= $localName;
376 $this->namespaceURI
= $namespaceURI;
377 $this->attribs
= $attribs;
378 $this->contents
= '';
379 $this->parent
= null;
380 $this->children
= [];
384 * Remove the given child from this element.
385 * @param BalanceElement $elt
387 private function removeChild( BalanceElement
$elt ) {
388 Assert
::precondition(
389 $this->parent
!== 'flat', "Can't removeChild after flattening $this"
392 $elt->parent
=== $this, 'elt', 'must have $this as a parent'
394 $idx = array_search( $elt, $this->children
, true );
395 Assert
::parameter( $idx !== false, '$elt', 'must be a child of $this' );
397 array_splice( $this->children
, $idx, 1 );
401 * Find $a in the list of children and insert $b before it.
402 * @param BalanceElement $a
403 * @param BalanceElement|string $b
405 public function insertBefore( BalanceElement
$a, $b ) {
406 Assert
::precondition(
407 $this->parent
!== 'flat', "Can't insertBefore after flattening."
409 $idx = array_search( $a, $this->children
, true );
410 Assert
::parameter( $idx !== false, '$a', 'must be a child of $this' );
411 if ( is_string( $b ) ) {
412 array_splice( $this->children
, $idx, 0, [ $b ] );
414 Assert
::parameter( $b->parent
!== 'flat', '$b', "Can't be flat" );
415 if ( $b->parent
!== null ) {
416 $b->parent
->removeChild( $b );
418 array_splice( $this->children
, $idx, 0, [ $b ] );
424 * Append $elt to the end of the list of children.
425 * @param BalanceElement|string $elt
427 public function appendChild( $elt ) {
428 Assert
::precondition(
429 $this->parent
!== 'flat', "Can't appendChild after flattening."
431 if ( is_string( $elt ) ) {
432 array_push( $this->children
, $elt );
435 // Remove $elt from parent, if it had one.
436 if ( $elt->parent
!== null ) {
437 $elt->parent
->removeChild( $elt );
439 array_push( $this->children
, $elt );
440 $elt->parent
= $this;
444 * Transfer all of the children of $elt to $this.
445 * @param BalanceElement $elt
447 public function adoptChildren( BalanceElement
$elt ) {
448 Assert
::precondition(
449 $elt->parent
!== 'flat', "Can't adoptChildren after flattening."
451 foreach ( $elt->children
as $child ) {
452 if ( !is_string( $child ) ) {
453 // This is an optimization which avoids an O(n^2) set of
454 // array_splice operations.
455 $child->parent
= null;
457 $this->appendChild( $child );
463 * Flatten this node and all of its children into a string, as specified
464 * by the HTML serialization specification, and replace this node
465 * in its parent by that string.
467 * @param array $config Balancer configuration; see Balancer::__construct().
472 public function flatten( array $config ) {
473 Assert
::parameter( $this->parent
!== null, '$this', 'must be a child' );
474 Assert
::parameter( $this->parent
!== 'flat', '$this', 'already flat' );
475 $idx = array_search( $this, $this->parent
->children
, true );
477 $idx !== false, '$this', 'must be a child of its parent'
479 $tidyCompat = $config['tidyCompat'];
482 foreach ( $this->children
as $elt ) {
483 if ( !is_string( $elt ) ) {
484 $elt = $elt->flatten( $config );
486 if ( $blank && preg_match( '/[^\t\n\f\r ]/', $elt ) ) {
490 if ( $this->isHtmlNamed( 'mw:p-wrap' ) ) {
491 $this->localName
= 'p';
492 } elseif ( $blank ) {
493 // Add 'mw-empty-elt' class so elements can be hidden via CSS
494 // for compatibility with legacy tidy.
495 if ( !count( $this->attribs
) &&
496 ( $this->localName
=== 'tr' ||
$this->localName
=== 'li' )
498 $this->attribs
= [ 'class' => "mw-empty-elt" ];
502 $flat = $blank ?
'' : "{$this}";
506 $this->parent
->children
[$idx] = $flat;
507 $this->parent
= 'flat'; // for assertion checking
512 * Serialize this node and all of its children to a string, as specified
513 * by the HTML serialization specification.
515 * @return string The serialization of the BalanceElement
516 * @see https://html.spec.whatwg.org/multipage/syntax.html#serialising-html-fragments
518 public function __toString() {
520 foreach ( $this->attribs
as $name => $value ) {
521 $encValue = Sanitizer
::encodeAttribute( $value );
522 $encAttribs .= " $name=\"$encValue\"";
524 if ( !$this->isA( BalanceSets
::$emptyElementSet ) ) {
525 $out = "<{$this->localName}{$encAttribs}>";
526 $len = strlen( $out );
528 foreach ( $this->children
as $elt ) {
531 $out .= "</{$this->localName}>";
533 $this->isA( BalanceSets
::$extraLinefeedSet ) &&
536 // Double the linefeed after pre/listing/textarea
537 // according to the HTML5 fragment serialization algorithm.
538 $out = substr( $out, 0, $len +
1 ) .
539 substr( $out, $len );
542 $out = "<{$this->localName}{$encAttribs} />";
544 count( $this->children
) === 0,
545 "Empty elements shouldn't have children."
551 // Utility functions on BalanceElements.
554 * Determine if $this represents a specific HTML tag, is a member of
555 * a tag set, or is equal to another BalanceElement.
557 * @param BalanceElement|array|string $set The target BalanceElement,
558 * set (from the BalanceSets class), or string (HTML tag name).
561 public function isA( $set ) {
562 if ( $set instanceof BalanceElement
) {
563 return $this === $set;
564 } elseif ( is_array( $set ) ) {
565 return isset( $set[$this->namespaceURI
] ) &&
566 isset( $set[$this->namespaceURI
][$this->localName
] );
568 // assume this is an HTML element name.
569 return $this->isHtml() && $this->localName
=== $set;
574 * Determine if this element is an HTML element with the specified name
575 * @param string $tagName
578 public function isHtmlNamed( $tagName ) {
579 return $this->namespaceURI
=== BalanceSets
::HTML_NAMESPACE
580 && $this->localName
=== $tagName;
584 * Determine if $this represents an element in the HTML namespace.
588 public function isHtml() {
589 return $this->namespaceURI
=== BalanceSets
::HTML_NAMESPACE
;
593 * Determine if $this represents a MathML text integration point,
594 * as defined in the HTML5 specification.
597 * @see https://html.spec.whatwg.org/multipage/syntax.html#mathml-text-integration-point
599 public function isMathmlTextIntegrationPoint() {
600 return $this->isA( BalanceSets
::$mathmlTextIntegrationPointSet );
604 * Determine if $this represents an HTML integration point,
605 * as defined in the HTML5 specification.
608 * @see https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
610 public function isHtmlIntegrationPoint() {
611 if ( $this->isA( BalanceSets
::$htmlIntegrationPointSet ) ) {
615 $this->namespaceURI
=== BalanceSets
::MATHML_NAMESPACE
&&
616 $this->localName
=== 'annotation-xml' &&
617 isset( $this->attribs
['encoding'] ) &&
618 ( strcasecmp( $this->attribs
['encoding'], 'text/html' ) == 0 ||
619 strcasecmp( $this->attribs
['encoding'], 'application/xhtml+xml' ) == 0 )
627 * Get a string key for the Noah's Ark algorithm
629 public function getNoahKey() {
630 if ( $this->noahKey
=== null ) {
631 $attribs = $this->attribs
;
633 $this->noahKey
= serialize( [ $this->namespaceURI
, $this->localName
, $attribs ] );
635 return $this->noahKey
;
640 * The "stack of open elements" as defined in the HTML5 tree builder
641 * spec. This contains methods to ensure that content (start tags, text)
642 * are inserted at the correct place in the output string, and to
643 * flatten BalanceElements are they are closed to avoid holding onto
644 * a complete DOM tree for the document in memory.
646 * The stack defines a PHP iterator to traverse it in "reverse order",
647 * that is, the most-recently-added element is visited first in a
652 * @see https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements
654 class BalanceStack
implements IteratorAggregate
{
656 * Backing storage for the stack.
657 * @var BalanceElement[] $elements
659 private $elements = [];
661 * Foster parent mode determines how nodes are inserted into the
663 * @var bool $fosterParentMode
664 * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
666 public $fosterParentMode = false;
668 * Configuration options governing flattening.
670 * @see Balancer::__construct()
674 * Reference to the current element
679 * Create a new BalanceStack with a single BalanceElement on it,
680 * representing the root <html> node.
681 * @param array $config Balancer configuration; see Balancer::_construct().
683 public function __construct( array $config ) {
684 // always a root <html> element on the stack
687 new BalanceElement( BalanceSets
::HTML_NAMESPACE
, 'html', [] )
689 $this->currentNode
= $this->elements
[0];
690 $this->config
= $config;
694 * Return a string representing the output of the tree builder:
695 * all the children of the root <html> node.
698 public function getOutput() {
699 // Don't include the outer '<html>....</html>'
701 foreach ( $this->elements
[0]->children
as $elt ) {
702 $out .= is_string( $elt ) ?
$elt :
703 $elt->flatten( $this->config
);
709 * Insert a comment at the appropriate place for inserting a node.
710 * @param string $value Content of the comment.
711 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-a-comment
713 public function insertComment( $value ) {
714 // Just another type of text node, except for tidy p-wrapping.
715 return $this->insertText( '<!--' . $value . '-->', true );
719 * Insert text at the appropriate place for inserting a node.
720 * @param string $value
721 * @param bool $isComment
722 * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
724 public function insertText( $value, $isComment = false ) {
726 $this->fosterParentMode
&&
727 $this->currentNode
->isA( BalanceSets
::$tableSectionRowSet )
729 $this->fosterParent( $value );
731 $this->config
['tidyCompat'] && !$isComment &&
732 $this->currentNode
->isA( BalanceSets
::$tidyPWrapSet )
734 $this->insertHTMLElement( 'mw:p-wrap', [] );
735 return $this->insertText( $value );
737 $this->currentNode
->appendChild( $value );
742 * Insert a BalanceElement at the appropriate place, pushing it
743 * on to the open elements stack.
744 * @param string $namespaceURI The element namespace
745 * @param string $tag The tag name
746 * @param string $attribs Normalized attributes, as a string.
747 * @return BalanceElement
748 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-a-foreign-element
750 public function insertForeignElement( $namespaceURI, $tag, $attribs ) {
751 return $this->insertElement(
752 new BalanceElement( $namespaceURI, $tag, $attribs )
757 * Insert an HTML element at the appropriate place, pushing it on to
758 * the open elements stack.
759 * @param string $tag The tag name
760 * @param string $attribs Normalized attributes, as a string.
761 * @return BalanceElement
762 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-an-html-element
764 public function insertHTMLElement( $tag, $attribs ) {
765 return $this->insertForeignElement(
766 BalanceSets
::HTML_NAMESPACE
, $tag, $attribs
771 * Insert an element at the appropriate place and push it on to the
772 * open elements stack.
773 * @param BalanceElement $elt
774 * @return BalanceElement
775 * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
777 public function insertElement( BalanceElement
$elt ) {
779 $this->currentNode
->isHtmlNamed( 'mw:p-wrap' ) &&
780 !$elt->isA( BalanceSets
::$tidyInlineSet )
782 // Tidy compatibility.
786 $this->fosterParentMode
&&
787 $this->currentNode
->isA( BalanceSets
::$tableSectionRowSet )
789 $elt = $this->fosterParent( $elt );
791 $this->currentNode
->appendChild( $elt );
793 Assert
::invariant( $elt->parent
!== null, "$elt must be in tree" );
794 Assert
::invariant( $elt->parent
!== 'flat', "$elt must not have been previous flattened" );
795 array_push( $this->elements
, $elt );
796 $this->currentNode
= $elt;
801 * Determine if the stack has $tag in scope.
802 * @param BalanceElement|array|string $tag
804 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
806 public function inScope( $tag ) {
807 return $this->inSpecificScope( $tag, BalanceSets
::$inScopeSet );
811 * Determine if the stack has $tag in button scope.
812 * @param BalanceElement|array|string $tag
814 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
816 public function inButtonScope( $tag ) {
817 return $this->inSpecificScope( $tag, BalanceSets
::inButtonScopeSet() );
821 * Determine if the stack has $tag in list item scope.
822 * @param BalanceElement|array|string $tag
824 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-list-item-scope
826 public function inListItemScope( $tag ) {
827 return $this->inSpecificScope( $tag, BalanceSets
::inListItemScopeSet() );
831 * Determine if the stack has $tag in table scope.
832 * @param BalanceElement|array|string $tag
834 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-table-scope
836 public function inTableScope( $tag ) {
837 return $this->inSpecificScope( $tag, BalanceSets
::$inTableScopeSet );
841 * Determine if the stack has $tag in select scope.
842 * @param BalanceElement|array|string $tag
844 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-select-scope
846 public function inSelectScope( $tag ) {
847 // Can't use inSpecificScope to implement this, since it involves
848 // *inverting* a set of tags. Implement manually.
849 foreach ( $this as $elt ) {
850 if ( $elt->isA( $tag ) ) {
853 if ( !$elt->isA( BalanceSets
::$inInvertedSelectScopeSet ) ) {
861 * Determine if the stack has $tag in a specific scope, $set.
862 * @param BalanceElement|array|string $tag
863 * @param BalanceElement|array|string $set
865 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-the-specific-scope
867 public function inSpecificScope( $tag, $set ) {
868 foreach ( $this as $elt ) {
869 if ( $elt->isA( $tag ) ) {
872 if ( $elt->isA( $set ) ) {
880 * Generate implied end tags.
881 * @param string $butnot
882 * @param bool $thorough True if we should generate end tags thoroughly.
883 * @see https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
885 public function generateImpliedEndTags( $butnot = null, $thorough = false ) {
886 $endTagSet = $thorough ?
887 BalanceSets
::$thoroughImpliedEndTagsSet :
888 BalanceSets
::$impliedEndTagsSet;
889 while ( $this->currentNode
) {
890 if ( $butnot !== null && $this->currentNode
->isHtmlNamed( $butnot ) ) {
893 if ( !$this->currentNode
->isA( $endTagSet ) ) {
901 * Return the adjusted current node.
903 public function adjustedCurrentNode( $fragmentContext ) {
904 return ( $fragmentContext && count( $this->elements
) === 1 ) ?
905 $fragmentContext : $this->currentNode
;
909 * Return an iterator over this stack which visits the current node
910 * first, and the root node last.
913 public function getIterator() {
914 return new ReverseArrayIterator( $this->elements
);
918 * Return the BalanceElement at the given position $idx, where
919 * position 0 represents the root element.
921 * @return BalanceElement
923 public function node( $idx ) {
924 return $this->elements
[ $idx ];
928 * Replace the element at position $idx in the BalanceStack with $elt.
930 * @param BalanceElement $elt
932 public function replaceAt( $idx, BalanceElement
$elt ) {
933 Assert
::precondition(
934 $this->elements
[$idx]->parent
!== 'flat',
935 'Replaced element should not have already been flattened.'
937 Assert
::precondition(
938 $elt->parent
!== 'flat',
939 'New element should not have already been flattened.'
941 $this->elements
[$idx] = $elt;
942 if ( $idx === count( $this->elements
) - 1 ) {
943 $this->currentNode
= $elt;
948 * Return the position of the given BalanceElement, set, or
949 * HTML tag name string in the BalanceStack.
950 * @param BalanceElement|array|string $tag
953 public function indexOf( $tag ) {
954 for ( $i = count( $this->elements
) - 1; $i >= 0; $i-- ) {
955 if ( $this->elements
[$i]->isA( $tag ) ) {
963 * Return the number of elements currently in the BalanceStack.
966 public function length() {
967 return count( $this->elements
);
971 * Remove the current node from the BalanceStack, flattening it
974 public function pop() {
975 $elt = array_pop( $this->elements
);
976 if ( count( $this->elements
) ) {
977 $this->currentNode
= $this->elements
[ count( $this->elements
) - 1 ];
979 $this->currentNode
= null;
981 if ( !$elt->isHtmlNamed( 'mw:p-wrap' ) ) {
982 $elt->flatten( $this->config
);
987 * Remove all nodes up to and including position $idx from the
988 * BalanceStack, flattening them in the process.
991 public function popTo( $idx ) {
992 for ( $length = count( $this->elements
); $length > $idx; $length-- ) {
998 * Pop elements off the stack up to and including the first
999 * element with the specified HTML tagname (or matching the given
1001 * @param BalanceElement|array|string $tag
1003 public function popTag( $tag ) {
1004 while ( $this->currentNode
) {
1005 if ( $this->currentNode
->isA( $tag ) ) {
1014 * Pop elements off the stack *not including* the first element
1015 * in the specified set.
1016 * @param BalanceElement|array|string $set
1018 public function clearToContext( $set ) {
1019 // Note that we don't loop to 0. Never pop the <html> elt off.
1020 for ( $length = count( $this->elements
); $length > 1; $length-- ) {
1021 if ( $this->currentNode
->isA( $set ) ) {
1029 * Remove the given $elt from the BalanceStack, optionally
1030 * flattening it in the process.
1031 * @param BalanceElement $elt The element to remove.
1032 * @param bool $flatten Whether to flatten the removed element.
1034 public function removeElement( BalanceElement
$elt, $flatten = true ) {
1036 $elt->parent
!== 'flat',
1038 '$elt should not already have been flattened.'
1041 $elt->parent
->parent
!== 'flat',
1043 'The parent of $elt should not already have been flattened.'
1045 $idx = array_search( $elt, $this->elements
, true );
1046 Assert
::parameter( $idx !== false, '$elt', 'must be in stack' );
1047 array_splice( $this->elements
, $idx, 1 );
1048 if ( $idx === count( $this->elements
) ) {
1049 $this->currentNode
= $this->elements
[$idx - 1];
1052 // serialize $elt into its parent
1053 // otherwise, it will eventually serialize when the parent
1054 // is serialized, we just hold onto the memory for its
1055 // tree of objects a little longer.
1056 $elt->flatten( $this->config
);
1058 Assert
::postcondition(
1059 array_search( $elt, $this->elements
, true ) === false,
1060 '$elt should no longer be in open elements stack'
1065 * Find $a in the BalanceStack and insert $b after it.
1066 * @param BalanceElement $a
1067 * @param BalanceElement $b
1069 public function insertAfter( BalanceElement
$a, BalanceElement
$b ) {
1070 $idx = $this->indexOf( $a );
1071 Assert
::parameter( $idx !== false, '$a', 'must be in stack' );
1072 if ( $idx === count( $this->elements
) - 1 ) {
1073 array_push( $this->elements
, $b );
1074 $this->currentNode
= $b;
1076 array_splice( $this->elements
, $idx +
1, 0, [ $b ] );
1080 // Fostering and adoption.
1083 * Foster parent the given $elt in the stack of open elements.
1084 * @param BalanceElement|string $elt
1085 * @return BalanceElement|string
1087 * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
1089 private function fosterParent( $elt ) {
1090 $lastTable = $this->indexOf( 'table' );
1091 $lastTemplate = $this->indexOf( 'template' );
1095 if ( $lastTemplate >= 0 && ( $lastTable < 0 ||
$lastTemplate > $lastTable ) ) {
1096 $parent = $this->elements
[$lastTemplate];
1097 } elseif ( $lastTable >= 0 ) {
1098 $parent = $this->elements
[$lastTable]->parent
;
1099 // Assume all tables have parents, since we're not running scripts!
1101 $parent !== null, "All tables should have parents"
1103 $before = $this->elements
[$lastTable];
1105 $parent = $this->elements
[0]; // the `html` element.
1108 if ( $this->config
['tidyCompat'] ) {
1109 if ( is_string( $elt ) ) {
1110 // We're fostering text: do we need a p-wrapper?
1111 if ( $parent->isA( BalanceSets
::$tidyPWrapSet ) ) {
1112 $this->insertHTMLElement( 'mw:p-wrap', [] );
1113 $this->insertText( $elt );
1117 // We're fostering an element; do we need to merge p-wrappers?
1118 if ( $elt->isHtmlNamed( 'mw:p-wrap' ) ) {
1120 array_search( $before, $parent->children
, true ) :
1121 count( $parent->children
);
1122 $after = $idx > 0 ?
$parent->children
[$idx - 1] : '';
1124 $after instanceof BalanceElement
&&
1125 $after->isHtmlNamed( 'mw:p-wrap' )
1127 return $after; // Re-use existing p-wrapper.
1134 $parent->insertBefore( $before, $elt );
1136 $parent->appendChild( $elt );
1142 * Run the "adoption agency algoritm" (AAA) for the given subject
1144 * @param string $tag The subject tag name.
1145 * @param BalanceActiveFormattingElements $afe The current
1146 * active formatting elements list.
1147 * @return true if the adoption agency algorithm "did something", false
1148 * if more processing is required by the caller.
1149 * @see https://html.spec.whatwg.org/multipage/syntax.html#adoption-agency-algorithm
1151 public function adoptionAgency( $tag, $afe ) {
1152 // If the current node is an HTML element whose tag name is subject,
1153 // and the current node is not in the list of active formatting
1154 // elements, then pop the current node off the stack of open
1155 // elements and abort these steps.
1157 $this->currentNode
->isHtmlNamed( $tag ) &&
1158 !$afe->isInList( $this->currentNode
)
1161 return true; // no more handling required
1164 // Outer loop: If outer loop counter is greater than or
1165 // equal to eight, then abort these steps.
1166 for ( $outer = 0; $outer < 8; $outer++
) {
1167 // Let the formatting element be the last element in the list
1168 // of active formatting elements that: is between the end of
1169 // the list and the last scope marker in the list, if any, or
1170 // the start of the list otherwise, and has the same tag name
1172 $fmtElt = $afe->findElementByTag( $tag );
1174 // If there is no such node, then abort these steps and instead
1175 // act as described in the "any other end tag" entry below.
1177 return false; // false means handle by the default case
1180 // Otherwise, if there is such a node, but that node is not in
1181 // the stack of open elements, then this is a parse error;
1182 // remove the element from the list, and abort these steps.
1183 $index = $this->indexOf( $fmtElt );
1185 $afe->remove( $fmtElt );
1186 return true; // true means no more handling required
1189 // Otherwise, if there is such a node, and that node is also in
1190 // the stack of open elements, but the element is not in scope,
1191 // then this is a parse error; ignore the token, and abort
1193 if ( !$this->inScope( $fmtElt ) ) {
1197 // Let the furthest block be the topmost node in the stack of
1198 // open elements that is lower in the stack than the formatting
1199 // element, and is an element in the special category. There
1200 // might not be one.
1201 $furthestBlock = null;
1202 $furthestBlockIndex = -1;
1203 $stackLength = $this->length();
1204 for ( $i = $index+
1; $i < $stackLength; $i++
) {
1205 if ( $this->node( $i )->isA( BalanceSets
::$specialSet ) ) {
1206 $furthestBlock = $this->node( $i );
1207 $furthestBlockIndex = $i;
1212 // If there is no furthest block, then the UA must skip the
1213 // subsequent steps and instead just pop all the nodes from the
1214 // bottom of the stack of open elements, from the current node
1215 // up to and including the formatting element, and remove the
1216 // formatting element from the list of active formatting
1218 if ( !$furthestBlock ) {
1219 $this->popTag( $fmtElt );
1220 $afe->remove( $fmtElt );
1224 // Let the common ancestor be the element immediately above
1225 // the formatting element in the stack of open elements.
1226 $ancestor = $this->node( $index-1 );
1228 // Let a bookmark note the position of the formatting
1229 // element in the list of active formatting elements
1230 // relative to the elements on either side of it in the
1232 $BOOKMARK = new BalanceElement( '[bookmark]', '[bookmark]', [] );
1233 $afe->insertAfter( $fmtElt, $BOOKMARK );
1235 // Let node and last node be the furthest block.
1236 $node = $furthestBlock;
1237 $lastNode = $furthestBlock;
1238 $nodeIndex = $furthestBlockIndex;
1242 for ( $inner = 1; true; $inner++
) {
1243 // Let node be the element immediately above node in
1244 // the stack of open elements, or if node is no longer
1245 // in the stack of open elements (e.g. because it got
1246 // removed by this algorithm), the element that was
1247 // immediately above node in the stack of open elements
1248 // before node was removed.
1249 $node = $this->node( --$nodeIndex );
1251 // If node is the formatting element, then go
1252 // to the next step in the overall algorithm.
1253 if ( $node === $fmtElt ) break;
1255 // If the inner loop counter is greater than three and node
1256 // is in the list of active formatting elements, then remove
1257 // node from the list of active formatting elements.
1258 $isAFE = $afe->isInList( $node );
1259 if ( $inner > 3 && $isAFE ) {
1260 $afe->remove( $node );
1264 // If node is not in the list of active formatting
1265 // elements, then remove node from the stack of open
1266 // elements and then go back to the step labeled inner
1269 // Don't flatten here, since we're about to relocate
1270 // parts of this $node.
1271 $this->removeElement( $node, false );
1275 // Create an element for the token for which the
1276 // element node was created with common ancestor as
1277 // the intended parent, replace the entry for node
1278 // in the list of active formatting elements with an
1279 // entry for the new element, replace the entry for
1280 // node in the stack of open elements with an entry for
1281 // the new element, and let node be the new element.
1282 $newElt = new BalanceElement(
1283 $node->namespaceURI
, $node->localName
, $node->attribs
);
1284 $afe->replace( $node, $newElt );
1285 $this->replaceAt( $nodeIndex, $newElt );
1288 // If last node is the furthest block, then move the
1289 // aforementioned bookmark to be immediately after the
1290 // new node in the list of active formatting elements.
1291 if ( $lastNode === $furthestBlock ) {
1292 $afe->remove( $BOOKMARK );
1293 $afe->insertAfter( $newElt, $BOOKMARK );
1296 // Insert last node into node, first removing it from
1297 // its previous parent node if any.
1298 $node->appendChild( $lastNode );
1300 // Let last node be node.
1304 // If the common ancestor node is a table, tbody, tfoot,
1305 // thead, or tr element, then, foster parent whatever last
1306 // node ended up being in the previous step, first removing
1307 // it from its previous parent node if any.
1309 $this->fosterParentMode
&&
1310 $ancestor->isA( BalanceSets
::$tableSectionRowSet )
1312 $this->fosterParent( $lastNode );
1314 // Otherwise, append whatever last node ended up being in
1315 // the previous step to the common ancestor node, first
1316 // removing it from its previous parent node if any.
1317 $ancestor->appendChild( $lastNode );
1320 // Create an element for the token for which the
1321 // formatting element was created, with furthest block
1322 // as the intended parent.
1323 $newElt2 = new BalanceElement(
1324 $fmtElt->namespaceURI
, $fmtElt->localName
, $fmtElt->attribs
);
1326 // Take all of the child nodes of the furthest block and
1327 // append them to the element created in the last step.
1328 $newElt2->adoptChildren( $furthestBlock );
1330 // Append that new element to the furthest block.
1331 $furthestBlock->appendChild( $newElt2 );
1333 // Remove the formatting element from the list of active
1334 // formatting elements, and insert the new element into the
1335 // list of active formatting elements at the position of
1336 // the aforementioned bookmark.
1337 $afe->remove( $fmtElt );
1338 $afe->replace( $BOOKMARK, $newElt2 );
1340 // Remove the formatting element from the stack of open
1341 // elements, and insert the new element into the stack of
1342 // open elements immediately below the position of the
1343 // furthest block in that stack.
1344 $this->removeElement( $fmtElt );
1345 $this->insertAfter( $furthestBlock, $newElt2 );
1352 * Return the contents of the open elements stack as a string for
1356 public function __toString() {
1358 foreach ( $this->elements
as $elt ) {
1359 array_push( $r, $elt->localName
);
1361 return implode( $r, ' ' );
1366 * A pseudo-element used as a marker in the list of active formatting elements
1371 class BalanceMarker
{
1377 * The list of active formatting elements, which is used to handle
1378 * mis-nested formatting element tags in the HTML5 tree builder
1383 * @see https://html.spec.whatwg.org/multipage/syntax.html#list-of-active-formatting-elements
1385 class BalanceActiveFormattingElements
{
1386 /** The last (most recent) element in the list */
1389 /** The first (least recent) element in the list */
1393 * An array of arrays representing the population of elements in each bucket
1394 * according to the Noah's Ark clause. The outer array is stack-like, with each
1395 * integer-indexed element representing a segment of the list, bounded by
1396 * markers. The first element represents the segment of the list before the
1399 * The inner arrays are indexed by "Noah key", which is a string which uniquely
1400 * identifies each bucket according to the rules in the spec. The value in
1401 * the inner array is the first (least recently inserted) element in the bucket,
1402 * and subsequent members of the bucket can be found by iterating through the
1403 * singly-linked list via $node->nextNoah.
1405 * This is optimised for the most common case of inserting into a bucket
1406 * with zero members, and deleting a bucket containing one member. In the
1407 * worst case, iteration through the list is still O(1) in the document
1408 * size, since each bucket can have at most 3 members.
1410 private $noahTableStack = [ [] ];
1412 public function __destruct() {
1413 for ( $node = $this->head
; $node; $node = $next ) {
1414 $next = $node->nextAFE
;
1415 $node->prevAFE
= $node->nextAFE
= $node->nextNoah
= null;
1417 $this->head
= $this->tail
= $this->noahTableStack
= null;
1420 public function insertMarker() {
1421 $elt = new BalanceMarker
;
1422 if ( $this->tail
) {
1423 $this->tail
->nextAFE
= $elt;
1424 $elt->prevAFE
= $this->tail
;
1429 $this->noahTableStack
[] = [];
1433 * Follow the steps required when the spec requires us to "push onto the
1434 * list of active formatting elements".
1435 * @param BalanceElement $elt
1437 public function push( BalanceElement
$elt ) {
1438 // Must not be in the list already
1439 if ( $elt->prevAFE
!== null ||
$this->head
=== $elt ) {
1440 throw new ParameterAssertionException( '$elt',
1441 'Cannot insert a node into the AFE list twice' );
1444 // "Noah's Ark clause" -- if there are already three copies of
1445 // this element before we encounter a marker, then drop the last
1447 $noahKey = $elt->getNoahKey();
1448 $table =& $this->noahTableStack
[ count( $this->noahTableStack
) - 1 ];
1449 if ( !isset( $table[$noahKey] ) ) {
1450 $table[$noahKey] = $elt;
1453 $head = $tail = $table[$noahKey];
1454 while ( $tail->nextNoah
) {
1455 $tail = $tail->nextNoah
;
1458 if ( $count >= 3 ) {
1459 $this->remove( $head );
1461 $tail->nextNoah
= $elt;
1463 // Add to the main AFE list
1464 if ( $this->tail
) {
1465 $this->tail
->nextAFE
= $elt;
1466 $elt->prevAFE
= $this->tail
;
1474 * Follow the steps required when the spec asks us to "clear the list of
1475 * active formatting elements up to the last marker".
1477 public function clearToMarker() {
1478 // Iterate back through the list starting from the tail
1479 $tail = $this->tail
;
1480 while ( $tail && !( $tail instanceof BalanceMarker
) ) {
1481 // Unlink the element
1482 $prev = $tail->prevAFE
;
1483 $tail->prevAFE
= null;
1485 $prev->nextAFE
= null;
1487 $tail->nextNoah
= null;
1490 // If we finished on a marker, unlink it and pop it off the Noah table stack
1492 $prev = $tail->prevAFE
;
1494 $prev->nextAFE
= null;
1497 array_pop( $this->noahTableStack
);
1499 // No marker: wipe the top-level Noah table (which is the only one)
1500 $this->noahTableStack
[0] = [];
1502 // If we removed all the elements, clear the head pointer
1506 $this->tail
= $tail;
1510 * Find and return the last element with the specified tag between the
1511 * end of the list and the last marker on the list.
1512 * Used when parsing <a> "in body mode".
1514 public function findElementByTag( $tag ) {
1516 while ( $elt && !( $elt instanceof BalanceMarker
) ) {
1517 if ( $elt->localName
=== $tag ) {
1520 $elt = $elt->prevAFE
;
1526 * Determine whether an element is in the list of formatting elements.
1527 * @param BalanceElement $elt
1530 public function isInList( BalanceElement
$elt ) {
1531 return $this->head
=== $elt ||
$elt->prevAFE
;
1535 * Find the element $elt in the list and remove it.
1536 * Used when parsing <a> in body mode.
1538 * @param BalanceElement $elt
1540 public function remove( BalanceElement
$elt ) {
1541 if ( $this->head
!== $elt && !$elt->prevAFE
) {
1542 throw new ParameterAssertionException( '$elt',
1543 "Attempted to remove an element which is not in the AFE list" );
1545 // Update head and tail pointers
1546 if ( $this->head
=== $elt ) {
1547 $this->head
= $elt->nextAFE
;
1549 if ( $this->tail
=== $elt ) {
1550 $this->tail
= $elt->prevAFE
;
1552 // Update previous element
1553 if ( $elt->prevAFE
) {
1554 $elt->prevAFE
->nextAFE
= $elt->nextAFE
;
1556 // Update next element
1557 if ( $elt->nextAFE
) {
1558 $elt->nextAFE
->prevAFE
= $elt->prevAFE
;
1560 // Clear pointers so that isInList() etc. will work
1561 $elt->prevAFE
= $elt->nextAFE
= null;
1563 $this->removeFromNoahList( $elt );
1566 private function addToNoahList( BalanceElement
$elt ) {
1567 $noahKey = $elt->getNoahKey();
1568 $table =& $this->noahTableStack
[ count( $this->noahTableStack
) - 1 ];
1569 if ( !isset( $table[$noahKey] ) ) {
1570 $table[$noahKey] = $elt;
1572 $tail = $table[$noahKey];
1573 while ( $tail->nextNoah
) {
1574 $tail = $tail->nextNoah
;
1576 $tail->nextNoah
= $elt;
1580 private function removeFromNoahList( BalanceElement
$elt ) {
1581 $table =& $this->noahTableStack
[ count( $this->noahTableStack
) - 1 ];
1582 $key = $elt->getNoahKey();
1583 $noahElt = $table[$key];
1584 if ( $noahElt === $elt ) {
1585 if ( $noahElt->nextNoah
) {
1586 $table[$key] = $noahElt->nextNoah
;
1587 $noahElt->nextNoah
= null;
1589 unset( $table[$key] );
1593 $prevNoahElt = $noahElt;
1594 $noahElt = $prevNoahElt->nextNoah
;
1595 if ( $noahElt === $elt ) {
1597 $prevNoahElt->nextNoah
= $elt->nextNoah
;
1598 $elt->nextNoah
= null;
1601 } while ( $noahElt );
1606 * Find element $a in the list and replace it with element $b
1608 * @param BalanceElement $a
1609 * @param BalanceElement $b
1611 public function replace( BalanceElement
$a, BalanceElement
$b ) {
1612 if ( $this->head
!== $a && !$a->prevAFE
) {
1613 throw new ParameterAssertionException( '$a',
1614 "Attempted to replace an element which is not in the AFE list" );
1616 // Update head and tail pointers
1617 if ( $this->head
=== $a ) {
1620 if ( $this->tail
=== $a ) {
1623 // Update previous element
1624 if ( $a->prevAFE
) {
1625 $a->prevAFE
->nextAFE
= $b;
1627 // Update next element
1628 if ( $a->nextAFE
) {
1629 $a->nextAFE
->prevAFE
= $b;
1631 $b->prevAFE
= $a->prevAFE
;
1632 $b->nextAFE
= $a->nextAFE
;
1633 $a->nextAFE
= $a->prevAFE
= null;
1635 $this->removeFromNoahList( $a );
1636 $this->addToNoahList( $b );
1640 * Find $a in the list and insert $b after it.
1642 * @param BalanceElement $a
1643 * @param BalanceElement $b
1645 public function insertAfter( BalanceElement
$a, BalanceElement
$b ) {
1646 if ( $this->head
!== $a && !$a->prevAFE
) {
1647 throw new ParameterAssertionException( '$a',
1648 "Attempted to insert after an element which is not in the AFE list" );
1650 if ( $this->tail
=== $a ) {
1653 if ( $a->nextAFE
) {
1654 $a->nextAFE
->prevAFE
= $b;
1656 $b->nextAFE
= $a->nextAFE
;
1659 $this->addToNoahList( $b );
1662 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
1664 * Reconstruct the active formatting elements.
1665 * @param BalanceStack $stack The open elements stack
1666 * @see https://html.spec.whatwg.org/multipage/syntax.html#reconstruct-the-active-formatting-elements
1668 // @codingStandardsIgnoreEnd
1669 public function reconstruct( $stack ) {
1670 $entry = $this->tail
;
1671 // If there are no entries in the list of active formatting elements,
1672 // then there is nothing to reconstruct
1676 // If the last is a marker, do nothing.
1677 if ( $entry instanceof BalanceMarker
) {
1680 // Or if it is an open element, do nothing.
1681 if ( $stack->indexOf( $entry ) >= 0 ) {
1685 // Loop backward through the list until we find a marker or an
1688 while ( $entry->prevAFE
) {
1689 $entry = $entry->prevAFE
;
1690 if ( $entry instanceof BalanceMarker ||
$stack->indexOf( $entry ) >= 0 ) {
1696 // Now loop forward, starting from the element after the current one (or
1697 // the first element if we didn't find a marker or open element),
1698 // recreating formatting elements and pushing them back onto the list
1699 // of open elements.
1701 $entry = $entry->nextAFE
;
1704 $newElement = $stack->insertHTMLElement(
1707 $this->replace( $entry, $newElement );
1708 $entry = $newElement->nextAFE
;
1713 * Get a string representation of the AFE list, for debugging
1715 public function __toString() {
1718 for ( $node = $this->head
; $node; $prev = $node, $node = $node->nextAFE
) {
1719 if ( $node instanceof BalanceMarker
) {
1723 $s .= $node->localName
. '#' . substr( md5( spl_object_hash( $node ) ), 0, 8 );
1724 if ( $node->nextNoah
) {
1725 $s .= " (noah sibling: {$node->nextNoah->localName}#" .
1726 substr( md5( spl_object_hash( $node->nextNoah
) ), 0, 8 ) .
1729 if ( $node->nextAFE
&& $node->nextAFE
->prevAFE
!== $node ) {
1730 $s .= " (reverse link is wrong!)";
1734 if ( $prev !== $this->tail
) {
1735 $s .= "(tail pointer is wrong!)\n";
1742 * An implementation of the tree building portion of the HTML5 parsing
1745 * This is used to balance and tidy output so that the result can
1746 * always be cleanly serialized/deserialized by an HTML5 parser. It
1747 * does *not* guarantee "conforming" output -- the HTML5 spec contains
1748 * a number of constraints which are not enforced by the HTML5 parsing
1749 * process. But the result will be free of gross errors: misnested or
1750 * unclosed tags, for example, and will be unchanged by spec-complient
1751 * parsing followed by serialization.
1753 * The tree building stage is structured as a state machine.
1754 * When comparing the implementation to
1755 * https://www.w3.org/TR/html5/syntax.html#tree-construction
1756 * note that each state is implemented as a function with a
1757 * name ending in `Mode` (because the HTML spec refers to them
1758 * as insertion modes). The current insertion mode is held by
1759 * the $parseMode property.
1761 * The following simplifications have been made:
1762 * - We handle body content only (ie, we start `in body`.)
1763 * - The document is never in "quirks mode".
1764 * - All occurrences of < and > have been entity escaped, so we
1765 * can parse tags by simply splitting on those two characters.
1766 * (This also simplifies the handling of < inside <textarea>.)
1767 * The character < must not appear inside comments.
1768 * Similarly, all attributes have been "cleaned" and are double-quoted
1770 * - All null characters are assumed to have been removed.
1771 * - The following elements are disallowed: <html>, <head>, <body>, <frameset>,
1772 * <frame>, <plaintext>, <isindex>, <xmp>, <iframe>,
1773 * <noembed>, <noscript>, <script>, <title>. As a result,
1774 * further simplifications can be made:
1775 * - `frameset-ok` is not tracked.
1776 * - `head element pointer` is not tracked (but presumed non-null)
1777 * - Tokenizer has only a single mode. (<textarea> wants RCDATA and
1778 * <style>/<noframes> want RAWTEXT modes which we only loosely emulate.)
1780 * We generally mark places where we omit cases from the spec due to
1781 * disallowed elements with a comment: `// OMITTED: <element-name>`.
1783 * The HTML spec keeps a flag during the parsing process to track
1784 * whether or not a "parse error" has been encountered. We don't
1785 * bother to track that flag, we just implement the error-handling
1786 * process as specified.
1790 * @see https://html.spec.whatwg.org/multipage/syntax.html#tree-construction
1794 /** @var \Iterator */
1795 private $bitsIterator;
1796 private $allowedHtmlElements;
1797 /** @var BalanceActiveFormattingElements */
1799 /** @var BalanceStack */
1802 private $allowComments;
1805 private $textIntegrationMode;
1806 private $pendingTableText;
1807 private $originalInsertionMode;
1808 private $fragmentContext;
1809 private $formElementPointer;
1810 private $ignoreLinefeed;
1814 /** @var callable|null */
1815 private $processingCallback;
1817 private $processingArgs;
1820 * Valid HTML5 comments.
1821 * Regex borrowed from Tim Starling's "remex-html" project.
1823 const VALID_COMMENT_REGEX
= "~ !--
1824 ( # 1. Comment match detector
1825 > | -> | # Invalid short close
1826 ( # 2. Comment contents
1836 ( # 3. Comment close
1837 --> | # Normal close
1838 --!> | # Comment end bang
1839 ( # 4. Indicate matches requiring EOF
1840 --! | # EOF in comment end bang state
1841 -- | # EOF in comment end state
1842 - | # EOF in comment end dash state
1843 # EOF in comment state
1847 ([^<]*) \z # 5. Non-tag text after the comment
1851 * Create a new Balancer.
1852 * @param array $config Balancer configuration. Includes:
1853 * 'strict' : boolean, defaults to false.
1854 * When true, enforces syntactic constraints on input:
1855 * all non-tag '<' must be escaped, all attributes must be
1856 * separated by a single space and double-quoted. This is
1857 * consistent with the output of the Sanitizer.
1858 * 'allowedHtmlElements' : array, defaults to null.
1859 * When present, the keys of this associative array give
1860 * the acceptable HTML tag names. When not present, no
1861 * tag sanitization is done.
1862 * 'tidyCompat' : boolean, defaults to false.
1863 * When true, the serialization algorithm is tweaked to
1864 * provide historical compatibility with the old "tidy"
1865 * program: <p>-wrapping is done to the children of
1866 * <body> and <blockquote> elements, and empty elements
1868 * 'allowComments': boolean, defaults to true.
1869 * When true, allows HTML comments in the input.
1870 * The Sanitizer generally strips all comments, so if you
1871 * are running on sanitized output you can set this to
1872 * false to get a bit more performance.
1874 public function __construct( array $config = [] ) {
1875 $this->config
= $config = $config +
[
1877 'allowedHtmlElements' => null,
1878 'tidyCompat' => false,
1879 'allowComments' => true,
1881 $this->allowedHtmlElements
= $config['allowedHtmlElements'];
1882 $this->strict
= $config['strict'];
1883 $this->allowComments
= $config['allowComments'];
1884 if ( $this->allowedHtmlElements
!== null ) {
1886 $bad = array_uintersect_assoc(
1887 $this->allowedHtmlElements
,
1888 BalanceSets
::$unsupportedSet[BalanceSets
::HTML_NAMESPACE
],
1889 function( $a, $b ) {
1890 // Ignore the values (just intersect the keys) by saying
1891 // all values are equal to each other.
1895 if ( count( $bad ) > 0 ) {
1896 $badstr = implode( array_keys( $bad ), ',' );
1897 throw new ParameterAssertionException(
1899 'Balance attempted with sanitization including ' .
1900 "unsupported elements: {$badstr}"
1907 * Return a balanced HTML string for the HTML fragment given by $text,
1908 * subject to the caveats listed in the class description. The result
1909 * will typically be idempotent -- that is, rebalancing the output
1910 * would result in no change.
1912 * @param string $text The markup to be balanced
1913 * @param callable $processingCallback Callback to do any variable or
1914 * parameter replacements in HTML attributes values
1915 * @param array|bool $processingArgs Arguments for the processing callback
1916 * @return string The balanced markup
1918 public function balance( $text, $processingCallback = null, $processingArgs = [] ) {
1919 $this->parseMode
= 'inBodyMode';
1920 $this->bitsIterator
= new ExplodeIterator( '<', $text );
1921 $this->afe
= new BalanceActiveFormattingElements();
1922 $this->stack
= new BalanceStack( $this->config
);
1923 $this->processingCallback
= $processingCallback;
1924 $this->processingArgs
= $processingArgs;
1926 $this->textIntegrationMode
=
1927 $this->ignoreLinefeed
=
1929 $this->inRAWTEXT
= false;
1931 // The stack is constructed with an <html> element already on it.
1932 // Set this up as a fragment parsed with <body> as the context.
1933 $this->fragmentContext
=
1934 new BalanceElement( BalanceSets
::HTML_NAMESPACE
, 'body', [] );
1935 $this->resetInsertionMode();
1936 $this->formElementPointer
= null;
1937 for ( $e = $this->fragmentContext
; $e != null; $e = $e->parent
) {
1938 if ( $e->isHtmlNamed( 'form' ) ) {
1939 $this->formElementPointer
= $e;
1944 // First element is text not tag
1945 $x = $this->bitsIterator
->current();
1946 $this->bitsIterator
->next();
1947 $this->insertToken( 'text', str_replace( '>', '>', $x ) );
1948 // Now process each tag.
1949 while ( $this->bitsIterator
->valid() ) {
1952 $this->insertToken( 'eof', null );
1953 $result = $this->stack
->getOutput();
1954 // Free memory before returning.
1955 $this->bitsIterator
= null;
1957 $this->stack
= null;
1958 $this->fragmentContext
= null;
1959 $this->formElementPointer
= null;
1964 * Pass a token to the tree builder. The $token will be one of the
1965 * strings "tag", "endtag", or "text".
1967 private function insertToken( $token, $value, $attribs = null, $selfClose = false ) {
1968 // validate tags against $unsupportedSet
1969 if ( $token === 'tag' ||
$token === 'endtag' ) {
1970 if ( isset( BalanceSets
::$unsupportedSet[BalanceSets
::HTML_NAMESPACE
][$value] ) ) {
1971 // As described in "simplifications" above, these tags are
1972 // not supported in the balancer.
1975 "Unsupported $token <$value> found."
1979 } elseif ( $token === 'text' && $value === '' ) {
1980 // Don't actually inject the empty string as a text token.
1983 // Support pre/listing/textarea by suppressing initial linefeed
1984 if ( $this->ignoreLinefeed
) {
1985 $this->ignoreLinefeed
= false;
1986 if ( $token === 'text' ) {
1987 if ( $value[0] === "\n" ) {
1988 if ( $value === "\n" ) {
1989 // Nothing would be left, don't inject the empty string.
1992 $value = substr( $value, 1 );
1996 // Some hoops we have to jump through
1997 $adjusted = $this->stack
->adjustedCurrentNode( $this->fragmentContext
);
2001 $this->stack
->length() === 0 ||
2002 $adjusted->isHtml() ||
2006 } elseif ( $adjusted->isMathmlTextIntegrationPoint() ) {
2007 if ( $token === 'text' ) {
2011 $value !== 'mglyph' && $value !== 'malignmark'
2016 $adjusted->namespaceURI
=== BalanceSets
::MATHML_NAMESPACE
&&
2017 $adjusted->localName
=== 'annotation-xml' &&
2018 $token === 'tag' && $value === 'svg'
2022 $adjusted->isHtmlIntegrationPoint() &&
2023 ( $token === 'tag' ||
$token === 'text' )
2028 return $this->insertForeignToken( $token, $value, $attribs, $selfClose );
2030 $func = $this->parseMode
;
2031 return $this->$func( $token, $value, $attribs, $selfClose );
2035 private function insertForeignToken( $token, $value, $attribs = null, $selfClose = false ) {
2036 if ( $token === 'text' ) {
2037 $this->stack
->insertText( $value );
2039 } elseif ( $token === 'tag' ) {
2042 if ( isset( $attribs['color'] )
2043 ||
isset( $attribs['face'] )
2044 ||
isset( $attribs['size'] )
2048 // otherwise, fall through
2093 if ( $this->fragmentContext
) {
2097 $this->stack
->pop();
2098 $node = $this->stack
->currentNode
;
2100 $node->isMathmlTextIntegrationPoint() ||
2101 $node->isHtmlIntegrationPoint() ||
2107 return $this->insertToken( $token, $value, $attribs, $selfClose );
2109 // "Any other start tag"
2110 $adjusted = ( $this->fragmentContext
&& $this->stack
->length()===1 ) ?
2111 $this->fragmentContext
: $this->stack
->currentNode
;
2112 $this->stack
->insertForeignElement(
2113 $adjusted->namespaceURI
, $value, $attribs
2116 $this->stack
->pop();
2119 } elseif ( $token === 'endtag' ) {
2121 foreach ( $this->stack
as $i => $node ) {
2122 if ( $node->isHtml() && !$first ) {
2123 // process the end tag as HTML
2124 $func = $this->parseMode
;
2125 return $this->$func( $token, $value, $attribs, $selfClose );
2126 } elseif ( $i === 0 ) {
2128 } elseif ( $node->localName
=== $value ) {
2129 $this->stack
->popTag( $node );
2138 * Grab the next "token" from $bitsIterator. This is either a open/close
2139 * tag or text or a comment, depending on whether the Sanitizer approves.
2141 private function advance() {
2142 $x = $this->bitsIterator
->current();
2143 $this->bitsIterator
->next();
2145 // Handle comments. These won't be generated by mediawiki (they
2146 // are stripped in the Sanitizer) but may be generated by extensions.
2148 $this->allowComments
&&
2149 !( $this->inRCDATA ||
$this->inRAWTEXT
) &&
2150 preg_match( Balancer
::VALID_COMMENT_REGEX
, $x, $regs, PREG_OFFSET_CAPTURE
) &&
2151 // verify EOF condition where necessary
2152 ( $regs[4][1] < 0 ||
!$this->bitsIterator
->valid() )
2154 $contents = $regs[2][0];
2155 $rest = $regs[5][0];
2156 $this->insertToken( 'comment', $contents );
2157 $this->insertToken( 'text', str_replace( '>', '>', $rest ) );
2160 // $slash: Does the current element start with a '/'?
2161 // $t: Current element name
2162 // $attribStr: String between element name and >
2163 // $brace: Ending '>' or '/>'
2164 // $rest: Everything until the next element from the $bitsIterator
2165 if ( preg_match( Sanitizer
::ELEMENT_BITS_REGEX
, $x, $regs ) ) {
2166 list( /* $qbar */, $slash, $t, $attribStr, $brace, $rest ) = $regs;
2167 $t = strtolower( $t );
2168 if ( $this->strict
) {
2169 // Verify that attributes are all properly double-quoted
2172 '/^( [:_A-Z0-9][-.:_A-Z0-9]*="[^"]*")*[ ]*$/i', $attribStr
2174 "Bad attribute string found"
2179 !$this->strict
, "< found which does not start a valid tag"
2181 $slash = $t = $attribStr = $brace = $rest = null;
2184 if ( $this->inRCDATA
) {
2185 if ( $slash && $t === $this->inRCDATA
) {
2186 $this->inRCDATA
= false;
2188 // No tags allowed; this emulates the "rcdata" tokenizer mode.
2192 if ( $this->inRAWTEXT
) {
2193 if ( $slash && $t === $this->inRAWTEXT
) {
2194 $this->inRAWTEXT
= false;
2196 // No tags allowed, no entity-escaping done.
2200 $sanitize = $this->allowedHtmlElements
!== null;
2202 $goodTag = $t && isset( $this->allowedHtmlElements
[$t] );
2205 if ( is_callable( $this->processingCallback
) ) {
2206 call_user_func_array( $this->processingCallback
, [ &$attribStr, $this->processingArgs
] );
2209 $goodTag = Sanitizer
::validateTag( $attribStr, $t );
2214 $attribs = Sanitizer
::decodeTagAttributes( $attribStr );
2215 $attribs = Sanitizer
::validateTagAttributes( $attribs, $t );
2217 $attribs = Sanitizer
::decodeTagAttributes( $attribStr );
2219 $goodTag = $this->insertToken(
2220 $slash ?
'endtag' : 'tag', $t, $attribs, $brace === '/>'
2224 $rest = str_replace( '>', '>', $rest );
2225 $this->insertToken( 'text', str_replace( '>', '>', $rest ) );
2226 } elseif ( $this->inRAWTEXT
) {
2227 $this->insertToken( 'text', "<$x" );
2229 // bad tag; serialize entire thing as text.
2230 $this->insertToken( 'text', '<' . str_replace( '>', '>', $x ) );
2234 private function switchMode( $mode ) {
2236 substr( $mode, -4 )==='Mode', '$mode', 'should end in Mode'
2238 $oldMode = $this->parseMode
;
2239 $this->parseMode
= $mode;
2243 private function switchModeAndReprocess( $mode, $token, $value, $attribs, $selfClose ) {
2244 $this->switchMode( $mode );
2245 return $this->insertToken( $token, $value, $attribs, $selfClose );
2248 private function resetInsertionMode() {
2250 foreach ( $this->stack
as $i => $node ) {
2253 if ( $this->fragmentContext
) {
2254 $node = $this->fragmentContext
;
2257 if ( $node->isHtml() ) {
2258 switch ( $node->localName
) {
2260 $stackLength = $this->stack
->length();
2261 for ( $j = $i +
1; $j < $stackLength-1; $j++
) {
2262 $ancestor = $this->stack
->node( $stackLength-$j-1 );
2263 if ( $ancestor->isHtmlNamed( 'template' ) ) {
2266 if ( $ancestor->isHtmlNamed( 'table' ) ) {
2267 $this->switchMode( 'inSelectInTableMode' );
2271 $this->switchMode( 'inSelectMode' );
2274 $this->switchMode( 'inRowMode' );
2279 $this->switchMode( 'inTableBodyMode' );
2282 $this->switchMode( 'inCaptionMode' );
2285 $this->switchMode( 'inColumnGroupMode' );
2288 $this->switchMode( 'inTableMode' );
2292 array_slice( $this->templateInsertionModes
, -1 )[0]
2296 $this->switchMode( 'inBodyMode' );
2298 // OMITTED: <frameset>
2304 if ( $node->isA( BalanceSets
::$tableCellSet ) ) {
2305 $this->switchMode( 'inCellMode' );
2312 $this->switchMode( 'inBodyMode' );
2318 private function stopParsing() {
2319 // Most of the spec methods are inapplicable, other than step 2:
2320 // "pop all the nodes off the stack of open elements".
2321 // We're going to keep the top-most <html> element on the stack, though.
2323 // Clear the AFE list first, otherwise the element objects will stay live
2324 // during serialization, potentially using O(N^2) memory. Note that
2325 // popping the stack will never result in reconstructing the active
2326 // formatting elements.
2328 $this->stack
->popTo( 1 );
2331 private function parseRawText( $value, $attribs = null ) {
2332 $this->stack
->insertHTMLElement( $value, $attribs );
2333 $this->inRAWTEXT
= $value;
2334 $this->originalInsertionMode
= $this->switchMode( 'inTextMode' );
2338 private function inTextMode( $token, $value, $attribs = null, $selfClose = false ) {
2339 if ( $token === 'text' ) {
2340 $this->stack
->insertText( $value );
2342 } elseif ( $token === 'eof' ) {
2343 $this->stack
->pop();
2344 return $this->switchModeAndReprocess(
2345 $this->originalInsertionMode
, $token, $value, $attribs, $selfClose
2347 } elseif ( $token === 'endtag' ) {
2348 $this->stack
->pop();
2349 $this->switchMode( $this->originalInsertionMode
);
2355 private function inHeadMode( $token, $value, $attribs = null, $selfClose = false ) {
2356 if ( $token === 'text' ) {
2357 if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
2358 $this->stack
->insertText( $matches[0] );
2359 $value = substr( $value, strlen( $matches[0] ) );
2361 if ( strlen( $value ) === 0 ) {
2362 return true; // All text handled.
2364 // Fall through to handle non-whitespace below.
2365 } elseif ( $token === 'tag' ) {
2368 // OMITTED: in a full HTML parser, this might change the encoding.
2375 $this->stack
->insertHTMLElement( $value, $attribs );
2376 $this->stack
->pop();
2379 // OMITTED: <noscript>
2382 return $this->parseRawText( $value, $attribs );
2383 // OMITTED: <script>
2385 $this->stack
->insertHTMLElement( $value, $attribs );
2386 $this->afe
->insertMarker();
2387 // OMITTED: frameset_ok
2388 $this->switchMode( 'inTemplateMode' );
2389 $this->templateInsertionModes
[] = $this->parseMode
;
2393 } elseif ( $token === 'endtag' ) {
2399 break; // handle at the bottom of the function
2401 if ( $this->stack
->indexOf( $value ) < 0 ) {
2402 return true; // Ignore the token.
2404 $this->stack
->generateImpliedEndTags( null, true /* thorough */ );
2405 $this->stack
->popTag( $value );
2406 $this->afe
->clearToMarker();
2407 array_pop( $this->templateInsertionModes
);
2408 $this->resetInsertionMode();
2411 // ignore any other end tag
2414 } elseif ( $token === 'comment' ) {
2415 $this->stack
->insertComment( $value );
2419 // If not handled above
2420 $this->inHeadMode( 'endtag', 'head' ); // synthetic </head>
2421 // Then redo this one
2422 return $this->insertToken( $token, $value, $attribs, $selfClose );
2425 private function inBodyMode( $token, $value, $attribs = null, $selfClose = false ) {
2426 if ( $token === 'text' ) {
2427 $this->afe
->reconstruct( $this->stack
);
2428 $this->stack
->insertText( $value );
2430 } elseif ( $token === 'eof' ) {
2431 if ( !empty( $this->templateInsertionModes
) ) {
2432 return $this->inTemplateMode( $token, $value, $attribs, $selfClose );
2434 $this->stopParsing();
2436 } elseif ( $token === 'tag' ) {
2445 // OMITTED: <script>
2449 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
2451 // OMITTED: <frameset>
2477 if ( $this->stack
->inButtonScope( 'p' ) ) {
2478 $this->inBodyMode( 'endtag', 'p' );
2480 $this->stack
->insertHTMLElement( $value, $attribs );
2489 if ( $this->stack
->inButtonScope( 'p' ) ) {
2490 $this->inBodyMode( 'endtag', 'p' );
2492 if ( $this->stack
->currentNode
->isA( BalanceSets
::$headingSet ) ) {
2493 $this->stack
->pop();
2495 $this->stack
->insertHTMLElement( $value, $attribs );
2500 if ( $this->stack
->inButtonScope( 'p' ) ) {
2501 $this->inBodyMode( 'endtag', 'p' );
2503 $this->stack
->insertHTMLElement( $value, $attribs );
2504 $this->ignoreLinefeed
= true;
2505 // OMITTED: frameset_ok
2510 $this->formElementPointer
&&
2511 $this->stack
->indexOf( 'template' ) < 0
2513 return true; // in a form, not in a template.
2515 if ( $this->stack
->inButtonScope( "p" ) ) {
2516 $this->inBodyMode( 'endtag', 'p' );
2518 $elt = $this->stack
->insertHTMLElement( $value, $attribs );
2519 if ( $this->stack
->indexOf( 'template' ) < 0 ) {
2520 $this->formElementPointer
= $elt;
2525 // OMITTED: frameset_ok
2526 foreach ( $this->stack
as $node ) {
2527 if ( $node->isHtmlNamed( 'li' ) ) {
2528 $this->inBodyMode( 'endtag', 'li' );
2532 $node->isA( BalanceSets
::$specialSet ) &&
2533 !$node->isA( BalanceSets
::$addressDivPSet )
2538 if ( $this->stack
->inButtonScope( 'p' ) ) {
2539 $this->inBodyMode( 'endtag', 'p' );
2541 $this->stack
->insertHTMLElement( $value, $attribs );
2546 // OMITTED: frameset_ok
2547 foreach ( $this->stack
as $node ) {
2548 if ( $node->isHtmlNamed( 'dd' ) ) {
2549 $this->inBodyMode( 'endtag', 'dd' );
2552 if ( $node->isHtmlNamed( 'dt' ) ) {
2553 $this->inBodyMode( 'endtag', 'dt' );
2557 $node->isA( BalanceSets
::$specialSet ) &&
2558 !$node->isA( BalanceSets
::$addressDivPSet )
2563 if ( $this->stack
->inButtonScope( 'p' ) ) {
2564 $this->inBodyMode( 'endtag', 'p' );
2566 $this->stack
->insertHTMLElement( $value, $attribs );
2569 // OMITTED: <plaintext>
2572 if ( $this->stack
->inScope( 'button' ) ) {
2573 $this->inBodyMode( 'endtag', 'button' );
2574 return $this->insertToken( $token, $value, $attribs, $selfClose );
2576 $this->afe
->reconstruct( $this->stack
);
2577 $this->stack
->insertHTMLElement( $value, $attribs );
2581 $activeElement = $this->afe
->findElementByTag( 'a' );
2582 if ( $activeElement ) {
2583 $this->inBodyMode( 'endtag', 'a' );
2584 if ( $this->afe
->isInList( $activeElement ) ) {
2585 $this->afe
->remove( $activeElement );
2586 // Don't flatten here, since when we fall
2587 // through below we might foster parent
2588 // the new <a> tag inside this one.
2589 $this->stack
->removeElement( $activeElement, false );
2605 $this->afe
->reconstruct( $this->stack
);
2606 $this->afe
->push( $this->stack
->insertHTMLElement( $value, $attribs ) );
2610 $this->afe
->reconstruct( $this->stack
);
2611 if ( $this->stack
->inScope( 'nobr' ) ) {
2612 $this->inBodyMode( 'endtag', 'nobr' );
2613 $this->afe
->reconstruct( $this->stack
);
2615 $this->afe
->push( $this->stack
->insertHTMLElement( $value, $attribs ) );
2621 $this->afe
->reconstruct( $this->stack
);
2622 $this->stack
->insertHTMLElement( $value, $attribs );
2623 $this->afe
->insertMarker();
2624 // OMITTED: frameset_ok
2628 // The document is never in "quirks mode"; see simplifications
2630 if ( $this->stack
->inButtonScope( 'p' ) ) {
2631 $this->inBodyMode( 'endtag', 'p' );
2633 $this->stack
->insertHTMLElement( $value, $attribs );
2634 // OMITTED: frameset_ok
2635 $this->switchMode( 'inTableMode' );
2644 $this->afe
->reconstruct( $this->stack
);
2645 $this->stack
->insertHTMLElement( $value, $attribs );
2646 $this->stack
->pop();
2647 // OMITTED: frameset_ok
2651 $this->afe
->reconstruct( $this->stack
);
2652 $this->stack
->insertHTMLElement( $value, $attribs );
2653 $this->stack
->pop();
2654 // OMITTED: frameset_ok
2655 // (hence we don't need to examine the tag's "type" attribute)
2662 $this->stack
->insertHTMLElement( $value, $attribs );
2663 $this->stack
->pop();
2667 if ( $this->stack
->inButtonScope( 'p' ) ) {
2668 $this->inBodyMode( 'endtag', 'p' );
2670 $this->stack
->insertHTMLElement( $value, $attribs );
2671 $this->stack
->pop();
2676 return $this->inBodyMode( $token, 'img', $attribs, $selfClose );
2678 // OMITTED: <isindex>
2681 $this->stack
->insertHTMLElement( $value, $attribs );
2682 $this->ignoreLinefeed
= true;
2683 $this->inRCDATA
= $value; // emulate rcdata tokenizer mode
2684 // OMITTED: frameset_ok
2688 // OMITTED: <iframe>
2689 // OMITTED: <noembed>
2690 // OMITTED: <noscript>
2693 $this->afe
->reconstruct( $this->stack
);
2694 $this->stack
->insertHTMLElement( $value, $attribs );
2695 switch ( $this->parseMode
) {
2697 case 'inCaptionMode':
2698 case 'inTableBodyMode':
2701 $this->switchMode( 'inSelectInTableMode' );
2704 $this->switchMode( 'inSelectMode' );
2710 if ( $this->stack
->currentNode
->isHtmlNamed( 'option' ) ) {
2711 $this->inBodyMode( 'endtag', 'option' );
2713 $this->afe
->reconstruct( $this->stack
);
2714 $this->stack
->insertHTMLElement( $value, $attribs );
2719 if ( $this->stack
->inScope( 'ruby' ) ) {
2720 $this->stack
->generateImpliedEndTags();
2722 $this->stack
->insertHTMLElement( $value, $attribs );
2727 if ( $this->stack
->inScope( 'ruby' ) ) {
2728 $this->stack
->generateImpliedEndTags( 'rtc' );
2730 $this->stack
->insertHTMLElement( $value, $attribs );
2734 $this->afe
->reconstruct( $this->stack
);
2735 // We skip the spec's "adjust MathML attributes" and
2736 // "adjust foreign attributes" steps, since the browser will
2737 // do this later when it parses the output and it doesn't affect
2739 $this->stack
->insertForeignElement(
2740 BalanceSets
::MATHML_NAMESPACE
, $value, $attribs
2743 // emit explicit </math> tag.
2744 $this->stack
->pop();
2749 $this->afe
->reconstruct( $this->stack
);
2750 // We skip the spec's "adjust SVG attributes" and
2751 // "adjust foreign attributes" steps, since the browser will
2752 // do this later when it parses the output and it doesn't affect
2754 $this->stack
->insertForeignElement(
2755 BalanceSets
::SVG_NAMESPACE
, $value, $attribs
2758 // emit explicit </svg> tag.
2759 $this->stack
->pop();
2774 // Ignore table tags if we're not inTableMode
2778 // Handle any other start tag here
2779 $this->afe
->reconstruct( $this->stack
);
2780 $this->stack
->insertHTMLElement( $value, $attribs );
2782 } elseif ( $token === 'endtag' ) {
2784 // </body>,</html> are unsupported.
2787 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
2815 // Ignore if there is not a matching open tag
2816 if ( !$this->stack
->inScope( $value ) ) {
2819 $this->stack
->generateImpliedEndTags();
2820 $this->stack
->popTag( $value );
2824 if ( $this->stack
->indexOf( 'template' ) < 0 ) {
2825 $openform = $this->formElementPointer
;
2826 $this->formElementPointer
= null;
2827 if ( !$openform ||
!$this->stack
->inScope( $openform ) ) {
2830 $this->stack
->generateImpliedEndTags();
2831 // Don't flatten yet if we're removing a <form> element
2832 // out-of-order. (eg. `<form><div></form>`)
2833 $flatten = ( $this->stack
->currentNode
=== $openform );
2834 $this->stack
->removeElement( $openform, $flatten );
2836 if ( !$this->stack
->inScope( 'form' ) ) {
2839 $this->stack
->generateImpliedEndTags();
2840 $this->stack
->popTag( 'form' );
2845 if ( !$this->stack
->inButtonScope( 'p' ) ) {
2846 $this->inBodyMode( 'tag', 'p', [] );
2847 return $this->insertToken( $token, $value, $attribs, $selfClose );
2849 $this->stack
->generateImpliedEndTags( $value );
2850 $this->stack
->popTag( $value );
2854 if ( !$this->stack
->inListItemScope( $value ) ) {
2855 return true; // ignore
2857 $this->stack
->generateImpliedEndTags( $value );
2858 $this->stack
->popTag( $value );
2863 if ( !$this->stack
->inScope( $value ) ) {
2864 return true; // ignore
2866 $this->stack
->generateImpliedEndTags( $value );
2867 $this->stack
->popTag( $value );
2876 if ( !$this->stack
->inScope( BalanceSets
::$headingSet ) ) {
2877 return true; // ignore
2879 $this->stack
->generateImpliedEndTags();
2880 $this->stack
->popTag( BalanceSets
::$headingSet );
2884 // Take a deep breath, then:
2901 if ( $this->stack
->adoptionAgency( $value, $this->afe
) ) {
2902 return true; // If we did something, we're done.
2904 break; // Go to the "any other end tag" case.
2909 if ( !$this->stack
->inScope( $value ) ) {
2910 return true; // ignore
2912 $this->stack
->generateImpliedEndTags();
2913 $this->stack
->popTag( $value );
2914 $this->afe
->clearToMarker();
2918 // Turn </br> into <br>
2919 return $this->inBodyMode( 'tag', $value, [] );
2922 // Any other end tag goes here
2923 foreach ( $this->stack
as $i => $node ) {
2924 if ( $node->isHtmlNamed( $value ) ) {
2925 $this->stack
->generateImpliedEndTags( $value );
2926 $this->stack
->popTo( $i ); // including $i
2928 } elseif ( $node->isA( BalanceSets
::$specialSet ) ) {
2929 return true; // ignore this close token.
2933 } elseif ( $token === 'comment' ) {
2934 $this->stack
->insertComment( $value );
2937 Assert
::invariant( false, "Bad token type: $token" );
2941 private function inTableMode( $token, $value, $attribs = null, $selfClose = false ) {
2942 if ( $token === 'text' ) {
2943 if ( $this->textIntegrationMode
) {
2944 return $this->inBodyMode( $token, $value, $attribs, $selfClose );
2945 } elseif ( $this->stack
->currentNode
->isA( BalanceSets
::$tableSectionRowSet ) ) {
2946 $this->pendingTableText
= '';
2947 $this->originalInsertionMode
= $this->parseMode
;
2948 return $this->switchModeAndReprocess( 'inTableTextMode',
2949 $token, $value, $attribs, $selfClose );
2951 // fall through to default case.
2952 } elseif ( $token === 'eof' ) {
2953 $this->stopParsing();
2955 } elseif ( $token === 'tag' ) {
2958 $this->afe
->insertMarker();
2959 $this->stack
->insertHTMLElement( $value, $attribs );
2960 $this->switchMode( 'inCaptionMode' );
2963 $this->stack
->clearToContext( BalanceSets
::$tableContextSet );
2964 $this->stack
->insertHTMLElement( $value, $attribs );
2965 $this->switchMode( 'inColumnGroupMode' );
2968 $this->inTableMode( 'tag', 'colgroup', [] );
2969 return $this->insertToken( $token, $value, $attribs, $selfClose );
2973 $this->stack
->clearToContext( BalanceSets
::$tableContextSet );
2974 $this->stack
->insertHTMLElement( $value, $attribs );
2975 $this->switchMode( 'inTableBodyMode' );
2980 $this->inTableMode( 'tag', 'tbody', [] );
2981 return $this->insertToken( $token, $value, $attribs, $selfClose );
2983 if ( !$this->stack
->inTableScope( $value ) ) {
2984 return true; // Ignore this tag.
2986 $this->inTableMode( 'endtag', $value );
2987 return $this->insertToken( $token, $value, $attribs, $selfClose );
2990 // OMITTED: <script>
2992 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
2995 if ( !isset( $attribs['type'] ) ||
strcasecmp( $attribs['type'], 'hidden' ) !== 0 ) {
2996 break; // Handle this as "everything else"
2998 $this->stack
->insertHTMLElement( $value, $attribs );
2999 $this->stack
->pop();
3004 $this->formElementPointer ||
3005 $this->stack
->indexOf( 'template' ) >= 0
3007 return true; // ignore this token
3009 $this->formElementPointer
=
3010 $this->stack
->insertHTMLElement( $value, $attribs );
3011 $this->stack
->popTag( $this->formElementPointer
);
3014 // Fall through for "anything else" clause.
3015 } elseif ( $token === 'endtag' ) {
3018 if ( !$this->stack
->inTableScope( $value ) ) {
3019 return true; // Ignore.
3021 $this->stack
->popTag( $value );
3022 $this->resetInsertionMode();
3035 return true; // Ignore the token.
3037 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
3039 // Fall through for "anything else" clause.
3040 } elseif ( $token === 'comment' ) {
3041 $this->stack
->insertComment( $value );
3044 // This is the "anything else" case:
3045 $this->stack
->fosterParentMode
= true;
3046 $this->inBodyMode( $token, $value, $attribs, $selfClose );
3047 $this->stack
->fosterParentMode
= false;
3051 private function inTableTextMode( $token, $value, $attribs = null, $selfClose = false ) {
3052 if ( $token === 'text' ) {
3053 $this->pendingTableText
.= $value;
3057 $text = $this->pendingTableText
;
3058 $this->pendingTableText
= '';
3059 if ( preg_match( '/[^\x09\x0A\x0C\x0D\x20]/', $text ) ) {
3060 // This should match the "anything else" case inTableMode
3061 $this->stack
->fosterParentMode
= true;
3062 $this->inBodyMode( 'text', $text );
3063 $this->stack
->fosterParentMode
= false;
3065 // Pending text is just whitespace.
3066 $this->stack
->insertText( $text );
3068 return $this->switchModeAndReprocess(
3069 $this->originalInsertionMode
, $token, $value, $attribs, $selfClose
3073 // helper for inCaptionMode
3074 private function endCaption() {
3075 if ( !$this->stack
->inTableScope( 'caption' ) ) {
3078 $this->stack
->generateImpliedEndTags();
3079 $this->stack
->popTag( 'caption' );
3080 $this->afe
->clearToMarker();
3081 $this->switchMode( 'inTableMode' );
3085 private function inCaptionMode( $token, $value, $attribs = null, $selfClose = false ) {
3086 if ( $token === 'tag' ) {
3097 if ( $this->endCaption() ) {
3098 $this->insertToken( $token, $value, $attribs, $selfClose );
3102 // Fall through to "anything else" case.
3103 } elseif ( $token === 'endtag' ) {
3106 $this->endCaption();
3109 if ( $this->endCaption() ) {
3110 $this->insertToken( $token, $value, $attribs, $selfClose );
3126 // Fall through to "anything else" case.
3128 // The Anything Else case
3129 return $this->inBodyMode( $token, $value, $attribs, $selfClose );
3132 private function inColumnGroupMode( $token, $value, $attribs = null, $selfClose = false ) {
3133 if ( $token === 'text' ) {
3134 if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
3135 $this->stack
->insertText( $matches[0] );
3136 $value = substr( $value, strlen( $matches[0] ) );
3138 if ( strlen( $value ) === 0 ) {
3139 return true; // All text handled.
3141 // Fall through to handle non-whitespace below.
3142 } elseif ( $token === 'tag' ) {
3146 $this->stack
->insertHTMLElement( $value, $attribs );
3147 $this->stack
->pop();
3150 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
3152 // Fall through for "anything else".
3153 } elseif ( $token === 'endtag' ) {
3156 if ( !$this->stack
->currentNode
->isHtmlNamed( 'colgroup' ) ) {
3157 return true; // Ignore the token.
3159 $this->stack
->pop();
3160 $this->switchMode( 'inTableMode' );
3163 return true; // Ignore the token.
3165 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
3167 // Fall through for "anything else".
3168 } elseif ( $token === 'eof' ) {
3169 return $this->inBodyMode( $token, $value, $attribs, $selfClose );
3170 } elseif ( $token === 'comment' ) {
3171 $this->stack
->insertComment( $value );
3176 if ( !$this->stack
->currentNode
->isHtmlNamed( 'colgroup' ) ) {
3177 return true; // Ignore the token.
3179 $this->inColumnGroupMode( 'endtag', 'colgroup' );
3180 return $this->insertToken( $token, $value, $attribs, $selfClose );
3183 // Helper function for inTableBodyMode
3184 private function endSection() {
3186 $this->stack
->inTableScope( 'tbody' ) ||
3187 $this->stack
->inTableScope( 'thead' ) ||
3188 $this->stack
->inTableScope( 'tfoot' )
3192 $this->stack
->clearToContext( BalanceSets
::$tableBodyContextSet );
3193 $this->stack
->pop();
3194 $this->switchMode( 'inTableMode' );
3197 private function inTableBodyMode( $token, $value, $attribs = null, $selfClose = false ) {
3198 if ( $token === 'tag' ) {
3201 $this->stack
->clearToContext( BalanceSets
::$tableBodyContextSet );
3202 $this->stack
->insertHTMLElement( $value, $attribs );
3203 $this->switchMode( 'inRowMode' );
3207 $this->inTableBodyMode( 'tag', 'tr', [] );
3208 $this->insertToken( $token, $value, $attribs, $selfClose );
3216 if ( $this->endSection() ) {
3217 $this->insertToken( $token, $value, $attribs, $selfClose );
3221 } elseif ( $token === 'endtag' ) {
3224 if ( $this->endSection() ) {
3225 $this->insertToken( $token, $value, $attribs, $selfClose );
3231 if ( $this->stack
->inTableScope( $value ) ) {
3232 $this->endSection();
3243 return true; // Ignore the token.
3247 return $this->inTableMode( $token, $value, $attribs, $selfClose );
3250 // Helper function for inRowMode
3251 private function endRow() {
3252 if ( !$this->stack
->inTableScope( 'tr' ) ) {
3255 $this->stack
->clearToContext( BalanceSets
::$tableRowContextSet );
3256 $this->stack
->pop();
3257 $this->switchMode( 'inTableBodyMode' );
3260 private function inRowMode( $token, $value, $attribs = null, $selfClose = false ) {
3261 if ( $token === 'tag' ) {
3265 $this->stack
->clearToContext( BalanceSets
::$tableRowContextSet );
3266 $this->stack
->insertHTMLElement( $value, $attribs );
3267 $this->switchMode( 'inCellMode' );
3268 $this->afe
->insertMarker();
3277 if ( $this->endRow() ) {
3278 $this->insertToken( $token, $value, $attribs, $selfClose );
3282 } elseif ( $token === 'endtag' ) {
3288 if ( $this->endRow() ) {
3289 $this->insertToken( $token, $value, $attribs, $selfClose );
3296 $this->stack
->inTableScope( $value ) &&
3299 $this->insertToken( $token, $value, $attribs, $selfClose );
3309 return true; // Ignore the token.
3313 return $this->inTableMode( $token, $value, $attribs, $selfClose );
3316 // Helper for inCellMode
3317 private function endCell() {
3318 if ( $this->stack
->inTableScope( 'td' ) ) {
3319 $this->inCellMode( 'endtag', 'td' );
3321 } elseif ( $this->stack
->inTableScope( 'th' ) ) {
3322 $this->inCellMode( 'endtag', 'th' );
3328 private function inCellMode( $token, $value, $attribs = null, $selfClose = false ) {
3329 if ( $token === 'tag' ) {
3340 if ( $this->endCell() ) {
3341 $this->insertToken( $token, $value, $attribs, $selfClose );
3345 } elseif ( $token === 'endtag' ) {
3349 if ( $this->stack
->inTableScope( $value ) ) {
3350 $this->stack
->generateImpliedEndTags();
3351 $this->stack
->popTag( $value );
3352 $this->afe
->clearToMarker();
3353 $this->switchMode( 'inRowMode' );
3368 if ( $this->stack
->inTableScope( $value ) ) {
3369 $this->stack
->generateImpliedEndTags();
3370 $this->stack
->popTag( BalanceSets
::$tableCellSet );
3371 $this->afe
->clearToMarker();
3372 $this->switchMode( 'inRowMode' );
3373 $this->insertToken( $token, $value, $attribs, $selfClose );
3379 return $this->inBodyMode( $token, $value, $attribs, $selfClose );
3382 private function inSelectMode( $token, $value, $attribs = null, $selfClose = false ) {
3383 if ( $token === 'text' ) {
3384 $this->stack
->insertText( $value );
3386 } elseif ( $token === 'eof' ) {
3387 return $this->inBodyMode( $token, $value, $attribs, $selfClose );
3388 } elseif ( $token === 'tag' ) {
3392 if ( $this->stack
->currentNode
->isHtmlNamed( 'option' ) ) {
3393 $this->stack
->pop();
3395 $this->stack
->insertHTMLElement( $value, $attribs );
3398 if ( $this->stack
->currentNode
->isHtmlNamed( 'option' ) ) {
3399 $this->stack
->pop();
3401 if ( $this->stack
->currentNode
->isHtmlNamed( 'optgroup' ) ) {
3402 $this->stack
->pop();
3404 $this->stack
->insertHTMLElement( $value, $attribs );
3407 $this->inSelectMode( 'endtag', $value ); // treat it like endtag
3412 if ( !$this->stack
->inSelectScope( 'select' ) ) {
3413 return true; // ignore token (fragment case)
3415 $this->inSelectMode( 'endtag', 'select' );
3416 return $this->insertToken( $token, $value, $attribs, $selfClose );
3419 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
3421 } elseif ( $token === 'endtag' ) {
3425 $this->stack
->currentNode
->isHtmlNamed( 'option' ) &&
3426 $this->stack
->length() >= 2 &&
3427 $this->stack
->node( $this->stack
->length() - 2 )->isHtmlNamed( 'optgroup' )
3429 $this->stack
->pop();
3431 if ( $this->stack
->currentNode
->isHtmlNamed( 'optgroup' ) ) {
3432 $this->stack
->pop();
3436 if ( $this->stack
->currentNode
->isHtmlNamed( 'option' ) ) {
3437 $this->stack
->pop();
3441 if ( !$this->stack
->inSelectScope( $value ) ) {
3442 return true; // fragment case
3444 $this->stack
->popTag( $value );
3445 $this->resetInsertionMode();
3448 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
3450 } elseif ( $token === 'comment' ) {
3451 $this->stack
->insertComment( $value );
3454 // anything else: just ignore the token
3458 private function inSelectInTableMode( $token, $value, $attribs = null, $selfClose = false ) {
3468 if ( $token === 'tag' ) {
3469 $this->inSelectInTableMode( 'endtag', 'select' );
3470 return $this->insertToken( $token, $value, $attribs, $selfClose );
3471 } elseif ( $token === 'endtag' ) {
3472 if ( $this->stack
->inTableScope( $value ) ) {
3473 $this->inSelectInTableMode( 'endtag', 'select' );
3474 return $this->insertToken( $token, $value, $attribs, $selfClose );
3480 return $this->inSelectMode( $token, $value, $attribs, $selfClose );
3483 private function inTemplateMode( $token, $value, $attribs = null, $selfClose = false ) {
3484 if ( $token === 'text' ||
$token === 'comment' ) {
3485 return $this->inBodyMode( $token, $value, $attribs, $selfClose );
3486 } elseif ( $token === 'eof' ) {
3487 if ( $this->stack
->indexOf( 'template' ) < 0 ) {
3488 $this->stopParsing();
3490 $this->stack
->popTag( 'template' );
3491 $this->afe
->clearToMarker();
3492 array_pop( $this->templateInsertionModes
);
3493 $this->resetInsertionMode();
3494 $this->insertToken( $token, $value, $attribs, $selfClose );
3497 } elseif ( $token === 'tag' ) {
3505 // OMITTED: <script>
3509 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
3516 return $this->switchModeAndReprocess(
3517 'inTableMode', $token, $value, $attribs, $selfClose
3521 return $this->switchModeAndReprocess(
3522 'inColumnGroupMode', $token, $value, $attribs, $selfClose
3526 return $this->switchModeAndReprocess(
3527 'inTableBodyMode', $token, $value, $attribs, $selfClose
3532 return $this->switchModeAndReprocess(
3533 'inRowMode', $token, $value, $attribs, $selfClose
3536 return $this->switchModeAndReprocess(
3537 'inBodyMode', $token, $value, $attribs, $selfClose
3539 } elseif ( $token === 'endtag' ) {
3542 return $this->inHeadMode( $token, $value, $attribs, $selfClose );
3546 Assert
::invariant( false, "Bad token type: $token" );