9e96b14c60ac2785cb1bbd279b392b081559198b
[lhc/web/wiklou.git] / includes / tidy / Balancer.php
1 <?php
2 /**
3 * An implementation of the tree building portion of the HTML5 parsing
4 * spec.
5 *
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.
10 *
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.
15 *
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
20 *
21 * @file
22 * @ingroup Parser
23 * @since 1.27
24 * @author C. Scott Ananian, 2016
25 */
26 namespace MediaWiki\Tidy;
27
28 use Wikimedia\Assert\Assert;
29 use Wikimedia\Assert\ParameterAssertionException;
30 use \ExplodeIterator;
31 use \IteratorAggregate;
32 use \ReverseArrayIterator;
33 use \Sanitizer;
34
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.
45
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.
53
54 # [1]: https://www.mediawiki.org/wiki/Library_infrastructure_for_MediaWiki
55
56 /**
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.
60 *
61 * @ingroup Parser
62 * @since 1.27
63 */
64 class BalanceSets {
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';
68
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,
76 'title' => true
77 ]
78 ];
79
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
87 ]
88 ];
89
90 public static $headingSet = [
91 self::HTML_NAMESPACE => [
92 'h1' => true, 'h2' => true, 'h3' => true,
93 'h4' => true, 'h5' => true, 'h6' => true
94 ]
95 ];
96
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
123 ],
124 self::SVG_NAMESPACE => [
125 'foreignobject' => true, 'desc' => true, 'title' => true
126 ],
127 self::MATHML_NAMESPACE => [
128 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
129 'mtext' => true, 'annotation-xml' => true
130 ]
131 ];
132
133 public static $addressDivPSet = [
134 self::HTML_NAMESPACE => [
135 'address' => true, 'div' => true, 'p' => true
136 ]
137 ];
138
139 public static $tableSectionRowSet = [
140 self::HTML_NAMESPACE => [
141 'table' => true, 'thead' => true, 'tbody' => true,
142 'tfoot' => true, 'tr' => true
143 ]
144 ];
145
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
151 ]
152 ];
153
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
161 ]
162 ];
163
164 public static $tableCellSet = [
165 self::HTML_NAMESPACE => [
166 'td' => true, 'th' => true
167 ]
168 ];
169 public static $tableContextSet = [
170 self::HTML_NAMESPACE => [
171 'table' => true, 'template' => true, 'html' => true
172 ]
173 ];
174
175 public static $tableBodyContextSet = [
176 self::HTML_NAMESPACE => [
177 'tbody' => true, 'tfoot' => true, 'thead' => true,
178 'template' => true, 'html' => true
179 ]
180 ];
181
182 public static $tableRowContextSet = [
183 self::HTML_NAMESPACE => [
184 'tr' => true, 'template' => true, 'html' => true
185 ]
186 ];
187
188 # OMITTED: formAssociatedSet, since we don't allow <form>
189
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,
195 'th' => true
196 ],
197 self::SVG_NAMESPACE => [
198 'foreignobject' => true, 'desc' => true, 'title' => true
199 ],
200 self::MATHML_NAMESPACE => [
201 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
202 'mtext' => true, 'annotation-xml' => true
203 ]
204 ];
205
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;
212 }
213 return self::$inListItemScopeSet;
214 }
215
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;
221 }
222 return self::$inButtonScopeSet;
223 }
224
225 public static $inTableScopeSet = [
226 self::HTML_NAMESPACE => [
227 'html' => true, 'table' => true, 'template' => true
228 ]
229 ];
230
231 public static $mathmlTextIntegrationPointSet = [
232 self::MATHML_NAMESPACE => [
233 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
234 'mtext' => true
235 ]
236 ];
237
238 public static $htmlIntegrationPointSet = [
239 self::SVG_NAMESPACE => [
240 'foreignobject' => true,
241 'desc' => true,
242 'title' => true
243 ]
244 ];
245
246 // For tidy compatibility.
247 public static $tidyPWrapSet = [
248 self::HTML_NAMESPACE => [
249 'body' => true, 'blockquote' => true,
250 // We parse with <body> as the fragment context, but the top-level
251 // element on the stack is actually <html>. We could use the
252 // "adjusted current node" everywhere to work around this, but it's
253 // easier just to add <html> to the p-wrap set.
254 'html' => true,
255 ],
256 ];
257 public static $tidyInlineSet = [
258 self::HTML_NAMESPACE => [
259 'a' => true, 'abbr' => true, 'acronym' => true, 'applet' => true,
260 'b' => true, 'basefont' => true, 'bdo' => true, 'big' => true,
261 'br' => true, 'button' => true, 'cite' => true, 'code' => true,
262 'dfn' => true, 'em' => true, 'font' => true, 'i' => true,
263 'iframe' => true, 'img' => true, 'input' => true, 'kbd' => true,
264 'label' => true, 'legend' => true, 'map' => true, 'object' => true,
265 'param' => true, 'q' => true, 'rb' => true, 'rbc' => true,
266 'rp' => true, 'rt' => true, 'rtc' => true, 'ruby' => true,
267 's' => true, 'samp' => true, 'select' => true, 'small' => true,
268 'span' => true, 'strike' => true, 'strong' => true, 'sub' => true,
269 'sup' => true, 'textarea' => true, 'tt' => true, 'u' => true,
270 'var' => true,
271 ],
272 ];
273 }
274
275 /**
276 * A BalanceElement is a simplified version of a DOM Node. The main
277 * difference is that we only keep BalanceElements around for nodes
278 * currently on the BalanceStack of open elements. As soon as an
279 * element is closed, with some minor exceptions relating to the
280 * tree builder "adoption agency algorithm", the element and all its
281 * children are serialized to a string using the flatten() method.
282 * This keeps our memory usage low.
283 *
284 * @ingroup Parser
285 * @since 1.27
286 */
287 class BalanceElement {
288 /**
289 * The namespace of the element.
290 * @var string $namespaceURI
291 */
292 public $namespaceURI;
293 /**
294 * The lower-cased name of the element.
295 * @var string $localName
296 */
297 public $localName;
298 /**
299 * Attributes for the element, in array form
300 * @var array $attribs
301 */
302 public $attribs;
303
304 /**
305 * Parent of this element, or the string "flat" if this element has
306 * already been flattened into its parent.
307 * @var string|null $parent
308 */
309 public $parent;
310
311 /**
312 * An array of children of this element. Typically only the last
313 * child will be an actual BalanceElement object; the rest will
314 * be strings, representing either text nodes or flattened
315 * BalanceElement objects.
316 * @var array $children
317 */
318 public $children;
319
320 /**
321 * A unique string identifier for Noah's Ark purposes, lazy initialized
322 */
323 private $noahKey;
324
325 /**
326 * The next active formatting element in the list, or null if this is the
327 * end of the AFE list or if the element is not in the AFE list.
328 */
329 public $nextAFE;
330
331 /**
332 * The previous active formatting element in the list, or null if this is
333 * the start of the list or if the element is not in the AFE list.
334 */
335 public $prevAFE;
336
337 /**
338 * The next element in the Noah's Ark species bucket.
339 */
340 public $nextNoah;
341
342 /**
343 * Make a new BalanceElement corresponding to the HTML DOM Element
344 * with the given localname, namespace, and attributes.
345 *
346 * @param string $namespaceURI The namespace of the element.
347 * @param string $localName The lowercased name of the tag.
348 * @param array $attribs Attributes of the element
349 */
350 public function __construct( $namespaceURI, $localName, array $attribs ) {
351 $this->localName = $localName;
352 $this->namespaceURI = $namespaceURI;
353 $this->attribs = $attribs;
354 $this->contents = '';
355 $this->parent = null;
356 $this->children = [];
357 }
358
359 /**
360 * Remove the given child from this element.
361 * @param BalanceElement $elt
362 */
363 private function removeChild( BalanceElement $elt ) {
364 Assert::precondition(
365 $this->parent !== 'flat', "Can't removeChild after flattening $this"
366 );
367 Assert::parameter(
368 $elt->parent === $this, 'elt', 'must have $this as a parent'
369 );
370 $idx = array_search( $elt, $this->children, true );
371 Assert::parameter( $idx !== false, '$elt', 'must be a child of $this' );
372 $elt->parent = null;
373 array_splice( $this->children, $idx, 1 );
374 }
375
376 /**
377 * Find $a in the list of children and insert $b before it.
378 * @param BalanceElement $a
379 * @param BalanceElement|string $b
380 */
381 public function insertBefore( BalanceElement $a, $b ) {
382 Assert::precondition(
383 $this->parent !== 'flat', "Can't insertBefore after flattening."
384 );
385 $idx = array_search( $a, $this->children, true );
386 Assert::parameter( $idx !== false, '$a', 'must be a child of $this' );
387 if ( is_string( $b ) ) {
388 array_splice( $this->children, $idx, 0, [ $b ] );
389 } else {
390 Assert::parameter( $b->parent !== 'flat', '$b', "Can't be flat" );
391 if ( $b->parent !== null ) {
392 $b->parent->removeChild( $b );
393 }
394 array_splice( $this->children, $idx, 0, [ $b ] );
395 $b->parent = $this;
396 }
397 }
398
399 /**
400 * Append $elt to the end of the list of children.
401 * @param BalanceElement|string $elt
402 */
403 public function appendChild( $elt ) {
404 Assert::precondition(
405 $this->parent !== 'flat', "Can't appendChild after flattening."
406 );
407 if ( is_string( $elt ) ) {
408 array_push( $this->children, $elt );
409 return;
410 }
411 // Remove $elt from parent, if it had one.
412 if ( $elt->parent !== null ) {
413 $elt->parent->removeChild( $elt );
414 }
415 array_push( $this->children, $elt );
416 $elt->parent = $this;
417 }
418
419 /**
420 * Transfer all of the children of $elt to $this.
421 * @param BalanceElement $elt
422 */
423 public function adoptChildren( BalanceElement $elt ) {
424 Assert::precondition(
425 $elt->parent !== 'flat', "Can't adoptChildren after flattening."
426 );
427 foreach ( $elt->children as $child ) {
428 if ( !is_string( $child ) ) {
429 // This is an optimization which avoids an O(n^2) set of
430 // array_splice operations.
431 $child->parent = null;
432 }
433 $this->appendChild( $child );
434 }
435 $elt->children = [];
436 }
437
438 /**
439 * Flatten this node and all of its children into a string, as specified
440 * by the HTML serialization specification, and replace this node
441 * in its parent by that string.
442 *
443 * @see __toString()
444 */
445 public function flatten( $tidyCompat = false ) {
446 Assert::parameter( $this->parent !== null, '$this', 'must be a child' );
447 Assert::parameter( $this->parent !== 'flat', '$this', 'already flat' );
448 $idx = array_search( $this, $this->parent->children, true );
449 Assert::parameter(
450 $idx !== false, '$this', 'must be a child of its parent'
451 );
452 if ( $tidyCompat ) {
453 $blank = true;
454 foreach ( $this->children as $elt ) {
455 if ( !is_string( $elt ) ) {
456 $elt = $elt->flatten( $tidyCompat );
457 }
458 if ( $blank && preg_match( '/[^\t\n\f\r ]/', $elt ) ) {
459 $blank = false;
460 }
461 }
462 if ( $this->isHtmlNamed( 'mw:p-wrap' ) ) {
463 $this->localName = 'p';
464 } elseif ( $blank ) {
465 // Add 'mw-empty-elt' class so elements can be hidden via CSS
466 // for compatibility with legacy tidy.
467 if ( !count( $this->attribs ) &&
468 ( $this->localName === 'tr' || $this->localName === 'li' )
469 ) {
470 $this->attribs = [ 'class' => "mw-empty-elt" ];
471 }
472 $blank = false;
473 }
474 $flat = $blank ? '' : "{$this}";
475 } else {
476 $flat = "{$this}";
477 }
478 $this->parent->children[$idx] = $flat;
479 $this->parent = 'flat'; # for assertion checking
480 return $flat;
481 }
482
483 /**
484 * Serialize this node and all of its children to a string, as specified
485 * by the HTML serialization specification.
486 *
487 * @return string The serialization of the BalanceElement
488 * @see https://html.spec.whatwg.org/multipage/syntax.html#serialising-html-fragments
489 */
490 public function __toString() {
491 $encAttribs = '';
492 foreach ( $this->attribs as $name => $value ) {
493 $encValue = Sanitizer::encodeAttribute( $value );
494 $encAttribs .= " $name=\"$encValue\"";
495 }
496 if ( !$this->isA( BalanceSets::$emptyElementSet ) ) {
497 $out = "<{$this->localName}{$encAttribs}>";
498 // flatten children
499 foreach ( $this->children as $elt ) {
500 $out .= "{$elt}";
501 }
502 $out .= "</{$this->localName}>";
503 } else {
504 $out = "<{$this->localName}{$encAttribs} />";
505 Assert::invariant(
506 count( $this->children ) === 0,
507 "Empty elements shouldn't have children."
508 );
509 }
510 return $out;
511 }
512
513 # Utility functions on BalanceElements.
514
515 /**
516 * Determine if $this represents a specific HTML tag, is a member of
517 * a tag set, or is equal to another BalanceElement.
518 *
519 * @param BalanceElement|array|string $set The target BalanceElement,
520 * set (from the BalanceSets class), or string (HTML tag name).
521 * @return bool
522 */
523 public function isA( $set ) {
524 if ( $set instanceof BalanceElement ) {
525 return $this === $set;
526 } elseif ( is_array( $set ) ) {
527 return isset( $set[$this->namespaceURI] ) &&
528 isset( $set[$this->namespaceURI][$this->localName] );
529 } else {
530 # assume this is an HTML element name.
531 return $this->isHtml() && $this->localName === $set;
532 }
533 }
534
535 /**
536 * Determine if this element is an HTML element with the specified name
537 * @param string $tagName
538 * @return bool
539 */
540 public function isHtmlNamed( $tagName ) {
541 return $this->namespaceURI === BalanceSets::HTML_NAMESPACE
542 && $this->localName === $tagName;
543 }
544
545 /**
546 * Determine if $this represents an element in the HTML namespace.
547 *
548 * @return bool
549 */
550 public function isHtml() {
551 return $this->namespaceURI === BalanceSets::HTML_NAMESPACE;
552 }
553
554 /**
555 * Determine if $this represents a MathML text integration point,
556 * as defined in the HTML5 specification.
557 *
558 * @return bool
559 * @see https://html.spec.whatwg.org/multipage/syntax.html#mathml-text-integration-point
560 */
561 public function isMathmlTextIntegrationPoint() {
562 return $this->isA( BalanceSets::$mathmlTextIntegrationPointSet );
563 }
564
565 /**
566 * Determine if $this represents an HTML integration point,
567 * as defined in the HTML5 specification.
568 *
569 * @return bool
570 * @see https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
571 */
572 public function isHtmlIntegrationPoint() {
573 if ( $this->isA( BalanceSets::$htmlIntegrationPointSet ) ) {
574 return true;
575 }
576 if (
577 $this->namespaceURI === BalanceSets::MATHML_NAMESPACE &&
578 $this->localName === 'annotation-xml' &&
579 isset( $this->attribs['encoding'] ) &&
580 ( strcasecmp( $this->attribs['encoding'], 'text/html' ) == 0 ||
581 strcasecmp( $this->attribs['encoding'], 'application/xhtml+xml' ) == 0 )
582 ) {
583 return true;
584 }
585 return false;
586 }
587
588 /**
589 * Get a string key for the Noah's Ark algorithm
590 */
591 public function getNoahKey() {
592 if ( $this->noahKey === null ) {
593 $attribs = $this->attribs;
594 ksort( $attribs );
595 $this->noahKey = serialize( [ $this->namespaceURI, $this->localName, $attribs ] );
596 }
597 return $this->noahKey;
598 }
599 }
600
601 /**
602 * The "stack of open elements" as defined in the HTML5 tree builder
603 * spec. This contains methods to ensure that content (start tags, text)
604 * are inserted at the correct place in the output string, and to
605 * flatten BalanceElements are they are closed to avoid holding onto
606 * a complete DOM tree for the document in memory.
607 *
608 * The stack defines a PHP iterator to traverse it in "reverse order",
609 * that is, the most-recently-added element is visited first in a
610 * foreach loop.
611 *
612 * @ingroup Parser
613 * @since 1.27
614 * @see https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements
615 */
616 class BalanceStack implements IteratorAggregate {
617 /**
618 * Backing storage for the stack.
619 * @var array $elements
620 */
621 private $elements = [];
622 /**
623 * Foster parent mode determines how nodes are inserted into the
624 * stack.
625 * @var bool $fosterParentMode
626 * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
627 */
628 public $fosterParentMode = false;
629 /**
630 * Tidy compatibility mode, determines behavior of body/blockquote
631 */
632 public $tidyCompat = false;
633 /**
634 * Reference to the current element
635 */
636 public $currentNode;
637
638 /**
639 * Create a new BalanceStack with a single BalanceElement on it,
640 * representing the root &lt;html&gt; node.
641 */
642 public function __construct() {
643 # always a root <html> element on the stack
644 array_push(
645 $this->elements,
646 new BalanceElement( BalanceSets::HTML_NAMESPACE, 'html', [] )
647 );
648 $this->currentNode = $this->elements[0];
649 }
650
651 /**
652 * Return a string representing the output of the tree builder:
653 * all the children of the root &lt;html&gt; node.
654 * @return string
655 */
656 public function getOutput() {
657 // Don't include the outer '<html>....</html>'
658 $out = '';
659 foreach ( $this->elements[0]->children as $elt ) {
660 $out .= is_string( $elt ) ? $elt :
661 $elt->flatten( $this->tidyCompat );
662 }
663 return $out;
664 }
665
666 /**
667 * Insert text at the appropriate place for inserting a node.
668 * @param string $value
669 * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
670 */
671 public function insertText( $value ) {
672 if (
673 $this->fosterParentMode &&
674 $this->currentNode->isA( BalanceSets::$tableSectionRowSet )
675 ) {
676 $this->fosterParent( $value );
677 } elseif (
678 $this->tidyCompat &&
679 $this->currentNode->isA( BalanceSets::$tidyPWrapSet )
680 ) {
681 $this->insertHTMLELement( 'mw:p-wrap', [] );
682 return $this->insertText( $value );
683 } else {
684 $this->currentNode->appendChild( $value );
685 }
686 }
687
688 /**
689 * Insert a BalanceElement at the appropriate place, pushing it
690 * on to the open elements stack.
691 * @param string $namespaceURI The element namespace
692 * @param string $tag The tag name
693 * @param string $attribs Normalized attributes, as a string.
694 * @return BalanceElement
695 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-a-foreign-element
696 */
697 public function insertForeignElement( $namespaceURI, $tag, $attribs ) {
698 return $this->insertElement(
699 new BalanceElement( $namespaceURI, $tag, $attribs )
700 );
701 }
702
703 /**
704 * Insert an HTML element at the appropriate place, pushing it on to
705 * the open elements stack.
706 * @param string $tag The tag name
707 * @param string $attribs Normalized attributes, as a string.
708 * @return BalanceElement
709 * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-an-html-element
710 */
711 public function insertHTMLElement( $tag, $attribs ) {
712 return $this->insertForeignElement(
713 BalanceSets::HTML_NAMESPACE, $tag, $attribs
714 );
715 }
716
717 /**
718 * Insert an element at the appropriate place and push it on to the
719 * open elements stack.
720 * @param BalanceElement $elt
721 * @return BalanceElement
722 * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
723 */
724 public function insertElement( BalanceElement $elt ) {
725 if (
726 $this->currentNode->isHtmlNamed( 'mw:p-wrap' ) &&
727 !$elt->isA( BalanceSets::$tidyInlineSet )
728 ) {
729 // Tidy compatibility.
730 $this->pop();
731 }
732 if (
733 $this->fosterParentMode &&
734 $this->currentNode->isA( BalanceSets::$tableSectionRowSet )
735 ) {
736 $elt = $this->fosterParent( $elt );
737 } else {
738 $this->currentNode->appendChild( $elt );
739 }
740 Assert::invariant( $elt->parent !== null, "$elt must be in tree" );
741 Assert::invariant( $elt->parent !== 'flat', "$elt must not have been previous flattened" );
742 array_push( $this->elements, $elt );
743 $this->currentNode = $elt;
744 return $elt;
745 }
746
747 /**
748 * Determine if the stack has $tag in scope.
749 * @param BalanceElement|array|string $tag
750 * @return bool
751 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
752 */
753 public function inScope( $tag ) {
754 return $this->inSpecificScope( $tag, BalanceSets::$inScopeSet );
755 }
756
757 /**
758 * Determine if the stack has $tag in button scope.
759 * @param BalanceElement|array|string $tag
760 * @return bool
761 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
762 */
763 public function inButtonScope( $tag ) {
764 return $this->inSpecificScope( $tag, BalanceSets::inButtonScopeSet() );
765 }
766
767 /**
768 * Determine if the stack has $tag in list item scope.
769 * @param BalanceElement|array|string $tag
770 * @return bool
771 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-list-item-scope
772 */
773 public function inListItemScope( $tag ) {
774 return $this->inSpecificScope( $tag, BalanceSets::inListItemScopeSet() );
775 }
776
777 /**
778 * Determine if the stack has $tag in table scope.
779 * @param BalanceElement|array|string $tag
780 * @return bool
781 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-table-scope
782 */
783 public function inTableScope( $tag ) {
784 return $this->inSpecificScope( $tag, BalanceSets::$inTableScopeSet );
785 }
786
787 /**
788 * Determine if the stack has $tag in a specific scope, $set.
789 * @param BalanceElement|array|string $tag
790 * @param BalanceElement|array|string $set
791 * @return bool
792 * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-the-specific-scope
793 */
794 public function inSpecificScope( $tag, $set ) {
795 foreach ( $this as $elt ) {
796 if ( $elt->isA( $tag ) ) {
797 return true;
798 }
799 if ( $elt->isA( $set ) ) {
800 return false;
801 }
802 }
803 return false;
804 }
805
806 /**
807 * Generate implied end tags.
808 * @param string $butnot
809 * @param bool $thorough True if we should generate end tags thoroughly.
810 * @see https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
811 */
812 public function generateImpliedEndTags( $butnot = null, $thorough = false ) {
813 $endTagSet = $thorough ?
814 BalanceSets::$thoroughImpliedEndTagsSet :
815 BalanceSets::$impliedEndTagsSet;
816 while ( $this->currentNode ) {
817 if ( $butnot !== null && $this->currentNode->isHtmlNamed( $butnot ) ) {
818 break;
819 }
820 if ( !$this->currentNode->isA( $endTagSet ) ) {
821 break;
822 }
823 $this->pop();
824 }
825 }
826
827 /**
828 * Return the adjusted current node.
829 */
830 public function adjustedCurrentNode( $fragmentContext ) {
831 return ( $fragmentContext && count( $this->elements ) === 1 ) ?
832 $fragmentContext : $this->currentNode;
833 }
834
835 /**
836 * Return an iterator over this stack which visits the current node
837 * first, and the root node last.
838 * @return Iterator
839 */
840 public function getIterator() {
841 return new ReverseArrayIterator( $this->elements );
842 }
843
844 /**
845 * Return the BalanceElement at the given position $idx, where
846 * position 0 represents the root element.
847 * @param int $idx
848 * @return BalanceElement
849 */
850 public function node( $idx ) {
851 return $this->elements[ $idx ];
852 }
853
854 /**
855 * Replace the element at position $idx in the BalanceStack with $elt.
856 * @param int $idx
857 * @param BalanceElement $elt
858 */
859 public function replaceAt( $idx, BalanceElement $elt ) {
860 Assert::precondition(
861 $this->elements[$idx]->parent !== 'flat',
862 'Replaced element should not have already been flattened.'
863 );
864 Assert::precondition(
865 $elt->parent !== 'flat',
866 'New element should not have already been flattened.'
867 );
868 $this->elements[$idx] = $elt;
869 if ( $idx === count( $this->elements ) - 1 ) {
870 $this->currentNode = $elt;
871 }
872 }
873
874 /**
875 * Return the position of the given BalanceElement, set, or
876 * HTML tag name string in the BalanceStack.
877 * @param BalanceElement|array|string $tag
878 * @return int
879 */
880 public function indexOf( $tag ) {
881 for ( $i = count( $this->elements ) - 1; $i >= 0; $i-- ) {
882 if ( $this->elements[$i]->isA( $tag ) ) {
883 return $i;
884 }
885 }
886 return -1;
887 }
888
889 /**
890 * Return the number of elements currently in the BalanceStack.
891 * @return int
892 */
893 public function length() {
894 return count( $this->elements );
895 }
896
897 /**
898 * Remove the current node from the BalanceStack, flattening it
899 * in the process.
900 */
901 public function pop() {
902 $elt = array_pop( $this->elements );
903 if ( count( $this->elements ) ) {
904 $this->currentNode = $this->elements[ count( $this->elements ) - 1 ];
905 } else {
906 $this->currentNode = null;
907 }
908 if ( !$elt->isHtmlNamed( 'mw:p-wrap' ) ) {
909 $elt->flatten( $this->tidyCompat );
910 }
911 }
912
913 /**
914 * Remove all nodes up to and including position $idx from the
915 * BalanceStack, flattening them in the process.
916 * @param int $idx
917 */
918 public function popTo( $idx ) {
919 $length = count( $this->elements );
920 for ( $length = count( $this->elements ); $length > $idx; $length-- ) {
921 $this->pop();
922 }
923 }
924
925 /**
926 * Pop elements off the stack up to and including the first
927 * element with the specified HTML tagname (or matching the given
928 * set).
929 * @param BalanceElement|array|string $tag
930 */
931 public function popTag( $tag ) {
932 while ( $this->currentNode ) {
933 if ( $this->currentNode->isA( $tag ) ) {
934 $this->pop();
935 break;
936 }
937 $this->pop();
938 }
939 }
940
941 /**
942 * Pop elements off the stack *not including* the first element
943 * in the specified set.
944 * @param BalanceElement|array|string $set
945 */
946 public function clearToContext( $set ) {
947 // Note that we don't loop to 0. Never pop the <html> elt off.
948 for ( $length = count( $this->elements ); $length > 1; $length-- ) {
949 if ( $this->currentNode->isA( $set ) ) {
950 break;
951 }
952 $this->pop();
953 }
954 }
955
956 /**
957 * Remove the given $elt from the BalanceStack, optionally
958 * flattening it in the process.
959 * @param BalanceElement $elt The element to remove.
960 * @param bool $flatten Whether to flatten the removed element.
961 */
962 public function removeElement( BalanceElement $elt, $flatten = true ) {
963 Assert::parameter(
964 $elt->parent !== 'flat',
965 '$elt',
966 '$elt should not already have been flattened.'
967 );
968 Assert::parameter(
969 $elt->parent->parent !== 'flat',
970 '$elt',
971 'The parent of $elt should not already have been flattened.'
972 );
973 $idx = array_search( $elt, $this->elements, true );
974 Assert::parameter( $idx !== false, '$elt', 'must be in stack' );
975 array_splice( $this->elements, $idx, 1 );
976 if ( $idx === count( $this->elements ) ) {
977 $this->currentNode = $this->elements[$idx - 1];
978 }
979 if ( $flatten ) {
980 // serialize $elt into its parent
981 // otherwise, it will eventually serialize when the parent
982 // is serialized, we just hold onto the memory for its
983 // tree of objects a little longer.
984 $elt->flatten( $this->tidyCompat );
985 }
986 Assert::postcondition(
987 array_search( $elt, $this->elements, true ) === false,
988 '$elt should no longer be in open elements stack'
989 );
990 }
991
992 /**
993 * Find $a in the BalanceStack and insert $b after it.
994 * @param BalanceElement $a
995 * @param BalanceElement $b
996 */
997 public function insertAfter( BalanceElement $a, BalanceElement $b ) {
998 $idx = $this->indexOf( $a );
999 Assert::parameter( $idx !== false, '$a', 'must be in stack' );
1000 if ( $idx === count( $this->elements ) - 1 ) {
1001 array_push( $this->elements, $b );
1002 $this->currentNode = $b;
1003 } else {
1004 array_splice( $this->elements, $idx + 1, 0, [ $b ] );
1005 }
1006 }
1007
1008 # Fostering and adoption.
1009
1010 /**
1011 * Foster parent the given $elt in the stack of open elements.
1012 * @param BalanceElement|string $elt
1013 * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
1014 */
1015 private function fosterParent( $elt ) {
1016 $lastTable = $this->indexOf( 'table' );
1017 $lastTemplate = $this->indexOf( 'template' );
1018 $parent = null;
1019 $before = null;
1020
1021 if ( $lastTemplate >= 0 && ( $lastTable < 0 || $lastTemplate > $lastTable ) ) {
1022 $parent = $this->elements[$lastTemplate];
1023 } elseif ( $lastTable >= 0 ) {
1024 $parent = $this->elements[$lastTable]->parent;
1025 # Assume all tables have parents, since we're not running scripts!
1026 Assert::invariant(
1027 $parent !== null, "All tables should have parents"
1028 );
1029 $before = $this->elements[$lastTable];
1030 } else {
1031 $parent = $this->elements[0]; // the `html` element.
1032 }
1033
1034 if ( $this->tidyCompat ) {
1035 if ( is_string( $elt ) ) {
1036 // We're fostering text: do we need a p-wrapper?
1037 if ( $parent->isA( BalanceSets::$tidyPWrapSet ) ) {
1038 $this->insertHTMLElement( 'mw:p-wrap', [] );
1039 $this->insertText( $elt );
1040 return $elt;
1041 }
1042 } else {
1043 // We're fostering an element; do we need to merge p-wrappers?
1044 if ( $elt->isHtmlNamed( 'mw:p-wrap' ) ) {
1045 $idx = $before ?
1046 array_search( $before, $parent->children, true ) :
1047 count( $parent->children );
1048 $after = $idx > 0 ? $parent->children[$idx - 1] : '';
1049 if (
1050 $after instanceof BalanceElement &&
1051 $after->isHtmlNamed( 'mw:p-wrap' )
1052 ) {
1053 return $after; // Re-use existing p-wrapper.
1054 }
1055 }
1056 }
1057 }
1058
1059 if ( $before ) {
1060 $parent->insertBefore( $before, $elt );
1061 } else {
1062 $parent->appendChild( $elt );
1063 }
1064 return $elt;
1065 }
1066
1067 /**
1068 * Run the "adoption agency algoritm" (AAA) for the given subject
1069 * tag name.
1070 * @param string $tag The subject tag name.
1071 * @param BalanceActiveFormattingElements $afe The current
1072 * active formatting elements list.
1073 * @return true if the adoption agency algorithm "did something", false
1074 * if more processing is required by the caller.
1075 * @see https://html.spec.whatwg.org/multipage/syntax.html#adoption-agency-algorithm
1076 */
1077 public function adoptionAgency( $tag, $afe ) {
1078 // If the current node is an HTML element whose tag name is subject,
1079 // and the current node is not in the list of active formatting
1080 // elements, then pop the current node off the stack of open
1081 // elements and abort these steps.
1082 if (
1083 $this->currentNode->isHtmlNamed( $tag ) &&
1084 !$afe->isInList( $this->currentNode )
1085 ) {
1086 $this->pop();
1087 return true; // no more handling required
1088 }
1089
1090 // Let outer loop counter be zero.
1091 $outer = 0;
1092
1093 // Outer loop: If outer loop counter is greater than or
1094 // equal to eight, then abort these steps.
1095 while ( $outer < 8 ) {
1096 // Increment outer loop counter by one.
1097 $outer++;
1098
1099 // Let the formatting element be the last element in the list
1100 // of active formatting elements that: is between the end of
1101 // the list and the last scope marker in the list, if any, or
1102 // the start of the list otherwise, and has the same tag name
1103 // as the token.
1104 $fmtelt = $afe->findElementByTag( $tag );
1105
1106 // If there is no such node, then abort these steps and instead
1107 // act as described in the "any other end tag" entry below.
1108 if ( !$fmtelt ) {
1109 return false; // false means handle by the default case
1110 }
1111
1112 // Otherwise, if there is such a node, but that node is not in
1113 // the stack of open elements, then this is a parse error;
1114 // remove the element from the list, and abort these steps.
1115 $index = $this->indexOf( $fmtelt );
1116 if ( $index < 0 ) {
1117 $afe->remove( $fmtelt );
1118 return true; // true means no more handling required
1119 }
1120
1121 // Otherwise, if there is such a node, and that node is also in
1122 // the stack of open elements, but the element is not in scope,
1123 // then this is a parse error; ignore the token, and abort
1124 // these steps.
1125 if ( !$this->inScope( $fmtelt ) ) {
1126 return true;
1127 }
1128
1129 // Let the furthest block be the topmost node in the stack of
1130 // open elements that is lower in the stack than the formatting
1131 // element, and is an element in the special category. There
1132 // might not be one.
1133 $furthestblock = null;
1134 $furthestblockindex = -1;
1135 $stacklen = $this->length();
1136 for ( $i = $index+1; $i < $stacklen; $i++ ) {
1137 if ( $this->node( $i )->isA( BalanceSets::$specialSet ) ) {
1138 $furthestblock = $this->node( $i );
1139 $furthestblockindex = $i;
1140 break;
1141 }
1142 }
1143
1144 // If there is no furthest block, then the UA must skip the
1145 // subsequent steps and instead just pop all the nodes from the
1146 // bottom of the stack of open elements, from the current node
1147 // up to and including the formatting element, and remove the
1148 // formatting element from the list of active formatting
1149 // elements.
1150 if ( !$furthestblock ) {
1151 $this->popTag( $fmtelt );
1152 $afe->remove( $fmtelt );
1153 return true;
1154 } else {
1155 // Let the common ancestor be the element immediately above
1156 // the formatting element in the stack of open elements.
1157 $ancestor = $this->node( $index-1 );
1158
1159 // Let a bookmark note the position of the formatting
1160 // element in the list of active formatting elements
1161 // relative to the elements on either side of it in the
1162 // list.
1163 $BOOKMARK = new BalanceElement( '[bookmark]', '[bookmark]', [] );
1164 $afe->insertAfter( $fmtelt, $BOOKMARK );
1165
1166 // Let node and last node be the furthest block.
1167 $node = $furthestblock;
1168 $lastnode = $furthestblock;
1169 $nodeindex = $furthestblockindex;
1170 $isAFE = false;
1171
1172 // Let inner loop counter be zero.
1173 $inner = 0;
1174
1175 while ( true ) {
1176
1177 // Increment inner loop counter by one.
1178 $inner++;
1179
1180 // Let node be the element immediately above node in
1181 // the stack of open elements, or if node is no longer
1182 // in the stack of open elements (e.g. because it got
1183 // removed by this algorithm), the element that was
1184 // immediately above node in the stack of open elements
1185 // before node was removed.
1186 $node = $this->node( --$nodeindex );
1187
1188 // If node is the formatting element, then go
1189 // to the next step in the overall algorithm.
1190 if ( $node === $fmtelt ) break;
1191
1192 // If the inner loop counter is greater than three and node
1193 // is in the list of active formatting elements, then remove
1194 // node from the list of active formatting elements.
1195 $isAFE = $afe->isInList( $node );
1196 if ( $inner > 3 && $isAFE ) {
1197 $afe->remove( $node );
1198 $isAFE = false;
1199 }
1200
1201 // If node is not in the list of active formatting
1202 // elements, then remove node from the stack of open
1203 // elements and then go back to the step labeled inner
1204 // loop.
1205 if ( !$isAFE ) {
1206 // Don't flatten here, since we're about to relocate
1207 // parts of this $node.
1208 $this->removeElement( $node, false );
1209 continue;
1210 }
1211
1212 // Create an element for the token for which the
1213 // element node was created with common ancestor as
1214 // the intended parent, replace the entry for node
1215 // in the list of active formatting elements with an
1216 // entry for the new element, replace the entry for
1217 // node in the stack of open elements with an entry for
1218 // the new element, and let node be the new element.
1219 $newelt = new BalanceElement(
1220 $node->namespaceURI, $node->localName, $node->attribs );
1221 $afe->replace( $node, $newelt );
1222 $this->replaceAt( $nodeindex, $newelt );
1223 $node = $newelt;
1224
1225 // If last node is the furthest block, then move the
1226 // aforementioned bookmark to be immediately after the
1227 // new node in the list of active formatting elements.
1228 if ( $lastnode === $furthestblock ) {
1229 $afe->remove( $BOOKMARK );
1230 $afe->insertAfter( $newelt, $BOOKMARK );
1231 }
1232
1233 // Insert last node into node, first removing it from
1234 // its previous parent node if any.
1235 $node->appendChild( $lastnode );
1236
1237 // Let last node be node.
1238 $lastnode = $node;
1239 }
1240
1241 // If the common ancestor node is a table, tbody, tfoot,
1242 // thead, or tr element, then, foster parent whatever last
1243 // node ended up being in the previous step, first removing
1244 // it from its previous parent node if any.
1245 if (
1246 $this->fosterParentMode &&
1247 $ancestor->isA( BalanceSets::$tableSectionRowSet )
1248 ) {
1249 $this->fosterParent( $lastnode );
1250 } else {
1251 // Otherwise, append whatever last node ended up being in
1252 // the previous step to the common ancestor node, first
1253 // removing it from its previous parent node if any.
1254 $ancestor->appendChild( $lastnode );
1255 }
1256
1257 // Create an element for the token for which the
1258 // formatting element was created, with furthest block
1259 // as the intended parent.
1260 $newelt2 = new BalanceElement(
1261 $fmtelt->namespaceURI, $fmtelt->localName, $fmtelt->attribs );
1262
1263 // Take all of the child nodes of the furthest block and
1264 // append them to the element created in the last step.
1265 $newelt2->adoptChildren( $furthestblock );
1266
1267 // Append that new element to the furthest block.
1268 $furthestblock->appendChild( $newelt2 );
1269
1270 // Remove the formatting element from the list of active
1271 // formatting elements, and insert the new element into the
1272 // list of active formatting elements at the position of
1273 // the aforementioned bookmark.
1274 $afe->remove( $fmtelt );
1275 $afe->replace( $BOOKMARK, $newelt2 );
1276
1277 // Remove the formatting element from the stack of open
1278 // elements, and insert the new element into the stack of
1279 // open elements immediately below the position of the
1280 // furthest block in that stack.
1281 $this->removeElement( $fmtelt );
1282 $this->insertAfter( $furthestblock, $newelt2 );
1283 }
1284 }
1285
1286 return true;
1287 }
1288
1289 /**
1290 * Return the contents of the open elements stack as a string for
1291 * debugging.
1292 * @return string
1293 */
1294 public function __toString() {
1295 $r = [];
1296 foreach ( $this->elements as $elt ) {
1297 array_push( $r, $elt->localName );
1298 }
1299 return implode( $r, ' ' );
1300 }
1301 }
1302
1303 /**
1304 * A pseudo-element used as a marker in the list of active formatting elements
1305 *
1306 * @ingroup Parser
1307 * @since 1.27
1308 */
1309 class BalanceMarker {
1310 public $nextAFE;
1311 public $prevAFE;
1312 }
1313
1314 /**
1315 * The list of active formatting elements, which is used to handle
1316 * mis-nested formatting element tags in the HTML5 tree builder
1317 * specification.
1318 *
1319 * @ingroup Parser
1320 * @since 1.27
1321 * @see https://html.spec.whatwg.org/multipage/syntax.html#list-of-active-formatting-elements
1322 */
1323 class BalanceActiveFormattingElements {
1324 /** The last (most recent) element in the list */
1325 private $tail;
1326
1327 /** The first (least recent) element in the list */
1328 private $head;
1329
1330 /**
1331 * An array of arrays representing the population of elements in each bucket
1332 * according to the Noah's Ark clause. The outer array is stack-like, with each
1333 * integer-indexed element representing a segment of the list, bounded by
1334 * markers. The first element represents the segment of the list before the
1335 * first marker.
1336 *
1337 * The inner arrays are indexed by "Noah key", which is a string which uniquely
1338 * identifies each bucket according to the rules in the spec. The value in
1339 * the inner array is the first (least recently inserted) element in the bucket,
1340 * and subsequent members of the bucket can be found by iterating through the
1341 * singly-linked list via $node->nextNoah.
1342 *
1343 * This is optimised for the most common case of inserting into a bucket
1344 * with zero members, and deleting a bucket containing one member. In the
1345 * worst case, iteration through the list is still O(1) in the document
1346 * size, since each bucket can have at most 3 members.
1347 */
1348 private $noahTableStack = [ [] ];
1349
1350 public function __destruct() {
1351 for ( $node = $this->head; $node; $node = $next ) {
1352 $next = $node->nextAFE;
1353 $node->prevAFE = $node->nextAFE = $node->nextNoah = null;
1354 }
1355 $this->head = $this->tail = $this->noahTableStack = null;
1356 }
1357
1358 public function insertMarker() {
1359 $elt = new BalanceMarker;
1360 if ( $this->tail ) {
1361 $this->tail->nextAFE = $elt;
1362 $elt->prevAFE = $this->tail;
1363 } else {
1364 $this->head = $elt;
1365 }
1366 $this->tail = $elt;
1367 $this->noahTableStack[] = [];
1368 }
1369
1370 /**
1371 * Follow the steps required when the spec requires us to "push onto the
1372 * list of active formatting elements".
1373 * @param BalanceElement $elt
1374 */
1375 public function push( BalanceElement $elt ) {
1376 // Must not be in the list already
1377 if ( $elt->prevAFE !== null || $this->head === $elt ) {
1378 throw new ParameterAssertionException( '$elt',
1379 'Cannot insert a node into the AFE list twice' );
1380 }
1381
1382 // "Noah's Ark clause" -- if there are already three copies of
1383 // this element before we encounter a marker, then drop the last
1384 // one.
1385 $noahKey = $elt->getNoahKey();
1386 $table =& $this->noahTableStack[ count( $this->noahTableStack ) - 1 ];
1387 if ( !isset( $table[$noahKey] ) ) {
1388 $table[$noahKey] = $elt;
1389 } else {
1390 $count = 1;
1391 $head = $tail = $table[$noahKey];
1392 while ( $tail->nextNoah ) {
1393 $tail = $tail->nextNoah;
1394 $count++;
1395 }
1396 if ( $count >= 3 ) {
1397 $this->remove( $head );
1398 }
1399 $tail->nextNoah = $elt;
1400 }
1401 // Add to the main AFE list
1402 if ( $this->tail ) {
1403 $this->tail->nextAFE = $elt;
1404 $elt->prevAFE = $this->tail;
1405 } else {
1406 $this->head = $elt;
1407 }
1408 $this->tail = $elt;
1409 }
1410
1411 /**
1412 * Follow the steps required when the spec asks us to "clear the list of
1413 * active formatting elements up to the last marker".
1414 */
1415 public function clearToMarker() {
1416 // Iterate back through the list starting from the tail
1417 $tail = $this->tail;
1418 while ( $tail && !( $tail instanceof BalanceMarker ) ) {
1419 // Unlink the element
1420 $prev = $tail->prevAFE;
1421 $tail->prevAFE = null;
1422 if ( $prev ) {
1423 $prev->nextAFE = null;
1424 }
1425 $tail->nextNoah = null;
1426 $tail = $prev;
1427 }
1428 // If we finished on a marker, unlink it and pop it off the Noah table stack
1429 if ( $tail ) {
1430 $prev = $tail->prevAFE;
1431 if ( $prev ) {
1432 $prev->nextAFE = null;
1433 }
1434 $tail = $prev;
1435 array_pop( $this->noahTableStack );
1436 } else {
1437 // No marker: wipe the top-level Noah table (which is the only one)
1438 $this->noahTableStack[0] = [];
1439 }
1440 // If we removed all the elements, clear the head pointer
1441 if ( !$tail ) {
1442 $this->head = null;
1443 }
1444 $this->tail = $tail;
1445 }
1446
1447 /**
1448 * Find and return the last element with the specified tag between the
1449 * end of the list and the last marker on the list.
1450 * Used when parsing &lt;a&gt; "in body mode".
1451 */
1452 public function findElementByTag( $tag ) {
1453 $elt = $this->tail;
1454 while ( $elt && !( $elt instanceof BalanceMarker ) ) {
1455 if ( $elt->localName === $tag ) {
1456 return $elt;
1457 }
1458 $elt = $elt->prevAFE;
1459 }
1460 return null;
1461 }
1462
1463 /**
1464 * Determine whether an element is in the list of formatting elements.
1465 * @return boolean
1466 */
1467 public function isInList( BalanceElement $elt ) {
1468 return $this->head === $elt || $elt->prevAFE;
1469 }
1470
1471 /**
1472 * Find the element $elt in the list and remove it.
1473 * Used when parsing &lt;a&gt; in body mode.
1474 */
1475 public function remove( BalanceElement $elt ) {
1476 if ( $this->head !== $elt && !$elt->prevAFE ) {
1477 throw new ParameterAssertionException( '$elt',
1478 "Attempted to remove an element which is not in the AFE list" );
1479 }
1480 // Update head and tail pointers
1481 if ( $this->head === $elt ) {
1482 $this->head = $elt->nextAFE;
1483 }
1484 if ( $this->tail === $elt ) {
1485 $this->tail = $elt->prevAFE;
1486 }
1487 // Update previous element
1488 if ( $elt->prevAFE ) {
1489 $elt->prevAFE->nextAFE = $elt->nextAFE;
1490 }
1491 // Update next element
1492 if ( $elt->nextAFE ) {
1493 $elt->nextAFE->prevAFE = $elt->prevAFE;
1494 }
1495 // Clear pointers so that isInList() etc. will work
1496 $elt->prevAFE = $elt->nextAFE = null;
1497 // Update Noah list
1498 $this->removeFromNoahList( $elt );
1499 }
1500
1501 private function addToNoahList( BalanceElement $elt ) {
1502 $noahKey = $elt->getNoahKey();
1503 $table =& $this->noahTableStack[ count( $this->noahTableStack ) - 1 ];
1504 if ( !isset( $table[$noahKey] ) ) {
1505 $table[$noahKey] = $elt;
1506 } else {
1507 $tail = $table[$noahKey];
1508 while ( $tail->nextNoah ) {
1509 $tail = $tail->nextNoah;
1510 }
1511 $tail->nextNoah = $elt;
1512 }
1513 }
1514
1515 private function removeFromNoahList( BalanceElement $elt ) {
1516 $table =& $this->noahTableStack[ count( $this->noahTableStack ) - 1 ];
1517 $key = $elt->getNoahKey();
1518 $noahElt = $table[$key];
1519 if ( $noahElt === $elt ) {
1520 if ( $noahElt->nextNoah ) {
1521 $table[$key] = $noahElt->nextNoah;
1522 $noahElt->nextNoah = null;
1523 } else {
1524 unset( $table[$key] );
1525 }
1526 } else {
1527 do {
1528 $prevNoahElt = $noahElt;
1529 $noahElt = $prevNoahElt->nextNoah;
1530 if ( $noahElt === $elt ) {
1531 // Found it, unlink
1532 $prevNoahElt->nextNoah = $elt->nextNoah;
1533 $elt->nextNoah = null;
1534 break;
1535 }
1536 } while ( $noahElt );
1537 }
1538 }
1539
1540 /**
1541 * Find element $a in the list and replace it with element $b
1542 */
1543 public function replace( BalanceElement $a, BalanceElement $b ) {
1544 if ( $this->head !== $a && !$a->prevAFE ) {
1545 throw new ParameterAssertionException( '$a',
1546 "Attempted to replace an element which is not in the AFE list" );
1547 }
1548 // Update head and tail pointers
1549 if ( $this->head === $a ) {
1550 $this->head = $b;
1551 }
1552 if ( $this->tail === $a ) {
1553 $this->tail = $b;
1554 }
1555 // Update previous element
1556 if ( $a->prevAFE ) {
1557 $a->prevAFE->nextAFE = $b;
1558 }
1559 // Update next element
1560 if ( $a->nextAFE ) {
1561 $a->nextAFE->prevAFE = $b;
1562 }
1563 $b->prevAFE = $a->prevAFE;
1564 $b->nextAFE = $a->nextAFE;
1565 $a->nextAFE = $a->prevAFE = null;
1566 // Update Noah list
1567 $this->removeFromNoahList( $a );
1568 $this->addToNoahList( $b );
1569 }
1570
1571 /**
1572 * Find $a in the list and insert $b after it.
1573 */
1574 public function insertAfter( BalanceElement $a, BalanceElement $b ) {
1575 if ( $this->head !== $a && !$a->prevAFE ) {
1576 throw new ParameterAssertionException( '$a',
1577 "Attempted to insert after an element which is not in the AFE list" );
1578 }
1579 if ( $this->tail === $a ) {
1580 $this->tail = $b;
1581 }
1582 if ( $a->nextAFE ) {
1583 $a->nextAFE->prevAFE = $b;
1584 }
1585 $b->nextAFE = $a->nextAFE;
1586 $b->prevAFE = $a;
1587 $a->nextAFE = $b;
1588 $this->addToNoahList( $b );
1589 }
1590
1591 // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
1592 /**
1593 * Reconstruct the active formatting elements.
1594 * @param BalanceStack $stack The open elements stack
1595 * @see https://html.spec.whatwg.org/multipage/syntax.html#reconstruct-the-active-formatting-elements
1596 */
1597 // @codingStandardsIgnoreEnd
1598 public function reconstruct( $stack ) {
1599 $entry = $this->tail;
1600 // If there are no entries in the list of active formatting elements,
1601 // then there is nothing to reconstruct
1602 if ( !$entry ) {
1603 return;
1604 }
1605 // If the last is a marker, do nothing.
1606 if ( $entry instanceof BalanceMarker ) {
1607 return;
1608 }
1609 // Or if it is an open element, do nothing.
1610 if ( $stack->indexOf( $entry ) >= 0 ) {
1611 return;
1612 }
1613
1614 // Loop backward through the list until we find a marker or an
1615 // open element
1616 while ( $entry->prevAFE ) {
1617 $entry = $entry->prevAFE;
1618 if ( $entry instanceof BalanceMarker || $stack->indexOf( $entry ) >= 0 ) {
1619 break;
1620 }
1621 }
1622
1623 // Now loop forward, starting from the element after the current one (or
1624 // the first element if we didn't find a marker or open element),
1625 // recreating formatting elements and pushing them back onto the list
1626 // of open elements.
1627 if ( $entry->prevAFE ) {
1628 $entry = $entry->nextAFE;
1629 }
1630 do {
1631 $newElement = $stack->insertHTMLElement(
1632 $entry->localName,
1633 $entry->attribs );
1634 $this->replace( $entry, $newElement );
1635 $entry = $newElement->nextAFE;
1636 } while ( $entry );
1637 }
1638
1639 /**
1640 * Get a string representation of the AFE list, for debugging
1641 */
1642 public function __toString() {
1643 $prev = null;
1644 $s = '';
1645 for ( $node = $this->head; $node; $prev = $node, $node = $node->nextAFE ) {
1646 if ( $node instanceof BalanceMarker ) {
1647 $s .= "MARKER\n";
1648 continue;
1649 }
1650 $s .= $node->localName . '#' . substr( md5( spl_object_hash( $node ) ), 0, 8 );
1651 if ( $node->nextNoah ) {
1652 $s .= " (noah sibling: {$node->nextNoah->localName}#" .
1653 substr( md5( spl_object_hash( $node->nextNoah ) ), 0, 8 ) .
1654 ')';
1655 }
1656 if ( $node->nextAFE && $node->nextAFE->prevAFE !== $node ) {
1657 $s .= " (reverse link is wrong!)";
1658 }
1659 $s .= "\n";
1660 }
1661 if ( $prev !== $this->tail ) {
1662 $s .= "(tail pointer is wrong!)\n";
1663 }
1664 return $s;
1665 }
1666 }
1667
1668 /**
1669 * An implementation of the tree building portion of the HTML5 parsing
1670 * spec.
1671 *
1672 * This is used to balance and tidy output so that the result can
1673 * always be cleanly serialized/deserialized by an HTML5 parser. It
1674 * does *not* guarantee "conforming" output -- the HTML5 spec contains
1675 * a number of constraints which are not enforced by the HTML5 parsing
1676 * process. But the result will be free of gross errors: misnested or
1677 * unclosed tags, for example, and will be unchanged by spec-complient
1678 * parsing followed by serialization.
1679 *
1680 * The tree building stage is structured as a state machine.
1681 * When comparing the implementation to
1682 * https://www.w3.org/TR/html5/syntax.html#tree-construction
1683 * note that each state is implemented as a function with a
1684 * name ending in `Mode` (because the HTML spec refers to them
1685 * as insertion modes). The current insertion mode is held by
1686 * the $parseMode property.
1687 *
1688 * The following simplifications have been made:
1689 * - We handle body content only (ie, we start `in body`.)
1690 * - The document is never in "quirks mode".
1691 * - All occurrences of < and > have been entity escaped, so we
1692 * can parse tags by simply splitting on those two characters.
1693 * Similarly, all attributes have been "cleaned" and are double-quoted
1694 * and escaped.
1695 * - All comments and null characters are assumed to have been removed.
1696 * - We don't alter linefeeds after <pre>/<listing>.
1697 * - The following elements are disallowed: <html>, <head>, <body>, <frameset>,
1698 * <form>, <frame>, <plaintext>, <isindex>, <textarea>, <xmp>, <iframe>,
1699 * <noembed>, <noscript>, <select>, <script>, <title>. As a result,
1700 * further simplifications can be made:
1701 * - `frameset-ok` is not tracked.
1702 * - `form element pointer` is not tracked.
1703 * - `head element pointer` is not tracked (but presumed non-null)
1704 * - Tokenizer has only a single mode.
1705 *
1706 * We generally mark places where we omit cases from the spec due to
1707 * disallowed elements with a comment: `# OMITTED: <element-name>`.
1708 *
1709 * The HTML spec keeps a flag during the parsing process to track
1710 * whether or not a "parse error" has been encountered. We don't
1711 * bother to track that flag, we just implement the error-handling
1712 * process as specified.
1713 *
1714 * @ingroup Parser
1715 * @since 1.27
1716 * @see https://html.spec.whatwg.org/multipage/syntax.html#tree-construction
1717 */
1718 class Balancer {
1719 private $parseMode;
1720 private $bitsIterator;
1721 private $allowedHtmlElements;
1722 private $afe;
1723 private $stack;
1724 private $strict;
1725 private $tidyCompat;
1726
1727 private $textIntegrationMode = false;
1728 private $pendingTableText;
1729 private $originalInsertionMode;
1730 private $fragmentContext;
1731
1732 /**
1733 * Create a new Balancer.
1734 * @param array $config Balancer configuration. Includes:
1735 * 'strict' : boolean, defaults to false.
1736 * When true, enforces syntactic constraints on input:
1737 * all non-tag '<' must be escaped, all attributes must be
1738 * separated by a single space and double-quoted. This is
1739 * consistent with the output of the Sanitizer.
1740 * 'allowedHtmlElements' : array, defaults to null.
1741 * When present, the keys of this associative array give
1742 * the acceptable HTML tag names. When not present, no
1743 * tag sanitization is done.
1744 * 'tidyCompat' : boolean, defaults to false.
1745 * When true, the serialization algorithm is tweaked to
1746 * provide historical compatibility with the old "tidy"
1747 * program: <p>-wrapping is done to the children of
1748 * <body> and <blockquote> elements, and empty elements
1749 * are removed.
1750 */
1751 public function __construct( array $config = [] ) {
1752 $config = $config + [
1753 'strict' => false,
1754 'allowedHtmlElements' => null,
1755 'tidyCompat' => false,
1756 ];
1757 $this->allowedHtmlElements = $config['allowedHtmlElements'];
1758 $this->strict = $config['strict'];
1759 $this->tidyCompat = $config['tidyCompat'];
1760 if ( $this->allowedHtmlElements !== null ) {
1761 # Sanity check!
1762 $bad = array_uintersect_assoc(
1763 $this->allowedHtmlElements,
1764 BalanceSets::$unsupportedSet[BalanceSets::HTML_NAMESPACE],
1765 function( $a, $b ) {
1766 // Ignore the values (just intersect the keys) by saying
1767 // all values are equal to each other.
1768 return 0;
1769 }
1770 );
1771 if ( count( $bad ) > 0 ) {
1772 $badstr = implode( array_keys( $bad ), ',' );
1773 throw new ParameterAssertionException(
1774 '$config',
1775 'Balance attempted with sanitization including ' .
1776 "unsupported elements: {$badstr}"
1777 );
1778 }
1779 }
1780 }
1781
1782 /**
1783 * Return a balanced HTML string for the HTML fragment given by $text,
1784 * subject to the caveats listed in the class description. The result
1785 * will typically be idempotent -- that is, rebalancing the output
1786 * would result in no change.
1787 *
1788 * @param string $text The markup to be balanced
1789 * @param callable $processingCallback Callback to do any variable or
1790 * parameter replacements in HTML attributes values
1791 * @param array|bool $processingArgs Arguments for the processing callback
1792 * @return string The balanced markup
1793 */
1794 public function balance( $text, $processingCallback = null, $processingArgs = [] ) {
1795 $this->parseMode = 'inBodyMode';
1796 $this->bitsIterator = new ExplodeIterator( '<', $text );
1797 $this->afe = new BalanceActiveFormattingElements();
1798 $this->stack = new BalanceStack();
1799 $this->stack->tidyCompat = $this->tidyCompat;
1800 $this->processingCallback = $processingCallback;
1801 $this->processingArgs = $processingArgs;
1802
1803 # The stack is constructed with an <html> element already on it.
1804 # Set this up as a fragment parsed with <body> as the context.
1805 $this->fragmentContext =
1806 new BalanceElement( BalanceSets::HTML_NAMESPACE, 'body', [] );
1807 $this->resetInsertionMode();
1808
1809 // First element is text not tag
1810 $x = $this->bitsIterator->current();
1811 $this->bitsIterator->next();
1812 $this->insertToken( 'text', str_replace( '>', '&gt;', $x ) );
1813 // Now process each tag.
1814 while ( $this->bitsIterator->valid() ) {
1815 $this->advance();
1816 }
1817 $this->insertToken( 'eof', null );
1818 $result = $this->stack->getOutput();
1819 // Free memory before returning.
1820 $this->bitsIterator = null;
1821 $this->afe = null;
1822 $this->stack = null;
1823 $this->fragmentContext = null;
1824 return $result;
1825 }
1826
1827 /**
1828 * Pass a token to the tree builder. The $token will be one of the
1829 * strings "tag", "endtag", or "text".
1830 */
1831 private function insertToken( $token, $value, $attribs = null, $selfclose = false ) {
1832 // validate tags against $unsupportedSet
1833 if ( $token === 'tag' || $token === 'endtag' ) {
1834 if ( isset( BalanceSets::$unsupportedSet[BalanceSets::HTML_NAMESPACE][$value] ) ) {
1835 # As described in "simplifications" above, these tags are
1836 # not supported in the balancer.
1837 Assert::invariant(
1838 !$this->strict,
1839 "Unsupported $token <$value> found."
1840 );
1841 return false;
1842 }
1843 } elseif ( $token === 'text' && $value === '' ) {
1844 # Don't actually inject the empty string as a text token.
1845 return true;
1846 }
1847 // Some hoops we have to jump through
1848 $adjusted = $this->stack->adjustedCurrentNode( $this->fragmentContext );
1849
1850 $isForeign = true;
1851 if (
1852 $this->stack->length() === 0 ||
1853 $adjusted->isHtml() ||
1854 $token === 'eof'
1855 ) {
1856 $isForeign = false;
1857 } elseif ( $adjusted->isMathmlTextIntegrationPoint() ) {
1858 if ( $token === 'text' ) {
1859 $isForeign = false;
1860 } elseif (
1861 $token === 'tag' &&
1862 $value !== 'mglyph' && $value !== 'malignmark'
1863 ) {
1864 $isForeign = false;
1865 }
1866 } elseif (
1867 $adjusted->namespaceURI === BalanceSets::MATHML_NAMESPACE &&
1868 $adjusted->localName === 'annotation-xml' &&
1869 $token === 'tag' && $value === 'svg'
1870 ) {
1871 $isForeign = false;
1872 } elseif (
1873 $adjusted->isHtmlIntegrationPoint() &&
1874 ( $token === 'tag' || $token === 'text' )
1875 ) {
1876 $isForeign = false;
1877 }
1878 if ( $isForeign ) {
1879 return $this->insertForeignToken( $token, $value, $attribs, $selfclose );
1880 } else {
1881 $func = $this->parseMode;
1882 return $this->$func( $token, $value, $attribs, $selfclose );
1883 }
1884 }
1885
1886 private function insertForeignToken( $token, $value, $attribs = null, $selfclose = false ) {
1887 if ( $token === 'text' ) {
1888 $this->stack->insertText( $value );
1889 return true;
1890 } elseif ( $token === 'tag' ) {
1891 switch ( $value ) {
1892 case 'font':
1893 if ( isset( $attribs['color'] )
1894 || isset( $attribs['face'] )
1895 || isset( $attribs['size'] )
1896 ) {
1897 break;
1898 }
1899 /* otherwise, fall through */
1900 case 'b':
1901 case 'big':
1902 case 'blockquote':
1903 case 'body':
1904 case 'br':
1905 case 'center':
1906 case 'code':
1907 case 'dd':
1908 case 'div':
1909 case 'dl':
1910 case 'dt':
1911 case 'em':
1912 case 'embed':
1913 case 'h1':
1914 case 'h2':
1915 case 'h3':
1916 case 'h4':
1917 case 'h5':
1918 case 'h6':
1919 case 'head':
1920 case 'hr':
1921 case 'i':
1922 case 'img':
1923 case 'li':
1924 case 'listing':
1925 case 'menu':
1926 case 'meta':
1927 case 'nobr':
1928 case 'ol':
1929 case 'p':
1930 case 'pre':
1931 case 'ruby':
1932 case 's':
1933 case 'small':
1934 case 'span':
1935 case 'strong':
1936 case 'strike':
1937 case 'sub':
1938 case 'sup':
1939 case 'table':
1940 case 'tt':
1941 case 'u':
1942 case 'ul':
1943 case 'var':
1944 if ( $this->fragmentContext ) {
1945 break;
1946 }
1947 while ( true ) {
1948 $this->stack->pop();
1949 $node = $this->stack->currentNode;
1950 if (
1951 $node->isMathmlTextIntegrationPoint() ||
1952 $node->isHtmlIntegrationPoint() ||
1953 $node->isHtml()
1954 ) {
1955 break;
1956 }
1957 }
1958 return $this->insertToken( $token, $value, $attribs, $selfclose );
1959 }
1960 // "Any other start tag"
1961 $adjusted = ( $this->fragmentContext && $this->stack->length()===1 ) ?
1962 $this->fragmentContext : $this->stack->currentNode;
1963 $this->stack->insertForeignElement(
1964 $adjusted->namespaceURI, $value, $attribs
1965 );
1966 if ( $selfclose ) {
1967 $this->stack->pop();
1968 }
1969 return true;
1970 } elseif ( $token === 'endtag' ) {
1971 $first = true;
1972 foreach ( $this->stack as $i => $node ) {
1973 if ( $node->isHtml() && !$first ) {
1974 // process the end tag as HTML
1975 $func = $this->parseMode;
1976 return $this->$func( $token, $value, $attribs, $selfclose );
1977 } elseif ( $i === 0 ) {
1978 return true;
1979 } elseif ( $node->localName === $value ) {
1980 $this->stack->popTag( $node );
1981 return true;
1982 }
1983 $first = false;
1984 }
1985 }
1986 }
1987
1988 /**
1989 * Grab the next "token" from $bitsIterator. This is either a open/close
1990 * tag or text, depending on whether the Sanitizer approves.
1991 */
1992 private function advance() {
1993 $x = $this->bitsIterator->current();
1994 $this->bitsIterator->next();
1995 $regs = [];
1996 # $slash: Does the current element start with a '/'?
1997 # $t: Current element name
1998 # $attribStr: String between element name and >
1999 # $brace: Ending '>' or '/>'
2000 # $rest: Everything until the next element from the $bitsIterator
2001 if ( preg_match( Sanitizer::ELEMENT_BITS_REGEX, $x, $regs ) ) {
2002 list( /* $qbar */, $slash, $t, $attribStr, $brace, $rest ) = $regs;
2003 $t = strtolower( $t );
2004 if ( $this->strict ) {
2005 /* Verify that attributes are all properly double-quoted */
2006 Assert::invariant(
2007 preg_match(
2008 '/^( [:_A-Z0-9][-.:_A-Z0-9]*="[^"]*")*[ ]*$/i', $attribStr
2009 ),
2010 "Bad attribute string found"
2011 );
2012 }
2013 } else {
2014 Assert::invariant(
2015 !$this->strict, "< found which does not start a valid tag"
2016 );
2017 $slash = $t = $attribStr = $brace = $rest = null;
2018 }
2019 $goodtag = $t;
2020 $sanitize = $this->allowedHtmlElements !== null;
2021 if ( $sanitize ) {
2022 $goodtag = $t && isset( $this->allowedHtmlElements[$t] );
2023 }
2024 if ( $goodtag ) {
2025 if ( is_callable( $this->processingCallback ) ) {
2026 call_user_func_array( $this->processingCallback, [ &$attribStr, $this->processingArgs ] );
2027 }
2028 if ( $sanitize ) {
2029 $goodtag = Sanitizer::validateTag( $attribStr, $t );
2030 }
2031 }
2032 if ( $goodtag ) {
2033 if ( $sanitize ) {
2034 $attribs = Sanitizer::decodeTagAttributes( $attribStr );
2035 $attribs = Sanitizer::validateTagAttributes( $attribs, $t );
2036 } else {
2037 $attribs = Sanitizer::decodeTagAttributes( $attribStr );
2038 }
2039 $goodtag = $this->insertToken(
2040 $slash ? 'endtag' : 'tag', $t, $attribs, $brace === '/>'
2041 );
2042 }
2043 if ( $goodtag ) {
2044 $rest = str_replace( '>', '&gt;', $rest );
2045 $this->insertToken( 'text', str_replace( '>', '&gt;', $rest ) );
2046 } else {
2047 # bad tag; serialize entire thing as text.
2048 $this->insertToken( 'text', '&lt;' . str_replace( '>', '&gt;', $x ) );
2049 }
2050 }
2051
2052 private function switchMode( $mode ) {
2053 Assert::parameter(
2054 substr( $mode, -4 )==='Mode', '$mode', 'should end in Mode'
2055 );
2056 $oldMode = $this->parseMode;
2057 $this->parseMode = $mode;
2058 return $oldMode;
2059 }
2060
2061 private function switchModeAndReprocess( $mode, $token, $value, $attribs, $selfclose ) {
2062 $this->switchMode( $mode );
2063 return $this->insertToken( $token, $value, $attribs, $selfclose );
2064 }
2065
2066 private function resetInsertionMode() {
2067 $last = false;
2068 foreach ( $this->stack as $i => $node ) {
2069 if ( $i === 0 ) {
2070 $last = true;
2071 if ( $this->fragmentContext ) {
2072 $node = $this->fragmentContext;
2073 }
2074 }
2075 if ( $node->isHtml() ) {
2076 switch ( $node->localName ) {
2077 # OMITTED: <select>
2078 /*
2079 case 'select':
2080 $stacklen = $this->stack->length();
2081 for ( $j = $i + 1; $j < $stacklen-1; $j++ ) {
2082 $ancestor = $this->stack->node( $stacklen-$j-1 );
2083 if ( $ancestor->isHtmlNamed( 'template' ) ) {
2084 break;
2085 }
2086 if ( $ancestor->isHtmlNamed( 'table' ) ) {
2087 $this->switchMode( 'inSelectInTableMode' );
2088 return;
2089 }
2090 }
2091 $this->switchMode( 'inSelectMode' );
2092 return;
2093 */
2094 case 'tr':
2095 $this->switchMode( 'inRowMode' );
2096 return;
2097 case 'tbody':
2098 case 'tfoot':
2099 case 'thead':
2100 $this->switchMode( 'inTableBodyMode' );
2101 return;
2102 case 'caption':
2103 $this->switchMode( 'inCaptionMode' );
2104 return;
2105 case 'colgroup':
2106 $this->switchMode( 'inColumnGroupMode' );
2107 return;
2108 case 'table':
2109 $this->switchMode( 'inTableMode' );
2110 return;
2111 case 'template':
2112 $this->switchMode(
2113 array_slice( $this->templateInsertionModes, -1 )[0]
2114 );
2115 return;
2116 case 'body':
2117 $this->switchMode( 'inBodyMode' );
2118 return;
2119 # OMITTED: <frameset>
2120 # OMITTED: <html>
2121 # OMITTED: <head>
2122 default:
2123 if ( !$last ) {
2124 # OMITTED: <head>
2125 if ( $node->isA( BalanceSets::$tableCellSet ) ) {
2126 $this->switchMode( 'inCellMode' );
2127 return;
2128 }
2129 }
2130 }
2131 }
2132 if ( $last ) {
2133 $this->switchMode( 'inBodyMode' );
2134 return;
2135 }
2136 }
2137 }
2138
2139 private function stopParsing() {
2140 # Most of the spec methods are inapplicable, other than step 2:
2141 # "pop all the nodes off the stack of open elements".
2142 # We're going to keep the top-most <html> element on the stack, though.
2143
2144 # Clear the AFE list first, otherwise the element objects will stay live
2145 # during serialization, potentially using O(N^2) memory. Note that
2146 # popping the stack will never result in reconstructing the active
2147 # formatting elements.
2148 $this->afe = null;
2149 $this->stack->popTo( 1 );
2150 }
2151
2152 private function parseRawText( $value, $attribs = null ) {
2153 $this->stack->insertHTMLElement( $value, $attribs );
2154 // XXX switch tokenizer to rawtext state?
2155 $this->originalInsertionMode = $this->switchMode( 'inTextMode' );
2156 return true;
2157 }
2158
2159 private function inTextMode( $token, $value, $attribs = null, $selfclose = false ) {
2160 if ( $token === 'text' ) {
2161 $this->stack->insertText( $value );
2162 return true;
2163 } elseif ( $token === 'eof' ) {
2164 $this->stack->pop();
2165 return $this->switchModeAndReprocess(
2166 $this->originalInsertionMode, $token, $value, $attribs, $selfclose
2167 );
2168 } elseif ( $token === 'endtag' ) {
2169 $this->stack->pop();
2170 $this->switchMode( $this->originalInsertionMode );
2171 return true;
2172 }
2173 return true;
2174 }
2175
2176 private function inHeadMode( $token, $value, $attribs = null, $selfclose = false ) {
2177 if ( $token === 'text' ) {
2178 if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
2179 $this->stack->insertText( $matches[0] );
2180 $value = substr( $value, strlen( $matches[0] ) );
2181 }
2182 if ( strlen( $value ) === 0 ) {
2183 return true; // All text handled.
2184 }
2185 // Fall through to handle non-whitespace below.
2186 } elseif ( $token === 'tag' ) {
2187 switch ( $value ) {
2188 case 'meta':
2189 # OMITTED: in a full HTML parser, this might change the encoding.
2190 /* falls through */
2191 # OMITTED: <html>
2192 case 'base':
2193 case 'basefont':
2194 case 'bgsound':
2195 case 'link':
2196 $this->stack->insertHTMLElement( $value, $attribs );
2197 $this->stack->pop();
2198 return true;
2199 # OMITTED: <title>
2200 # OMITTED: <noscript>
2201 case 'noframes':
2202 case 'style':
2203 return $this->parseRawText( $value, $attribs );
2204 # OMITTED: <script>
2205 case 'template':
2206 $this->stack->insertHTMLElement( $value, $attribs );
2207 $this->afe->insertMarker();
2208 # OMITTED: frameset_ok
2209 $this->switchMode( 'inTemplateMode' );
2210 $this->templateInsertionModes[] = $this->parseMode;
2211 return true;
2212 # OMITTED: <head>
2213 }
2214 } elseif ( $token === 'endtag' ) {
2215 switch ( $value ) {
2216 # OMITTED: <head>
2217 # OMITTED: <body>
2218 # OMITTED: <html>
2219 case 'br':
2220 break; // handle at the bottom of the function
2221 case 'template':
2222 if ( $this->stack->indexOf( $value ) < 0 ) {
2223 return true; // Ignore the token.
2224 }
2225 $this->stack->generateImpliedEndTags( null, true /* thorough */ );
2226 $this->stack->popTag( $value );
2227 $this->afe->clearToMarker();
2228 array_pop( $this->templateInsertionModes );
2229 $this->resetInsertionMode();
2230 return true;
2231 default:
2232 // ignore any other end tag
2233 return true;
2234 }
2235 }
2236
2237 // If not handled above
2238 $this->inHeadMode( 'endtag', 'head' ); // synthetic </head>
2239 // Then redo this one
2240 return $this->insertToken( $token, $value, $attribs, $selfclose );
2241 }
2242
2243 private function inBodyMode( $token, $value, $attribs = null, $selfclose = false ) {
2244 if ( $token === 'text' ) {
2245 $this->afe->reconstruct( $this->stack );
2246 $this->stack->insertText( $value );
2247 return true;
2248 } elseif ( $token === 'eof' ) {
2249 if ( !empty( $this->templateInsertionModes ) ) {
2250 return $this->inTemplateMode( $token, $value, $attribs, $selfclose );
2251 }
2252 $this->stopParsing();
2253 return true;
2254 } elseif ( $token === 'tag' ) {
2255 switch ( $value ) {
2256 # OMITTED: <html>
2257 case 'base':
2258 case 'basefont':
2259 case 'bgsound':
2260 case 'link':
2261 case 'meta':
2262 case 'noframes':
2263 # OMITTED: <script>
2264 case 'style':
2265 case 'template':
2266 # OMITTED: <title>
2267 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2268 # OMITTED: <body>
2269 # OMITTED: <frameset>
2270
2271 case 'address':
2272 case 'article':
2273 case 'aside':
2274 case 'blockquote':
2275 case 'center':
2276 case 'details':
2277 case 'dialog':
2278 case 'dir':
2279 case 'div':
2280 case 'dl':
2281 case 'fieldset':
2282 case 'figcaption':
2283 case 'figure':
2284 case 'footer':
2285 case 'header':
2286 case 'hgroup':
2287 case 'main':
2288 case 'menu':
2289 case 'nav':
2290 case 'ol':
2291 case 'p':
2292 case 'section':
2293 case 'summary':
2294 case 'ul':
2295 if ( $this->stack->inButtonScope( 'p' ) ) {
2296 $this->inBodyMode( 'endtag', 'p' );
2297 }
2298 $this->stack->insertHTMLElement( $value, $attribs );
2299 return true;
2300
2301 case 'h1':
2302 case 'h2':
2303 case 'h3':
2304 case 'h4':
2305 case 'h5':
2306 case 'h6':
2307 if ( $this->stack->inButtonScope( 'p' ) ) {
2308 $this->inBodyMode( 'endtag', 'p' );
2309 }
2310 if ( $this->stack->currentNode->isA( BalanceSets::$headingSet ) ) {
2311 $this->stack->pop();
2312 }
2313 $this->stack->insertHTMLElement( $value, $attribs );
2314 return true;
2315
2316 case 'pre':
2317 case 'listing':
2318 if ( $this->stack->inButtonScope( 'p' ) ) {
2319 $this->inBodyMode( 'endtag', 'p' );
2320 }
2321 $this->stack->insertHTMLElement( $value, $attribs );
2322 # As described in "simplifications" above:
2323 # 1. We don't touch the next token, even if it's a linefeed.
2324 # 2. OMITTED: frameset_ok
2325 return true;
2326
2327 # OMITTED: <form>
2328
2329 case 'li':
2330 # OMITTED: frameset_ok
2331 foreach ( $this->stack as $node ) {
2332 if ( $node->isHtmlNamed( 'li' ) ) {
2333 $this->inBodyMode( 'endtag', 'li' );
2334 break;
2335 }
2336 if (
2337 $node->isA( BalanceSets::$specialSet ) &&
2338 !$node->isA( BalanceSets::$addressDivPSet )
2339 ) {
2340 break;
2341 }
2342 }
2343 if ( $this->stack->inButtonScope( 'p' ) ) {
2344 $this->inBodyMode( 'endtag', 'p' );
2345 }
2346 $this->stack->insertHTMLElement( $value, $attribs );
2347 return true;
2348
2349 case 'dd':
2350 case 'dt':
2351 # OMITTED: frameset_ok
2352 foreach ( $this->stack as $node ) {
2353 if ( $node->isHtmlNamed( 'dd' ) ) {
2354 $this->inBodyMode( 'endtag', 'dd' );
2355 break;
2356 }
2357 if ( $node->isHtmlNamed( 'dt' ) ) {
2358 $this->inBodyMode( 'endtag', 'dt' );
2359 break;
2360 }
2361 if (
2362 $node->isA( BalanceSets::$specialSet ) &&
2363 !$node->isA( BalanceSets::$addressDivPSet )
2364 ) {
2365 break;
2366 }
2367 }
2368 if ( $this->stack->inButtonScope( 'p' ) ) {
2369 $this->inBodyMode( 'endtag', 'p' );
2370 }
2371 $this->stack->insertHTMLElement( $value, $attribs );
2372 return true;
2373
2374 # OMITTED: <plaintext>
2375
2376 case 'button':
2377 if ( $this->stack->inScope( 'button' ) ) {
2378 $this->inBodyMode( 'endtag', 'button' );
2379 return $this->insertToken( $token, $value, $attribs, $selfclose );
2380 }
2381 $this->afe->reconstruct( $this->stack );
2382 $this->stack->insertHTMLElement( $value, $attribs );
2383 return true;
2384
2385 case 'a':
2386 $activeElement = $this->afe->findElementByTag( 'a' );
2387 if ( $activeElement ) {
2388 $this->inBodyMode( 'endtag', 'a' );
2389 if ( $this->afe->isInList( $activeElement ) ) {
2390 $this->afe->remove( $activeElement );
2391 // Don't flatten here, since when we fall
2392 // through below we might foster parent
2393 // the new <a> tag inside this one.
2394 $this->stack->removeElement( $activeElement, false );
2395 }
2396 }
2397 /* Falls through */
2398 case 'b':
2399 case 'big':
2400 case 'code':
2401 case 'em':
2402 case 'font':
2403 case 'i':
2404 case 's':
2405 case 'small':
2406 case 'strike':
2407 case 'strong':
2408 case 'tt':
2409 case 'u':
2410 $this->afe->reconstruct( $this->stack );
2411 $this->afe->push( $this->stack->insertHTMLElement( $value, $attribs ), $attribs );
2412 return true;
2413
2414 case 'nobr':
2415 $this->afe->reconstruct( $this->stack );
2416 if ( $this->stack->inScope( 'nobr' ) ) {
2417 $this->inBodyMode( 'endtag', 'nobr' );
2418 $this->afe->reconstruct( $this->stack );
2419 }
2420 $this->afe->push( $this->stack->insertHTMLElement( $value, $attribs ), $attribs );
2421 return true;
2422
2423 case 'applet':
2424 case 'marquee':
2425 case 'object':
2426 $this->afe->reconstruct( $this->stack );
2427 $this->stack->insertHTMLElement( $value, $attribs );
2428 $this->afe->insertMarker();
2429 # OMITTED: frameset_ok
2430 return true;
2431
2432 case 'table':
2433 # The document is never in "quirks mode"; see simplifications
2434 # above.
2435 if ( $this->stack->inButtonScope( 'p' ) ) {
2436 $this->inBodyMode( 'endtag', 'p' );
2437 }
2438 $this->stack->insertHTMLElement( $value, $attribs );
2439 # OMITTED: frameset_ok
2440 $this->switchMode( 'inTableMode' );
2441 return true;
2442
2443 case 'area':
2444 case 'br':
2445 case 'embed':
2446 case 'img':
2447 case 'keygen':
2448 case 'wbr':
2449 $this->afe->reconstruct( $this->stack );
2450 $this->stack->insertHTMLElement( $value, $attribs );
2451 $this->stack->pop();
2452 # OMITTED: frameset_ok
2453 return true;
2454
2455 case 'input':
2456 $this->afe->reconstruct( $this->stack );
2457 $this->stack->insertHTMLElement( $value, $attribs );
2458 $this->stack->pop();
2459 # OMITTED: frameset_ok
2460 # (hence we don't need to examine the tag's "type" attribute)
2461 return true;
2462
2463 case 'menuitem':
2464 case 'param':
2465 case 'source':
2466 case 'track':
2467 $this->stack->insertHTMLElement( $value, $attribs );
2468 $this->stack->pop();
2469 return true;
2470
2471 case 'hr':
2472 if ( $this->stack->inButtonScope( 'p' ) ) {
2473 $this->inBodyMode( 'endtag', 'p' );
2474 }
2475 $this->stack->insertHTMLElement( $value, $attribs );
2476 $this->stack->pop();
2477 return true;
2478
2479 case 'image':
2480 # warts!
2481 return $this->inBodyMode( $token, 'img', $attribs, $selfclose );
2482
2483 # OMITTED: <isindex>
2484 # OMITTED: <textarea>
2485 # OMITTED: <xmp>
2486 # OMITTED: <iframe>
2487 # OMITTED: <noembed>
2488 # OMITTED: <noscript>
2489
2490 # OMITTED: <select>
2491 /*
2492 case 'select':
2493 $this->afe->reconstruct( $this->stack );
2494 $this->stack->insertHTMLElement( $value, $attribs );
2495 switch ( $this->parseMode ) {
2496 case 'inTableMode':
2497 case 'inCaptionMode':
2498 case 'inTableBodyMode':
2499 case 'inRowMode':
2500 case 'inCellMode':
2501 $this->switchMode( 'inSelectInTableMode' );
2502 return true;
2503 default:
2504 $this->switchMode( 'inSelectMode' );
2505 return true;
2506 }
2507 */
2508
2509 case 'optgroup':
2510 case 'option':
2511 if ( $this->stack->currentNode->isHtmlNamed( 'option' ) ) {
2512 $this->inBodyMode( 'endtag', 'option' );
2513 }
2514 $this->afe->reconstruct( $this->stack );
2515 $this->stack->insertHTMLElement( $value, $attribs );
2516 return true;
2517
2518 case 'rb':
2519 case 'rtc':
2520 if ( $this->stack->inScope( 'ruby' ) ) {
2521 $this->stack->generateImpliedEndTags();
2522 }
2523 $this->stack->insertHTMLElement( $value, $attribs );
2524 return true;
2525
2526 case 'rp':
2527 case 'rt':
2528 if ( $this->stack->inScope( 'ruby' ) ) {
2529 $this->stack->generateImpliedEndTags( 'rtc' );
2530 }
2531 $this->stack->insertHTMLElement( $value, $attribs );
2532 return true;
2533
2534 case 'math':
2535 $this->afe->reconstruct( $this->stack );
2536 # We skip the spec's "adjust MathML attributes" and
2537 # "adjust foreign attributes" steps, since the browser will
2538 # do this later when it parses the output and it doesn't affect
2539 # balancing.
2540 $this->stack->insertForeignElement(
2541 BalanceSets::MATHML_NAMESPACE, $value, $attribs
2542 );
2543 if ( $selfclose ) {
2544 # emit explicit </math> tag.
2545 $this->stack->pop();
2546 }
2547 return true;
2548
2549 case 'svg':
2550 $this->afe->reconstruct( $this->stack );
2551 # We skip the spec's "adjust SVG attributes" and
2552 # "adjust foreign attributes" steps, since the browser will
2553 # do this later when it parses the output and it doesn't affect
2554 # balancing.
2555 $this->stack->insertForeignElement(
2556 BalanceSets::SVG_NAMESPACE, $value, $attribs
2557 );
2558 if ( $selfclose ) {
2559 # emit explicit </svg> tag.
2560 $this->stack->pop();
2561 }
2562 return true;
2563
2564 case 'caption':
2565 case 'col':
2566 case 'colgroup':
2567 # OMITTED: <frame>
2568 case 'head':
2569 case 'tbody':
2570 case 'td':
2571 case 'tfoot':
2572 case 'th':
2573 case 'thead':
2574 case 'tr':
2575 // Ignore table tags if we're not inTableMode
2576 return true;
2577 }
2578
2579 // Handle any other start tag here
2580 $this->afe->reconstruct( $this->stack );
2581 $this->stack->insertHTMLElement( $value, $attribs );
2582 return true;
2583 } elseif ( $token === 'endtag' ) {
2584 switch ( $value ) {
2585 # </body>,</html> are unsupported.
2586
2587 case 'template':
2588 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2589
2590 case 'address':
2591 case 'article':
2592 case 'aside':
2593 case 'blockquote':
2594 case 'button':
2595 case 'center':
2596 case 'details':
2597 case 'dialog':
2598 case 'dir':
2599 case 'div':
2600 case 'dl':
2601 case 'fieldset':
2602 case 'figcaption':
2603 case 'figure':
2604 case 'footer':
2605 case 'header':
2606 case 'hgroup':
2607 case 'listing':
2608 case 'main':
2609 case 'menu':
2610 case 'nav':
2611 case 'ol':
2612 case 'pre':
2613 case 'section':
2614 case 'summary':
2615 case 'ul':
2616 // Ignore if there is not a matching open tag
2617 if ( !$this->stack->inScope( $value ) ) {
2618 return true;
2619 }
2620 $this->stack->generateImpliedEndTags();
2621 $this->stack->popTag( $value );
2622 return true;
2623
2624 # OMITTED: <form>
2625
2626 case 'p':
2627 if ( !$this->stack->inButtonScope( 'p' ) ) {
2628 $this->inBodyMode( 'tag', 'p', [] );
2629 return $this->insertToken( $token, $value, $attribs, $selfclose );
2630 }
2631 $this->stack->generateImpliedEndTags( $value );
2632 $this->stack->popTag( $value );
2633 return true;
2634
2635 case 'li':
2636 if ( !$this->stack->inListItemScope( $value ) ) {
2637 return true; # ignore
2638 }
2639 $this->stack->generateImpliedEndTags( $value );
2640 $this->stack->popTag( $value );
2641 return true;
2642
2643 case 'dd':
2644 case 'dt':
2645 if ( !$this->stack->inScope( $value ) ) {
2646 return true; # ignore
2647 }
2648 $this->stack->generateImpliedEndTags( $value );
2649 $this->stack->popTag( $value );
2650 return true;
2651
2652 case 'h1':
2653 case 'h2':
2654 case 'h3':
2655 case 'h4':
2656 case 'h5':
2657 case 'h6':
2658 if ( !$this->stack->inScope( BalanceSets::$headingSet ) ) {
2659 return;
2660 }
2661 $this->stack->generateImpliedEndTags();
2662 $this->stack->popTag( BalanceSets::$headingSet );
2663 return true;
2664
2665 case 'sarcasm':
2666 # Take a deep breath, then:
2667 break;
2668
2669 case 'a':
2670 case 'b':
2671 case 'big':
2672 case 'code':
2673 case 'em':
2674 case 'font':
2675 case 'i':
2676 case 'nobr':
2677 case 's':
2678 case 'small':
2679 case 'strike':
2680 case 'strong':
2681 case 'tt':
2682 case 'u':
2683 if ( $this->stack->adoptionAgency( $value, $this->afe ) ) {
2684 return true; # If we did something, we're done.
2685 }
2686 break; # Go to the "any other end tag" case.
2687
2688 case 'applet':
2689 case 'marquee':
2690 case 'object':
2691 if ( !$this->stack->inScope( $value ) ) {
2692 return true; # ignore
2693 }
2694 $this->stack->generateImpliedEndTags();
2695 $this->stack->popTag( $value );
2696 $this->afe->clearToMarker();
2697 return true;
2698
2699 case 'br':
2700 # Turn </br> into <br>
2701 return $this->inBodyMode( 'tag', $value, [] );
2702 }
2703
2704 // Any other end tag goes here
2705 foreach ( $this->stack as $i => $node ) {
2706 if ( $node->isHtmlNamed( $value ) ) {
2707 $this->stack->generateImpliedEndTags( $value );
2708 $this->stack->popTo( $i ); # including $i
2709 break;
2710 } elseif ( $node->isA( BalanceSets::$specialSet ) ) {
2711 return true; // ignore this close token.
2712 }
2713 }
2714 return true;
2715 } else {
2716 Assert::invariant( false, "Bad token type: $token" );
2717 }
2718 }
2719
2720 private function inTableMode( $token, $value, $attribs = null, $selfclose = false ) {
2721 if ( $token === 'text' ) {
2722 if ( $this->textIntegrationMode ) {
2723 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
2724 } elseif ( $this->stack->currentNode->isA( BalanceSets::$tableSectionRowSet ) ) {
2725 $this->pendingTableText = '';
2726 $this->originalInsertionMode = $this->parseMode;
2727 return $this->switchModeAndReprocess( 'inTableTextMode', $token, $value, $attribs, $selfclose );
2728 }
2729 // fall through to default case.
2730 } elseif ( $token === 'eof' ) {
2731 $this->stopParsing();
2732 return true;
2733 } elseif ( $token === 'tag' ) {
2734 switch ( $value ) {
2735 case 'caption':
2736 $this->afe->insertMarker();
2737 $this->stack->insertHTMLElement( $value, $attribs );
2738 $this->switchMode( 'inCaptionMode' );
2739 return true;
2740 case 'colgroup':
2741 $this->stack->clearToContext( BalanceSets::$tableContextSet );
2742 $this->stack->insertHTMLElement( $value, $attribs );
2743 $this->switchMode( 'inColumnGroupMode' );
2744 return true;
2745 case 'col':
2746 $this->inTableMode( 'tag', 'colgroup', [] );
2747 return $this->insertToken( $token, $value, $attribs, $selfclose );
2748 case 'tbody':
2749 case 'tfoot':
2750 case 'thead':
2751 $this->stack->clearToContext( BalanceSets::$tableContextSet );
2752 $this->stack->insertHTMLElement( $value, $attribs );
2753 $this->switchMode( 'inTableBodyMode' );
2754 return true;
2755 case 'td':
2756 case 'th':
2757 case 'tr':
2758 $this->inTableMode( 'tag', 'tbody', [] );
2759 return $this->insertToken( $token, $value, $attribs, $selfclose );
2760 case 'table':
2761 if ( !$this->stack->inTableScope( $value ) ) {
2762 return true; // Ignore this tag.
2763 }
2764 $this->inTableMode( 'endtag', $value );
2765 return $this->insertToken( $token, $value, $attribs, $selfclose );
2766
2767 case 'style':
2768 # OMITTED: <script>
2769 case 'template':
2770 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2771
2772 case 'input':
2773 if ( !isset( $attribs['type'] ) || strcasecmp( $attribs['type'], 'hidden' ) !== 0 ) {
2774 break; // Handle this as "everything else"
2775 }
2776 $this->stack->insertHTMLElement( $value, $attribs );
2777 $this->stack->pop();
2778 return true;
2779
2780 # OMITTED: <form>
2781 }
2782 // Fall through for "anything else" clause.
2783 } elseif ( $token === 'endtag' ) {
2784 switch ( $value ) {
2785 case 'table':
2786 if ( !$this->stack->inTableScope( $value ) ) {
2787 return true; // Ignore.
2788 }
2789 $this->stack->popTag( $value );
2790 $this->resetInsertionMode();
2791 return true;
2792 # OMITTED: <body>
2793 case 'caption':
2794 case 'col':
2795 case 'colgroup':
2796 # OMITTED: <html>
2797 case 'tbody':
2798 case 'td':
2799 case 'tfoot':
2800 case 'th':
2801 case 'thead':
2802 case 'tr':
2803 return true; // Ignore the token.
2804 case 'template':
2805 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2806 }
2807 // Fall through for "anything else" clause.
2808 }
2809 // This is the "anything else" case:
2810 $this->stack->fosterParentMode = true;
2811 $this->inBodyMode( $token, $value, $attribs, $selfclose );
2812 $this->stack->fosterParentMode = false;
2813 return true;
2814 }
2815
2816 private function inTableTextMode( $token, $value, $attribs = null, $selfclose = false ) {
2817 if ( $token === 'text' ) {
2818 $this->pendingTableText .= $value;
2819 return true;
2820 }
2821 // Non-text token:
2822 $text = $this->pendingTableText;
2823 $this->pendingTableText = '';
2824 if ( preg_match( '/[^\x09\x0A\x0C\x0D\x20]/', $text ) ) {
2825 // This should match the "anything else" case inTableMode
2826 $this->stack->fosterParentMode = true;
2827 $this->inBodyMode( 'text', $text );
2828 $this->stack->fosterParentMode = false;
2829 } else {
2830 // Pending text is just whitespace.
2831 $this->stack->insertText( $text );
2832 }
2833 return $this->switchModeAndReprocess(
2834 $this->originalInsertionMode, $token, $value, $attribs, $selfclose
2835 );
2836 }
2837
2838 // helper for inCaptionMode
2839 private function endCaption() {
2840 if ( !$this->stack->inTableScope( 'caption' ) ) {
2841 return false;
2842 }
2843 $this->stack->generateImpliedEndTags();
2844 $this->stack->popTag( 'caption' );
2845 $this->afe->clearToMarker();
2846 $this->switchMode( 'inTableMode' );
2847 return true;
2848 }
2849
2850 private function inCaptionMode( $token, $value, $attribs = null, $selfclose = false ) {
2851 if ( $token === 'tag' ) {
2852 switch ( $value ) {
2853 case 'caption':
2854 case 'col':
2855 case 'colgroup':
2856 case 'tbody':
2857 case 'td':
2858 case 'tfoot':
2859 case 'th':
2860 case 'thead':
2861 case 'tr':
2862 if ( $this->endCaption() ) {
2863 $this->insertToken( $token, $value, $attribs, $selfclose );
2864 }
2865 return true;
2866 }
2867 // Fall through to "anything else" case.
2868 } elseif ( $token === 'endtag' ) {
2869 switch ( $value ) {
2870 case 'caption':
2871 $this->endCaption();
2872 return true;
2873 case 'table':
2874 if ( $this->endCaption() ) {
2875 $this->insertToken( $token, $value, $attribs, $selfclose );
2876 }
2877 return true;
2878 case 'body':
2879 case 'col':
2880 case 'colgroup':
2881 # OMITTED: <html>
2882 case 'tbody':
2883 case 'td':
2884 case 'tfoot':
2885 case 'th':
2886 case 'thead':
2887 case 'tr':
2888 // Ignore the token
2889 return true;
2890 }
2891 // Fall through to "anything else" case.
2892 }
2893 // The Anything Else case
2894 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
2895 }
2896
2897 private function inColumnGroupMode( $token, $value, $attribs = null, $selfclose = false ) {
2898 if ( $token === 'text' ) {
2899 if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
2900 $this->stack->insertText( $matches[0] );
2901 $value = substr( $value, strlen( $matches[0] ) );
2902 }
2903 if ( strlen( $value ) === 0 ) {
2904 return true; // All text handled.
2905 }
2906 // Fall through to handle non-whitespace below.
2907 } elseif ( $token === 'tag' ) {
2908 switch ( $value ) {
2909 # OMITTED: <html>
2910 case 'col':
2911 $this->stack->insertHTMLElement( $value, $attribs );
2912 $this->stack->pop();
2913 return true;
2914 case 'template':
2915 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2916 }
2917 // Fall through for "anything else".
2918 } elseif ( $token === 'endtag' ) {
2919 switch ( $value ) {
2920 case 'colgroup':
2921 if ( !$this->stack->currentNode->isHtmlNamed( 'colgroup' ) ) {
2922 return true; // Ignore the token.
2923 }
2924 $this->stack->pop();
2925 $this->switchMode( 'inTableMode' );
2926 return true;
2927 case 'col':
2928 return true; // Ignore the token.
2929 case 'template':
2930 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
2931 }
2932 // Fall through for "anything else".
2933 } elseif ( $token === 'eof' ) {
2934 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
2935 }
2936
2937 // Anything else
2938 if ( !$this->stack->currentNode->isHtmlNamed( 'colgroup' ) ) {
2939 return true; // Ignore the token.
2940 }
2941 $this->inColumnGroupMode( 'endtag', 'colgroup' );
2942 return $this->insertToken( $token, $value, $attribs, $selfclose );
2943 }
2944
2945 // Helper function for inTableBodyMode
2946 private function endSection() {
2947 if ( !(
2948 $this->stack->inTableScope( 'tbody' ) ||
2949 $this->stack->inTableScope( 'thead' ) ||
2950 $this->stack->inTableScope( 'tfoot' )
2951 ) ) {
2952 return false;
2953 }
2954 $this->stack->clearToContext( BalanceSets::$tableBodyContextSet );
2955 $this->stack->pop();
2956 $this->switchMode( 'inTableMode' );
2957 return true;
2958 }
2959 private function inTableBodyMode( $token, $value, $attribs = null, $selfclose = false ) {
2960 if ( $token === 'tag' ) {
2961 switch ( $value ) {
2962 case 'tr':
2963 $this->stack->clearToContext( BalanceSets::$tableBodyContextSet );
2964 $this->stack->insertHTMLElement( $value, $attribs );
2965 $this->switchMode( 'inRowMode' );
2966 return true;
2967 case 'th':
2968 case 'td':
2969 $this->inTableBodyMode( 'tag', 'tr', [] );
2970 $this->insertToken( $token, $value, $attribs, $selfclose );
2971 return true;
2972 case 'caption':
2973 case 'col':
2974 case 'colgroup':
2975 case 'tbody':
2976 case 'tfoot':
2977 case 'thead':
2978 if ( $this->endSection() ) {
2979 $this->insertToken( $token, $value, $attribs, $selfclose );
2980 }
2981 return true;
2982 }
2983 } elseif ( $token === 'endtag' ) {
2984 switch ( $value ) {
2985 case 'table':
2986 if ( $this->endSection() ) {
2987 $this->insertToken( $token, $value, $attribs, $selfclose );
2988 }
2989 return true;
2990 case 'tbody':
2991 case 'tfoot':
2992 case 'thead':
2993 if ( $this->stack->inTableScope( $value ) ) {
2994 $this->endSection();
2995 }
2996 return true;
2997 # OMITTED: <body>
2998 case 'caption':
2999 case 'col':
3000 case 'colgroup':
3001 # OMITTED: <html>
3002 case 'td':
3003 case 'th':
3004 case 'tr':
3005 return true; // Ignore the token.
3006 }
3007 }
3008 // Anything else:
3009 return $this->inTableMode( $token, $value, $attribs, $selfclose );
3010 }
3011
3012 // Helper function for inRowMode
3013 private function endRow() {
3014 if ( !$this->stack->inTableScope( 'tr' ) ) {
3015 return false;
3016 }
3017 $this->stack->clearToContext( BalanceSets::$tableRowContextSet );
3018 $this->stack->pop();
3019 $this->switchMode( 'inTableBodyMode' );
3020 return true;
3021 }
3022 private function inRowMode( $token, $value, $attribs = null, $selfclose = false ) {
3023 if ( $token === 'tag' ) {
3024 switch ( $value ) {
3025 case 'th':
3026 case 'td':
3027 $this->stack->clearToContext( BalanceSets::$tableRowContextSet );
3028 $this->stack->insertHTMLElement( $value, $attribs );
3029 $this->switchMode( 'inCellMode' );
3030 $this->afe->insertMarker();
3031 return true;
3032 case 'caption':
3033 case 'col':
3034 case 'colgroup':
3035 case 'tbody':
3036 case 'tfoot':
3037 case 'thead':
3038 case 'tr':
3039 if ( $this->endRow() ) {
3040 $this->insertToken( $token, $value, $attribs, $selfclose );
3041 }
3042 return true;
3043 }
3044 } elseif ( $token === 'endtag' ) {
3045 switch ( $value ) {
3046 case 'tr':
3047 $this->endRow();
3048 return true;
3049 case 'table':
3050 if ( $this->endRow() ) {
3051 $this->insertToken( $token, $value, $attribs, $selfclose );
3052 }
3053 return true;
3054 case 'tbody':
3055 case 'tfoot':
3056 case 'thead':
3057 if (
3058 $this->stack->inTableScope( $value ) &&
3059 $this->endRow()
3060 ) {
3061 $this->insertToken( $token, $value, $attribs, $selfclose );
3062 }
3063 return true;
3064 # OMITTED: <body>
3065 case 'caption':
3066 case 'col':
3067 case 'colgroup':
3068 # OMITTED: <html>
3069 case 'td':
3070 case 'th':
3071 return true; // Ignore the token.
3072 }
3073 }
3074 // Anything else:
3075 return $this->inTableMode( $token, $value, $attribs, $selfclose );
3076 }
3077
3078 // Helper for inCellMode
3079 private function endCell() {
3080 if ( $this->stack->inTableScope( 'td' ) ) {
3081 $this->inCellMode( 'endtag', 'td' );
3082 return true;
3083 } elseif ( $this->stack->inTableScope( 'th' ) ) {
3084 $this->inCellMode( 'endtag', 'th' );
3085 return true;
3086 } else {
3087 return false;
3088 }
3089 }
3090 private function inCellMode( $token, $value, $attribs = null, $selfclose = false ) {
3091 if ( $token === 'tag' ) {
3092 switch ( $value ) {
3093 case 'caption':
3094 case 'col':
3095 case 'colgroup':
3096 case 'tbody':
3097 case 'td':
3098 case 'tfoot':
3099 case 'th':
3100 case 'thead':
3101 case 'tr':
3102 if ( $this->endCell() ) {
3103 $this->insertToken( $token, $value, $attribs, $selfclose );
3104 }
3105 return true;
3106 }
3107 } elseif ( $token === 'endtag' ) {
3108 switch ( $value ) {
3109 case 'td':
3110 case 'th':
3111 if ( $this->stack->inTableScope( $value ) ) {
3112 $this->stack->generateImpliedEndTags();
3113 $this->stack->popTag( $value );
3114 $this->afe->clearToMarker();
3115 $this->switchMode( 'inRowMode' );
3116 }
3117 return true;
3118 # OMITTED: <body>
3119 case 'caption':
3120 case 'col':
3121 case 'colgroup':
3122 # OMITTED: <html>
3123 return true;
3124
3125 case 'table':
3126 case 'tbody':
3127 case 'tfoot':
3128 case 'thead':
3129 case 'tr':
3130 if ( $this->stack->inTableScope( $value ) ) {
3131 $this->stack->generateImpliedEndTags();
3132 $this->stack->popTag( BalanceSets::$tableCellSet );
3133 $this->afe->clearToMarker();
3134 $this->switchMode( 'inRowMode' );
3135 $this->insertToken( $token, $value, $attribs, $selfclose );
3136 }
3137 return true;
3138 }
3139 }
3140 // Anything else:
3141 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
3142 }
3143
3144 # OMITTED: <select>
3145 /*
3146 private function inSelectMode( $token, $value, $attribs = null, $selfclose = false ) {
3147 Assert::invariant( false, 'Unimplemented' );
3148 }
3149
3150 private function inSelectInTableMode( $token, $value, $attribs = null, $selfclose = false ) {
3151 Assert::invariant( false, 'Unimplemented' );
3152 }
3153 */
3154
3155 private function inTemplateMode( $token, $value, $attribs = null, $selfclose = false ) {
3156 if ( $token === 'text' ) {
3157 return $this->inBodyMode( $token, $value, $attribs, $selfclose );
3158 } elseif ( $token === 'eof' ) {
3159 if ( $this->stack->indexOf( 'template' ) < 0 ) {
3160 $this->stopParsing();
3161 } else {
3162 $this->stack->popTag( 'template' );
3163 $this->afe->clearToMarker();
3164 array_pop( $this->templateInsertionModes );
3165 $this->resetInsertionMode();
3166 $this->insertToken( $token, $value, $attribs, $selfclose );
3167 }
3168 return true;
3169 } elseif ( $token === 'tag' ) {
3170 switch ( $value ) {
3171 case 'base':
3172 case 'basefont':
3173 case 'bgsound':
3174 case 'link':
3175 case 'meta':
3176 case 'noframes':
3177 # OMITTED: <script>
3178 case 'style':
3179 case 'template':
3180 # OMITTED: <title>
3181 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
3182
3183 case 'caption':
3184 case 'colgroup':
3185 case 'tbody':
3186 case 'tfoot':
3187 case 'thead':
3188 return $this->switchModeAndReprocess(
3189 'inTableMode', $token, $value, $attribs, $selfclose
3190 );
3191
3192 case 'col':
3193 return $this->switchModeAndReprocess(
3194 'inColumnGroupMode', $token, $value, $attribs, $selfclose
3195 );
3196
3197 case 'tr':
3198 return $this->switchModeAndReprocess(
3199 'inTableBodyMode', $token, $value, $attribs, $selfclose
3200 );
3201
3202 case 'td':
3203 case 'th':
3204 return $this->switchModeAndReprocess(
3205 'inRowMode', $token, $value, $attribs, $selfclose
3206 );
3207 }
3208 return $this->switchModeAndReprocess(
3209 'inBodyMode', $token, $value, $attribs, $selfclose
3210 );
3211 } elseif ( $token === 'endtag' ) {
3212 switch ( $value ) {
3213 case 'template':
3214 return $this->inHeadMode( $token, $value, $attribs, $selfclose );
3215 }
3216 return true;
3217 } else {
3218 Assert::invariant( false, "Bad token type: $token" );
3219 }
3220 }
3221 }