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,
248 * A BalanceElement is a simplified version of a DOM Node. The main
249 * difference is that we only keep BalanceElements around for nodes
250 * currently on the BalanceStack of open elements. As soon as an
251 * element is closed, with some minor exceptions relating to the
252 * tree builder "adoption agency algorithm", the element and all its
253 * children are serialized to a string using the flatten() method.
254 * This keeps our memory usage low.
259 class BalanceElement
{
261 * The namespace of the element.
262 * @var string $namespaceURI
264 public $namespaceURI;
266 * The lower-cased name of the element.
267 * @var string $localName
271 * Attributes for the element, as normalized by
272 * Sanitizer::safeEncodeTagAttributes. Attributes are space-separated
273 * and attribute values are double-quoted. Elements with no
274 * attributes should have a zero-length string here.
275 * @var string $attribs
280 * Parent of this element, or the string "flat" if this element has
281 * already been flattened into its parent.
282 * @var string|null $parent
287 * An array of children of this element. Typically only the last
288 * child will be an actual BalanceElement object; the rest will
289 * be strings, representing either text nodes or flattened
290 * BalanceElement objects.
291 * @var array $children
296 * Make a new BalanceElement corresponding to the HTML DOM Element
297 * with the given localname, namespace, and attributes.
299 * @param string $namespaceURI The namespace of the element.
300 * @param string $localName The lowercased name of the tag.
301 * @param string $attribs Attributes of the element, as normalized
302 * by Sanitizer:safeEncodeTagAttributes.
304 public function __construct( $namespaceURI, $localName, $attribs ) {
305 Assert
::parameterType( 'string', $namespaceURI, '$namespaceURI' );
306 Assert
::parameterType( 'string', $localName, '$localName' );
307 Assert
::parameterType( 'string', $attribs, '$attribs' );
309 $this->localName
= $localName;
310 $this->namespaceURI
= $namespaceURI;
311 $this->attribs
= $attribs;
312 $this->contents
= '';
313 $this->parent
= null;
314 $this->children
= [];
318 * Remove the given child from this element.
319 * @param BalanceElement $elt
321 private function removeChild( $elt ) {
322 Assert
::precondition(
323 $this->parent
!== 'flat', "Can't removeChild after flattening $this"
325 Assert
::parameterType( 'MediaWiki\Tidy\BalanceElement', $elt, '$elt' );
327 $elt->parent
=== $this, 'elt', 'must have $this as a parent'
329 $idx = array_search( $elt, $this->children
, true );
330 Assert
::parameter( $idx !== false, '$elt', 'must be a child of $this' );
332 array_splice( $this->children
, $idx, 1 );
336 * Find $a in the list of children and insert $b before it.
337 * @param BalanceElement $a
338 * @param BalanceElement|string $b
340 public function insertBefore( $a, $b ) {
341 Assert
::precondition(
342 $this->parent
!== 'flat', "Can't insertBefore after flattening."
344 Assert
::parameterType( 'MediaWiki\Tidy\BalanceElement', $a, '$a' );
345 Assert
::parameterType( 'MediaWiki\Tidy\BalanceElement|string', $b, '$b' );
346 $idx = array_search( $a, $this->children
, true );
347 Assert
::parameter( $idx !== false, '$a', 'must be a child of $this' );
348 if ( is_string( $b ) ) {
349 array_splice( $this->children
, $idx, 0, [ $b ] );
351 Assert
::parameter( $b->parent
!== 'flat', '$b', "Can't be flat" );
352 if ( $b->parent
!== null ) {
353 $b->parent
->removeChild( $b );
355 array_splice( $this->children
, $idx, 0, [ $b ] );
361 * Append $elt to the end of the list of children.
362 * @param BalanceElement|string $elt
364 public function appendChild( $elt ) {
365 Assert
::precondition(
366 $this->parent
!== 'flat', "Can't appendChild after flattening."
368 Assert
::parameterType( 'MediaWiki\Tidy\BalanceElement|string', $elt, '$elt' );
369 if ( is_string( $elt ) ) {
370 array_push( $this->children
, $elt );
373 // Remove $elt from parent, if it had one.
374 if ( $elt->parent
!== null ) {
375 $elt->parent
->removeChild( $elt );
377 array_push( $this->children
, $elt );
378 $elt->parent
= $this;
382 * Transfer all of the children of $elt to $this.
383 * @param BalanceElement $elt
385 public function adoptChildren( $elt ) {
386 Assert
::parameterType( 'MediaWiki\Tidy\BalanceElement', $elt, '$elt' );
387 Assert
::precondition(
388 $elt->parent
!== 'flat', "Can't adoptChildren after flattening."
390 foreach ( $elt->children
as $child ) {
391 if ( !is_string( $child ) ) {
392 // This is an optimization which avoids an O(n^2) set of
393 // array_splice operations.
394 $child->parent
= null;
396 $this->appendChild( $child );
402 * Flatten this node and all of its children into a string, as specified
403 * by the HTML serialization specification, and replace this node
404 * in its parent by that string.
408 public function flatten() {
409 Assert
::parameter( $this->parent
!== null, '$this', 'must be a child' );
410 Assert
::parameter( $this->parent
!== 'flat', '$this', 'already flat' );
411 $idx = array_search( $this, $this->parent
->children
, true );
413 $idx !== false, '$this', 'must be a child of its parent'
416 $this->parent
->children
[$idx] = $flat;
417 $this->parent
= 'flat'; # for assertion checking
422 * Serialize this node and all of its children to a string, as specified
423 * by the HTML serialization specification.
425 * @return string The serialization of the BalanceElement
426 * @see https://html.spec.whatwg.org/multipage/syntax.html#serialising-html-fragments
428 public function __toString() {
429 $out = "<{$this->localName}{$this->attribs}>";
430 if ( !$this->isA( BalanceSets
::$emptyElementSet ) ) {
432 foreach ( $this->children
as $elt ) {
435 $out .= "</{$this->localName}>";
438 count( $this->children
) === 0,
439 "Empty elements shouldn't have children."
445 # Utility functions on BalanceElements.
448 * Determine if $this represents a specific HTML tag, is a member of
449 * a tag set, or is equal to another BalanceElement.
451 * @param BalanceElement|array|string $set The target BalanceElement,
452 * set (from the BalanceSets class), or string (HTML tag name).
455 public function isA( $set ) {
456 Assert
::parameterType( 'MediaWiki\Tidy\BalanceElement|array|string', $set, '$set' );
457 if ( $set instanceof BalanceElement
) {
458 return $this === $set;
459 } elseif ( is_array( $set ) ) {
460 return isset( $set[$this->namespaceURI
] ) &&
461 isset( $set[$this->namespaceURI
][$this->localName
] );
463 # assume this is an HTML element name.
464 return $this->isHtml() && $this->localName
=== $set;
469 * Determine if $this represents an element in the HTML namespace.
473 public function isHtml() {
474 return $this->namespaceURI
=== BalanceSets
::HTML_NAMESPACE
;
478 * Determine if $this represents a MathML text integration point,
479 * as defined in the HTML5 specification.
482 * @see https://html.spec.whatwg.org/multipage/syntax.html#mathml-text-integration-point
484 public function isMathmlTextIntegrationPoint() {
485 return $this->isA( BalanceSets
::$mathmlTextIntegrationPointSet );
489 * Determine if $this represents an HTML integration point,
490 * as defined in the HTML5 specification.
493 * @see https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
495 public function isHtmlIntegrationPoint() {
496 if ( $this->isA( BalanceSets
::$htmlIntegrationPointSet ) ) {
500 $this->namespaceURI
=== BalanceSets
::MATHML_NAMESPACE
&&
501 $this->localName
=== 'annotation-xml' &&
502 // We rely on Sanitizer::fixTagAttributes having run on $attribs
503 // to normalize the form of the tag parameters.
504 preg_match( ':(^| )encoding="(text/html|application/xhtml+xml)":i', $this->attribs
)
513 * The "stack of open elements" as defined in the HTML5 tree builder
514 * spec. This contains methods to ensure that content (start tags, text)
515 * are inserted at the correct place in the output string, and to
516 * flatten BalanceElements are they are closed to avoid holding onto
517 * a complete DOM tree for the document in memory.
519 * The stack defines a PHP iterator to traverse it in "reverse order",
520 * that is, the most-recently-added element is visited first in a
525 * @see https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements
527 class BalanceStack
implements IteratorAggregate
{
529 * Backing storage for the stack.
530 * @var array $elements
532 private $elements = [];
534 * Foster parent mode determines how nodes are inserted into the
536 * @var bool $fosterParentMode
537 * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
539 public $fosterParentMode = false;
542 * Create a new BalanceStack with a single BalanceElement on it,
543 * representing the root <html> node.
545 public function __construct() {
546 # always a root <html> element on the stack
549 new BalanceElement( BalanceSets
::HTML_NAMESPACE
, 'html', '' )
554 * Return a string representing the output of the tree builder:
555 * all the children of the root <html> node.
558 public function getOutput() {
559 // Don't include the outer '<html>....</html>'
561 foreach ( $this->elements
[0]->children
as $elt ) {
562 $out .= is_string( $elt ) ?
$elt : $elt->flatten();
568 * Insert text at the appropriate place for inserting a node.
569 * @param string $value
570 * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
572 public function insertText( $value ) {
573 Assert
::parameterType( 'string', $value, '$value' );
575 $this->fosterParentMode
&&
576 $this->currentNode()->isA( BalanceSets
::$tableSectionRowSet )
578 $this->fosterParent( $value );
580 $this->currentNode()->appendChild( $value );
585 * Insert a BalanceElement at the appropriate place, pushing it
586 * on to the open elements stack.
587 * @param string $namespaceURI The element namespace
588 * @param string $tag The tag name
589 * @param string $attribs Normalized attributes, as a string.
590 * @return BalanceElement
591 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-a-foreign-element
593 public function insertForeignElement( $namespaceURI, $tag, $attribs ) {
594 return $this->insertElement(
595 new BalanceElement( $namespaceURI, $tag, $attribs )
600 * Insert an HTML element at the appropriate place, pushing it on to
601 * the open elements stack.
602 * @param string $tag The tag name
603 * @param string $attribs Normalized attributes, as a string.
604 * @return BalanceElement
605 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-an-html-element
607 public function insertHTMLElement( $tag, $attribs ) {
608 return $this->insertForeignElement(
609 BalanceSets
::HTML_NAMESPACE
, $tag, $attribs
614 * Insert an element at the appropriate place and push it on to the
615 * open elements stack.
616 * @param BalanceElement $elt
617 * @return BalanceElement
618 * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
620 public function insertElement( $elt ) {
621 Assert
::parameterType( 'MediaWiki\Tidy\BalanceElement', $elt, '$elt' );
623 $this->fosterParentMode
&&
624 $this->currentNode()->isA( BalanceSets
::$tableSectionRowSet )
626 $elt = $this->fosterParent( $elt );
628 $this->currentNode()->appendChild( $elt );
630 Assert
::invariant( $elt->parent
!== null, "$elt must be in tree" );
631 Assert
::invariant( $elt->parent
!== 'flat', "$elt must not have been previous flattened" );
632 array_push( $this->elements
, $elt );
637 * Determine if the stack has $tag in scope.
638 * @param BalanceElement|array|string $tag
640 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
642 public function inScope( $tag ) {
643 return $this->inSpecificScope( $tag, BalanceSets
::$inScopeSet );
647 * Determine if the stack has $tag in button scope.
648 * @param BalanceElement|array|string $tag
650 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
652 public function inButtonScope( $tag ) {
653 return $this->inSpecificScope( $tag, BalanceSets
::inButtonScopeSet() );
657 * Determine if the stack has $tag in list item scope.
658 * @param BalanceElement|array|string $tag
660 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-list-item-scope
662 public function inListItemScope( $tag ) {
663 return $this->inSpecificScope( $tag, BalanceSets
::inListItemScopeSet() );
667 * Determine if the stack has $tag in table scope.
668 * @param BalanceElement|array|string $tag
670 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-table-scope
672 public function inTableScope( $tag ) {
673 return $this->inSpecificScope( $tag, BalanceSets
::$inTableScopeSet );
677 * Determine if the stack has $tag in a specific scope, $set.
678 * @param BalanceElement|array|string $tag
679 * @param BalanceElement|array|string $set
681 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-the-specific-scope
683 public function inSpecificScope( $tag, $set ) {
684 foreach ( $this as $elt ) {
685 if ( $elt->isA( $tag ) ) {
688 if ( $elt->isA( $set ) ) {
696 * Generate implied end tags.
697 * @param BalanceElement|array|string|null $butnot
698 * @param bool $thorough True if we should generate end tags thoroughly.
699 * @see https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
701 public function generateImpliedEndTags( $butnot = null, $thorough = false ) {
702 $endTagSet = $thorough ?
703 BalanceSets
::$thoroughImpliedEndTagsSet :
704 BalanceSets
::$impliedEndTagsSet;
705 while ( $this->length() > 0 ) {
706 if ( $butnot !== null && $this->currentNode()->isA( $butnot ) ) {
709 if ( !$this->currentNode()->isA( $endTagSet ) ) {
717 * Return the current node (the element in the stack with the largest
719 * @return BalanceElement
720 * @see https://html.spec.whatwg.org/multipage/syntax.html#current-node
722 public function currentNode() {
723 return $this->node( count( $this->elements
) - 1 );
727 * Return the adjusted current node.
729 public function adjustedCurrentNode( $fragmentContext ) {
730 return ( $fragmentContext && $this->length() === 1 ) ?
731 $fragmentContext : $this->currentNode();
735 * Return an iterator over this stack which visits the current node
736 * first, and the root node last.
739 public function getIterator() {
740 return new ReverseArrayIterator( $this->elements
);
744 * Return the BalanceElement at the given position $idx, where
745 * position 0 represents the root element.
747 * @return BalanceElement
749 public function node( $idx ) {
750 return $this->elements
[ $idx ];
754 * Replace the element at position $idx in the BalanceStack with $elt.
756 * @param BalanceElement $elt
758 public function replaceAt( $idx, $elt ) {
759 Assert
::parameterType( 'MediaWiki\Tidy\BalanceElement', $elt, '$elt' );
760 Assert
::precondition(
761 $this->elements
[$idx]->parent
!== 'flat',
762 'Replaced element should not have already been flattened.'
764 Assert
::precondition(
765 $elt->parent
!== 'flat',
766 'New element should not have already been flattened.'
768 $this->elements
[$idx] = $elt;
772 * Return the position of the given BalanceElement, set, or
773 * HTML tag name string in the BalanceStack.
774 * @param BalanceElement|array|string $tag
777 public function indexOf( $tag ) {
778 for ( $i = count( $this->elements
) - 1; $i >= 0; $i-- ) {
779 if ( $this->elements
[$i]->isA( $tag ) ) {
787 * Return the number of elements currently in the BalanceStack.
790 public function length() {
791 return count( $this->elements
);
795 * Remove the current node from the BalanceStack, flattening it
798 public function pop() {
799 $elt = array_pop( $this->elements
);
804 * Remove all nodes up to and including position $idx from the
805 * BalanceStack, flattening them in the process.
808 public function popTo( $idx ) {
809 while ( $this->length() > $idx ) {
815 * Pop elements off the stack up to and including the first
816 * element with the specified HTML tagname (or matching the given
818 * @param BalanceElement|array|string $tag
820 public function popTag( $tag ) {
821 while ( $this->length() > 0 ) {
822 if ( $this->currentNode()->isA( $tag ) ) {
831 * Pop elements off the stack *not including* the first element
832 * in the specified set.
833 * @param BalanceElement|array|string $set
835 public function clearToContext( $set ) {
836 // Note that we don't loop to 0. Never pop the <html> elt off.
837 while ( $this->length() > 1 ) {
838 if ( $this->currentNode()->isA( $set ) ) {
846 * Remove the given $elt from the BalanceStack, optionally
847 * flattening it in the process.
848 * @param BalanceElement $elt The element to remove.
849 * @param bool $flatten Whether to flatten the removed element.
851 public function removeElement( $elt, $flatten = true ) {
852 Assert
::parameterType( 'MediaWiki\Tidy\BalanceElement', $elt, '$elt' );
854 $elt->parent
!== 'flat',
856 '$elt should not already have been flattened.'
859 $elt->parent
->parent
!== 'flat',
861 'The parent of $elt should not already have been flattened.'
863 $idx = array_search( $elt, $this->elements
, true );
864 Assert
::parameter( $idx !== false, '$elt', 'must be in stack' );
865 array_splice( $this->elements
, $idx, 1 );
867 // serialize $elt into its parent
868 // otherwise, it will eventually serialize when the parent
869 // is serialized, we just hold onto the memory for its
870 // tree of objects a little longer.
873 Assert
::postcondition(
874 array_search( $elt, $this->elements
, true ) === false,
875 '$elt should no longer be in open elements stack'
880 * Find $a in the BalanceStack and insert $b after it.
881 * @param BalanceElement $a
882 * @param BalanceElement $b
884 public function insertAfter( $a, $b ) {
885 Assert
::parameterType( 'MediaWiki\Tidy\BalanceElement', $a, '$a' );
886 Assert
::parameterType( 'MediaWiki\Tidy\BalanceElement', $b, '$b' );
887 $idx = $this->indexOf( $a );
888 Assert
::parameter( $idx !== false, '$a', 'must be in stack' );
889 array_splice( $this->elements
, $idx +
1, 0, [ $b ] );
892 # Fostering and adoption.
895 * Foster parent the given $elt in the stack of open elements.
896 * @param BalanceElement|string $elt
897 * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
899 private function fosterParent( $elt ) {
900 Assert
::parameterType( 'MediaWiki\Tidy\BalanceElement|string', $elt, '$elt' );
901 $lastTable = $this->indexOf( 'table' );
902 $lastTemplate = $this->indexOf( 'template' );
906 if ( $lastTemplate >= 0 && ( $lastTable < 0 ||
$lastTemplate > $lastTable ) ) {
907 $parent = $this->elements
[$lastTemplate];
908 } elseif ( $lastTable >= 0 ) {
909 $parent = $this->elements
[$lastTable]->parent
;
910 # Assume all tables have parents, since we're not running scripts!
912 $parent !== null, "All tables should have parents"
914 $before = $this->elements
[$lastTable];
916 $parent = $this->elements
[0]; // the `html` element.
919 $parent->insertBefore( $before, $elt );
921 $parent->appendChild( $elt );
927 * Run the "adoption agency algoritm" (AAA) for the given subject
929 * @param string $tag The subject tag name.
930 * @param BalanceActiveFormattingElements $afe The current
931 * active formatting elements list.
932 * @return true if the adoption agency algorithm "did something", false
933 * if more processing is required by the caller.
934 * @see https://html.spec.whatwg.org/multipage/syntax.html#adoption-agency-algorithm
936 public function adoptionAgency( $tag, $afe ) {
937 // If the current node is an HTML element whose tag name is subject,
938 // and the current node is not in the list of active formatting
939 // elements, then pop the current node off the stack of open
940 // elements and abort these steps.
942 $this->currentNode()->isA( $tag ) &&
943 $afe->indexOf( $this->currentNode() ) < 0
946 return true; // no more handling required
949 // Let outer loop counter be zero.
952 // Outer loop: If outer loop counter is greater than or
953 // equal to eight, then abort these steps.
954 while ( $outer < 8 ) {
955 // Increment outer loop counter by one.
958 // Let the formatting element be the last element in the list
959 // of active formatting elements that: is between the end of
960 // the list and the last scope marker in the list, if any, or
961 // the start of the list otherwise, and has the same tag name
963 $fmtelt = $afe->findElementByTag( $tag );
965 // If there is no such node, then abort these steps and instead
966 // act as described in the "any other end tag" entry below.
968 return false; // false means handle by the default case
971 // Otherwise, if there is such a node, but that node is not in
972 // the stack of open elements, then this is a parse error;
973 // remove the element from the list, and abort these steps.
974 $index = $this->indexOf( $fmtelt );
976 $afe->remove( $fmtelt );
977 return true; // true means no more handling required
980 // Otherwise, if there is such a node, and that node is also in
981 // the stack of open elements, but the element is not in scope,
982 // then this is a parse error; ignore the token, and abort
984 if ( !$this->inScope( $fmtelt ) ) {
988 // Let the furthest block be the topmost node in the stack of
989 // open elements that is lower in the stack than the formatting
990 // element, and is an element in the special category. There
992 $furthestblock = null;
993 $furthestblockindex = -1;
994 $stacklen = $this->length();
995 for ( $i = $index+
1; $i < $stacklen; $i++
) {
996 if ( $this->node( $i )->isA( BalanceSets
::$specialSet ) ) {
997 $furthestblock = $this->node( $i );
998 $furthestblockindex = $i;
1003 // If there is no furthest block, then the UA must skip the
1004 // subsequent steps and instead just pop all the nodes from the
1005 // bottom of the stack of open elements, from the current node
1006 // up to and including the formatting element, and remove the
1007 // formatting element from the list of active formatting
1009 if ( !$furthestblock ) {
1010 $this->popTag( $fmtelt );
1011 $afe->remove( $fmtelt );
1014 // Let the common ancestor be the element immediately above
1015 // the formatting element in the stack of open elements.
1016 $ancestor = $this->node( $index-1 );
1018 // Let a bookmark note the position of the formatting
1019 // element in the list of active formatting elements
1020 // relative to the elements on either side of it in the
1022 $BOOKMARK = new BalanceElement( '[bookmark]', '[bookmark]', '' );
1023 $afe->insertAfter( $fmtelt, $BOOKMARK );
1025 // Let node and last node be the furthest block.
1026 $node = $furthestblock;
1027 $lastnode = $furthestblock;
1028 $nodeindex = $furthestblockindex;
1031 // Let inner loop counter be zero.
1036 // Increment inner loop counter by one.
1039 // Let node be the element immediately above node in
1040 // the stack of open elements, or if node is no longer
1041 // in the stack of open elements (e.g. because it got
1042 // removed by this algorithm), the element that was
1043 // immediately above node in the stack of open elements
1044 // before node was removed.
1045 $node = $this->node( --$nodeindex );
1047 // If node is the formatting element, then go
1048 // to the next step in the overall algorithm.
1049 if ( $node === $fmtelt ) break;
1051 // If the inner loop counter is greater than three and node
1052 // is in the list of active formatting elements, then remove
1053 // node from the list of active formatting elements.
1054 $nodeafeindex = $afe->indexOf( $node );
1055 if ( $inner > 3 && $nodeafeindex !== -1 ) {
1056 $afe->remove( $node );
1060 // If node is not in the list of active formatting
1061 // elements, then remove node from the stack of open
1062 // elements and then go back to the step labeled inner
1064 if ( $nodeafeindex === -1 ) {
1065 // Don't flatten here, since we're about to relocate
1066 // parts of this $node.
1067 $this->removeElement( $node, false );
1071 // Create an element for the token for which the
1072 // element node was created with common ancestor as
1073 // the intended parent, replace the entry for node
1074 // in the list of active formatting elements with an
1075 // entry for the new element, replace the entry for
1076 // node in the stack of open elements with an entry for
1077 // the new element, and let node be the new element.
1078 $newelt = $afe->cloneAt( $nodeafeindex ); // XXX
1079 $afe->replace( $node, $newelt );
1080 $this->replaceAt( $nodeindex, $newelt );
1083 // If last node is the furthest block, then move the
1084 // aforementioned bookmark to be immediately after the
1085 // new node in the list of active formatting elements.
1086 if ( $lastnode === $furthestblock ) {
1087 $afe->remove( $BOOKMARK );
1088 $afe->insertAfter( $newelt, $BOOKMARK );
1091 // Insert last node into node, first removing it from
1092 // its previous parent node if any.
1093 $node->appendChild( $lastnode );
1095 // Let last node be node.
1099 // If the common ancestor node is a table, tbody, tfoot,
1100 // thead, or tr element, then, foster parent whatever last
1101 // node ended up being in the previous step, first removing
1102 // it from its previous parent node if any.
1104 $this->fosterParentMode
&&
1105 $ancestor->isA( BalanceSets
::$tableSectionRowSet )
1107 $this->fosterParent( $lastnode );
1109 // Otherwise, append whatever last node ended up being in
1110 // the previous step to the common ancestor node, first
1111 // removing it from its previous parent node if any.
1112 $ancestor->appendChild( $lastnode );
1115 // Create an element for the token for which the
1116 // formatting element was created, with furthest block
1117 // as the intended parent.
1118 $newelt2 = $afe->cloneAt( $afe->indexOf( $fmtelt ) );
1120 // Take all of the child nodes of the furthest block and
1121 // append them to the element created in the last step.
1122 $newelt2->adoptChildren( $furthestblock );
1124 // Append that new element to the furthest block.
1125 $furthestblock->appendChild( $newelt2 );
1127 // Remove the formatting element from the list of active
1128 // formatting elements, and insert the new element into the
1129 // list of active formatting elements at the position of
1130 // the aforementioned bookmark.
1131 $afe->remove( $fmtelt );
1132 $afe->replace( $BOOKMARK, $newelt2 );
1134 // Remove the formatting element from the stack of open
1135 // elements, and insert the new element into the stack of
1136 // open elements immediately below the position of the
1137 // furthest block in that stack.
1138 $this->removeElement( $fmtelt );
1139 $this->insertAfter( $furthestblock, $newelt2 );
1147 * Return the contents of the open elements stack as a string for
1151 public function __toString() {
1153 foreach ( $this->elements
as $elt ) {
1154 array_push( $r, $elt->localName
);
1156 return implode( $r, ' ' );
1161 * The list of active formatting elements, which is used to handle
1162 * mis-nested formatting element tags in the HTML5 tree builder
1167 * @see https://html.spec.whatwg.org/multipage/syntax.html#list-of-active-formatting-elements
1169 class BalanceActiveFormattingElements
{
1170 private $elemList = [];
1171 private $attribList = [];
1172 private static $MARKER = '|';
1174 public function insertMarker() {
1175 $this->elemList
[] = self
::$MARKER;
1176 $this->attribList
[] = self
::$MARKER;
1179 public function push( $elt, $attribs ) {
1180 // "Noah's Ark clause" -- if there are already three copies of
1181 // this element before we encounter a marker, then drop the last
1184 for ( $i = count( $this->elemList
) - 1; $i >= 0; $i-- ) {
1185 if ( $this->elemList
[$i] === self
::$MARKER ) {
1188 // Note that we rely on Sanitizer::fixTagAttributes having run
1189 // previously with the $sorted option true. The attributes are
1190 // thus canonicalized, which allows us to compare $attribs with
1191 // a simple string compare.
1193 $this->elemList
[$i]->localName
=== $elt->localName
&&
1194 $this->attribList
[$i] === $elt->attribs
1197 if ( $count === 3 ) {
1198 array_splice( $this->elemList
, $i, 1 );
1199 array_splice( $this->attribList
, $i, 1 );
1204 // Now push the new element onto the list.
1205 $this->elemList
[] = $elt;
1206 // Spec says we have to clone the attribs, in case the element's
1207 // attributes are later modified.
1208 $this->attribList
[] = $elt->attribs
;
1211 public function clearToMarker() {
1212 # This is deliberately >0 not >=0, since it doesn't matter if element
1213 # 0 is the marker, we clear the whole list in that case regardless.
1214 for ( $i = count( $this->elemList
) - 1; $i > 0; $i-- ) {
1215 if ( $this->elemList
[$i] === self
::$MARKER ) {
1219 array_splice( $this->elemList
, $i );
1220 array_splice( $this->attribList
, $i );
1224 * Find and return the last element with the specified tag between the
1225 * end of the list and the last marker on the list.
1226 * Used when parsing <a> "in body mode".
1228 public function findElementByTag( $tag ) {
1229 for ( $i = count( $this->elemList
) - 1; $i >= 0; $i-- ) {
1230 $elt = $this->elemList
[$i];
1231 if ( $elt === self
::$MARKER ) {
1234 if ( $elt->localName
=== $tag ) {
1241 public function indexOf( $elt ) {
1242 for ( $i = count( $this->elemList
) - 1; $i >= 0; $i-- ) {
1243 if ( $this->elemList
[$i] === $elt ) {
1251 * Find the element $elt in the list and remove it.
1252 * Used when parsing <a> in body mode.
1254 public function remove( $elt ) {
1255 $idx = $this->indexOf( $elt );
1256 Assert
::parameter( $idx >= 0, '$elt', 'should be present in afe list' );
1257 array_splice( $this->elemList
, $idx, 1 );
1258 array_splice( $this->attribList
, $idx, 1 );
1262 * Find element $a in the list and replace it with element $b,
1263 * optionally replacing the stored attributes as well with $attribs.
1265 public function replace( $a, $b, $attribs=null ) {
1266 $idx = $this->indexOf( $a );
1268 $this->elemList
[ $idx ] = $b;
1269 if ( $attribs !== null ) {
1270 $this->attribList
[ $idx ] = $attribs;
1276 * Find $a in the list and insert $b after it.
1277 * This is only used for insert a bookmark object, so the
1278 * $this->attribList contents don't really matter.
1280 public function insertAfter( $a, $b ) {
1281 $idx = $this->indexOf( $a );
1283 array_splice( $this->elemList
, $idx, 0, [ $b ] );
1284 array_splice( $this->attribList
, $idx, 0, [ '' ] );
1289 * Make a copy of element $idx on the list of active formatting
1290 * elements, using its original attributes not current attributes.
1291 * (In full HTML spec, current attributes could have been modified
1294 public function cloneAt( $idx ) {
1295 $node = $this->elemList
[$idx];
1296 $attribs = $this->attribList
[$idx];
1297 return new BalanceElement(
1298 $node->namespaceURI
, $node->localName
, $attribs
1302 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
1304 * Reconstruct the active formatting elements.
1305 * @param BalanceStack $stack The open elements stack
1306 * @see https://html.spec.whatwg.org/multipage/syntax.html#reconstruct-the-active-formatting-elements
1308 // @codingStandardsIgnoreEnd
1309 public function reconstruct( $stack ) {
1310 if ( empty( $this->elemList
) ) {
1313 $len = count( $this->elemList
);
1314 $entry = $this->elemList
[$len - 1];
1315 // If the last is a marker, do nothing.
1316 if ( $entry === self
::$MARKER ) {
1319 // Or if it is an open element, do nothing.
1320 if ( $stack->indexOf( $entry ) >= 0 ) {
1324 // Loop backward through the list until we find a marker or an
1325 // open element, and then move forward one from there.
1326 for ( $i = $len - 2; $i >= 0; $i-- ) {
1327 $entry = $this->elemList
[$i];
1328 if ( $entry === self
::$MARKER ) {
1331 if ( $stack->indexOf( $entry ) >= 0 ) {
1336 // Now loop forward, starting from the element after the current
1337 // one, recreating formatting elements and pushing them back onto
1338 // the list of open elements
1339 for ( $i++
; $i < $len; $i++
) {
1340 $this->elemList
[$i] = $stack->insertHTMLElement(
1341 $this->elemList
[$i]->localName
,
1342 $this->attribList
[$i]
1349 * An implementation of the tree building portion of the HTML5 parsing
1352 * This is used to balance and tidy output so that the result can
1353 * always be cleanly serialized/deserialized by an HTML5 parser. It
1354 * does *not* guarantee "conforming" output -- the HTML5 spec contains
1355 * a number of constraints which are not enforced by the HTML5 parsing
1356 * process. But the result will be free of gross errors: misnested or
1357 * unclosed tags, for example, and will be unchanged by spec-complient
1358 * parsing followed by serialization.
1360 * The tree building stage is structured as a state machine.
1361 * When comparing the implementation to
1362 * https://www.w3.org/TR/html5/syntax.html#tree-construction
1363 * note that each state is implemented as a function with a
1364 * name ending in `Mode` (because the HTML spec refers to them
1365 * as insertion modes). The current insertion mode is held by
1366 * the $parseMode property.
1368 * The following simplifications have been made:
1369 * - We handle body content only (ie, we start `in body`.)
1370 * - The document is never in "quirks mode".
1371 * - All occurrences of < and > have been entity escaped, so we
1372 * can parse tags by simply splitting on those two characters.
1373 * Similarly, all attributes have been "cleaned" and are double-quoted
1375 * - All comments and null characters are assumed to have been removed.
1376 * - We don't alter linefeeds after <pre>/<listing>.
1377 * - The following elements are disallowed: <html>, <head>, <body>, <frameset>,
1378 * <form>, <frame>, <plaintext>, <isindex>, <textarea>, <xmp>, <iframe>,
1379 * <noembed>, <noscript>, <select>, <script>, <title>. As a result,
1380 * further simplifications can be made:
1381 * - `frameset-ok` is not tracked.
1382 * - `form element pointer` is not tracked.
1383 * - `head element pointer` is not tracked (but presumed non-null)
1384 * - Tokenizer has only a single mode.
1386 * We generally mark places where we omit cases from the spec due to
1387 * disallowed elements with a comment: `# OMITTED: <element-name>`.
1389 * The HTML spec keeps a flag during the parsing process to track
1390 * whether or not a "parse error" has been encountered. We don't
1391 * bother to track that flag, we just implement the error-handling
1392 * process as specified.
1396 * @see https://html.spec.whatwg.org/multipage/syntax.html#tree-construction
1400 private $bitsIterator;
1401 private $allowedHtmlElements;
1406 private $textIntegrationMode = false;
1407 private $pendingTableText;
1408 private $originalInsertionMode;
1409 private $fragmentContext;
1412 * Create a new Balancer.
1413 * @param array $config Balancer configuration. Includes:
1414 * 'strict' : boolean, defaults to false.
1415 * When true, enforces syntactic constraints on input:
1416 * all non-tag '<' must be escaped, all attributes must be
1417 * separated by a single space and double-quoted. This is
1418 * consistent with the output of the Sanitizer.
1419 * 'allowedHtmlElements' : array, defaults to null.
1420 * When present, the keys of this associative array give
1421 * the acceptable HTML tag names. When not present, no
1422 * tag sanitization is done.
1424 public function __construct( array $config ) {
1425 $config = $config +
[
1427 'allowedHtmlElements' => null,
1429 $this->allowedHtmlElements
= $config['allowedHtmlElements'];
1430 $this->strict
= $config['strict'];
1431 if ( $this->allowedHtmlElements
!== null ) {
1433 $bad = array_uintersect_assoc(
1434 $this->allowedHtmlElements
,
1435 BalanceSets
::$unsupportedSet[BalanceSets
::HTML_NAMESPACE
],
1436 function( $a, $b ) {
1437 // Ignore the values (just intersect the keys) by saying
1438 // all values are equal to each other.
1442 if ( count( $bad ) > 0 ) {
1443 $badstr = implode( array_keys( $bad ), ',' );
1444 throw new ParameterAssertionException(
1446 'Balance attempted with sanitization including ' .
1447 "unsupported elements: {$badstr}"
1454 * Return a balanced HTML string for the HTML fragment given by $text,
1455 * subject to the caveats listed in the class description. The result
1456 * will typically be idempotent -- that is, rebalancing the output
1457 * would result in no change.
1459 * @param string $text The markup to be balanced
1460 * @param callable $processingCallback Callback to do any variable or
1461 * parameter replacements in HTML attributes values
1462 * @param array|bool $processingArgs Arguments for the processing callback
1463 * @return string The balanced markup
1465 public function balance( $text, $processingCallback = null, $processingArgs = [] ) {
1466 $this->parseMode
= 'inBodyMode';
1467 $this->bitsIterator
= new ExplodeIterator( '<', $text );
1468 $this->afe
= new BalanceActiveFormattingElements();
1469 $this->stack
= new BalanceStack();
1470 $this->processingCallback
= $processingCallback;
1471 $this->processingArgs
= $processingArgs;
1473 # The stack is constructed with an <html> element already on it.
1474 # Set this up as a fragment parsed with <body> as the context.
1475 $this->fragmentContext
=
1476 new BalanceElement( BalanceSets
::HTML_NAMESPACE
, 'body', '' );
1477 $this->resetInsertionMode();
1479 // First element is text not tag
1480 $x = $this->bitsIterator
->current();
1481 $this->bitsIterator
->next();
1482 $this->insertToken( 'text', str_replace( '>', '>', $x ) );
1483 // Now process each tag.
1484 while ( $this->bitsIterator
->valid() ) {
1487 $this->insertToken( 'eof', null );
1488 $result = $this->stack
->getOutput();
1489 // Free memory before returning.
1490 $this->bitsIterator
= null;
1492 $this->stack
= null;
1493 $this->fragmentContext
= null;
1498 * Pass a token to the tree builder. The $token will be one of the
1499 * strings "tag", "endtag", or "text".
1501 private function insertToken( $token, $value, $attribs = null, $selfclose = false ) {
1502 // validate tags against $unsupportedSet
1503 if ( $token === 'tag' ||
$token === 'endtag' ) {
1504 if ( isset( BalanceSets
::$unsupportedSet[BalanceSets
::HTML_NAMESPACE
][$value] ) ) {
1505 # As described in "simplifications" above, these tags are
1506 # not supported in the balancer.
1509 "Unsupported $token <$value> found."
1513 } elseif ( $token === 'text' && $value === '' ) {
1514 # Don't actually inject the empty string as a text token.
1517 // Some hoops we have to jump through
1518 $adjusted = $this->stack
->adjustedCurrentNode( $this->fragmentContext
);
1522 $this->stack
->length() === 0 ||
1523 $adjusted->isHtml() ||
1527 } elseif ( $adjusted->isMathmlTextIntegrationPoint() ) {
1528 if ( $token === 'text' ) {
1532 $value !== 'mglyph' && $value !== 'malignmark'
1537 $adjusted->namespaceURI
=== BalanceSets
::MATHML_NAMESPACE
&&
1538 $adjusted->localName
=== 'annotation-xml' &&
1539 $token === 'tag' && $value === 'svg'
1543 $adjusted->isHtmlIntegrationPoint() &&
1544 ( $token === 'tag' ||
$token === 'text' )
1549 return $this->insertForeignToken( $token, $value, $attribs, $selfclose );
1551 $func = $this->parseMode
;
1552 return $this->$func( $token, $value, $attribs, $selfclose );
1556 private function insertForeignToken( $token, $value, $attribs = null, $selfclose = false ) {
1557 if ( $token === 'text' ) {
1558 $this->stack
->insertText( $value );
1560 } elseif ( $token === 'tag' ) {
1563 // We rely on Sanitizer::fixTagAttributes having run on $attribs
1564 // to normalize the form of the tag parameters.
1565 if ( !preg_match( '/(^| )(color|face|size)="/i', $attribs ) ) {
1568 /* otherwise, fall through */
1613 if ( $this->fragmentContext
) {
1617 $this->stack
->pop();
1618 $node = $this->stack
->currentNode();
1620 $node->isMathmlTextIntegrationPoint() ||
1621 $node->isHtmlIntegrationPoint() ||
1627 return $this->insertToken( $token, $value, $attribs, $selfclose );
1629 // "Any other start tag"
1630 $adjusted = ( $this->fragmentContext
&& $this->stack
->length()===1 ) ?
1631 $this->fragmentContext
: $this->stack
->currentNode();
1632 $this->stack
->insertForeignElement(
1633 $adjusted->namespaceURI
, $value, $attribs
1636 $this->stack
->pop();
1639 } elseif ( $token === 'endtag' ) {
1641 foreach ( $this->stack
as $i => $node ) {
1642 if ( $node->isHtml() && !$first ) {
1643 // process the end tag as HTML
1644 $func = $this->parseMode
;
1645 return $this->$func( $token, $value, $attribs, $selfclose );
1646 } elseif ( $i === 0 ) {
1648 } elseif ( $node->localName
=== $value ) {
1649 $this->stack
->popTag( $node );
1658 * Grab the next "token" from $bitsIterator. This is either a open/close
1659 * tag or text, depending on whether the Sanitizer approves.
1661 private function advance() {
1662 $x = $this->bitsIterator
->current();
1663 $this->bitsIterator
->next();
1665 # $slash: Does the current element start with a '/'?
1666 # $t: Current element name
1667 # $attribs: String between element name and >
1668 # $brace: Ending '>' or '/>'
1669 # $rest: Everything until the next element from the $bitsIterator
1670 if ( preg_match( Sanitizer
::ELEMENT_BITS_REGEX
, $x, $regs ) ) {
1671 list( /* $qbar */, $slash, $t, $attribs, $brace, $rest ) = $regs;
1672 $t = strtolower( $t );
1673 if ( $this->strict
) {
1674 /* Verify that attributes are all properly double-quoted */
1677 '/^( [:_A-Z0-9][-.:_A-Z0-9]*="[^"]*")*[ ]*$/i', $attribs
1679 "Bad attribute string found"
1684 !$this->strict
, "< found which does not start a valid tag"
1686 $slash = $t = $attribs = $brace = $rest = null;
1689 $sanitize = $this->allowedHtmlElements
!== null;
1691 $goodtag = $t && isset( $this->allowedHtmlElements
[$t] );
1694 if ( is_callable( $this->processingCallback
) ) {
1695 call_user_func_array( $this->processingCallback
, [ &$attribs, $this->processingArgs
] );
1698 $goodtag = Sanitizer
::validateTag( $attribs, $t );
1703 $newattribs = Sanitizer
::fixTagAttributes( $attribs, $t, true );
1705 $decoded = Sanitizer
::decodeTagAttributes( $attribs );
1707 $newattribs = Sanitizer
::safeEncodeTagAttributes( $decoded );
1709 $goodtag = $this->insertToken(
1710 $slash ?
'endtag' : 'tag', $t, $newattribs, $brace === '/>'
1714 $rest = str_replace( '>', '>', $rest );
1715 $this->insertToken( 'text', str_replace( '>', '>', $rest ) );
1717 # bad tag; serialize entire thing as text.
1718 $this->insertToken( 'text', '<' . str_replace( '>', '>', $x ) );
1722 private function switchMode( $mode ) {
1724 substr( $mode, -4 )==='Mode', '$mode', 'should end in Mode'
1726 $oldMode = $this->parseMode
;
1727 $this->parseMode
= $mode;
1731 private function switchModeAndReprocess( $mode, $token, $value, $attribs, $selfclose ) {
1732 $this->switchMode( $mode );
1733 return $this->insertToken( $token, $value, $attribs, $selfclose );
1736 private function resetInsertionMode() {
1738 foreach ( $this->stack
as $i => $node ) {
1741 if ( $this->fragmentContext
) {
1742 $node = $this->fragmentContext
;
1745 if ( $node->isHtml() ) {
1746 switch ( $node->localName
) {
1750 $stacklen = $this->stack->length();
1751 for ( $j = $i + 1; $j < $stacklen-1; $j++ ) {
1752 $ancestor = $this->stack->node( $stacklen-$j-1 );
1753 if ( $ancestor->isA( 'template' ) ) {
1756 if ( $ancestor->isA( 'table' ) ) {
1757 $this->switchMode( 'inSelectInTableMode' );
1761 $this->switchMode( 'inSelectMode' );
1765 $this->switchMode( 'inRowMode' );
1770 $this->switchMode( 'inTableBodyMode' );
1773 $this->switchMode( 'inCaptionMode' );
1776 $this->switchMode( 'inColumnGroupMode' );
1779 $this->switchMode( 'inTableMode' );
1783 array_slice( $this->templateInsertionModes
, -1 )[0]
1787 $this->switchMode( 'inBodyMode' );
1789 # OMITTED: <frameset>
1795 if ( $node->isA( BalanceSets
::$tableCellSet ) ) {
1796 $this->switchMode( 'inCellMode' );
1803 $this->switchMode( 'inBodyMode' );
1809 private function stopParsing() {
1810 # Most of the spec methods are inapplicable, other than step 2:
1811 # "pop all the nodes off the stack of open elements".
1812 # We're going to keep the top-most <html> element on the stack, though.
1813 while ( $this->stack
->length() > 1 ) {
1814 $this->stack
->pop();
1818 private function parseRawText( $value, $attribs = null ) {
1819 $this->stack
->insertHTMLElement( $value, $attribs );
1820 // XXX switch tokenizer to rawtext state?
1821 $this->originalInsertionMode
= $this->switchMode( 'inTextMode' );
1825 private function inTextMode( $token, $value, $attribs = null, $selfclose = false ) {
1826 if ( $token === 'text' ) {
1827 $this->stack
->insertText( $value );
1829 } elseif ( $token === 'eof' ) {
1830 $this->stack
->pop();
1831 return $this->switchModeAndReprocess(
1832 $this->originalInsertionMode
, $token, $value, $attribs, $selfclose
1834 } elseif ( $token === 'endtag' ) {
1835 $this->stack
->pop();
1836 $this->switchMode( $this->originalInsertionMode
);
1842 private function inHeadMode( $token, $value, $attribs = null, $selfclose = false ) {
1843 if ( $token === 'text' ) {
1844 if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
1845 $this->stack
->insertText( $matches[0] );
1846 $value = substr( $value, strlen( $matches[0] ) );
1848 if ( strlen( $value ) === 0 ) {
1849 return true; // All text handled.
1851 // Fall through to handle non-whitespace below.
1852 } elseif ( $token === 'tag' ) {
1859 $this->stack
->insertHTMLElement( $value, $attribs );
1860 $this->stack
->pop();
1863 # OMITTED: <noscript>
1866 return $this->parseRawText( $value, $attribs );
1869 $this->stack
->insertHTMLElement( $value, $attribs );
1870 $this->afe
->insertMarker();
1871 # OMITTED: frameset_ok
1872 $this->switchMode( 'inTemplateMode' );
1873 $this->templateInsertionModes
[] = $this->parseMode
;
1877 } elseif ( $token === 'endtag' ) {
1883 break; // handle at the bottom of the function
1885 if ( $this->stack
->indexOf( $value ) < 0 ) {
1886 return true; // Ignore the token.
1888 $this->stack
->generateImpliedEndTags( null, true /* thorough */ );
1889 $this->stack
->popTag( $value );
1890 $this->afe
->clearToMarker();
1891 array_pop( $this->templateInsertionModes
);
1892 $this->resetInsertionMode();
1895 // ignore any other end tag
1900 // If not handled above
1901 $this->inHeadMode( 'endtag', 'head' ); // synthetic </head>
1902 // Then redo this one
1903 return $this->insertToken( $token, $value, $attribs, $selfclose );
1906 private function inBodyMode( $token, $value, $attribs = null, $selfclose = false ) {
1907 if ( $token === 'text' ) {
1908 $this->afe
->reconstruct( $this->stack
);
1909 $this->stack
->insertText( $value );
1911 } elseif ( $token === 'eof' ) {
1912 if ( !empty( $this->templateInsertionModes
) ) {
1913 return $this->inTemplateMode( $token, $value, $attribs, $selfclose );
1915 $this->stopParsing();
1917 } elseif ( $token === 'tag' ) {
1930 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
1932 # OMITTED: <frameset>
1958 if ( $this->stack
->inButtonScope( 'p' ) ) {
1959 $this->inBodyMode( 'endtag', 'p' );
1961 $this->stack
->insertHTMLElement( $value, $attribs );
1970 if ( $this->stack
->inButtonScope( 'p' ) ) {
1971 $this->inBodyMode( 'endtag', 'p' );
1973 if ( $this->stack
->currentNode()->isA( BalanceSets
::$headingSet ) ) {
1974 $this->stack
->pop();
1976 $this->stack
->insertHTMLElement( $value, $attribs );
1981 if ( $this->stack
->inButtonScope( 'p' ) ) {
1982 $this->inBodyMode( 'endtag', 'p' );
1984 $this->stack
->insertHTMLElement( $value, $attribs );
1985 # As described in "simplifications" above:
1986 # 1. We don't touch the next token, even if it's a linefeed.
1987 # 2. OMITTED: frameset_ok
1993 # OMITTED: frameset_ok
1994 foreach ( $this->stack
as $node ) {
1995 if ( $node->isA( 'li' ) ) {
1996 $this->inBodyMode( 'endtag', 'li' );
2000 $node->isA( BalanceSets
::$specialSet ) &&
2001 !$node->isA( BalanceSets
::$addressDivPSet )
2006 if ( $this->stack
->inButtonScope( 'p' ) ) {
2007 $this->inBodyMode( 'endtag', 'p' );
2009 $this->stack
->insertHTMLElement( $value, $attribs );
2014 # OMITTED: frameset_ok
2015 foreach ( $this->stack
as $node ) {
2016 if ( $node->isA( 'dd' ) ) {
2017 $this->inBodyMode( 'endtag', 'dd' );
2020 if ( $node->isA( 'dt' ) ) {
2021 $this->inBodyMode( 'endtag', 'dt' );
2025 $node->isA( BalanceSets
::$specialSet ) &&
2026 !$node->isA( BalanceSets
::$addressDivPSet )
2031 if ( $this->stack
->inButtonScope( 'p' ) ) {
2032 $this->inBodyMode( 'endtag', 'p' );
2034 $this->stack
->insertHTMLElement( $value, $attribs );
2037 # OMITTED: <plaintext>
2040 if ( $this->stack
->inScope( 'button' ) ) {
2041 $this->inBodyMode( 'endtag', 'button' );
2042 return $this->insertToken( $token, $value, $attribs, $selfclose );
2044 $this->afe
->reconstruct( $this->stack
);
2045 $this->stack
->insertHTMLElement( $value, $attribs );
2049 $activeElement = $this->afe
->findElementByTag( 'a' );
2050 if ( $activeElement ) {
2051 $this->inBodyMode( 'endtag', 'a' );
2052 if ( $this->afe
->indexOf( $activeElement ) >= 0 ) {
2053 $this->afe
->remove( $activeElement );
2054 // Don't flatten here, since when we fall
2055 // through below we might foster parent
2056 // the new <a> tag inside this one.
2057 $this->stack
->removeElement( $activeElement, false );
2073 $this->afe
->reconstruct( $this->stack
);
2074 $this->afe
->push( $this->stack
->insertHTMLElement( $value, $attribs ), $attribs );
2078 $this->afe
->reconstruct( $this->stack
);
2079 if ( $this->stack
->inScope( 'nobr' ) ) {
2080 $this->inBodyMode( 'endtag', 'nobr' );
2081 $this->afe
->reconstruct( $this->stack
);
2083 $this->afe
->push( $this->stack
->insertHTMLElement( $value, $attribs ), $attribs );
2089 $this->afe
->reconstruct( $this->stack
);
2090 $this->stack
->insertHTMLElement( $value, $attribs );
2091 $this->afe
->insertMarker();
2092 # OMITTED: frameset_ok
2096 # The document is never in "quirks mode"; see simplifications
2098 if ( $this->stack
->inButtonScope( 'p' ) ) {
2099 $this->inBodyMode( 'endtag', 'p' );
2101 $this->stack
->insertHTMLElement( $value, $attribs );
2102 # OMITTED: frameset_ok
2103 $this->switchMode( 'inTableMode' );
2112 $this->afe
->reconstruct( $this->stack
);
2113 $this->stack
->insertHTMLElement( $value, $attribs );
2114 $this->stack
->pop();
2115 # OMITTED: frameset_ok
2119 $this->afe
->reconstruct( $this->stack
);
2120 $this->stack
->insertHTMLElement( $value, $attribs );
2121 $this->stack
->pop();
2122 # OMITTED: frameset_ok
2123 # (hence we don't need to examine the tag's "type" attribute)
2130 $this->stack
->insertHTMLElement( $value, $attribs );
2131 $this->stack
->pop();
2135 if ( $this->stack
->inButtonScope( 'p' ) ) {
2136 $this->inBodyMode( 'endtag', 'p' );
2138 $this->stack
->insertHTMLElement( $value, $attribs );
2139 $this->stack
->pop();
2144 return $this->inBodyMode( $token, 'img', $attribs, $selfclose );
2146 # OMITTED: <isindex>
2147 # OMITTED: <textarea>
2150 # OMITTED: <noembed>
2151 # OMITTED: <noscript>
2156 $this->afe->reconstruct( $this->stack );
2157 $this->stack->insertHTMLElement( $value, $attribs );
2158 switch ( $this->parseMode ) {
2160 case 'inCaptionMode':
2161 case 'inTableBodyMode':
2164 $this->switchMode( 'inSelectInTableMode' );
2167 $this->switchMode( 'inSelectMode' );
2174 if ( $this->stack
->currentNode()->isA( 'option' ) ) {
2175 $this->inBodyMode( 'endtag', 'option' );
2177 $this->afe
->reconstruct( $this->stack
);
2178 $this->stack
->insertHTMLElement( $value, $attribs );
2183 if ( $this->stack
->inScope( 'ruby' ) ) {
2184 $this->stack
->generateImpliedEndTags();
2186 $this->stack
->insertHTMLElement( $value, $attribs );
2191 if ( $this->stack
->inScope( 'ruby' ) ) {
2192 $this->stack
->generateImpliedEndTags( 'rtc' );
2194 $this->stack
->insertHTMLElement( $value, $attribs );
2198 $this->afe
->reconstruct( $this->stack
);
2199 # We skip the spec's "adjust MathML attributes" and
2200 # "adjust foreign attributes" steps, since the browser will
2201 # do this later when it parses the output and it doesn't affect
2203 $this->stack
->insertForeignElement(
2204 BalanceSets
::MATHML_NAMESPACE
, $value, $attribs
2207 # emit explicit </math> tag.
2208 $this->stack
->pop();
2213 $this->afe
->reconstruct( $this->stack
);
2214 # We skip the spec's "adjust SVG attributes" and
2215 # "adjust foreign attributes" steps, since the browser will
2216 # do this later when it parses the output and it doesn't affect
2218 $this->stack
->insertForeignElement(
2219 BalanceSets
::SVG_NAMESPACE
, $value, $attribs
2222 # emit explicit </svg> tag.
2223 $this->stack
->pop();
2238 // Ignore table tags if we're not inTableMode
2242 // Handle any other start tag here
2243 $this->afe
->reconstruct( $this->stack
);
2244 $this->stack
->insertHTMLElement( $value, $attribs );
2246 } elseif ( $token === 'endtag' ) {
2248 # </body>,</html> are unsupported.
2251 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2279 // Ignore if there is not a matching open tag
2280 if ( !$this->stack
->inScope( $value ) ) {
2283 $this->stack
->generateImpliedEndTags();
2284 $this->stack
->popTag( $value );
2290 if ( !$this->stack
->inButtonScope( 'p' ) ) {
2291 $this->inBodyMode( 'tag', 'p', '' );
2292 return $this->insertToken( $token, $value, $attribs, $selfclose );
2294 $this->stack
->generateImpliedEndTags( $value );
2295 $this->stack
->popTag( $value );
2299 if ( !$this->stack
->inListItemScope( $value ) ) {
2300 return true; # ignore
2302 $this->stack
->generateImpliedEndTags( $value );
2303 $this->stack
->popTag( $value );
2308 if ( !$this->stack
->inScope( $value ) ) {
2309 return true; # ignore
2311 $this->stack
->generateImpliedEndTags( $value );
2312 $this->stack
->popTag( $value );
2321 if ( !$this->stack
->inScope( BalanceSets
::$headingSet ) ) {
2324 $this->stack
->generateImpliedEndTags();
2325 $this->stack
->popTag( BalanceSets
::$headingSet );
2329 # Take a deep breath, then:
2346 if ( $this->stack
->adoptionAgency( $value, $this->afe
) ) {
2347 return true; # If we did something, we're done.
2349 break; # Go to the "any other end tag" case.
2354 if ( !$this->stack
->inScope( $value ) ) {
2355 return true; # ignore
2357 $this->stack
->generateImpliedEndTags();
2358 $this->stack
->popTag( $value );
2359 $this->afe
->clearToMarker();
2363 # Turn </br> into <br>
2364 return $this->inBodyMode( 'tag', $value, '' );
2367 // Any other end tag goes here
2368 foreach ( $this->stack
as $i => $node ) {
2369 if ( $node->isA( $value ) ) {
2370 $this->stack
->generateImpliedEndTags( $value );
2371 $this->stack
->popTo( $i ); # including $i
2373 } elseif ( $node->isA( BalanceSets
::$specialSet ) ) {
2374 return true; // ignore this close token.
2379 Assert
::invariant( false, "Bad token type: $token" );
2383 private function inTableMode( $token, $value, $attribs = null, $selfclose = false ) {
2384 if ( $token === 'text' ) {
2385 if ( $this->textIntegrationMode
) {
2386 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
2387 } elseif ( $this->stack
->currentNode()->isA( BalanceSets
::$tableSectionRowSet ) ) {
2388 $this->pendingTableText
= '';
2389 $this->originalInsertionMode
= $this->parseMode
;
2390 return $this->switchModeAndReprocess( 'inTableTextMode', $token, $value, $attribs, $selfclose );
2392 // fall through to default case.
2393 } elseif ( $token === 'eof' ) {
2394 $this->stopParsing();
2396 } elseif ( $token === 'tag' ) {
2399 $this->afe
->insertMarker();
2400 $this->stack
->insertHTMLElement( $value, $attribs );
2401 $this->switchMode( 'inCaptionMode' );
2404 $this->stack
->clearToContext( BalanceSets
::$tableContextSet );
2405 $this->stack
->insertHTMLElement( $value, $attribs );
2406 $this->switchMode( 'inColumnGroupMode' );
2409 $this->inTableMode( 'tag', 'colgroup', '' );
2410 return $this->insertToken( $token, $value, $attribs, $selfclose );
2414 $this->stack
->clearToContext( BalanceSets
::$tableContextSet );
2415 $this->stack
->insertHTMLElement( $value, $attribs );
2416 $this->switchMode( 'inTableBodyMode' );
2421 $this->inTableMode( 'tag', 'tbody', '' );
2422 return $this->insertToken( $token, $value, $attribs, $selfclose );
2424 if ( !$this->stack
->inTableScope( $value ) ) {
2425 return true; // Ignore this tag.
2427 $this->inTableMode( 'endtag', $value );
2428 return $this->insertToken( $token, $value, $attribs, $selfclose );
2433 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2436 // We rely on Sanitizer::fixTagAttributes having run on $attribs
2437 // to normalize the form of the tag parameters.
2438 if ( !preg_match( '/(^| )type="hidden"/i', $attribs ) ) {
2439 break; // Handle this as "everything else"
2441 $this->stack
->insertHTMLElement( $value, $attribs );
2442 $this->stack
->pop();
2447 // Fall through for "anything else" clause.
2448 } elseif ( $token === 'endtag' ) {
2451 if ( !$this->stack
->inTableScope( $value ) ) {
2452 return true; // Ignore.
2454 $this->stack
->popTag( $value );
2455 $this->resetInsertionMode();
2468 return true; // Ignore the token.
2470 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2472 // Fall through for "anything else" clause.
2474 // This is the "anything else" case:
2475 $this->stack
->fosterParentMode
= true;
2476 $this->inBodyMode( $token, $value, $attribs, $selfclose );
2477 $this->stack
->fosterParentMode
= false;
2481 private function inTableTextMode( $token, $value, $attribs = null, $selfclose = false ) {
2482 if ( $token === 'text' ) {
2483 $this->pendingTableText
.= $value;
2487 $text = $this->pendingTableText
;
2488 $this->pendingTableText
= '';
2489 if ( preg_match( '/[^\x09\x0A\x0C\x0D\x20]/', $text ) ) {
2490 // This should match the "anything else" case inTableMode
2491 $this->stack
->fosterParentMode
= true;
2492 $this->inBodyMode( 'text', $text );
2493 $this->stack
->fosterParentMode
= false;
2495 // Pending text is just whitespace.
2496 $this->stack
->insertText( $text );
2498 return $this->switchModeAndReprocess(
2499 $this->originalInsertionMode
, $token, $value, $attribs, $selfclose
2503 // helper for inCaptionMode
2504 private function endCaption() {
2505 if ( !$this->stack
->inTableScope( 'caption' ) ) {
2508 $this->stack
->generateImpliedEndTags();
2509 $this->stack
->popTag( 'caption' );
2510 $this->afe
->clearToMarker();
2511 $this->switchMode( 'inTableMode' );
2515 private function inCaptionMode( $token, $value, $attribs = null, $selfclose = false ) {
2516 if ( $token === 'tag' ) {
2527 if ( $this->endCaption() ) {
2528 $this->insertToken( $token, $value, $attribs, $selfclose );
2532 // Fall through to "anything else" case.
2533 } elseif ( $token === 'endtag' ) {
2536 $this->endCaption();
2539 if ( $this->endCaption() ) {
2540 $this->insertToken( $token, $value, $attribs, $selfclose );
2556 // Fall through to "anything else" case.
2558 // The Anything Else case
2559 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
2562 private function inColumnGroupMode( $token, $value, $attribs = null, $selfclose = false ) {
2563 if ( $token === 'text' ) {
2564 if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
2565 $this->stack
->insertText( $matches[0] );
2566 $value = substr( $value, strlen( $matches[0] ) );
2568 if ( strlen( $value ) === 0 ) {
2569 return true; // All text handled.
2571 // Fall through to handle non-whitespace below.
2572 } elseif ( $token === 'tag' ) {
2576 $this->stack
->insertHTMLElement( $value, $attribs );
2577 $this->stack
->pop();
2580 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2582 // Fall through for "anything else".
2583 } elseif ( $token === 'endtag' ) {
2586 if ( !$this->stack
->currentNode()->isA( 'colgroup' ) ) {
2587 return true; // Ignore the token.
2589 $this->stack
->pop();
2590 $this->switchMode( 'inTableMode' );
2593 return true; // Ignore the token.
2595 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2597 // Fall through for "anything else".
2598 } elseif ( $token === 'eof' ) {
2599 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
2603 if ( !$this->stack
->currentNode()->isA( 'colgroup' ) ) {
2604 return true; // Ignore the token.
2606 $this->inColumnGroupMode( 'endtag', 'colgroup' );
2607 return $this->insertToken( $token, $value, $attribs, $selfclose );
2610 // Helper function for inTableBodyMode
2611 private function endSection() {
2613 $this->stack
->inTableScope( 'tbody' ) ||
2614 $this->stack
->inTableScope( 'thead' ) ||
2615 $this->stack
->inTableScope( 'tfoot' )
2619 $this->stack
->clearToContext( BalanceSets
::$tableBodyContextSet );
2620 $this->stack
->pop();
2621 $this->switchMode( 'inTableMode' );
2624 private function inTableBodyMode( $token, $value, $attribs = null, $selfclose = false ) {
2625 if ( $token === 'tag' ) {
2628 $this->stack
->clearToContext( BalanceSets
::$tableBodyContextSet );
2629 $this->stack
->insertHTMLElement( $value, $attribs );
2630 $this->switchMode( 'inRowMode' );
2634 $this->inTableBodyMode( 'tag', 'tr', '' );
2635 $this->insertToken( $token, $value, $attribs, $selfclose );
2643 if ( $this->endSection() ) {
2644 $this->insertToken( $token, $value, $attribs, $selfclose );
2648 } elseif ( $token === 'endtag' ) {
2651 if ( $this->endSection() ) {
2652 $this->insertToken( $token, $value, $attribs, $selfclose );
2658 if ( $this->stack
->inTableScope( $value ) ) {
2659 $this->endSection();
2670 return true; // Ignore the token.
2674 return $this->inTableMode( $token, $value, $attribs, $selfclose );
2677 // Helper function for inRowMode
2678 private function endRow() {
2679 if ( !$this->stack
->inTableScope( 'tr' ) ) {
2682 $this->stack
->clearToContext( BalanceSets
::$tableRowContextSet );
2683 $this->stack
->pop();
2684 $this->switchMode( 'inTableBodyMode' );
2687 private function inRowMode( $token, $value, $attribs = null, $selfclose = false ) {
2688 if ( $token === 'tag' ) {
2692 $this->stack
->clearToContext( BalanceSets
::$tableRowContextSet );
2693 $this->stack
->insertHTMLElement( $value, $attribs );
2694 $this->switchMode( 'inCellMode' );
2695 $this->afe
->insertMarker();
2704 if ( $this->endRow() ) {
2705 $this->insertToken( $token, $value, $attribs, $selfclose );
2709 } elseif ( $token === 'endtag' ) {
2715 if ( $this->endRow() ) {
2716 $this->insertToken( $token, $value, $attribs, $selfclose );
2723 $this->stack
->inTableScope( $value ) &&
2726 $this->insertToken( $token, $value, $attribs, $selfclose );
2736 return true; // Ignore the token.
2740 return $this->inTableMode( $token, $value, $attribs, $selfclose );
2743 // Helper for inCellMode
2744 private function endCell() {
2745 if ( $this->stack
->inTableScope( 'td' ) ) {
2746 $this->inCellMode( 'endtag', 'td' );
2748 } elseif ( $this->stack
->inTableScope( 'th' ) ) {
2749 $this->inCellMode( 'endtag', 'th' );
2755 private function inCellMode( $token, $value, $attribs = null, $selfclose = false ) {
2756 if ( $token === 'tag' ) {
2767 if ( $this->endCell() ) {
2768 $this->insertToken( $token, $value, $attribs, $selfclose );
2772 } elseif ( $token === 'endtag' ) {
2776 if ( $this->stack
->inTableScope( $value ) ) {
2777 $this->stack
->generateImpliedEndTags();
2778 $this->stack
->popTag( $value );
2779 $this->afe
->clearToMarker();
2780 $this->switchMode( 'inRowMode' );
2795 if ( $this->stack
->inTableScope( $value ) ) {
2796 $this->stack
->generateImpliedEndTags();
2797 $this->stack
->popTag( BalanceSets
::$tableCellSet );
2798 $this->afe
->clearToMarker();
2799 $this->switchMode( 'inRowMode' );
2800 $this->insertToken( $token, $value, $attribs, $selfclose );
2806 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
2811 private function inSelectMode( $token, $value, $attribs = null, $selfclose = false ) {
2812 Assert::invariant( false, 'Unimplemented' );
2815 private function inSelectInTableMode( $token, $value, $attribs = null, $selfclose = false ) {
2816 Assert::invariant( false, 'Unimplemented' );
2820 private function inTemplateMode( $token, $value, $attribs = null, $selfclose = false ) {
2821 if ( $token === 'text' ) {
2822 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
2823 } elseif ( $token === 'eof' ) {
2824 if ( $this->stack
->indexOf( 'template' ) < 0 ) {
2825 $this->stopParsing();
2827 $this->stack
->popTag( 'template' );
2828 $this->afe
->clearToMarker();
2829 array_pop( $this->templateInsertionModes
);
2830 $this->resetInsertionMode();
2831 $this->insertToken( $token, $value, $attribs, $selfclose );
2834 } elseif ( $token === 'tag' ) {
2846 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2853 return $this->switchModeAndReprocess(
2854 'inTableMode', $token, $value, $attribs, $selfclose
2858 return $this->switchModeAndReprocess(
2859 'inColumnGroupMode', $token, $value, $attribs, $selfclose
2863 return $this->switchModeAndReprocess(
2864 'inTableBodyMode', $token, $value, $attribs, $selfclose
2869 return $this->switchModeAndReprocess(
2870 'inRowMode', $token, $value, $attribs, $selfclose
2873 return $this->switchModeAndReprocess(
2874 'inBodyMode', $token, $value, $attribs, $selfclose
2876 } elseif ( $token === 'endtag' ) {
2879 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2883 Assert
::invariant( false, "Bad token type: $token" );