Debian Codegraph @

vendor/wikimedia/remex-html/src/Tokenizer/Tokenizer.php

raw
1 <?php
2
3 namespace Wikimedia\RemexHtml\Tokenizer;
4
5 use Wikimedia\RemexHtml\HTMLData;
6 use Wikimedia\RemexHtml\PropGuard;
7
8 /**
9 * HTML 5 tokenizer
10 *
11 * Based on the W3C recommendation as published 01 November 2016:
12 * https://www.w3.org/TR/2016/REC-html51-20161101/
13 */
14 class Tokenizer {
15 use PropGuard;
16
17 // States
18 public const STATE_START = 1;
19 public const STATE_DATA = 2;
20 public const STATE_RCDATA = 3;
21 public const STATE_RAWTEXT = 4;
22 public const STATE_SCRIPT_DATA = 5;
23 public const STATE_PLAINTEXT = 6;
24 public const STATE_EOF = 7;
25 public const STATE_CURRENT = 8;
26
27 // Match indices for the data state regex
28 private const MD_END_TAG_OPEN = 1;
29 private const MD_TAG_NAME = 2;
30 private const MD_TAG_AFTER_LOWERCASE = 3;
31 private const MD_COMMENT = 4;
32 private const MD_COMMENT_INNER = 5;
33 private const MD_COMMENT_END = 6;
34 private const MD_DOCTYPE = 7;
35 private const MD_DT_NAME_WS = 8;
36 private const MD_DT_NAME = 9;
37 private const MD_DT_PUBLIC_WS = 10;
38 private const MD_DT_PUBLIC_DQ = 11;
39 private const MD_DT_PUBLIC_SQ = 12;
40 private const MD_DT_PUBSYS_WS = 13;
41 private const MD_DT_PUBSYS_DQ = 14;
42 private const MD_DT_PUBSYS_SQ = 15;
43 private const MD_DT_SYSTEM_WS = 16;
44 private const MD_DT_SYSTEM_DQ = 17;
45 private const MD_DT_SYSTEM_SQ = 18;
46 private const MD_DT_BOGUS = 19;
47 private const MD_DT_END = 20;
48 private const MD_CDATA = 21;
49 private const MD_BOGUS_COMMENT = 22;
50
51 // Match indices for the character reference regex
52 private const MC_PREFIX = 1;
53 private const MC_DECIMAL = 2;
54 private const MC_HEXDEC = 3;
55 private const MC_SEMICOLON = 4;
56 private const MC_HASH = 5;
57 private const MC_NAMED = 6;
58 private const MC_SUFFIX = 7;
59 private const MC_INVALID = 8;
60
61 // Match indices for the attribute regex
62 private const MA_SLASH = 1;
63 private const MA_NAME = 2;
64 private const MA_SIMPLE_NAME = 3;
65 private const MA_DQUOTED = 4;
66 private const MA_DQUOTED_CHARREF = 5;
67 private const MA_DQUOTED_UNSIMPLE = 6;
68 private const MA_SQUOTED = 7;
69 private const MA_SQUOTED_CHARREF = 8;
70 private const MA_SQUOTED_UNSIMPLE = 9;
71 private const MA_UNQUOTED = 10;
72 private const MA_UNQUOTED_UNSIMPLE = 11;
73
74 // Characters
75 protected const REPLACEMENT_CHAR = "\xef\xbf\xbd";
76 protected const BYTE_ORDER_MARK = "\xef\xbb\xbf";
77
78 /**
79 * A list of "common well-behaved entities", used to optimize fast paths
80 */
81 private const COMMON_ENTITIES = [
82 '&amp;' => '&',
83 '&apos;' => "'",
84 '&lt;' => '<',
85 '&gt;' => '>',
86 '&quot;' => '"',
87 '&nbsp;' => "\u{00A0}",
88 ];
89
90 protected bool $ignoreErrors;
91 protected bool $ignoreCharRefs;
92 protected bool $ignoreNulls;
93 protected bool $skipPreprocess;
94 protected bool $lazyAttributes;
95 protected bool $scriptingFlag;
96 /** @var string|null */
97 protected $appropriateEndTag;
98 protected TokenHandler $listener;
99 /** @var int */
100 protected $state;
101 /** @var bool */
102 protected $preprocessed;
103 /** @var string */
104 protected $text;
105 /** @var int */
106 protected $pos;
107 /** @var int */
108 protected $length;
109 /** @var callable|null */
110 protected $enableCdataCallback;
111 /** @var string|null */
112 protected $fragmentNamespace;
113 /** @var string|null */
114 protected $fragmentName;
115
116 /**
117 * Constructor
118 *
119 * @param TokenHandler $listener The object which receives token events
120 * @param string $text The text to tokenize
121 * @param array $options Associative array of options, including:
122 * - ignoreErrors: True to improve performance by ignoring errors. The
123 * token stream should still be the same, except that error() won't be
124 * called.
125 * - ignoreCharRefs: True to ignore character references. Character tokens
126 * will contain the unexpanded character references, and no errors
127 * related to invalid character references will be raised. Performance
128 * will be improved. This is not compliant behaviour.
129 * - ignoreNulls: True to ignore NULL bytes in the input stream, instead
130 * of raising errors and converting them to U+FFFD as is usually
131 * required by the spec.
132 * - skipPreprocess: True to skip the "preprocessing the input stream"
133 * stage, which normalizes line endings and raises errors on certain
134 * control characters. Advisable if the input stream is already
135 * appropriately normalized.
136 * - lazyAttributes: True to construct attributes lazily, saving
137 * processing time (at the expense of memory usage) if most attributes
138 * are not going to be accessed. Default false.
139 * - scriptingFlag: True if the scripting flag is enabled. Default true.
140 * Setting this to false cause the contents of <noscript> elements to be
141 * processed as normal content. The scriptingFlag option in the
142 * TreeBuilder should be set to the same value.
143 */
144 public function __construct( TokenHandler $listener, $text, $options = [] ) {
145 $this->listener = $listener;
146 $this->text = $text;
147 $this->pos = 0;
148 $this->preprocessed = false;
149 $this->length = strlen( $text );
150 $this->ignoreErrors = !empty( $options['ignoreErrors'] );
151 $this->ignoreCharRefs = !empty( $options['ignoreCharRefs'] );
152 $this->ignoreNulls = !empty( $options['ignoreNulls'] );
153 $this->skipPreprocess = !empty( $options['skipPreprocess'] );
154 $this->lazyAttributes = $options['lazyAttributes'] ?? false;
155 $this->scriptingFlag = $options['scriptingFlag'] ?? true;
156 }
157
158 /**
159 * @param callable|null $cb
160 */
161 public function setEnableCdataCallback( $cb ) {
162 $this->enableCdataCallback = $cb;
163 }
164
165 /**
166 * Run the tokenizer on the whole input stream. This is the normal entry point.
167 *
168 * @param array $options An associative array of options:
169 * - state : One of the STATE_* constants, a state in which to start.
170 * - appropriateEndTag : The "appropriate end tag", which needs to be set
171 * if entering one of the raw text states.
172 * - fragmentNamespace : The fragment namespace
173 * - fragmentName : The fragment tag name
174 */
175 public function execute( $options = [] ) {
176 if ( isset( $options['state'] ) ) {
177 $this->state = $options['state'];
178 } else {
179 $this->state = self::STATE_START;
180 }
181
182 if ( isset( $options['fragmentNamespace'] ) ) {
183 $this->setFragmentContext( $options['fragmentNamespace'], $options['fragmentName'] );
184 } else {
185 $this->fragmentNamespace = null;
186 $this->fragmentName = null;
187 }
188 $this->appropriateEndTag =
189 $options['appropriateEndTag'] ?? null;
190 $this->preprocess();
191 $this->listener->startDocument( $this, $this->fragmentNamespace, $this->fragmentName );
192
193 $this->executeInternal( true );
194 }
195
196 /**
197 * Get the preprocessed input text. Source offsets in event parameters are
198 * relative to this string. If skipPreprocess was specified, this will be
199 * the same as the input string.
200 * @return string
201 */
202 public function getPreprocessedText() {
203 $this->preprocess();
204 return $this->text;
205 }
206
207 /**
208 * Change the state of the tokenizer during parsing. This for use by the
209 * tree builder to switch the tokenizer into one of the raw text states.
210 *
211 * @param int $state One of the STATE_* constants
212 * @param string $appropriateEndTag The appropriate end tag
213 */
214 public function switchState( $state, $appropriateEndTag ) {
215 $this->state = $state;
216 $this->appropriateEndTag = $appropriateEndTag;
217 }
218
219 /**
220 * Initialize the tokenizer for fragment parsing
221 *
222 * @param string $namespace The namespace of the context element
223 * @param string $tagName The name of the context element
224 */
225 public function setFragmentContext( $namespace, $tagName ) {
226 $this->fragmentNamespace = $namespace;
227 $this->fragmentName = $tagName;
228
229 if ( strval( $namespace ) !== '' && $namespace !== HTMLData::NS_HTML ) {
230 return;
231 }
232
233 switch ( $tagName ) {
234 case 'title':
235 case 'textarea':
236 $this->state = self::STATE_RCDATA;
237 break;
238
239 case 'style':
240 case 'xmp':
241 case 'iframe':
242 case 'noembed':
243 case 'noframes':
244 $this->state = self::STATE_RAWTEXT;
245 break;
246
247 case 'script':
248 $this->state = self::STATE_SCRIPT_DATA;
249 break;
250
251 case 'noscript':
252 if ( $this->scriptingFlag ) {
253 $this->state = self::STATE_RAWTEXT;
254 }
255 break;
256
257 case 'plaintext':
258 $this->state = self::STATE_PLAINTEXT;
259 break;
260 }
261 }
262
263 /**
264 * Notify the tokenizer that the document will be tokenized by repeated step()
265 * calls. This must be called once only, before the first call to step().
266 */
267 public function beginStepping() {
268 $this->state = self::STATE_START;
269 $this->preprocess();
270 $this->listener->startDocument( $this, null, null );
271 }
272
273 /**
274 * Tokenize a minimum amount of text from the input stream, and emit the
275 * resulting events.
276 *
277 * @return bool True if the input continues and step() should be called
278 * again, false on EOF
279 */
280 public function step() {
281 if ( $this->state === null ) {
282 $this->fatal( "beginStepping() must be called before step()" );
283 }
284 return $this->executeInternal( false );
285 }
286
287 /**
288 * Preprocess the input text, if it hasn't been done already.
289 */
290 protected function preprocess() {
291 if ( $this->preprocessed || $this->skipPreprocess ) {
292 return;
293 }
294
295 // Normalize line endings
296 if ( strcspn( $this->text, "\r" ) !== strlen( $this->text ) ) {
297 $this->text = preg_replace( '/\r\n?/', "\n", $this->text );
298 $this->length = strlen( $this->text );
299 }
300
301 // Raise parse errors for any control characters
302 static $re;
303 if ( $re === null ) {
304 // Note that we deliberately do not use the 'u' flag on the
305 // regexp below, as that bypasses the PCRE JIT. Instead we
306 // rewrite character classes containing codepoints which
307 // require more than one UTF-8 byte as alternations.
308 $re = '/[' .
309 // "C0 controls" (u0000 - u001F) but not
310 // "ASCII whitespace" (u0009, u000A, u000C, u000D, u0020) or
311 // NULL (u0000)
312 // https://infra.spec.whatwg.org/#c0-control
313 // https://infra.spec.whatwg.org/#ascii-whitespace
314 '\x{0001}-\x{0008}' .
315 '\x{000B}' .
316 '\x{000E}-\x{001F}' .
317 // "Controls" other than C0 controls (u007F - u009F)
318 // https://infra.spec.whatwg.org/#control
319 '\x{007F}]|' .
320 // (We can't use character classes above u007F)
321 "\u{0080}|\u{0081}|\u{0082}|\u{0083}|" .
322 "\u{0084}|\u{0085}|\u{0086}|\u{0087}|" .
323 "\u{0088}|\u{0089}|\u{008A}|\u{008B}|" .
324 "\u{008C}|\u{008D}|\u{008E}|\u{008F}|" .
325 "\u{0090}|\u{0091}|\u{0092}|\u{0093}|" .
326 "\u{0094}|\u{0095}|\u{0096}|\u{0097}|" .
327 "\u{0098}|\u{0099}|\u{009A}|\u{009B}|" .
328 "\u{009C}|\u{009D}|\u{009E}|\u{009F}|" .
329 // HTML spec calls these "noncharacters"
330 // https://infra.spec.whatwg.org/#noncharacter
331 "\u{FDD0}|\u{FDD1}|\u{FDD2}|\u{FDD3}|" .
332 "\u{FDD4}|\u{FDD5}|\u{FDD6}|\u{FDD7}|" .
333 "\u{FDD8}|\u{FDD9}|\u{FDDA}|\u{FDDB}|" .
334 "\u{FDDC}|\u{FDDD}|\u{FDDE}|\u{FDDF}|" .
335 "\u{FDE0}|\u{FDE1}|\u{FDE2}|\u{FDE3}|" .
336 "\u{FDE4}|\u{FDE5}|\u{FDE6}|\u{FDE7}|" .
337 "\u{FDE8}|\u{FDE9}|\u{FDEA}|\u{FDEB}|" .
338 "\u{FDEC}|\u{FDED}|\u{FDEE}|\u{FDEF}|" .
339 "\u{FFFE}|\u{FFFF}|" .
340 "\u{1FFFE}|\u{1FFFF}|" .
341 "\u{2FFFE}|\u{2FFFF}|" .
342 "\u{3FFFE}|\u{3FFFF}|" .
343 "\u{4FFFE}|\u{4FFFF}|" .
344 "\u{5FFFE}|\u{5FFFF}|" .
345 "\u{6FFFE}|\u{6FFFF}|" .
346 "\u{7FFFE}|\u{7FFFF}|" .
347 "\u{8FFFE}|\u{8FFFF}|" .
348 "\u{9FFFE}|\u{9FFFF}|" .
349 "\u{AFFFE}|\u{AFFFF}|" .
350 "\u{BFFFE}|\u{BFFFF}|" .
351 "\u{CFFFE}|\u{CFFFF}|" .
352 "\u{DFFFE}|\u{DFFFF}|" .
353 "\u{EFFFE}|\u{EFFFF}|" .
354 "\u{FFFFE}|\u{FFFFF}|" .
355 "\u{10FFFE}|\u{10FFFF}/S";
356 }
357 if ( !$this->ignoreErrors ) {
358 $pos = 0;
359 while ( $pos < $this->length ) {
360 $count = preg_match( $re, $this->text, $m, PREG_OFFSET_CAPTURE, $pos );
361 if ( $count === false ) {
362 $this->throwPregError();
363 } elseif ( !$count ) {
364 break;
365 }
366 $pos = $m[0][1];
367 $this->error( "disallowed control character", $pos );
368 $pos += strlen( $m[0][0] );
369 }
370 }
371 }
372
373 /**
374 * The main state machine, the common implementation of step() and execute().
375 * @param bool $loop Set to true to loop until finished, false to step once.
376 * @return bool True if the input continues, false on EOF
377 */
378 protected function executeInternal( $loop ) {
379 $eof = false;
380
381 do {
382 switch ( $this->state ) {
383 case self::STATE_DATA:
384 $this->state = $this->dataState( $loop );
385 break;
386
387 case self::STATE_RCDATA:
388 $this->state = $this->textElementState( false );
389 break;
390
391 case self::STATE_RAWTEXT:
392 $this->state = $this->textElementState( true );
393 break;
394
395 case self::STATE_SCRIPT_DATA:
396 $this->state = $this->scriptDataState();
397 break;
398
399 case self::STATE_PLAINTEXT:
400 $this->state = $this->plaintextState();
401 break;
402
403 case self::STATE_START:
404 $this->state = self::STATE_DATA;
405 break;
406
407 case self::STATE_EOF:
408 $this->listener->endDocument( $this->length );
409 $eof = true;
410 break 2;
411
412 default:
413 $this->fatal( 'invalid state' );
414 }
415 } while ( $loop );
416
417 return !$eof;
418 }
419
420 /**
421 * Consume input text starting from the "data state".
422 *
423 * @param bool $loop True to loop while still in the data state, false to
424 * process a single less-than sign.
425 * @return int The next state index
426 */
427 protected function dataState( $loop ) {
428 $re = "~ <
429 (?:
430 ( /? ) # 1. End tag open
431
432 ( # 2. Tag name
433 # Try to match the ASCII letter required for the start of a start
434 # or end tag. If this fails, a slash matched above can be
435 # backtracked and then fed into the bogus comment alternative below.
436 # As an optimization, notice if the tag is all-lowercase;
437 # we can skip strtolower and null handling in that case.
438 (?:
439 [a-z]++
440 # Portion after initial all-lowercase prefix
441 ( [^\t\n\f />]*+ ) |
442
443 # Capture initial uppercase letter
444 [A-Z]
445 # Then capture the rest of the tag name
446 [^\t\n\f />]*+
447 )
448 )
449
450 |
451
452 # Comment
453 !--
454 ( # 4. Comment match detector
455 > | -> | # Invalid short close
456 ( # 5. Comment contents
457 (?:
458 (?! --> )
459 (?! --!> )
460 (?! --! \\z )
461 (?! -- \\z )
462 (?! - \\z )
463 .
464 )*+
465 )
466 ( # 6. Comment close
467 --> | # Normal close
468 --!> | # Comment end bang
469 --! | # EOF in comment end bang state
470 -- | # EOF in comment end state
471 - | # EOF in comment end dash state
472 # EOF in comment state
473 )
474 ) |
475 ( (?i) # 7. Doctype
476 ! DOCTYPE
477
478 # There must be at least one whitespace character to suppress
479 # a parse error, but if there isn't one, this is still a
480 # DOCTYPE. There is no way for the DOCTYPE string to end up
481 # as a character node, the DOCTYPE subexpression must always
482 # wholly match if we matched up to this point.
483
484 ( [\t\n\f ]*+ ) # 8. Required whitespace
485 ( [^\t\n\f >]*+ ) # 9. DOCTYPE name
486 [\t\n\f ]*+
487 (?:
488 # After DOCTYPE name state
489 PUBLIC
490 ( [\t\n\f ]* ) # 10. Required whitespace
491 (?:
492 \" ( [^\">]* ) \"? | # 11. Double-quoted identifier
493 ' ( [^'>]* ) '? | # 12. Single-quoted identifier
494 # Non-match: bogus
495 )
496 (?:
497 # After DOCTYPE public identifier state
498 # Assert quoted identifier before here
499 (?<= \" | ' )
500 ( [\t\n\f ]* ) # 13. Required whitespace
501 (?:
502 \" ( [^\">]* ) \"? | # 14. Double-quoted identifier
503 ' ( [^'>]* ) '? | # 15. Single-quoted identifier
504 # Non-match: no system ID
505 )
506 )?
507 |
508 SYSTEM
509 ( [\t\n\f ]* ) # 16. Required whitespace
510 (?:
511 \" ( [^\">]* ) \"? | # 17. Double-quoted identifier
512 ' ( [^'>]* ) '? | # 18. Single-quoted identifier
513 # Non-match: bogus
514 )
515 | # No keyword is OK
516 )
517 [\t\n\f ]*
518 ( [^>]*+ ) # 19. Bogus DOCTYPE
519 ( >? ) # 20. End of DOCTYPE
520 ) |
521 ( ! \[CDATA\[ ) | # 21. CDATA section
522 ( [!?/] [^>]*+ ) >? # 22. Bogus comment
523
524 # Anything else: parse error and emit literal less-than sign.
525 # We will let the match fail at this position and later check
526 # for less-than signs in the resulting text node.
527 )
528 ~xs";
529
530 $nextState = self::STATE_DATA;
531 do {
532 # As an optimization, quick scan ahead to the first "difficult"
533 # character
534 $npos = strcspn( $this->text, "<&\0", $this->pos ) + $this->pos;
535 # While the "difficult" section is in fact a simple entity, keep
536 # skipping ahead.
537 $mpos = $npos;
538 while ( preg_match( '/&(?:amp|apos|lt|gt|quot|nbsp);/A', $this->text, $m, 0, $mpos ) === 1 ) {
539 $mpos += strlen( $m[0] );
540 $mpos += strcspn( $this->text, "<&\0", $mpos );
541 }
542 $count = preg_match( $re, $this->text, $m, PREG_OFFSET_CAPTURE, $mpos );
543 if ( $count === false ) {
544 $this->throwPregError();
545 } elseif ( !$count ) {
546 // Text runs to end
547 $dataIsSimple = ( $npos === $this->length );
548 $dataHasSimpleRefs = ( $mpos === $this->length );
549 $this->emitDataRange(
550 $this->pos, $this->length - $this->pos,
551 $dataIsSimple, $dataHasSimpleRefs
552 );
553 $this->pos = $this->length;
554 $nextState = self::STATE_EOF;
555 break;
556 }
557
558 $startPos = $m[0][1];
559 $dataIsSimple = ( $npos === $startPos );
560 $dataHasSimpleRefs = ( $mpos === $startPos );
561 $tagName = isset( $m[self::MD_TAG_NAME] ) ? $m[self::MD_TAG_NAME][0] : '';
562
563 $this->emitDataRange( $this->pos, $startPos - $this->pos, $dataIsSimple, $dataHasSimpleRefs );
564 $this->pos = $startPos;
565 $nextPos = $m[0][1] + strlen( $m[0][0] );
566
567 if ( isset( $m[self::MD_CDATA] ) && $m[self::MD_CDATA][1] >= 0 ) {
568 if ( $this->enableCdataCallback ) {
569 $isCdata = ( $this->enableCdataCallback )();
570 } else {
571 $isCdata = false;
572 }
573 if ( !$isCdata ) {
574 $m[self::MD_BOGUS_COMMENT] = $m[self::MD_CDATA];
575 }
576 }
577
578 if ( strlen( $tagName ) ) {
579 // Tag
580 $isEndTag = (bool)strlen( $m[self::MD_END_TAG_OPEN][0] );
581 $isAllLower = isset( $m[self::MD_TAG_AFTER_LOWERCASE] ) &&
582 $m[self::MD_TAG_AFTER_LOWERCASE][0] === '';
583 if ( !$isAllLower ) {
584 // As an optimization, we skip these steps for the common
585 // case of an all-lowercase tag name
586 if ( !$this->ignoreNulls ) {
587 $tagName = $this->handleNulls( $tagName, $m[self::MD_TAG_NAME][1] );
588 }
589 $tagName = strtolower( $tagName );
590 }
591 $this->pos = $nextPos;
592 if ( $nextPos < $this->length && $this->text[ $nextPos ] === '>' ) {
593 // "Simple tag" optimization; skip attribute parsing and
594 // stay in this state
595 $this->pos = ++$nextPos;
596 if ( $isEndTag ) {
597 $this->listener->endTag(
598 $tagName, $startPos, $nextPos - $startPos
599 );
600 } else {
601 $this->listener->startTag(
602 $tagName, new PlainAttributes(), false,
603 $startPos, $nextPos - $startPos
604 );
605 }
606 // Respect any state switch imposed by the parser
607 $nextState = $this->state;
608 continue;
609 }
610 $nextState = $this->handleAttribsAndClose( self::STATE_DATA,
611 $tagName, $isEndTag, $startPos );
612 $nextPos = $this->pos;
613 if ( $nextState === self::STATE_EOF ) {
614 break;
615 }
616
617 // Respect any state switch imposed by the parser
618 $nextState = $this->state;
619
620 } elseif ( isset( $m[self::MD_COMMENT] ) && $m[self::MD_COMMENT][1] >= 0 ) {
621 // Comment
622 $this->interpretCommentMatches( $m );
623 } elseif ( isset( $m[self::MD_DOCTYPE] ) && $m[self::MD_DOCTYPE][1] >= 0 ) {
624 // DOCTYPE
625 $this->interpretDoctypeMatches( $m );
626 } elseif ( isset( $m[self::MD_CDATA] ) && $m[self::MD_CDATA][1] >= 0 ) {
627 // CDATA
628 if ( $this->enableCdataCallback
629 && ( $this->enableCdataCallback )()
630 ) {
631 $this->pos += strlen( $m[self::MD_CDATA][0] ) + 1;
632 $endPos = strpos( $this->text, ']]>', $this->pos );
633 if ( $endPos === false ) {
634 $this->emitCdataRange( $this->pos, $this->length - $this->pos,
635 $startPos, $this->length - $startPos );
636 $this->pos = $this->length;
637 $nextState = self::STATE_EOF;
638 break;
639 } else {
640 $outerEndPos = $endPos + strlen( ']]>' );
641 $this->emitCdataRange( $this->pos, $endPos - $this->pos,
642 $startPos, $outerEndPos - $startPos );
643 $nextPos = $outerEndPos;
644 }
645 } else {
646 // Bogus comment
647 $this->error( "unexpected CDATA interpreted as bogus comment" );
648 $endPos = strpos( $this->text, '>', $this->pos );
649 $bogusPos = $this->pos + 2;
650 if ( $endPos === false ) {
651 $nextPos = $this->length;
652 $contents = substr( $this->text, $bogusPos );
653 } else {
654 $nextPos = $endPos + 1;
655 $contents = substr( $this->text, $bogusPos, $endPos - $bogusPos );
656 }
657 $contents = $this->handleNulls( $contents, $bogusPos );
658 $this->listener->comment( $contents, $this->pos, $endPos - $this->pos );
659 }
660 } elseif ( isset( $m[self::MD_BOGUS_COMMENT] ) && $m[self::MD_BOGUS_COMMENT][1] >= 0 ) {
661 // Bogus comment
662 $contents = $m[self::MD_BOGUS_COMMENT][0];
663 $bogusPos = $m[self::MD_BOGUS_COMMENT][1];
664 if ( $m[0][0] === '</>' ) {
665 $this->error( "empty end tag" );
666 // No token emitted
667 } elseif ( $m[0][0] === '</' ) {
668 $this->error( 'EOF in end tag' );
669 $sourceStart = $m[0][1];
670 '@phan-var int $sourceStart'; /** @var int $sourceStart */
671 $this->listener->characters( '</', 0, 2, $sourceStart, 2 );
672 } else {
673 $this->error( "unexpected <{$contents[0]} interpreted as bogus comment" );
674 if ( $contents[0] !== '?' ) {
675 // For starting types other than <?, the initial character is
676 // not in the tag contents
677 $contents = substr( $contents, 1 );
678 $bogusPos++;
679 }
680
681 $contents = $this->handleNulls( $contents, $bogusPos );
682 $this->listener->comment( $contents, $startPos, $nextPos - $startPos );
683 }
684 } else {
685 $this->fatal( 'unexpected data state match' );
686 }
687 $this->pos = $nextPos;
688 } while ( $loop && $nextState === self::STATE_DATA );
689
690 return $nextState;
691 }
692
693 /**
694 * Interpret the data state match results for a detected comment, and emit
695 * events as appropriate.
696 *
697 * @param array $m The match array
698 */
699 protected function interpretCommentMatches( $m ) {
700 $outerStart = $m[0][1];
701 $outerLength = strlen( $m[0][0] );
702 $innerStart = $outerStart + strlen( '<!--' );
703 $innerLength = isset( $m[self::MD_COMMENT_INNER] ) ? strlen( $m[self::MD_COMMENT_INNER][0] ) : 0;
704 $contents = $innerLength ? $m[self::MD_COMMENT_INNER][0] : '';
705
706 if ( $m[0][0] === '<!-->' || $m[0][0] === '<!--->' ) {
707 // These are special cases in the comment start state
708 $this->error( 'not enough dashes in empty comment', $outerStart );
709 $this->listener->comment( '', $outerStart, $outerLength );
710 return;
711 }
712
713 if ( !$this->ignoreNulls ) {
714 $contents = $this->handleNulls( $contents, $innerStart );
715 }
716 $close = $m[self::MD_COMMENT_END][0];
717 $closePos = $m[self::MD_COMMENT_END][1];
718
719 if ( !$this->ignoreErrors ) {
720 if ( $close === '--!>' ) {
721 $this->error( 'invalid comment end bang', $closePos );
722 } elseif ( $close === '-' || $close === '--' || $close === '--!' ) {
723 $this->error( 'EOF part way through comment close', $closePos );
724 } elseif ( $close === '' ) {
725 $this->error( 'EOF in comment', $closePos );
726 }
727
728 $dashSearchLength = $innerLength;
729 while ( $dashSearchLength > 0 && $contents[$dashSearchLength - 1] === '-' ) {
730 $this->error( 'invalid extra dash at comment end',
731 $innerStart + $dashSearchLength - 1 );
732 $dashSearchLength--;
733 }
734
735 $offset = 0;
736 while ( $offset !== false && $offset < $dashSearchLength ) {
737 $offset = strpos( $contents, '--', $offset );
738 if ( $offset !== false ) {
739 $this->error( 'bare "--" found in comment', $innerStart + $offset );
740 $offset += 2;
741 }
742 }
743 }
744
745 $this->listener->comment( $contents, $outerStart, $outerLength );
746 }
747
748 /**
749 * Interpret the data state match results for a detected DOCTYPE token,
750 * and emit events as appropriate.
751 *
752 * @param array $m The match array
753 */
754 protected function interpretDoctypeMatches( $m ) {
755 $igerr = $this->ignoreErrors;
756 $name = null;
757 $public = null;
758 $system = null;
759 $quirks = false;
760
761 // Missing ">" can only be caused by EOF
762 $eof = !strlen( $m[self::MD_DT_END][0] );
763
764 if ( strlen( $m[self::MD_DT_BOGUS][0] ) ) {
765 // Bogus DOCTYPE state
766 if ( !$igerr ) {
767 $this->error( 'invalid DOCTYPE contents', $m[self::MD_DT_BOGUS][1] );
768 }
769 // Set quirks mode unless there was a properly quoted SYSTEM identifier
770 $haveDq = isset( $m[self::MD_DT_SYSTEM_DQ] ) && $m[self::MD_DT_SYSTEM_DQ][1] >= 0;
771 $haveSq = isset( $m[self::MD_DT_SYSTEM_SQ] ) && $m[self::MD_DT_SYSTEM_SQ][1] >= 0;
772 if ( !$haveDq && !$haveSq ) {
773 $quirks = true;
774 }
775 // EOF in the bogus state does not set quirks mode (but it is a parse error)
776 if ( $eof && !$igerr ) {
777 $this->error( 'unterminated DOCTYPE' );
778 }
779 } elseif ( $eof ) {
780 if ( !$igerr ) {
781 $this->error( 'unterminated DOCTYPE' );
782 }
783 $quirks = true;
784 }
785
786 if ( !$igerr && !$eof && !strlen( $m[self::MD_DT_NAME_WS][0] ) ) {
787 $this->error( 'missing whitespace', $m[self::MD_DT_NAME_WS][1] );
788 }
789
790 if ( strlen( $m[self::MD_DT_NAME][0] ) ) {
791 // DOCTYPE name
792 $name = $this->handleNulls( strtolower( $m[self::MD_DT_NAME][0] ), $m[self::MD_DT_NAME][1] );
793 } else {
794 if ( !$eof && !$igerr ) {
795 $this->error( 'missing DOCTYPE name',
796 $m[self::MD_DOCTYPE][1] + strlen( '!DOCTYPE' ) );
797 }
798 $quirks = true;
799 }
800
801 if ( isset( $m[self::MD_DT_PUBLIC_WS] ) && $m[self::MD_DT_PUBLIC_WS][1] >= 0 ) {
802 // PUBLIC keyword found
803 $public = $this->interpretDoctypeQuoted( $m,
804 self::MD_DT_PUBLIC_DQ, self::MD_DT_PUBLIC_SQ, $quirks );
805 if ( $public === null ) {
806 $quirks = true;
807 if ( !$eof && !$igerr ) {
808 $this->error( 'missing public identifier', $m[self::MD_DT_PUBLIC_WS][1] );
809 }
810 } elseif ( !$igerr && !$eof && !strlen( $m[self::MD_DT_PUBLIC_WS][0] ) ) {
811 $this->error( 'missing whitespace', $m[self::MD_DT_PUBLIC_WS][1] );
812 }
813
814 // Check for a system ID after the public ID
815 $haveDq = isset( $m[self::MD_DT_PUBSYS_DQ] ) && $m[self::MD_DT_PUBSYS_DQ][1] >= 0;
816 $haveSq = isset( $m[self::MD_DT_PUBSYS_SQ] ) && $m[self::MD_DT_PUBSYS_SQ][1] >= 0;
817 if ( $haveDq || $haveSq ) {
818 if ( !$igerr && !strlen( $m[self::MD_DT_PUBSYS_WS][0] ) ) {
819 $this->error( 'missing whitespace', $m[self::MD_DT_PUBSYS_WS][1] );
820 }
821 $system = $this->interpretDoctypeQuoted( $m,
822 self::MD_DT_PUBSYS_DQ, self::MD_DT_PUBSYS_SQ, $quirks );
823 }
824 } elseif ( isset( $m[self::MD_DT_SYSTEM_WS] ) && $m[self::MD_DT_SYSTEM_WS][1] >= 0 ) {
825 // SYSTEM keyword found
826 $system = $this->interpretDoctypeQuoted( $m,
827 self::MD_DT_SYSTEM_DQ, self::MD_DT_SYSTEM_SQ, $quirks );
828 if ( $system === null ) {
829 $quirks = true;
830 $this->error( 'missing system identifier', $m[self::MD_DT_SYSTEM_WS][1] );
831 } elseif ( !$igerr && !strlen( $m[self::MD_DT_SYSTEM_WS][0] ) ) {
832 $this->error( 'missing whitespace', $m[self::MD_DT_SYSTEM_WS][1] );
833 }
834
835 }
836 $this->listener->doctype( $name, $public, $system, $quirks, $m[0][1], strlen( $m[0][0] ) );
837 }
838
839 /**
840 * DOCTYPE helper which interprets a quoted string (or lack thereof)
841 * @param array $m
842 * @param int $dq
843 * @param int $sq
844 * @param bool &$quirks
845 * @return string|null The quoted value, with nulls replaced.
846 */
847 protected function interpretDoctypeQuoted( $m, $dq, $sq, &$quirks ) {
848 if ( isset( $m[$dq] ) && $m[$dq][1] >= 0 ) {
849 $value = $m[$dq][0];
850 $startPos = $m[$dq][1];
851 } elseif ( isset( $m[$sq] ) && $m[$sq][1] >= 0 ) {
852 $value = $m[$sq][0];
853 $startPos = $m[$sq][1];
854 } else {
855 return null;
856 }
857 $endPos = $startPos + strlen( $value );
858 if ( $endPos >= $this->length ) {
859 // This is a parse error, but we already emitted a generic EOF error
860 $quirks = true;
861 } elseif ( $this->text[$endPos] === '>' ) {
862 $this->error( 'DOCTYPE identifier terminated by ">"', $endPos );
863 $quirks = true;
864 }
865 $value = $this->handleNulls( $value, $startPos );
866 return $value;
867 }
868
869 /**
870 * Generic helper for all those points in the spec where U+0000 needs to be
871 * replaced with U+FFFD with a parse error issued.
872 *
873 * @param string $text The text to be converted
874 * @param int $sourcePos The input byte offset from which $text was
875 * extracted, for error position reporting.
876 * @return string The converted text
877 */
878 protected function handleNulls( $text, $sourcePos ) {
879 if ( $this->ignoreNulls ) {
880 return $text;
881 }
882 if ( !$this->ignoreErrors ) {
883 $offset = 0;
884 while ( true ) {
885 $nullPos = strpos( $text, "\0", $offset );
886 if ( $nullPos === false ) {
887 break;
888 }
889 $this->error( "replaced null character", $sourcePos + $nullPos );
890 if ( $nullPos < strlen( $text ) - 1 ) {
891 $offset = $nullPos + 1;
892 } else {
893 break;
894 }
895 }
896 }
897 return str_replace( "\0", self::REPLACEMENT_CHAR, $text );
898 }
899
900 /**
901 * Generic helper for points in the spec which say that an error should
902 * be issued when certain ASCII characters are seen, with no other action
903 * taken.
904 *
905 * @param string $mask Mask for strcspn
906 * @param string $text The input text
907 * @param int $offset The start of the range within $text to search
908 * @param int $length The length of the range within $text to search
909 * @param int $sourcePos The offset within the input text corresponding
910 * to $text, for error position reporting.
911 */
912 protected function handleAsciiErrors( $mask, $text, $offset, $length, $sourcePos ) {
913 while ( $length > 0 ) {
914 $validLength = strcspn( $text, $mask, $offset, $length );
915 $offset += $validLength;
916 $length -= $validLength;
917 if ( $length <= 0 ) {
918 break;
919 }
920 $char = $text[$offset];
921 $codepoint = ord( $char );
922 if ( $codepoint < 0x20 || $codepoint >= 0x7f ) {
923 $this->error( sprintf( 'unexpected U+00%02X', $codepoint ), $offset + $sourcePos );
924 } else {
925 $this->error( "unexpected \"$char\"", $offset + $sourcePos );
926 }
927 $offset++;
928 $length--;
929 }
930 }
931
932 // This string isn't used directly: it's input to GenerateDataFiles.php
933 // which will substitute in the named entities and create a
934 // compile-time constant string in HtmlData::CHAR_REF_REGEX
935 // Only compile-time constants are handled efficiently in the
936 // regexp cache; otherwise we pay for a 26k strcmp each time we
937 // fetch the regexp from the cache.
938 public const CHARREF_REGEX = '~
939 ( .*? ) # 1. prefix
940 &
941 (?:
942 \# (?:
943 0*(\d+) | # 2. decimal
944 [xX]0*([0-9A-Fa-f]+) # 3. hexadecimal
945 )
946 ( ; ) ? # 4. semicolon
947 |
948 ( \# ) # 5. bare hash
949 |
950 ({{NAMED_ENTITY_REGEX}}) # 6. known named
951 (?:
952 (?<! ; ) # Assert no semicolon prior
953 ( [=a-zA-Z0-9] ) # 7. attribute suffix
954 )?
955 |
956 ( [a-zA-Z0-9]+ ; ) # 8. invalid named
957 )
958 # S = study, for efficient knownNamed
959 # A = anchor, to avoid unnecessary movement of the whole pattern on failure
960 ~xAsS';
961
962 /**
963 * Expand character references in some text, and emit errors as appropriate.
964 * @param string $text The text to expand
965 * @param int $sourcePos The input position of $text
966 * @param bool $inAttr True if the text is within an attribute value
967 * @param string $additionalAllowedChar An unused string which the spec
968 * inexplicably spends a lot of space telling you how to derive. It
969 * suppresses errors in a place where no errors are emitted anyway.
970 * @return string The expanded text
971 */
972 protected function handleCharRefs( $text, $sourcePos, $inAttr = false,
973 $additionalAllowedChar = ''
974 ) {
975 if ( $this->ignoreCharRefs ) {
976 return $text;
977 }
978
979 $out = '';
980 $pos = 0;
981 $length = strlen( $text );
982 $matches = [];
983 $count = preg_match_all( HTMLData::CHAR_REF_REGEX, $text, $matches, PREG_SET_ORDER );
984 if ( $count === false ) {
985 $this->throwPregError();
986 }
987
988 foreach ( $matches as $m ) {
989 $out .= $m[self::MC_PREFIX];
990 $errorPos = $sourcePos + $pos + strlen( $m[self::MC_PREFIX] );
991 $pos += strlen( $m[0] );
992
993 if ( isset( $m[self::MC_HASH] ) && strlen( $m[self::MC_HASH] ) ) {
994 // Bare &#
995 $this->error( 'Expected digits after &#', $errorPos );
996 $out .= '&#';
997 continue;
998 }
999
1000 $knownNamed = $m[self::MC_NAMED] ?? '';
1001 $attributeSuffix = $m[self::MC_SUFFIX] ?? '';
1002
1003 $haveSemicolon =
1004 ( isset( $m[self::MC_SEMICOLON] ) && strlen( $m[self::MC_SEMICOLON] ) )
1005 || ( strlen( $knownNamed ) && $knownNamed[ strlen( $knownNamed ) - 1 ] === ';' )
1006 || ( isset( $m[self::MC_INVALID] ) && strlen( $m[self::MC_INVALID] ) );
1007
1008 if ( $inAttr && !$haveSemicolon ) {
1009 if ( strlen( $attributeSuffix ) ) {
1010 if ( !$this->ignoreErrors && $attributeSuffix === '=' ) {
1011 $this->error( 'invalid equals sign after named character reference' );
1012 }
1013 $out .= '&' . $knownNamed . $attributeSuffix;
1014 continue;
1015 }
1016 }
1017
1018 if ( !$this->ignoreErrors && !$haveSemicolon ) {
1019 $this->error( 'character reference missing semicolon', $errorPos );
1020 }
1021
1022 if ( isset( $m[self::MC_DECIMAL] ) && strlen( $m[self::MC_DECIMAL] ) ) {
1023 // Decimal
1024 if ( strlen( $m[self::MC_DECIMAL] ) > 7 ) {
1025 $this->error( 'invalid numeric reference', $errorPos );
1026 $out .= self::REPLACEMENT_CHAR;
1027 continue;
1028 }
1029 $codepoint = intval( $m[self::MC_DECIMAL] );
1030 } elseif ( isset( $m[self::MC_HEXDEC] ) && strlen( $m[self::MC_HEXDEC] ) ) {
1031 // Hexadecimal
1032 if ( strlen( $m[self::MC_HEXDEC] ) > 6 ) {
1033 $this->error( 'invalid numeric reference', $errorPos );
1034 $out .= self::REPLACEMENT_CHAR;
1035 continue;
1036 }
1037 $codepoint = intval( $m[self::MC_HEXDEC], 16 );
1038 } elseif ( $knownNamed !== '' ) {
1039 $out .= HTMLData::NAMED_ENTITY_TRANSLATION[$knownNamed] . $attributeSuffix;
1040 continue;
1041 } elseif ( isset( $m[self::MC_INVALID] ) && strlen( $m[self::MC_INVALID] ) ) {
1042 if ( !$this->ignoreErrors ) {
1043 $this->error( 'invalid named reference', $errorPos );
1044 }
1045 $out .= '&' . $m[self::MC_INVALID];
1046 continue;
1047 } else {
1048 $this->fatal( 'unable to identify char ref submatch' );
1049 // @phan-suppress-next-line PhanPluginUnreachableCode False positive that var is not defined
1050 $codepoint = 0;
1051 }
1052
1053 // Interpret $codepoint
1054 if ( $codepoint === 0
1055 || ( $codepoint >= 0xD800 && $codepoint <= 0xDFFF )
1056 || $codepoint > 0x10FFFF
1057 ) {
1058 if ( !$this->ignoreErrors ) {
1059 $this->error( 'invalid numeric reference', $errorPos );
1060 }
1061 $out .= self::REPLACEMENT_CHAR;
1062 } elseif ( isset( HTMLData::LEGACY_NUMERIC_ENTITIES[$codepoint] ) ) {
1063 if ( !$this->ignoreErrors ) {
1064 $this->error( 'invalid reference to non-ASCII control character', $errorPos );
1065 }
1066 $out .= HTMLData::LEGACY_NUMERIC_ENTITIES[$codepoint];
1067 } else {
1068 if ( !$this->ignoreErrors ) {
1069 $disallowedCodepoints = [
1070 0x000B => true,
1071 0xFFFE => true, 0xFFFF => true,
1072 0x1FFFE => true, 0x1FFFF => true,
1073 0x2FFFE => true, 0x2FFFF => true,
1074 0x3FFFE => true, 0x3FFFF => true,
1075 0x4FFFE => true, 0x4FFFF => true,
1076 0x5FFFE => true, 0x5FFFF => true,
1077 0x6FFFE => true, 0x6FFFF => true,
1078 0x7FFFE => true, 0x7FFFF => true,
1079 0x8FFFE => true, 0x8FFFF => true,
1080 0x9FFFE => true, 0x9FFFF => true,
1081 0xAFFFE => true, 0xAFFFF => true,
1082 0xBFFFE => true, 0xBFFFF => true,
1083 0xCFFFE => true, 0xCFFFF => true,
1084 0xDFFFE => true, 0xDFFFF => true,
1085 0xEFFFE => true, 0xEFFFF => true,
1086 0xFFFFE => true, 0xFFFFF => true,
1087 0x10FFFE => true, 0x10FFFF => true ];
1088 if (
1089 ( $codepoint >= 1 && $codepoint <= 8 ) ||
1090 ( $codepoint >= 0x0d && $codepoint <= 0x1f ) ||
1091 ( $codepoint >= 0x7f && $codepoint <= 0x9f ) ||
1092 ( $codepoint >= 0xfdd0 && $codepoint <= 0xfdef ) ||
1093 isset( $disallowedCodepoints[$codepoint] )
1094 ) {
1095 $this->error( 'invalid numeric reference to control character',
1096 $errorPos );
1097 }
1098 }
1099
1100 $out .= \UtfNormal\Utils::codepointToUtf8( $codepoint );
1101 }
1102 }
1103 if ( $pos < $length ) {
1104 $out .= substr( $text, $pos );
1105 }
1106 return $out;
1107 }
1108
1109 /**
1110 * Emit a range of the input text as a character token, and emit related
1111 * errors, with validity rules as per the data state.
1112 *
1113 * @param int $pos Offset within the input text
1114 * @param int $length The length of the range
1115 * @param bool $isSimple True if you know that the data range does not
1116 * contain < \0 or &; false is safe if you're not sure
1117 * @param bool $hasSimpleRefs True if you know that any character
1118 * references are semicolon terminated and in the list of self::COMMON_ENTITIES;
1119 * false is safe if you're not sure
1120 */
1121 protected function emitDataRange( $pos, $length, $isSimple = false, $hasSimpleRefs = false ) {
1122 if ( $length === 0 ) {
1123 return;
1124 }
1125 if ( $this->ignoreCharRefs && $this->ignoreNulls && $this->ignoreErrors ) {
1126 // Pretend this data range doesn't contain < \0 or &
1127 $isSimple = true;
1128 }
1129 if ( $isSimple ) {
1130 $this->listener->characters( $this->text, $pos, $length, $pos, $length );
1131 } else {
1132 if ( !$this->ignoreErrors ) {
1133 // Any bare "<" in a data state text node is a parse error.
1134 // Uniquely to the data state, nulls are just flagged as errors
1135 // and passed through, they are not replaced.
1136 $this->handleAsciiErrors( "<\0", $this->text, $pos, $length, 0 );
1137 }
1138
1139 $text = substr( $this->text, $pos, $length );
1140 if ( $hasSimpleRefs ) {
1141 $text = strtr( $text, self::COMMON_ENTITIES );
1142 } else {
1143 $text = $this->handleCharRefs( $text, $pos );
1144 }
1145 $this->listener->characters( $text, 0, strlen( $text ), $pos, $length );
1146 }
1147 }
1148
1149 /**
1150 * Emit a range of characters from the input text, with validity rules as
1151 * per the CDATA section state.
1152 *
1153 * @param int $innerPos The position after the <![CDATA[
1154 * @param int $innerLength The length of the string not including the terminating ]]>
1155 * @param int $outerPos The position of the start of the <!CDATA[
1156 * @param int $outerLength The length of the whole input region being emitted
1157 */
1158 protected function emitCdataRange( $innerPos, $innerLength, $outerPos, $outerLength ) {
1159 $this->listener->characters( $this->text, $innerPos, $innerLength,
1160 $outerPos, $outerLength );
1161 }
1162
1163 /**
1164 * Emit a range of characters from the input text, either from RCDATA,
1165 * RAWTEXT, script data or PLAINTEXT. The only difference between these
1166 * states is whether or not character references are expanded, so we take
1167 * that as a parameter.
1168 *
1169 * @param bool $ignoreCharRefs
1170 * @param int $pos The input position
1171 * @param int $length The length of the range to be emitted
1172 */
1173 protected function emitRawTextRange( $ignoreCharRefs, $pos, $length ) {
1174 if ( $length === 0 ) {
1175 return;
1176 }
1177 $ignoreCharRefs = $ignoreCharRefs || $this->ignoreCharRefs;
1178 if ( $ignoreCharRefs && $this->ignoreNulls ) {
1179 $this->listener->characters( $this->text, $pos, $length, $pos, $length );
1180 } else {
1181 $text = substr( $this->text, $pos, $length );
1182 if ( !$ignoreCharRefs ) {
1183 $text = $this->handleCharRefs( $text, $pos );
1184 }
1185 $text = $this->handleNulls( $text, $pos );
1186 $this->listener->characters( $text, 0, strlen( $text ), $pos, $length );
1187 }
1188 }
1189
1190 /**
1191 * The entry point for the RCDATA and RAWTEXT states.
1192 * @param bool $ignoreCharRefs True to ignore character references regardless
1193 * of configuration, false to respect the configuration.
1194 * @return int The next state index
1195 */
1196 protected function textElementState( $ignoreCharRefs ) {
1197 if ( $this->appropriateEndTag === null ) {
1198 $this->emitRawTextRange( $ignoreCharRefs, $this->pos, $this->length - $this->pos );
1199 $this->pos = $this->length;
1200 return self::STATE_EOF;
1201 }
1202
1203 $re = "~</
1204 {$this->appropriateEndTag}
1205 # Assert that the end tag name state is exited appropriately,
1206 # since the anything else case leads to the tag being treated as
1207 # a literal
1208 (?=[\t\n\f />])
1209 ~ix";
1210
1211 do {
1212 $count = preg_match( $re, $this->text, $m, PREG_OFFSET_CAPTURE, $this->pos );
1213
1214 if ( $count === false ) {
1215 $this->throwPregError();
1216 } elseif ( !$count ) {
1217 // Text runs to end
1218 $this->emitRawTextRange( $ignoreCharRefs, $this->pos, $this->length - $this->pos );
1219 $this->pos = $this->length;
1220 return self::STATE_EOF;
1221 }
1222 $startPos = $m[0][1];
1223
1224 // Emit text before tag
1225 $this->emitRawTextRange( $ignoreCharRefs, $this->pos, $startPos - $this->pos );
1226
1227 $matchLength = strlen( $m[0][0] );
1228 $this->pos = $startPos + $matchLength;
1229 $nextState = $this->handleAttribsAndClose( self::STATE_RCDATA,
1230 $this->appropriateEndTag, true, $startPos );
1231 } while ( $nextState === self::STATE_RCDATA );
1232 return $nextState;
1233 }
1234
1235 /**
1236 * Advance $this->pos, consuming all tag attributes found at the current
1237 * position. The new position will be at the end of the tag or at the end
1238 * of the input string.
1239 *
1240 * To improve performance of consumers which don't need to read the
1241 * attribute array, interpretation of the PCRE match results is deferred.
1242 *
1243 * - @todo: Make deferral configurable.
1244 * - @todo: Measure performance improvement, assess whether the LazyAttributes
1245 * feature is warranted.
1246 *
1247 * @return Attributes
1248 */
1249 protected function consumeAttribs() {
1250 static $re;
1251 if ( $re === null ) {
1252 $re = '~
1253 [\t\n\f ]*+ # Ignored whitespace before attribute name
1254 (?! /> ) # Do not consume self-closing end of tag
1255 (?! > ) # Do not consume normal closing bracket
1256
1257 (?:
1258 # Before attribute name state
1259 # A bare slash at this point, not part of a self-closing end tag, is
1260 # consumed and ignored (with a parse error), returning to the before
1261 # attribute name state.
1262 ( / ) | # 1. Bare slash
1263
1264 # Attribute name state
1265 # Note that the first character can be an equals sign, this is a parse error
1266 # but still generates an attribute called "=". Thus the only way the match
1267 # could fail here is due to EOF.
1268
1269 ( # 2. Attribute name
1270 (?:
1271 ( [-a-z]++ ) | # 3. Optional "simple" prefix
1272 [^\t\n\f />]
1273 )
1274 [^\t\n\f =/>]*+
1275 )
1276
1277 # After attribute name state
1278 [\t\n\f ]*+
1279
1280 (?:
1281 =
1282 # Before attribute value state
1283 # Ignore whitespace
1284 [\t\n\f ]*+
1285 (?:
1286 # If an end-quote is omitted, the attribute will run to the end of the
1287 # string, leaving no closing bracket. So the caller will detect the
1288 # unexpected EOF and will not emit the tag, which is correct.
1289 " ( # 4. Double-quoted attribute values
1290 [^"&\r\0]*+ # Simple prefix
1291 ( # 5. Perhaps some simple entities
1292 (?: &(?:amp|apos|lt|gt|quot|nbsp); | [^"&\r\0] )*+
1293 )
1294 ( [^"]*+ ) # 6. Unsimple suffix
1295 ) "? |
1296 \' ( # 7. Single-quoted attribute value
1297 [^\'&\r\0]*+ # Simple prefix
1298 ( # 8. Perhaps some simple entities
1299 (?: &(?:amp|apos|lt|gt|quot|nbsp); | [^\'&\r\0] )*+
1300 )
1301 ( [^\']*+ ) # 9. Unsimple suffix
1302 ) \'? |
1303 ( # 10. Unquoted attribute value
1304 [^\t\n\f >\r"&\'\0=<`]*+ # Simple prefix
1305 ( [^\t\n\f >]*+ ) # 11. Unsimple suffix
1306 )
1307 )
1308 # Or nothing: an attribute with an empty value. The attribute name was
1309 # terminated by a slash, closing bracket or EOF
1310 |
1311 )
1312 )
1313 # The /A modifier causes preg_match_all to give contiguous chunks
1314 ~xAS';
1315 }
1316 $count = preg_match_all( $re, $this->text, $m,
1317 PREG_SET_ORDER | PREG_OFFSET_CAPTURE, $this->pos );
1318 if ( $count === false ) {
1319 $this->throwPregError();
1320 // @phan-suppress-next-line PhanPluginUnreachableCode False positive that var is not defined
1321 $attribs = new PlainAttributes();
1322 } elseif ( $count ) {
1323 $this->pos = $m[$count - 1][0][1] + strlen( $m[$count - 1][0][0] );
1324 $attribs = $this->lazyAttributes
1325 ? new LazyAttributes( $m, function ( $m ) {
1326 return $this->interpretAttribMatches( $m );
1327 } )
1328 : new PlainAttributes( $this->interpretAttribMatches( $m ) );
1329 } else {
1330 $attribs = new PlainAttributes();
1331 }
1332
1333 // Consume trailing whitespace. This is strictly part of the before attribute
1334 // name state, but we didn't consume it in the regex since we used a principle
1335 // of one match equals one attribute.
1336 $this->pos += strspn( $this->text, "\t\n\f ", $this->pos );
1337 return $attribs;
1338 }
1339
1340 /**
1341 * Interpret the results of the attribute preg_match_all(). Emit errors as
1342 * appropriate and return an associative array.
1343 *
1344 * @param array $matches
1345 * @return array
1346 */
1347 protected function interpretAttribMatches( $matches ) {
1348 $attributes = [];
1349 foreach ( $matches as $m ) {
1350 if ( strlen( $m[self::MA_SLASH][0] ) ) {
1351 $this->error( 'unexpected bare slash', $m[self::MA_SLASH][1] );
1352 continue;
1353 }
1354 $name = $m[self::MA_NAME][0];
1355 $isSimple = isset( $m[self::MA_SIMPLE_NAME] ) &&
1356 ( strlen( $name ) === strlen( $m[self::MA_SIMPLE_NAME][0] ) );
1357 if ( !$isSimple ) {
1358 // We can skip these steps if we already know the name is simple
1359 if ( !$this->ignoreErrors ) {
1360 $this->handleAsciiErrors( "\"'<=", $name, 0, strlen( $name ), $m[self::MA_NAME][1] );
1361 }
1362 if ( !$this->ignoreNulls ) {
1363 $name = $this->handleNulls( $m[self::MA_NAME][0], $m[self::MA_NAME][1] );
1364 }
1365 $name = strtolower( $name );
1366 }
1367 $additionalAllowedChar = '';
1368 $isSimple = true;
1369 if ( isset( $m[self::MA_DQUOTED] ) && $m[self::MA_DQUOTED][1] >= 0 ) {
1370 // Double-quoted attribute value
1371 $additionalAllowedChar = '"';
1372 $value = $m[self::MA_DQUOTED][0];
1373 $pos = $m[self::MA_DQUOTED][1];
1374 $isSimple = !strlen( $m[self::MA_DQUOTED_UNSIMPLE][0] );
1375 if ( $isSimple && strlen( $m[self::MA_DQUOTED_CHARREF][0] ) && !$this->ignoreCharRefs ) {
1376 // Efficiently handle well-behaved character references
1377 $value = strtr( $value, self::COMMON_ENTITIES );
1378 }
1379 } elseif ( isset( $m[self::MA_SQUOTED] ) && $m[self::MA_SQUOTED][1] >= 0 ) {
1380 // Single-quoted attribute value
1381 $additionalAllowedChar = "'";
1382 $value = $m[self::MA_SQUOTED][0];
1383 $pos = $m[self::MA_SQUOTED][1];
1384 $isSimple = !strlen( $m[self::MA_SQUOTED_UNSIMPLE][0] );
1385 if ( $isSimple && strlen( $m[self::MA_SQUOTED_CHARREF][0] ) && !$this->ignoreCharRefs ) {
1386 // Efficiently handle well-behaved character references
1387 $value = strtr( $value, self::COMMON_ENTITIES );
1388 }
1389 } elseif ( isset( $m[self::MA_UNQUOTED] ) && $m[self::MA_UNQUOTED][1] >= 0 ) {
1390 // Unquoted attribute value
1391 $value = $m[self::MA_UNQUOTED][0];
1392 $pos = $m[self::MA_UNQUOTED][1];
1393 $isSimple = !strlen( $m[self::MA_UNQUOTED_UNSIMPLE][0] );
1394 // Search for parse errors
1395 if ( !$this->ignoreErrors ) {
1396 if ( $value === '' ) {
1397 // ">" in the before attribute value state is a parse error
1398 $this->error( 'empty unquoted attribute', $pos );
1399 }
1400 if ( !$isSimple ) {
1401 $this->handleAsciiErrors( "\"'<=`", $value, 0, strlen( $value ), $pos );
1402 }
1403 }
1404 } else {
1405 $value = '';
1406 // reassure phan
1407 $pos = -1;
1408 }
1409 if ( $additionalAllowedChar && !$this->ignoreErrors ) {
1410 // After attribute value (quoted) state
1411 // Quoted attributes must be followed by a space, "/" or ">"
1412 $aavPos = $m[0][1] + strlen( $m[0][0] );
1413 if ( $aavPos < $this->length ) {
1414 $aavChar = $this->text[$aavPos];
1415 if ( !preg_match( '~^[\t\n\f />]~', $aavChar ) ) {
1416 $this->error( 'missing space between attributes', $aavPos );
1417 }
1418 }
1419 }
1420 if ( !$isSimple && $value !== '' ) {
1421 if ( !$this->ignoreNulls ) {
1422 $value = $this->handleNulls( $value, $pos );
1423 }
1424 if ( !$this->ignoreCharRefs ) {
1425 $value = $this->handleCharRefs( $value, $pos, true, $additionalAllowedChar );
1426 }
1427 }
1428 if ( isset( $attributes[$name] ) ) {
1429 $this->error( "duplicate attribute", $m[0][1] );
1430 } else {
1431 $attributes[$name] = $value;
1432 }
1433 }
1434 return $attributes;
1435 }
1436
1437 /**
1438 * Consume attributes, and the closing bracket which follows attributes.
1439 * Emit the appropriate tag event, or in the case of broken attributes in
1440 * text states, emit characters.
1441 *
1442 * @param int $state The current state
1443 * @param string $tagName The normalized tag name
1444 * @param bool $isEndTag True if this is an end tag, false if it is a start tag
1445 * @param int $startPos The input position of the start of the current tag.
1446 * @return int The next state
1447 */
1448 protected function handleAttribsAndClose( $state, $tagName, $isEndTag, $startPos ) {
1449 $attribStartPos = $this->pos;
1450 $attribs = $this->consumeAttribs();
1451 $pos = $this->pos;
1452
1453 // Literal characters are emitted on EOF or "anything else" from the
1454 // end tag substates of the text states.
1455 // (spec ref 8.2.4 sections 11-19, 25-27)
1456 $isDataState = $state === self::STATE_DATA;
1457 $isLiteral = $attribStartPos === $pos && !$isDataState;
1458
1459 if ( $pos >= $this->length ) {
1460 $this->error( 'unexpected end of file inside tag' );
1461 if ( $isLiteral ) {
1462 $this->listener->characters( $this->text,
1463 $startPos, $this->length - $startPos,
1464 $startPos, $this->length - $startPos );
1465 }
1466 return self::STATE_EOF;
1467 }
1468 if ( $isEndTag && !$this->ignoreErrors && $attribs->count() ) {
1469 $this->error( 'end tag has an attribute' );
1470 }
1471
1472 if ( $this->text[$pos] === '/' && $this->text[$pos + 1] === '>' ) {
1473 $pos += 2;
1474 $selfClose = true;
1475 } elseif ( $this->text[$pos] === '>' ) {
1476 $pos++;
1477 $selfClose = false;
1478 } elseif ( $isLiteral ) {
1479 $this->listener->characters( $this->text,
1480 $startPos, $attribStartPos - $startPos,
1481 $startPos, $attribStartPos - $startPos );
1482 return $state;
1483 } else {
1484 $this->fatal( 'failed to find an already-matched ">"' );
1485 // @phan-suppress-next-line PhanPluginUnreachableCode False positive that var is not defined
1486 $selfClose = false;
1487 }
1488 $this->pos = $pos;
1489 if ( $isEndTag ) {
1490 if ( $selfClose ) {
1491 $this->error( 'self-closing end tag' );
1492 }
1493 $this->listener->endTag( $tagName, $startPos, $pos - $startPos );
1494 } else {
1495 $this->listener->startTag( $tagName, $attribs, $selfClose,
1496 $startPos, $pos - $startPos );
1497 }
1498 return self::STATE_DATA;
1499 }
1500
1501 /**
1502 * Process input text in the PLAINTEXT state
1503 * @return int The next state index
1504 */
1505 protected function plaintextState() {
1506 $this->emitRawTextRange( true, $this->pos, $this->length - $this->pos );
1507 return self::STATE_EOF;
1508 }
1509
1510 /**
1511 * Process input text in the script data state
1512 * @return int The next state index
1513 */
1514 protected function scriptDataState() {
1515 if ( $this->appropriateEndTag === null ) {
1516 $this->pos = $this->length;
1517 return self::STATE_EOF;
1518 }
1519
1520 $re = <<<REGEX
1521 ~
1522 (?: # Outer loop start
1523 # Script data state
1524 # Stop iteration if we previously matched an appropriate end tag.
1525 # This is a conditional subpattern: if capture 1 previously
1526 # matched, then run the pattern /$./ which always fails.
1527 (?(1) $. )
1528 .*?
1529 (?:
1530 $ |
1531 (
1532 </ {$this->appropriateEndTag}
1533 # If we hit the "anything else" case in the script data
1534 # end tag name state, don't exit
1535 (?= [\t\n\f />] )
1536 ) | # 1. Appropriate end tag
1537 <!--
1538 # Script data escaped dash dash state
1539 # Hyphens at this point are consumed without a state transition
1540 # and so are not part of a comment-end.
1541 -*+
1542
1543 (?: # Inner loop start
1544 # Script data escaped state
1545 .*?
1546 (?:
1547 $ |
1548 # Stop at, but do not consume, comment-close or end tag.
1549 # This causes the inner loop to exit, since restarting the
1550 # inner loop at this input position will cause the loop
1551 # body to match zero characters. Repeating a zero-character
1552 # match causes the repeat to terminate.
1553 (?= --> ) |
1554 (?= </ {$this->appropriateEndTag} [\t\n\f />] ) |
1555 <script [\t\n\f />]
1556 # Script data double escaped state
1557 .*?
1558 (?:
1559 $ |
1560 # Stop at, but do not consume, comment-close
1561 (?= --> ) |
1562 </script [\t\n\f />]
1563 )
1564 )
1565 )*
1566
1567
1568 # Consume the comment close which exited the inner loop, if any
1569 (?: --> )?
1570 )
1571 )*+
1572 ~xsiA
1573 REGEX;
1574
1575 do {
1576 $count = preg_match( $re, $this->text, $m, 0, $this->pos );
1577 if ( $count === false ) {
1578 $this->throwPregError();
1579 } elseif ( !$count ) {
1580 $this->fatal( 'unexpected regex failure: this pattern can match zero characters' );
1581 }
1582
1583 $startPos = $this->pos;
1584 $matchLength = strlen( $m[0] );
1585 $endTagLength = isset( $m[1] ) ? strlen( $m[1] ) : 0;
1586 $textLength = $matchLength - $endTagLength;
1587 $this->emitRawTextRange( true, $startPos, $textLength );
1588 $this->pos = $startPos + $matchLength;
1589 $tagStartPos = $startPos + $textLength;
1590
1591 if ( $endTagLength ) {
1592 $nextState = $this->handleAttribsAndClose( self::STATE_SCRIPT_DATA,
1593 $this->appropriateEndTag, true, $tagStartPos );
1594 } else {
1595 $nextState = self::STATE_EOF;
1596 }
1597 } while ( $nextState === self::STATE_SCRIPT_DATA );
1598 return $nextState;
1599 }
1600
1601 /**
1602 * Emit a parse error event.
1603 * @param string $text The error message
1604 * @param int|null $pos The error position, or null to use the current position
1605 */
1606 protected function error( $text, $pos = null ) {
1607 if ( !$this->ignoreErrors ) {
1608 if ( $pos === null ) {
1609 $pos = $this->pos;
1610 }
1611 $this->listener->error( $text, $pos );
1612 }
1613 }
1614
1615 /**
1616 * Throw an exception for a specified reason. This is used for API errors
1617 * and assertion-like checks.
1618 * @param string $text The error message
1619 * @throws TokenizerError
1620 * @return never
1621 */
1622 protected function fatal( $text ) {
1623 throw new TokenizerError( __CLASS__ . ": " . $text );
1624 }
1625
1626 /**
1627 * Interpret preg_last_error() and throw a suitable exception. This is
1628 * called when preg_match() or similar returns false.
1629 *
1630 * Notes for users:
1631 *
1632 * - PCRE internal error: may be due to JIT stack space exhaustion prior
1633 * to PHP 7, due to excessive recursion. Increase stack space.
1634 *
1635 * - pcre.backtrack_limit exhausted: The backtrack limit should be at least
1636 * double the input size, the defaults are way too small. Increase it in
1637 * configuration.
1638 *
1639 * @return never
1640 */
1641 protected function throwPregError() {
1642 if ( defined( 'PREG_JIT_STACKLIMIT_ERROR' ) ) {
1643 $PREG_JIT_STACKLIMIT_ERROR = PREG_JIT_STACKLIMIT_ERROR;
1644 } else {
1645 $PREG_JIT_STACKLIMIT_ERROR = 'undefined error';
1646 }
1647 switch ( preg_last_error() ) {
1648 case PREG_NO_ERROR:
1649 $msg = "PCRE returned false but gave PREG_NO_ERROR";
1650 break;
1651
1652 case PREG_INTERNAL_ERROR:
1653 $msg = "PCRE internal error";
1654 break;
1655
1656 case PREG_BACKTRACK_LIMIT_ERROR:
1657 $msg = "pcre.backtrack_limit exhausted";
1658 break;
1659
1660 case PREG_RECURSION_LIMIT_ERROR:
1661 $msg = "pcre.recursion_limit exhausted";
1662 break;
1663
1664 case $PREG_JIT_STACKLIMIT_ERROR:
1665 $msg = "PCRE JIT stack space exhausted";
1666 break;
1667
1668 case PREG_BAD_UTF8_ERROR:
1669 case PREG_BAD_UTF8_OFFSET_ERROR:
1670 default:
1671 $msg = "PCRE unexpected error";
1672 }
1673
1674 throw new TokenizerError( __CLASS__ . ": $msg" );
1675 }
1676 }