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