| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * HTML API: WP_HTML_Tag_Processor class 4 * 5 * Scans through an HTML document to find specific tags, then 6 * transforms those tags by adding, removing, or updating the 7 * values of the HTML attributes within that tag (opener). 8 * 9 * Does not fully parse HTML or _recurse_ into the HTML structure 10 * Instead this scans linearly through a document and only parses 11 * the HTML tag openers. 12 * 13 * ### Possible future direction for this module 14 * 15 * - Prune the whitespace when removing classes/attributes: e.g. "a b c" -> "c" not " c". 16 * This would increase the size of the changes for some operations but leave more 17 * natural-looking output HTML. 18 * 19 * @package WordPress 20 * @subpackage HTML-API 21 * @since 6.2.0 22 */ 23 24 /** 25 * Core class used to modify attributes in an HTML document for tags matching a query. 26 * 27 * ## Usage 28 * 29 * Use of this class requires three steps: 30 * 31 * 1. Create a new class instance with your input HTML document. 32 * 2. Find the tag(s) you are looking for. 33 * 3. Request changes to the attributes in those tag(s). 34 * 35 * Example: 36 * 37 * $tags = new WP_HTML_Tag_Processor( $html ); 38 * if ( $tags->next_tag( 'option' ) ) { 39 * $tags->set_attribute( 'selected', true ); 40 * } 41 * 42 * ### Finding tags 43 * 44 * The `next_tag()` function moves the internal cursor through 45 * your input HTML document until it finds a tag meeting any of 46 * the supplied restrictions in the optional query argument. If 47 * no argument is provided then it will find the next HTML tag, 48 * regardless of what kind it is. 49 * 50 * If you want to _find whatever the next tag is_: 51 * 52 * $tags->next_tag(); 53 * 54 * | Goal | Query | 55 * |-----------------------------------------------------------|---------------------------------------------------------------------------------| 56 * | Find any tag. | `$tags->next_tag();` | 57 * | Find next image tag. | `$tags->next_tag( array( 'tag_name' => 'img' ) );` | 58 * | Find next image tag (without passing the array). | `$tags->next_tag( 'img' );` | 59 * | Find next tag containing the `fullwidth` CSS class. | `$tags->next_tag( array( 'class_name' => 'fullwidth' ) );` | 60 * | Find next image tag containing the `fullwidth` CSS class. | `$tags->next_tag( array( 'tag_name' => 'img', 'class_name' => 'fullwidth' ) );` | 61 * 62 * If a tag was found meeting your criteria then `next_tag()` 63 * will return `true` and you can proceed to modify it. If it 64 * returns `false`, however, it failed to find the tag and 65 * moved the cursor to the end of the file. 66 * 67 * Once the cursor reaches the end of the file the processor 68 * is done and if you want to reach an earlier tag you will 69 * need to recreate the processor and start over, as it's 70 * unable to back up or move in reverse. 71 * 72 * See the section on bookmarks for an exception to this 73 * no-backing-up rule. 74 * 75 * #### Custom queries 76 * 77 * Sometimes it's necessary to further inspect an HTML tag than 78 * the query syntax here permits. In these cases one may further 79 * inspect the search results using the read-only functions 80 * provided by the processor or external state or variables. 81 * 82 * Example: 83 * 84 * // Paint up to the first five DIV or SPAN tags marked with the "jazzy" style. 85 * $remaining_count = 5; 86 * while ( $remaining_count > 0 && $tags->next_tag() ) { 87 * if ( 88 * ( 'DIV' === $tags->get_tag() || 'SPAN' === $tags->get_tag() ) && 89 * 'jazzy' === $tags->get_attribute( 'data-style' ) 90 * ) { 91 * $tags->add_class( 'theme-style-everest-jazz' ); 92 * $remaining_count--; 93 * } 94 * } 95 * 96 * `get_attribute()` will return `null` if the attribute wasn't present 97 * on the tag when it was called. It may return `""` (the empty string) 98 * in cases where the attribute was present but its value was empty. 99 * For boolean attributes, those whose name is present but no value is 100 * given, it will return `true` (the only way to set `false` for an 101 * attribute is to remove it). 102 * 103 * #### When matching fails 104 * 105 * When `next_tag()` returns `false` it could mean different things: 106 * 107 * - The requested tag wasn't found in the input document. 108 * - The input document ended in the middle of an HTML syntax element. 109 * 110 * When a document ends in the middle of a syntax element it will pause 111 * the processor. This is to make it possible in the future to extend the 112 * input document and proceed - an important requirement for chunked 113 * streaming parsing of a document. 114 * 115 * Example: 116 * 117 * $processor = new WP_HTML_Tag_Processor( 'This <div is="a" partial="token' ); 118 * false === $processor->next_tag(); 119 * 120 * If a special element (see next section) is encountered but no closing tag 121 * is found it will count as an incomplete tag. The parser will pause as if 122 * the opening tag were incomplete. 123 * 124 * Example: 125 * 126 * $processor = new WP_HTML_Tag_Processor( '<style>// there could be more styling to come' ); 127 * false === $processor->next_tag(); 128 * 129 * $processor = new WP_HTML_Tag_Processor( '<style>// this is everything</style><div>' ); 130 * true === $processor->next_tag( 'DIV' ); 131 * 132 * #### Special self-contained elements 133 * 134 * Some HTML elements are handled in a special way; their start and end tags 135 * act like a void tag. These are special because their contents can't contain 136 * HTML markup. Everything inside these elements is handled in a special way 137 * and content that _appears_ like HTML tags inside of them isn't. There can 138 * be no nesting in these elements. 139 * 140 * In the following list, "raw text" means that all of the content in the HTML 141 * until the matching closing tag is treated verbatim without any replacements 142 * and without any parsing. 143 * 144 * - IFRAME allows no content but requires a closing tag. 145 * - NOEMBED (deprecated) content is raw text. 146 * - NOFRAMES (deprecated) content is raw text. 147 * - SCRIPT content is plaintext apart from legacy rules allowing `</script>` inside an HTML comment. 148 * - STYLE content is raw text. 149 * - TITLE content is plain text but character references are decoded. 150 * - TEXTAREA content is plain text but character references are decoded. 151 * - XMP (deprecated) content is raw text. 152 * 153 * ### Modifying HTML attributes for a found tag 154 * 155 * Once you've found the start of an opening tag you can modify 156 * any number of the attributes on that tag. You can set a new 157 * value for an attribute, remove the entire attribute, or do 158 * nothing and move on to the next opening tag. 159 * 160 * Example: 161 * 162 * if ( $tags->next_tag( array( 'class_name' => 'wp-group-block' ) ) ) { 163 * $tags->set_attribute( 'title', 'This groups the contained content.' ); 164 * $tags->remove_attribute( 'data-test-id' ); 165 * } 166 * 167 * If `set_attribute()` is called for an existing attribute it will 168 * overwrite the existing value. Similarly, calling `remove_attribute()` 169 * for a non-existing attribute has no effect on the document. Both 170 * of these methods are safe to call without knowing if a given attribute 171 * exists beforehand. 172 * 173 * ### Modifying CSS classes for a found tag 174 * 175 * The tag processor treats the `class` attribute as a special case. 176 * Because it's a common operation to add or remove CSS classes, this 177 * interface adds helper methods to make that easier. 178 * 179 * As with attribute values, adding or removing CSS classes is a safe 180 * operation that doesn't require checking if the attribute or class 181 * exists before making changes. If removing the only class then the 182 * entire `class` attribute will be removed. 183 * 184 * Example: 185 * 186 * // from `<span>Yippee!</span>` 187 * // to `<span class="is-active">Yippee!</span>` 188 * $tags->add_class( 'is-active' ); 189 * 190 * // from `<span class="excited">Yippee!</span>` 191 * // to `<span class="excited is-active">Yippee!</span>` 192 * $tags->add_class( 'is-active' ); 193 * 194 * // from `<span class="is-active heavy-accent">Yippee!</span>` 195 * // to `<span class="is-active heavy-accent">Yippee!</span>` 196 * $tags->add_class( 'is-active' ); 197 * 198 * // from `<input type="text" class="is-active rugby not-disabled" length="24">` 199 * // to `<input type="text" class="is-active not-disabled" length="24"> 200 * $tags->remove_class( 'rugby' ); 201 * 202 * // from `<input type="text" class="rugby" length="24">` 203 * // to `<input type="text" length="24"> 204 * $tags->remove_class( 'rugby' ); 205 * 206 * // from `<input type="text" length="24">` 207 * // to `<input type="text" length="24"> 208 * $tags->remove_class( 'rugby' ); 209 * 210 * When class changes are enqueued but a direct change to `class` is made via 211 * `set_attribute` then the changes to `set_attribute` (or `remove_attribute`) 212 * will take precedence over those made through `add_class` and `remove_class`. 213 * 214 * ### Bookmarks 215 * 216 * While scanning through the input HTML document it's possible to set 217 * a named bookmark when a particular tag is found. Later on, after 218 * continuing to scan other tags, it's possible to `seek` to one of 219 * the set bookmarks and then proceed again from that point forward. 220 * 221 * Because bookmarks create processing overhead one should avoid 222 * creating too many of them. As a rule, create only bookmarks 223 * of known string literal names; avoid creating "mark_{$index}" 224 * and so on. It's fine from a performance standpoint to create a 225 * bookmark and update it frequently, such as within a loop. 226 * 227 * $total_todos = 0; 228 * while ( $p->next_tag( array( 'tag_name' => 'UL', 'class_name' => 'todo' ) ) ) { 229 * $p->set_bookmark( 'list-start' ); 230 * while ( $p->next_tag( array( 'tag_closers' => 'visit' ) ) ) { 231 * if ( 'UL' === $p->get_tag() && $p->is_tag_closer() ) { 232 * $p->set_bookmark( 'list-end' ); 233 * $p->seek( 'list-start' ); 234 * $p->set_attribute( 'data-contained-todos', (string) $total_todos ); 235 * $total_todos = 0; 236 * $p->seek( 'list-end' ); 237 * break; 238 * } 239 * 240 * if ( 'LI' === $p->get_tag() && ! $p->is_tag_closer() ) { 241 * $total_todos++; 242 * } 243 * } 244 * } 245 * 246 * ## Tokens and finer-grained processing. 247 * 248 * It's possible to scan through every lexical token in the 249 * HTML document using the `next_token()` function. This 250 * alternative form takes no argument and provides no built-in 251 * query syntax. 252 * 253 * Example: 254 * 255 * $title = '(untitled)'; 256 * $text = ''; 257 * while ( $processor->next_token() ) { 258 * switch ( $processor->get_token_name() ) { 259 * case '#text': 260 * $text .= $processor->get_modifiable_text(); 261 * break; 262 * 263 * case 'BR': 264 * $text .= "\n"; 265 * break; 266 * 267 * case 'TITLE': 268 * $title = $processor->get_modifiable_text(); 269 * break; 270 * } 271 * } 272 * return trim( "# {$title}\n\n{$text}" ); 273 * 274 * ### Tokens and _modifiable text_. 275 * 276 * #### Special "atomic" HTML elements. 277 * 278 * Not all HTML elements are able to contain other elements inside of them. 279 * For instance, the contents inside a TITLE element are plaintext (except 280 * that character references like & will be decoded). This means that 281 * if the string `<img>` appears inside a TITLE element, then it's not an 282 * image tag, but rather it's text describing an image tag. Likewise, the 283 * contents of a SCRIPT or STYLE element are handled entirely separately in 284 * a browser than the contents of other elements because they represent a 285 * different language than HTML. 286 * 287 * For these elements the Tag Processor treats the entire sequence as one, 288 * from the opening tag, including its contents, through its closing tag. 289 * This means that it's not possible to match the closing tag for a 290 * SCRIPT element unless it's unexpected; the Tag Processor already matched 291 * it when it found the opening tag. 292 * 293 * The inner contents of these elements are that element's _modifiable text_. 294 * 295 * The special elements are: 296 * - `SCRIPT` whose contents are treated as raw plaintext but supports a legacy 297 * style of including JavaScript inside of HTML comments to avoid accidentally 298 * closing the SCRIPT from inside a JavaScript string. E.g. `console.log( '</script>' )`. 299 * - `TITLE` and `TEXTAREA` whose contents are treated as plaintext and then any 300 * character references are decoded. E.g. `1 < 2 < 3` becomes `1 < 2 < 3`. 301 * - `IFRAME`, `NOEMBED`, `NOFRAMES`, `STYLE`, `XMP` whose contents are treated as 302 * raw plaintext and left as-is. E.g. `1 < 2 < 3` remains `1 < 2 < 3`. 303 * 304 * #### Other tokens with modifiable text. 305 * 306 * There are also non-elements which are void/self-closing in nature and contain 307 * modifiable text that is part of that individual syntax token itself. 308 * 309 * - `#text` nodes, whose entire token _is_ the modifiable text. 310 * - HTML comments and tokens that become comments due to some syntax error. The 311 * text for these tokens is the portion of the comment inside of the syntax. 312 * E.g. for `<!-- comment -->` the text is `" comment "` (note the spaces are included). 313 * - `CDATA` sections, whose text is the content inside of the section itself. E.g. for 314 * `<![CDATA[some content]]>` the text is `"some content"` (with restrictions [1]). 315 * - "Funky comments," which are a special case of invalid closing tags whose name is 316 * invalid. The text for these nodes is the text that a browser would transform into 317 * an HTML comment when parsing. E.g. for `</%post_author>` the text is `%post_author`. 318 * - `DOCTYPE` declarations like `<DOCTYPE html>` which have no closing tag. 319 * - Processing instruction nodes like `<?wp __( "Like" ); ?>` (with restrictions [2]). 320 * - The empty end tag `</>` which is ignored in the browser and DOM. 321 * 322 * [1]: There are no CDATA sections in HTML. When encountering `<![CDATA[`, everything 323 * until the next `>` becomes a bogus HTML comment, meaning there can be no CDATA 324 * section in an HTML document containing `>`. The Tag Processor will first find 325 * all valid and bogus HTML comments, and then if the comment _would_ have been a 326 * CDATA section _were they to exist_, it will indicate this as the type of comment. 327 * 328 * [2]: HTML recognizes processing instructions whose target starts with an ASCII letter 329 * or `_` and continues with ASCII alphanumerics, `-`, or `_`. The reserved `xml` 330 * and `xml-stylesheet` targets, as well as XML-valid targets with characters 331 * outside this set, transform into bogus comments in the DOM instead. Processing 332 * instructions exhibit the same constraint as CDATA sections, in that `>` cannot 333 * exist within the token since the processing instruction ends at the first `>`. 334 * 335 * ## Design and limitations 336 * 337 * The Tag Processor is designed to linearly scan HTML documents and tokenize 338 * HTML tags and their attributes. It's designed to do this as efficiently as 339 * possible without compromising parsing integrity. Therefore it will be 340 * slower than some methods of modifying HTML, such as those incorporating 341 * over-simplified PCRE patterns, but will not introduce the defects and 342 * failures that those methods bring in, which lead to broken page renders 343 * and often to security vulnerabilities. On the other hand, it will be faster 344 * than full-blown HTML parsers such as DOMDocument and use considerably 345 * less memory. It requires a negligible memory overhead, enough to consider 346 * it a zero-overhead system. 347 * 348 * The performance characteristics are maintained by avoiding tree construction 349 * and semantic cleanups which are specified in HTML5. Because of this, for 350 * example, it's not possible for the Tag Processor to associate any given 351 * opening tag with its corresponding closing tag, or to return the inner markup 352 * inside an element. Systems may be built on top of the Tag Processor to do 353 * this, but the Tag Processor is and should be constrained so it can remain an 354 * efficient, low-level, and reliable HTML scanner. 355 * 356 * The Tag Processor's design incorporates a "garbage-in-garbage-out" philosophy. 357 * HTML5 specifies that certain invalid content be transformed into different forms 358 * for display, such as removing null bytes from an input document and replacing 359 * invalid characters with the Unicode replacement character `U+FFFD` (visually "�"). 360 * Where errors or transformations exist within the HTML5 specification, the Tag Processor 361 * leaves those invalid inputs untouched, passing them through to the final browser 362 * to handle. While this implies that certain operations will be non-spec-compliant, 363 * such as reading the value of an attribute with invalid content, it also preserves a 364 * simplicity and efficiency for handling those error cases. 365 * 366 * Most operations within the Tag Processor are designed to minimize the difference 367 * between an input and output document for any given change. For example, the 368 * `add_class` and `remove_class` methods preserve whitespace and the class ordering 369 * within the `class` attribute; and when encountering tags with duplicated attributes, 370 * the Tag Processor will leave those invalid duplicate attributes where they are but 371 * update the proper attribute which the browser will read for parsing its value. An 372 * exception to this rule is that all attribute updates store their values as 373 * double-quoted strings, meaning that attributes on input with single-quoted or 374 * unquoted values will appear in the output with double-quotes. 375 * 376 * ### Scripting Flag 377 * 378 * The Tag Processor parses HTML with the "scripting flag" disabled. This means 379 * that it doesn't run any scripts while parsing the page. In a browser with 380 * JavaScript enabled, for example, the script can change the parse of the 381 * document as it loads. On the server, however, evaluating JavaScript is not 382 * only impractical, but also unwanted. 383 * 384 * Practically this means that the Tag Processor will descend into NOSCRIPT 385 * elements and process its child tags. Were the scripting flag enabled, such 386 * as in a typical browser, the contents of NOSCRIPT are skipped entirely. 387 * 388 * This allows the HTML API to process the content that will be presented in 389 * a browser when scripting is disabled, but it offers a different view of a 390 * page than most browser sessions will experience. E.g. the tags inside the 391 * NOSCRIPT disappear. 392 * 393 * ### Text Encoding 394 * 395 * The Tag Processor assumes that the input HTML document is encoded with a 396 * text encoding compatible with 7-bit ASCII's '<', '>', '&', ';', '/', '=', 397 * "'", '"', 'a' - 'z', 'A' - 'Z', and the whitespace characters ' ', tab, 398 * carriage-return, newline, and form-feed. 399 * 400 * In practice, this includes almost every single-byte encoding as well as 401 * UTF-8. Notably, however, it does not include UTF-16. If providing input 402 * that's incompatible, then convert the encoding beforehand. 403 * 404 * @since 6.2.0 405 * @since 6.2.1 Fix: Support for various invalid comments; attribute updates are case-insensitive. 406 * @since 6.3.2 Fix: Skip HTML-like content inside rawtext elements such as STYLE. 407 * @since 6.5.0 Pauses processor when input ends in an incomplete syntax token. 408 * Introduces "special" elements which act like void elements, e.g. TITLE, STYLE. 409 * Allows scanning through all tokens and processing modifiable text, where applicable. 410 */ 411 class WP_HTML_Tag_Processor { 412 /** 413 * The maximum number of bookmarks allowed to exist at 414 * any given time. 415 * 416 * @since 6.2.0 417 * @var int 418 * 419 * @see WP_HTML_Tag_Processor::set_bookmark() 420 */ 421 const MAX_BOOKMARKS = 10; 422 423 /** 424 * Maximum number of times seek() can be called. 425 * Prevents accidental infinite loops. 426 * 427 * @since 6.2.0 428 * @var int 429 * 430 * @see WP_HTML_Tag_Processor::seek() 431 */ 432 const MAX_SEEK_OPS = 1000; 433 434 /** 435 * The HTML document to parse. 436 * 437 * @since 6.2.0 438 * @var string 439 */ 440 protected $html; 441 442 /** 443 * The last query passed to next_tag(). 444 * 445 * @since 6.2.0 446 * @var array|null 447 */ 448 private $last_query; 449 450 /** 451 * The tag name this processor currently scans for. 452 * 453 * @since 6.2.0 454 * @var string|null 455 */ 456 private $sought_tag_name; 457 458 /** 459 * The CSS class name this processor currently scans for. 460 * 461 * @since 6.2.0 462 * @var string|null 463 */ 464 private $sought_class_name; 465 466 /** 467 * The match offset this processor currently scans for. 468 * 469 * @since 6.2.0 470 * @var int|null 471 */ 472 private $sought_match_offset; 473 474 /** 475 * Whether to visit tag closers, e.g. </div>, when walking an input document. 476 * 477 * @since 6.2.0 478 * @var bool 479 */ 480 private $stop_on_tag_closers; 481 482 /** 483 * Specifies mode of operation of the parser at any given time. 484 * 485 * | State | Meaning | 486 * |--------------------------|----------------------------------------------------------------------| 487 * | *Ready* | The parser is ready to run. | 488 * | *Complete* | There is nothing left to parse. | 489 * | *Incomplete* | The HTML ended in the middle of a token; nothing more can be parsed. | 490 * | *Matched tag* | Found an HTML tag; it's possible to modify its attributes. | 491 * | *Text node* | Found a #text node; this is plaintext and modifiable. | 492 * | *CDATA node* | Found a CDATA section; this is modifiable. | 493 * | *Comment* | Found a comment or bogus comment; this is modifiable. | 494 * | *Presumptuous* | Found an empty tag closer: `</>`. | 495 * | *Funky comment* | Found a tag closer with an invalid tag name; this is modifiable. | 496 * | *Processing instruction* | Found a processing instruction, e.g. `<?pi-target data>`. | 497 * 498 * @since 6.5.0 499 * 500 * @see WP_HTML_Tag_Processor::STATE_READY 501 * @see WP_HTML_Tag_Processor::STATE_COMPLETE 502 * @see WP_HTML_Tag_Processor::STATE_INCOMPLETE_INPUT 503 * @see WP_HTML_Tag_Processor::STATE_MATCHED_TAG 504 * @see WP_HTML_Tag_Processor::STATE_TEXT_NODE 505 * @see WP_HTML_Tag_Processor::STATE_CDATA_NODE 506 * @see WP_HTML_Tag_Processor::STATE_COMMENT 507 * @see WP_HTML_Tag_Processor::STATE_DOCTYPE 508 * @see WP_HTML_Tag_Processor::STATE_PRESUMPTUOUS_TAG 509 * @see WP_HTML_Tag_Processor::STATE_FUNKY_COMMENT 510 * @see WP_HTML_Tag_Processor::STATE_PROCESSING_INSTRUCTION 511 * 512 * @var string 513 */ 514 protected $parser_state = self::STATE_READY; 515 516 /** 517 * Indicates if the document is in quirks mode or no-quirks mode. 518 * 519 * Impact on HTML parsing: 520 * 521 * - In `NO_QUIRKS_MODE` (also known as "standard mode"): 522 * - CSS class and ID selectors match byte-for-byte (case-sensitively). 523 * - A TABLE start tag `<table>` implicitly closes any open `P` element. 524 * 525 * - In `QUIRKS_MODE`: 526 * - CSS class and ID selectors match in an ASCII case-insensitive manner. 527 * - A TABLE start tag `<table>` opens a `TABLE` element as a child of a `P` 528 * element if one is open. 529 * 530 * Quirks and no-quirks mode are thus mostly about styling, but have an impact when 531 * tables are found inside paragraph elements. 532 * 533 * @see self::QUIRKS_MODE 534 * @see self::NO_QUIRKS_MODE 535 * 536 * @since 6.7.0 537 * 538 * @var string 539 */ 540 protected $compat_mode = self::NO_QUIRKS_MODE; 541 542 /** 543 * Indicates whether the parser is inside foreign content, 544 * e.g. inside an SVG or MathML element. 545 * 546 * One of 'html', 'svg', or 'math'. 547 * 548 * Several parsing rules change based on whether the parser 549 * is inside foreign content, including whether CDATA sections 550 * are allowed and whether a self-closing flag indicates that 551 * an element has no content. 552 * 553 * @since 6.7.0 554 * 555 * @var string 556 */ 557 private $parsing_namespace = 'html'; 558 559 /** 560 * What kind of syntax token became an HTML comment. 561 * 562 * Since there are many ways in which HTML syntax can create an HTML comment, 563 * this indicates which of those caused it. This allows the Tag Processor to 564 * represent more from the original input document than would appear in the DOM. 565 * 566 * @since 6.5.0 567 * 568 * @var string|null 569 */ 570 protected $comment_type = null; 571 572 /** 573 * What kind of text the matched text node represents, if it was subdivided. 574 * 575 * @see self::TEXT_IS_NULL_SEQUENCE 576 * @see self::TEXT_IS_WHITESPACE 577 * @see self::TEXT_IS_GENERIC 578 * @see self::subdivide_text_appropriately 579 * 580 * @since 6.7.0 581 * 582 * @var string 583 */ 584 protected $text_node_classification = self::TEXT_IS_GENERIC; 585 586 /** 587 * How many bytes from the original HTML document have been read and parsed. 588 * 589 * This value points to the latest byte offset in the input document which 590 * has been already parsed. It is the internal cursor for the Tag Processor 591 * and updates while scanning through the HTML tokens. 592 * 593 * @since 6.2.0 594 * @var int 595 */ 596 private $bytes_already_parsed = 0; 597 598 /** 599 * Byte offset in input document where current token starts. 600 * 601 * Example: 602 * 603 * <div id="test">... 604 * 01234 605 * - token starts at 0 606 * 607 * @since 6.5.0 608 * 609 * @var int|null 610 */ 611 private $token_starts_at; 612 613 /** 614 * Byte length of current token. 615 * 616 * Example: 617 * 618 * <div id="test">... 619 * 0123456789012345 620 * - token length is 15 - 0 = 15 621 * 622 * a <!-- comment --> is a token. 623 * 0123456789 123456789 123456789 624 * - token length is 18 - 2 = 16 625 * 626 * @since 6.5.0 627 * 628 * @var int|null 629 */ 630 private $token_length; 631 632 /** 633 * Whether the current tag token has the self-closing flag. 634 * 635 * @since 7.1.0 636 * 637 * @var bool 638 */ 639 private $has_self_closing_flag = false; 640 641 /** 642 * Byte offset in input document where current tag name starts. 643 * 644 * Example: 645 * 646 * <div id="test">... 647 * 01234 648 * - tag name starts at 1 649 * 650 * @since 6.2.0 651 * 652 * @var int|null 653 */ 654 private $tag_name_starts_at; 655 656 /** 657 * Byte length of current tag name. 658 * 659 * Example: 660 * 661 * <div id="test">... 662 * 01234 663 * --- tag name length is 3 664 * 665 * @since 6.2.0 666 * 667 * @var int|null 668 */ 669 private $tag_name_length; 670 671 /** 672 * Byte offset into input document where current modifiable text starts. 673 * 674 * @since 6.5.0 675 * 676 * @var int 677 */ 678 private $text_starts_at; 679 680 /** 681 * Byte length of modifiable text. 682 * 683 * @since 6.5.0 684 * 685 * @var int 686 */ 687 private $text_length; 688 689 /** 690 * Whether the current tag is an opening tag, e.g. <div>, or a closing tag, e.g. </div>. 691 * 692 * @var bool 693 */ 694 private $is_closing_tag; 695 696 /** 697 * Lazily-built index of attributes found within an HTML tag, keyed by the attribute name. 698 * 699 * Example: 700 * 701 * // Supposing the parser is working through this content 702 * // and stops after recognizing the `id` attribute. 703 * // <div id="test-4" class=outline title="data:text/plain;base64=asdk3nk1j3fo8"> 704 * // ^ parsing will continue from this point. 705 * $this->attributes = array( 706 * 'id' => new WP_HTML_Attribute_Token( 'id', 9, 6, 5, 11, false ) 707 * ); 708 * 709 * // When picking up parsing again, or when asking to find the 710 * // `class` attribute we will continue and add to this array. 711 * $this->attributes = array( 712 * 'id' => new WP_HTML_Attribute_Token( 'id', 9, 6, 5, 11, false ), 713 * 'class' => new WP_HTML_Attribute_Token( 'class', 23, 7, 17, 13, false ) 714 * ); 715 * 716 * // Note that only the `class` attribute value is stored in the index. 717 * // That's because it is the only value used by this class at the moment. 718 * 719 * @since 6.2.0 720 * @var WP_HTML_Attribute_Token[] 721 * @phpstan-var array<non-empty-string, WP_HTML_Attribute_Token> 722 */ 723 private $attributes = array(); 724 725 /** 726 * Tracks spans of duplicate attributes on a given tag, used for removing 727 * all copies of an attribute when calling `remove_attribute()`. 728 * 729 * @since 6.3.2 730 * 731 * @var (WP_HTML_Span[])[]|null 732 */ 733 private $duplicate_attributes = null; 734 735 /** 736 * Which class names to add or remove from a tag. 737 * 738 * These are tracked separately from attribute updates because they are 739 * semantically distinct, whereas this interface exists for the common 740 * case of adding and removing class names while other attributes are 741 * generally modified as with DOM `setAttribute` calls. 742 * 743 * When modifying an HTML document these will eventually be collapsed 744 * into a single `set_attribute( 'class', $changes )` call. 745 * 746 * Example: 747 * 748 * // Add the `wp-block-group` class, remove the `wp-group` class. 749 * $classname_updates = array( 750 * // Indexed by a comparable class name. 751 * 'wp-block-group' => WP_HTML_Tag_Processor::ADD_CLASS, 752 * 'wp-group' => WP_HTML_Tag_Processor::REMOVE_CLASS 753 * ); 754 * 755 * @since 6.2.0 756 * @var array<non-empty-string, self::ADD_CLASS|self::REMOVE_CLASS> 757 */ 758 private $classname_updates = array(); 759 760 /** 761 * Tracks a semantic location in the original HTML which 762 * shifts with updates as they are applied to the document. 763 * 764 * @since 6.2.0 765 * @var WP_HTML_Span[] 766 */ 767 protected $bookmarks = array(); 768 769 const ADD_CLASS = true; 770 const REMOVE_CLASS = false; 771 const SKIP_CLASS = null; 772 773 /** 774 * Lexical replacements to apply to input HTML document. 775 * 776 * "Lexical" in this class refers to the part of this class which 777 * operates on pure text _as text_ and not as HTML. There's a line 778 * between the public interface, with HTML-semantic methods like 779 * `set_attribute` and `add_class`, and an internal state that tracks 780 * text offsets in the input document. 781 * 782 * When higher-level HTML methods are called, those have to transform their 783 * operations (such as setting an attribute's value) into text diffing 784 * operations (such as replacing the sub-string from indices A to B with 785 * some given new string). These text-diffing operations are the lexical 786 * updates. 787 * 788 * As new higher-level methods are added they need to collapse their 789 * operations into these lower-level lexical updates since that's the 790 * Tag Processor's internal language of change. Any code which creates 791 * these lexical updates must ensure that they do not cross HTML syntax 792 * boundaries, however, so these should never be exposed outside of this 793 * class or any classes which intentionally expand its functionality. 794 * 795 * These are enqueued while editing the document instead of being immediately 796 * applied to avoid processing overhead, string allocations, and string 797 * copies when applying many updates to a single document. 798 * 799 * Example: 800 * 801 * // Replace an attribute stored with a new value, indices 802 * // sourced from the lazily-parsed HTML recognizer. 803 * $start = $attributes['src']->start; 804 * $length = $attributes['src']->length; 805 * $modifications[] = new WP_HTML_Text_Replacement( $start, $length, $new_value ); 806 * 807 * // Correspondingly, something like this will appear in this array. 808 * $lexical_updates = array( 809 * WP_HTML_Text_Replacement( 14, 28, 'https://my-site.my-domain/wp-content/uploads/2014/08/kittens.jpg' ) 810 * ); 811 * 812 * @since 6.2.0 813 * @var array<int|string, WP_HTML_Text_Replacement> 814 */ 815 protected $lexical_updates = array(); 816 817 /** 818 * Tracks and limits `seek()` calls to prevent accidental infinite loops. 819 * 820 * @since 6.2.0 821 * @var int 822 * 823 * @see WP_HTML_Tag_Processor::seek() 824 */ 825 protected $seek_count = 0; 826 827 /** 828 * Whether the parser should skip over an immediately-following linefeed 829 * character, as is the case with LISTING, PRE, and TEXTAREA. 830 * 831 * > If the next token is a U+000A LINE FEED (LF) character token, then 832 * > ignore that token and move on to the next one. (Newlines at the start 833 * > of [these] elements are ignored as an authoring convenience.) 834 * 835 * @since 6.7.0 836 * 837 * @var int|null 838 */ 839 private $skip_newline_at = null; 840 841 /** 842 * Constructor. 843 * 844 * @since 6.2.0 845 * 846 * @param string $html HTML to process. 847 */ 848 public function __construct( $html ) { 849 if ( ! is_string( $html ) ) { 850 _doing_it_wrong( 851 __METHOD__, 852 __( 'The HTML parameter must be a string.' ), 853 '6.9.0' 854 ); 855 $html = ''; 856 } 857 $this->html = $html; 858 } 859 860 /** 861 * Switches parsing mode into a new namespace, such as when 862 * encountering an SVG tag and entering foreign content. 863 * 864 * @since 6.7.0 865 * 866 * @param string $new_namespace One of 'html', 'svg', or 'math' indicating into what 867 * namespace the next tokens will be processed. 868 * @return bool Whether the namespace was valid and changed. 869 */ 870 public function change_parsing_namespace( string $new_namespace ): bool { 871 if ( ! in_array( $new_namespace, array( 'html', 'math', 'svg' ), true ) ) { 872 return false; 873 } 874 875 $this->parsing_namespace = $new_namespace; 876 return true; 877 } 878 879 /** 880 * Finds the next tag matching the $query. 881 * 882 * @since 6.2.0 883 * @since 6.5.0 No longer processes incomplete tokens at end of document; pauses the processor at start of token. 884 * 885 * @param array|string|null $query { 886 * Optional. Which tag name to find, having which class, etc. Default is to find any tag. 887 * 888 * @type string|null $tag_name Which tag to find, or `null` for "any tag." 889 * @type int|null $match_offset Find the Nth tag matching all search criteria. 890 * 1 for "first" tag, 3 for "third," etc. 891 * Defaults to first tag. 892 * @type string|null $class_name Tag must contain this whole class name to match. 893 * @type string|null $tag_closers "visit" or "skip": whether to stop on tag closers, e.g. </div>. 894 * } 895 * @return bool Whether a tag was matched. 896 * 897 * @phpstan-impure 898 */ 899 public function next_tag( $query = null ): bool { 900 $this->parse_query( $query ); 901 $already_found = 0; 902 903 do { 904 if ( false === $this->next_token() ) { 905 return false; 906 } 907 908 if ( self::STATE_MATCHED_TAG !== $this->parser_state ) { 909 continue; 910 } 911 912 if ( $this->matches() ) { 913 ++$already_found; 914 } 915 } while ( $already_found < $this->sought_match_offset ); 916 917 return true; 918 } 919 920 /** 921 * Finds the next token in the HTML document. 922 * 923 * An HTML document can be viewed as a stream of tokens, 924 * where tokens are things like HTML tags, HTML comments, 925 * text nodes, etc. This method finds the next token in 926 * the HTML document and returns whether it found one. 927 * 928 * If it starts parsing a token and reaches the end of the 929 * document then it will seek to the start of the last 930 * token and pause, returning `false` to indicate that it 931 * failed to find a complete token. 932 * 933 * Possible token types, based on the HTML specification: 934 * 935 * - an HTML tag, whether opening, closing, or void. 936 * - a text node - the plaintext inside tags. 937 * - an HTML comment. 938 * - a DOCTYPE declaration. 939 * - an HTML processing instruction, e.g. `<?pi …data?>`. 940 * 941 * @since 6.5.0 942 * @since 6.7.0 Recognizes CDATA sections within foreign content. 943 * @since 7.1.0 Recognizes processing instructions. 944 * 945 * @return bool Whether a token was parsed. 946 */ 947 public function next_token(): bool { 948 return $this->base_class_next_token(); 949 } 950 951 /** 952 * Internal method which finds the next token in the HTML document. 953 * 954 * This method is a protected internal function which implements the logic for 955 * finding the next token in a document. It exists so that the parser can update 956 * its state without affecting the location of the cursor in the document and 957 * without triggering subclass methods for things like `next_token()`, e.g. when 958 * applying patches before searching for the next token. 959 * 960 * @since 6.5.0 961 * @ignore 962 * 963 * @return bool Whether a token was parsed. 964 */ 965 private function base_class_next_token(): bool { 966 $was_at = $this->bytes_already_parsed; 967 $this->after_tag(); 968 969 // Don't proceed if there's nothing more to scan. 970 if ( 971 self::STATE_COMPLETE === $this->parser_state || 972 self::STATE_INCOMPLETE_INPUT === $this->parser_state 973 ) { 974 return false; 975 } 976 977 /* 978 * The next step in the parsing loop determines the parsing state; 979 * clear it so that state doesn't linger from the previous step. 980 */ 981 $this->parser_state = self::STATE_READY; 982 983 if ( $this->bytes_already_parsed >= strlen( $this->html ) ) { 984 $this->parser_state = self::STATE_COMPLETE; 985 return false; 986 } 987 988 // Find the next tag if it exists. 989 if ( false === $this->parse_next_tag() ) { 990 if ( self::STATE_INCOMPLETE_INPUT === $this->parser_state ) { 991 $this->bytes_already_parsed = $was_at; 992 } 993 994 return false; 995 } 996 997 /* 998 * For legacy reasons the rest of this function handles tags and their 999 * attributes. If the processor has reached the end of the document 1000 * or if it matched any other token then it should return here to avoid 1001 * attempting to process tag-specific syntax. 1002 */ 1003 if ( 1004 self::STATE_INCOMPLETE_INPUT !== $this->parser_state && 1005 self::STATE_COMPLETE !== $this->parser_state && 1006 self::STATE_MATCHED_TAG !== $this->parser_state 1007 ) { 1008 return true; 1009 } 1010 1011 // Parse all of its attributes. 1012 while ( $this->parse_next_attribute() ) { 1013 continue; 1014 } 1015 1016 // Ensure that the tag closes before the end of the document. 1017 if ( 1018 self::STATE_INCOMPLETE_INPUT === $this->parser_state || 1019 $this->bytes_already_parsed >= strlen( $this->html ) 1020 ) { 1021 // Does this appropriately clear state (parsed attributes)? 1022 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 1023 $this->bytes_already_parsed = $was_at; 1024 1025 return false; 1026 } 1027 1028 $tag_ends_at = strpos( $this->html, '>', $this->bytes_already_parsed ); 1029 if ( false === $tag_ends_at ) { 1030 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 1031 $this->bytes_already_parsed = $was_at; 1032 1033 return false; 1034 } 1035 $this->parser_state = self::STATE_MATCHED_TAG; 1036 $this->bytes_already_parsed = $tag_ends_at + 1; 1037 $this->token_length = $this->bytes_already_parsed - $this->token_starts_at; 1038 1039 /* 1040 * Certain tags require additional processing. The first-letter pre-check 1041 * avoids unnecessary string allocation when comparing the tag names. 1042 * 1043 * - IFRAME 1044 * - LISTING (deprecated) 1045 * - NOEMBED (deprecated) 1046 * - NOFRAMES (deprecated) 1047 * - PRE 1048 * - SCRIPT 1049 * - STYLE 1050 * - TEXTAREA 1051 * - TITLE 1052 * - XMP (deprecated) 1053 */ 1054 if ( 1055 $this->is_closing_tag || 1056 'html' !== $this->parsing_namespace || 1057 1 !== strspn( $this->html, 'iIlLnNpPsStTxX', $this->tag_name_starts_at, 1 ) 1058 ) { 1059 return true; 1060 } 1061 1062 $tag_name = $this->get_tag(); 1063 1064 /* 1065 * For LISTING, PRE, and TEXTAREA, the first linefeed of an immediately-following 1066 * text node is ignored as an authoring convenience. 1067 * 1068 * @see static::skip_newline_at 1069 */ 1070 if ( 'LISTING' === $tag_name || 'PRE' === $tag_name ) { 1071 $this->skip_newline_at = $this->bytes_already_parsed; 1072 return true; 1073 } 1074 1075 /* 1076 * There are certain elements whose children are not DATA but are instead 1077 * RCDATA or RAWTEXT. These cannot contain other elements, and the contents 1078 * are parsed as plaintext, with character references decoded in RCDATA but 1079 * not in RAWTEXT. 1080 * 1081 * These elements are described here as "self-contained" or special atomic 1082 * elements whose end tag is consumed with the opening tag, and they will 1083 * contain modifiable text inside of them. 1084 * 1085 * Preserve the opening tag pointers, as these will be overwritten 1086 * when finding the closing tag. They will be reset after finding 1087 * the closing tag to point to the opening of the special atomic 1088 * tag sequence. 1089 */ 1090 $tag_name_starts_at = $this->tag_name_starts_at; 1091 $tag_name_length = $this->tag_name_length; 1092 $tag_ends_at = $this->token_starts_at + $this->token_length; 1093 $has_self_closing_flag = $this->has_self_closing_flag; 1094 $attributes = $this->attributes; 1095 $duplicate_attributes = $this->duplicate_attributes; 1096 1097 // Find the closing tag if necessary. 1098 switch ( $tag_name ) { 1099 case 'SCRIPT': 1100 $found_closer = $this->skip_script_data(); 1101 break; 1102 1103 case 'TEXTAREA': 1104 case 'TITLE': 1105 $found_closer = $this->skip_rcdata( $tag_name ); 1106 break; 1107 1108 /* 1109 * In the browser this list would include the NOSCRIPT element, 1110 * but the Tag Processor is an environment with the scripting 1111 * flag disabled, meaning that it needs to descend into the 1112 * NOSCRIPT element to be able to properly process what will be 1113 * sent to a browser. 1114 * 1115 * Note that this rule makes HTML5 syntax incompatible with XML, 1116 * because the parsing of this token depends on client application. 1117 * The NOSCRIPT element cannot be represented in the XHTML syntax. 1118 */ 1119 case 'IFRAME': 1120 case 'NOEMBED': 1121 case 'NOFRAMES': 1122 case 'STYLE': 1123 case 'XMP': 1124 $found_closer = $this->skip_rawtext( $tag_name ); 1125 break; 1126 1127 // No other tags should be treated in their entirety here. 1128 default: 1129 return true; 1130 } 1131 1132 if ( ! $found_closer ) { 1133 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 1134 $this->bytes_already_parsed = $was_at; 1135 return false; 1136 } 1137 1138 /* 1139 * The values here look like they reference the opening tag but they reference 1140 * the closing tag instead. This is why the opening tag values were stored 1141 * above in a variable. It reads confusingly here, but that's because the 1142 * functions that skip the contents have moved all the internal cursors past 1143 * the inner content of the tag. 1144 */ 1145 $this->token_starts_at = $was_at; 1146 $this->token_length = $this->bytes_already_parsed - $this->token_starts_at; 1147 $this->text_starts_at = $tag_ends_at; 1148 $this->text_length = $this->tag_name_starts_at - $this->text_starts_at; 1149 $this->tag_name_starts_at = $tag_name_starts_at; 1150 $this->tag_name_length = $tag_name_length; 1151 $this->has_self_closing_flag = $has_self_closing_flag; 1152 $this->attributes = $attributes; 1153 $this->duplicate_attributes = $duplicate_attributes; 1154 1155 return true; 1156 } 1157 1158 /** 1159 * Whether the processor paused because the input HTML document ended 1160 * in the middle of a syntax element, such as in the middle of a tag. 1161 * 1162 * Example: 1163 * 1164 * $processor = new WP_HTML_Tag_Processor( '<input type="text" value="Th' ); 1165 * false === $processor->next_tag(); 1166 * true === $processor->paused_at_incomplete_token(); 1167 * 1168 * @since 6.5.0 1169 * 1170 * @return bool Whether the parse paused at the start of an incomplete token. 1171 */ 1172 public function paused_at_incomplete_token(): bool { 1173 return self::STATE_INCOMPLETE_INPUT === $this->parser_state; 1174 } 1175 1176 /** 1177 * Generator for a foreach loop to step through each class name for the matched tag. 1178 * 1179 * This generator function is designed to be used inside a "foreach" loop. 1180 * 1181 * Example: 1182 * 1183 * $p = new WP_HTML_Tag_Processor( "<div class='free <egg<\tlang-en'>" ); 1184 * $p->next_tag(); 1185 * foreach ( $p->class_list() as $class_name ) { 1186 * echo "{$class_name} "; 1187 * } 1188 * // Outputs: "free <egg> lang-en " 1189 * 1190 * @since 6.4.0 1191 * 1192 * @return Generator<int, non-empty-string> 1193 */ 1194 public function class_list() { 1195 if ( self::STATE_MATCHED_TAG !== $this->parser_state ) { 1196 return; 1197 } 1198 1199 /** @var string $class contains the string value of the class attribute, with character references decoded. */ 1200 $class = $this->get_attribute( 'class' ); 1201 1202 if ( ! is_string( $class ) ) { 1203 return; 1204 } 1205 1206 $seen = array(); 1207 1208 $is_quirks = self::QUIRKS_MODE === $this->compat_mode; 1209 1210 $at = 0; 1211 while ( $at < strlen( $class ) ) { 1212 // Skip past any initial boundary characters. 1213 $at += strspn( $class, " \t\f\r\n", $at ); 1214 if ( $at >= strlen( $class ) ) { 1215 return; 1216 } 1217 1218 // Find the byte length until the next boundary. 1219 $length = strcspn( $class, " \t\f\r\n", $at ); 1220 if ( 0 === $length ) { 1221 return; 1222 } 1223 1224 $name = substr( $class, $at, $length ); 1225 if ( $is_quirks ) { 1226 $name = strtolower( $name ); 1227 } 1228 $at += $length; 1229 1230 /* 1231 * It's expected that the number of class names for a given tag is relatively small. 1232 * Given this, it is probably faster overall to scan an array for a value rather 1233 * than to use the class name as a key and check if it's a key of $seen. 1234 */ 1235 if ( in_array( $name, $seen, true ) ) { 1236 continue; 1237 } 1238 1239 $seen[] = $name; 1240 yield $name; 1241 } 1242 } 1243 1244 1245 /** 1246 * Returns if a matched tag contains the given ASCII case-insensitive class name. 1247 * 1248 * @since 6.4.0 1249 * 1250 * @param string $wanted_class Look for this CSS class name, ASCII case-insensitive. 1251 * @return bool|null Whether the matched tag contains the given class name, or null if not matched. 1252 */ 1253 public function has_class( $wanted_class ): ?bool { 1254 if ( self::STATE_MATCHED_TAG !== $this->parser_state ) { 1255 return null; 1256 } 1257 1258 $case_insensitive = self::QUIRKS_MODE === $this->compat_mode; 1259 1260 $wanted_length = strlen( $wanted_class ); 1261 foreach ( $this->class_list() as $class_name ) { 1262 if ( 1263 strlen( $class_name ) === $wanted_length && 1264 0 === substr_compare( $class_name, $wanted_class, 0, strlen( $wanted_class ), $case_insensitive ) 1265 ) { 1266 return true; 1267 } 1268 } 1269 1270 return false; 1271 } 1272 1273 1274 /** 1275 * Sets a bookmark in the HTML document. 1276 * 1277 * Bookmarks represent specific places or tokens in the HTML 1278 * document, such as a tag opener or closer. When applying 1279 * edits to a document, such as setting an attribute, the 1280 * text offsets of that token may shift; the bookmark is 1281 * kept updated with those shifts and remains stable unless 1282 * the entire span of text in which the token sits is removed. 1283 * 1284 * Release bookmarks when they are no longer needed. 1285 * 1286 * Example: 1287 * 1288 * <main><h2>Surprising fact you may not know!</h2></main> 1289 * ^ ^ 1290 * \-|-- this `H2` opener bookmark tracks the token 1291 * 1292 * <main class="clickbait"><h2>Surprising fact you may no… 1293 * ^ ^ 1294 * \-|-- it shifts with edits 1295 * 1296 * Bookmarks provide the ability to seek to a previously-scanned 1297 * place in the HTML document. This avoids the need to re-scan 1298 * the entire document. 1299 * 1300 * Example: 1301 * 1302 * <ul><li>One</li><li>Two</li><li>Three</li></ul> 1303 * ^^^^ 1304 * want to note this last item 1305 * 1306 * $p = new WP_HTML_Tag_Processor( $html ); 1307 * $in_list = false; 1308 * while ( $p->next_tag( array( 'tag_closers' => $in_list ? 'visit' : 'skip' ) ) ) { 1309 * if ( 'UL' === $p->get_tag() ) { 1310 * if ( $p->is_tag_closer() ) { 1311 * $in_list = false; 1312 * $p->set_bookmark( 'resume' ); 1313 * if ( $p->seek( 'last-li' ) ) { 1314 * $p->add_class( 'last-li' ); 1315 * } 1316 * $p->seek( 'resume' ); 1317 * $p->release_bookmark( 'last-li' ); 1318 * $p->release_bookmark( 'resume' ); 1319 * } else { 1320 * $in_list = true; 1321 * } 1322 * } 1323 * 1324 * if ( 'LI' === $p->get_tag() ) { 1325 * $p->set_bookmark( 'last-li' ); 1326 * } 1327 * } 1328 * 1329 * Bookmarks intentionally hide the internal string offsets 1330 * to which they refer. They are maintained internally as 1331 * updates are applied to the HTML document and therefore 1332 * retain their "position" - the location to which they 1333 * originally pointed. The inability to use bookmarks with 1334 * functions like `substr` is therefore intentional to guard 1335 * against accidentally breaking the HTML. 1336 * 1337 * Because bookmarks allocate memory and require processing 1338 * for every applied update, they are limited and require 1339 * a name. They should not be created with programmatically-made 1340 * names, such as "li_{$index}" with some loop. As a general 1341 * rule they should only be created with string-literal names 1342 * like "start-of-section" or "last-paragraph". 1343 * 1344 * Bookmarks are a powerful tool to enable complicated behavior. 1345 * Consider double-checking that you need this tool if you are 1346 * reaching for it, as inappropriate use could lead to broken 1347 * HTML structure or unwanted processing overhead. 1348 * 1349 * @since 6.2.0 1350 * 1351 * @param string $name Identifies this particular bookmark. 1352 * @return bool Whether the bookmark was successfully created. 1353 */ 1354 public function set_bookmark( $name ): bool { 1355 // It only makes sense to set a bookmark if the parser has paused on a concrete token. 1356 if ( 1357 self::STATE_COMPLETE === $this->parser_state || 1358 self::STATE_INCOMPLETE_INPUT === $this->parser_state 1359 ) { 1360 return false; 1361 } 1362 1363 if ( ! array_key_exists( $name, $this->bookmarks ) && count( $this->bookmarks ) >= static::MAX_BOOKMARKS ) { 1364 _doing_it_wrong( 1365 __METHOD__, 1366 __( 'Too many bookmarks: cannot create any more.' ), 1367 '6.2.0' 1368 ); 1369 return false; 1370 } 1371 1372 $this->bookmarks[ $name ] = new WP_HTML_Span( $this->token_starts_at, $this->token_length ); 1373 1374 return true; 1375 } 1376 1377 1378 /** 1379 * Removes a bookmark that is no longer needed. 1380 * 1381 * Releasing a bookmark frees up the small 1382 * performance overhead it requires. 1383 * 1384 * @param string $name Name of the bookmark to remove. 1385 * @return bool Whether the bookmark already existed before removal. 1386 */ 1387 public function release_bookmark( $name ): bool { 1388 if ( ! array_key_exists( $name, $this->bookmarks ) ) { 1389 return false; 1390 } 1391 1392 unset( $this->bookmarks[ $name ] ); 1393 1394 return true; 1395 } 1396 1397 /** 1398 * Skips contents of generic rawtext elements. 1399 * 1400 * @since 6.3.2 1401 * @ignore 1402 * 1403 * @see https://html.spec.whatwg.org/#generic-raw-text-element-parsing-algorithm 1404 * 1405 * @param string $tag_name The uppercase tag name which will close the RAWTEXT region. 1406 * @return bool Whether an end to the RAWTEXT region was found before the end of the document. 1407 */ 1408 private function skip_rawtext( string $tag_name ): bool { 1409 /* 1410 * These two functions distinguish themselves on whether character references are 1411 * decoded, and since functionality to read the inner markup isn't supported, it's 1412 * not necessary to implement these two functions separately. 1413 */ 1414 return $this->skip_rcdata( $tag_name ); 1415 } 1416 1417 /** 1418 * Skips contents of RCDATA elements, namely title and textarea tags. 1419 * 1420 * @since 6.2.0 1421 * @ignore 1422 * 1423 * @see https://html.spec.whatwg.org/multipage/parsing.html#rcdata-state 1424 * 1425 * @param string $tag_name The uppercase tag name which will close the RCDATA region. 1426 * @return bool Whether an end to the RCDATA region was found before the end of the document. 1427 */ 1428 private function skip_rcdata( string $tag_name ): bool { 1429 $html = $this->html; 1430 $doc_length = strlen( $html ); 1431 $tag_length = strlen( $tag_name ); 1432 1433 $at = $this->bytes_already_parsed; 1434 1435 while ( false !== $at && $at < $doc_length ) { 1436 $at = strpos( $this->html, '</', $at ); 1437 $this->tag_name_starts_at = $at; 1438 1439 // Fail if there is no possible tag closer. 1440 if ( false === $at || ( $at + 2 + $tag_length ) >= $doc_length ) { 1441 return false; 1442 } 1443 1444 $at += 2; 1445 1446 /* 1447 * Find a case-insensitive match to the tag name. 1448 * 1449 * Because tag names are limited to US-ASCII there is no 1450 * need to perform any kind of Unicode normalization when 1451 * comparing; any character which could be impacted by such 1452 * normalization could not be part of a tag name. 1453 */ 1454 for ( $i = 0; $i < $tag_length; $i++ ) { 1455 $tag_char = $tag_name[ $i ]; 1456 $html_char = $html[ $at + $i ]; 1457 1458 if ( $html_char !== $tag_char && strtoupper( $html_char ) !== $tag_char ) { 1459 $at += $i; 1460 continue 2; 1461 } 1462 } 1463 1464 $at += $tag_length; 1465 $this->bytes_already_parsed = $at; 1466 1467 if ( $at >= strlen( $html ) ) { 1468 return false; 1469 } 1470 1471 /* 1472 * Ensure that the tag name terminates to avoid matching on 1473 * substrings of a longer tag name. For example, the sequence 1474 * "</textarearug" should not match for "</textarea" even 1475 * though "textarea" is found within the text. 1476 */ 1477 $c = $html[ $at ]; 1478 if ( ' ' !== $c && "\t" !== $c && "\r" !== $c && "\n" !== $c && '/' !== $c && '>' !== $c ) { 1479 continue; 1480 } 1481 1482 while ( $this->parse_next_attribute() ) { 1483 continue; 1484 } 1485 1486 $at = $this->bytes_already_parsed; 1487 if ( $at >= strlen( $this->html ) ) { 1488 return false; 1489 } 1490 1491 if ( '>' === $html[ $at ] ) { 1492 $this->bytes_already_parsed = $at + 1; 1493 return true; 1494 } 1495 1496 if ( $at + 1 >= strlen( $this->html ) ) { 1497 return false; 1498 } 1499 1500 if ( '/' === $html[ $at ] && '>' === $html[ $at + 1 ] ) { 1501 $this->bytes_already_parsed = $at + 2; 1502 return true; 1503 } 1504 } 1505 1506 return false; 1507 } 1508 1509 /** 1510 * Skips contents of script tags. 1511 * 1512 * @since 6.2.0 1513 * @ignore 1514 * 1515 * @return bool Whether the script tag was closed before the end of the document. 1516 */ 1517 private function skip_script_data(): bool { 1518 $state = 'unescaped'; 1519 $html = $this->html; 1520 $doc_length = strlen( $html ); 1521 $at = $this->bytes_already_parsed; 1522 1523 while ( false !== $at && $at < $doc_length ) { 1524 $at += strcspn( $html, '-<', $at ); 1525 1526 /* 1527 * Optimization: Terminating a complete script element requires at least eight 1528 * additional bytes in the document. Some checks below may cause local escaped 1529 * state transitions when processing shorter strings, but those transitions are 1530 * irrelevant if the script tag is incomplete and the function must return false. 1531 * 1532 * This may need updating if those transitions become significant or exported from 1533 * this function in some way, such as when building safe methods to embed JavaScript 1534 * or data inside a SCRIPT element. 1535 * 1536 * $at may be here. 1537 * ↓ 1538 * ...</script> 1539 * ╰──┬───╯ 1540 * $at + 8 additional bytes are required for a non-false return value. 1541 * 1542 * This single check eliminates the need to check lengths for the shorter spans: 1543 * 1544 * $at may be here. 1545 * ↓ 1546 * <script><!-- --></script> 1547 * ├╯ 1548 * $at + 2 additional characters does not require a length check. 1549 * 1550 * The transition from "escaped" to "unescaped" is not relevant if the document ends: 1551 * 1552 * $at may be here. 1553 * ↓ 1554 * <script><!-- -->[[END-OF-DOCUMENT]] 1555 * ╰──┬───╯ 1556 * $at + 8 additional bytes is not satisfied, return false. 1557 */ 1558 if ( $at + 8 >= $doc_length ) { 1559 return false; 1560 } 1561 1562 /* 1563 * For all script states a "-->" transitions 1564 * back into the normal unescaped script mode, 1565 * even if that's the current state. 1566 */ 1567 if ( 1568 '-' === $html[ $at ] && 1569 '-' === $html[ $at + 1 ] && 1570 '>' === $html[ $at + 2 ] 1571 ) { 1572 $at += 3; 1573 $state = 'unescaped'; 1574 continue; 1575 } 1576 1577 /* 1578 * Everything of interest past here starts with "<". 1579 * Check this character and advance position regardless. 1580 */ 1581 if ( '<' !== $html[ $at++ ] ) { 1582 continue; 1583 } 1584 1585 /* 1586 * "<!--" only transitions from _unescaped_ to _escaped_. This byte sequence is only 1587 * significant in the _unescaped_ state and is ignored in any other state. 1588 */ 1589 if ( 1590 'unescaped' === $state && 1591 '!' === $html[ $at ] && 1592 '-' === $html[ $at + 1 ] && 1593 '-' === $html[ $at + 2 ] 1594 ) { 1595 $at += 3; 1596 1597 /* 1598 * The parser is ready to enter the _escaped_ state, but may remain in the 1599 * _unescaped_ state. This occurs when "<!--" is immediately followed by a 1600 * sequence of 0 or more "-" followed by ">". This is similar to abruptly closed 1601 * HTML comments like "<!-->" or "<!--->". 1602 * 1603 * Note that this check may advance the position significantly and requires a 1604 * length check to prevent bad offsets on inputs like `<script><!---------`. 1605 */ 1606 $at += strspn( $html, '-', $at ); 1607 if ( $at < $doc_length && '>' === $html[ $at ] ) { 1608 ++$at; 1609 continue; 1610 } 1611 1612 $state = 'escaped'; 1613 continue; 1614 } 1615 1616 if ( '/' === $html[ $at ] ) { 1617 $closer_potentially_starts_at = $at - 1; 1618 $is_closing = true; 1619 ++$at; 1620 } else { 1621 $is_closing = false; 1622 } 1623 1624 /* 1625 * At this point the only remaining state-changes occur with the 1626 * <script> and </script> tags; unless one of these appears next, 1627 * proceed scanning to the next potential token in the text. 1628 */ 1629 if ( ! ( 1630 ( 's' === $html[ $at ] || 'S' === $html[ $at ] ) && 1631 ( 'c' === $html[ $at + 1 ] || 'C' === $html[ $at + 1 ] ) && 1632 ( 'r' === $html[ $at + 2 ] || 'R' === $html[ $at + 2 ] ) && 1633 ( 'i' === $html[ $at + 3 ] || 'I' === $html[ $at + 3 ] ) && 1634 ( 'p' === $html[ $at + 4 ] || 'P' === $html[ $at + 4 ] ) && 1635 ( 't' === $html[ $at + 5 ] || 'T' === $html[ $at + 5 ] ) 1636 ) ) { 1637 continue; 1638 } 1639 1640 /* 1641 * Ensure that the script tag terminates to avoid matching on 1642 * substrings of a non-match. For example, the sequence 1643 * "<script123" should not end a script region even though 1644 * "<script" is found within the text. 1645 */ 1646 $at += 6; 1647 $c = $html[ $at ]; 1648 if ( 1649 /** 1650 * These characters trigger state transitions of interest: 1651 * 1652 * - @see {https://html.spec.whatwg.org/multipage/parsing.html#script-data-end-tag-name-state} 1653 * - @see {https://html.spec.whatwg.org/multipage/parsing.html#script-data-escaped-end-tag-name-state} 1654 * - @see {https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escape-start-state} 1655 * - @see {https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escape-end-state} 1656 * 1657 * The "\r" character is not present in the above references. However, "\r" must be 1658 * treated the same as "\n". This is because the HTML Standard requires newline 1659 * normalization during preprocessing which applies this replacement. 1660 * 1661 * - @see https://html.spec.whatwg.org/multipage/parsing.html#preprocessing-the-input-stream 1662 * - @see https://infra.spec.whatwg.org/#normalize-newlines 1663 */ 1664 '>' !== $c && 1665 ' ' !== $c && 1666 "\n" !== $c && 1667 '/' !== $c && 1668 "\t" !== $c && 1669 "\f" !== $c && 1670 "\r" !== $c 1671 ) { 1672 continue; 1673 } 1674 1675 if ( 'escaped' === $state && ! $is_closing ) { 1676 $state = 'double-escaped'; 1677 continue; 1678 } 1679 1680 if ( 'double-escaped' === $state && $is_closing ) { 1681 $state = 'escaped'; 1682 continue; 1683 } 1684 1685 if ( $is_closing ) { 1686 $this->bytes_already_parsed = $closer_potentially_starts_at; 1687 $this->tag_name_starts_at = $closer_potentially_starts_at; 1688 if ( $this->bytes_already_parsed >= $doc_length ) { 1689 return false; 1690 } 1691 1692 while ( $this->parse_next_attribute() ) { 1693 continue; 1694 } 1695 1696 if ( $this->bytes_already_parsed >= $doc_length ) { 1697 return false; 1698 } 1699 1700 if ( '>' === $html[ $this->bytes_already_parsed ] ) { 1701 ++$this->bytes_already_parsed; 1702 return true; 1703 } 1704 } 1705 1706 ++$at; 1707 } 1708 1709 return false; 1710 } 1711 1712 /** 1713 * Parses the next tag. 1714 * 1715 * This will find and start parsing the next tag, including 1716 * the opening `<`, the potential closer `/`, and the tag 1717 * name. It does not parse the attributes or scan to the 1718 * closing `>`; these are left for other methods. 1719 * 1720 * @since 6.2.0 1721 * @since 6.2.1 Support abruptly-closed comments, invalid-tag-closer-comments, and empty elements. 1722 * @ignore 1723 * 1724 * @return bool Whether a tag was found before the end of the document. 1725 */ 1726 private function parse_next_tag(): bool { 1727 $this->after_tag(); 1728 1729 $html = $this->html; 1730 $doc_length = strlen( $html ); 1731 $was_at = $this->bytes_already_parsed; 1732 $at = $was_at; 1733 1734 while ( $at < $doc_length ) { 1735 $at = strpos( $html, '<', $at ); 1736 if ( false === $at ) { 1737 break; 1738 } 1739 1740 if ( $at > $was_at ) { 1741 /* 1742 * A "<" normally starts a new HTML tag or syntax token, but in cases where the 1743 * following character can't produce a valid token, the "<" is instead treated 1744 * as plaintext and the parser should skip over it. This avoids a problem when 1745 * following earlier practices of typing emoji with text, e.g. "<3". This 1746 * should be a heart, not a tag. It's supposed to be rendered, not hidden. 1747 * 1748 * At this point the parser checks if this is one of those cases and if it is 1749 * will continue searching for the next "<" in search of a token boundary. 1750 * 1751 * @see https://html.spec.whatwg.org/#tag-open-state 1752 */ 1753 if ( 1 !== strspn( $html, '!/?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', $at + 1, 1 ) ) { 1754 ++$at; 1755 continue; 1756 } 1757 1758 $this->parser_state = self::STATE_TEXT_NODE; 1759 $this->token_starts_at = $was_at; 1760 $this->token_length = $at - $was_at; 1761 $this->text_starts_at = $was_at; 1762 $this->text_length = $this->token_length; 1763 $this->bytes_already_parsed = $at; 1764 return true; 1765 } 1766 1767 $this->token_starts_at = $at; 1768 1769 if ( $at + 1 < $doc_length && '/' === $this->html[ $at + 1 ] ) { 1770 $this->is_closing_tag = true; 1771 ++$at; 1772 } else { 1773 $this->is_closing_tag = false; 1774 } 1775 1776 /* 1777 * HTML tag names must start with [a-zA-Z] otherwise they are not tags. 1778 * For example, "<3" is rendered as text, not a tag opener. If at least 1779 * one letter follows the "<" then _it is_ a tag, but if the following 1780 * character is anything else it _is not a tag_. 1781 * 1782 * It's not uncommon to find non-tags starting with `<` in an HTML 1783 * document, so it's good for performance to make this pre-check before 1784 * continuing to attempt to parse a tag name. 1785 * 1786 * Reference: 1787 * * https://html.spec.whatwg.org/multipage/parsing.html#data-state 1788 * * https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state 1789 */ 1790 $tag_name_prefix_length = strspn( $html, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', $at + 1 ); 1791 if ( $tag_name_prefix_length > 0 ) { 1792 ++$at; 1793 $this->parser_state = self::STATE_MATCHED_TAG; 1794 $this->tag_name_starts_at = $at; 1795 $this->tag_name_length = $tag_name_prefix_length + strcspn( $html, " \t\f\r\n/>", $at + $tag_name_prefix_length ); 1796 $this->bytes_already_parsed = $at + $this->tag_name_length; 1797 return true; 1798 } 1799 1800 /* 1801 * Abort if no tag is found before the end of 1802 * the document. There is nothing left to parse. 1803 */ 1804 if ( $at + 1 >= $doc_length ) { 1805 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 1806 1807 return false; 1808 } 1809 1810 /* 1811 * `<!` transitions to markup declaration open state 1812 * https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state 1813 */ 1814 if ( ! $this->is_closing_tag && '!' === $html[ $at + 1 ] ) { 1815 /* 1816 * `<!--` transitions to a comment state – apply further comment rules. 1817 * https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state 1818 */ 1819 if ( 0 === substr_compare( $html, '--', $at + 2, 2 ) ) { 1820 $closer_at = $at + 4; 1821 // If it's not possible to close the comment then there is nothing more to scan. 1822 if ( $doc_length <= $closer_at ) { 1823 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 1824 1825 return false; 1826 } 1827 1828 // Abruptly-closed empty comments are a sequence of dashes followed by `>`. 1829 $span_of_dashes = strspn( $html, '-', $closer_at ); 1830 if ( $doc_length <= $span_of_dashes + $closer_at ) { 1831 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 1832 1833 return false; 1834 } 1835 1836 if ( '>' === $html[ $closer_at + $span_of_dashes ] ) { 1837 /* 1838 * @todo When implementing `set_modifiable_text()` ensure that updates to this token 1839 * don't break the syntax for short comments, e.g. `<!--->`. Unlike other comment 1840 * and bogus comment syntax, these leave no clear insertion point for text and 1841 * they need to be modified specially in order to contain text. E.g. to store 1842 * `?` as the modifiable text, the `<!--->` needs to become `<!--?-->`, which 1843 * involves inserting an additional `-` into the token after the modifiable text. 1844 */ 1845 $this->parser_state = self::STATE_COMMENT; 1846 $this->comment_type = self::COMMENT_AS_ABRUPTLY_CLOSED_COMMENT; 1847 $this->token_length = $closer_at + $span_of_dashes + 1 - $this->token_starts_at; 1848 1849 // Only provide modifiable text if the token is long enough to contain it. 1850 if ( $span_of_dashes >= 2 ) { 1851 $this->comment_type = self::COMMENT_AS_HTML_COMMENT; 1852 $this->text_starts_at = $this->token_starts_at + 4; 1853 $this->text_length = $span_of_dashes - 2; 1854 } 1855 1856 $this->bytes_already_parsed = $closer_at + $span_of_dashes + 1; 1857 return true; 1858 } 1859 1860 /* 1861 * Comments may be closed by either a --> or an invalid --!>. 1862 * The first occurrence closes the comment. 1863 * 1864 * See https://html.spec.whatwg.org/#parse-error-incorrectly-closed-comment 1865 */ 1866 --$closer_at; // Pre-increment inside condition below reduces risk of accidental infinite looping. 1867 while ( ++$closer_at < $doc_length ) { 1868 $closer_at = strpos( $html, '--', $closer_at ); 1869 if ( false === $closer_at ) { 1870 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 1871 1872 return false; 1873 } 1874 1875 if ( $closer_at + 2 < $doc_length && '>' === $html[ $closer_at + 2 ] ) { 1876 $this->parser_state = self::STATE_COMMENT; 1877 $this->comment_type = self::COMMENT_AS_HTML_COMMENT; 1878 $this->token_length = $closer_at + 3 - $this->token_starts_at; 1879 $this->text_starts_at = $this->token_starts_at + 4; 1880 $this->text_length = $closer_at - $this->text_starts_at; 1881 $this->bytes_already_parsed = $closer_at + 3; 1882 return true; 1883 } 1884 1885 if ( 1886 $closer_at + 3 < $doc_length && 1887 '!' === $html[ $closer_at + 2 ] && 1888 '>' === $html[ $closer_at + 3 ] 1889 ) { 1890 $this->parser_state = self::STATE_COMMENT; 1891 $this->comment_type = self::COMMENT_AS_HTML_COMMENT; 1892 $this->token_length = $closer_at + 4 - $this->token_starts_at; 1893 $this->text_starts_at = $this->token_starts_at + 4; 1894 $this->text_length = $closer_at - $this->text_starts_at; 1895 $this->bytes_already_parsed = $closer_at + 4; 1896 return true; 1897 } 1898 } 1899 } 1900 1901 /* 1902 * `<!DOCTYPE` transitions to DOCTYPE state – skip to the nearest > 1903 * These are ASCII-case-insensitive. 1904 * https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state 1905 */ 1906 if ( 1907 $doc_length > $at + 8 && 1908 ( 'D' === $html[ $at + 2 ] || 'd' === $html[ $at + 2 ] ) && 1909 ( 'O' === $html[ $at + 3 ] || 'o' === $html[ $at + 3 ] ) && 1910 ( 'C' === $html[ $at + 4 ] || 'c' === $html[ $at + 4 ] ) && 1911 ( 'T' === $html[ $at + 5 ] || 't' === $html[ $at + 5 ] ) && 1912 ( 'Y' === $html[ $at + 6 ] || 'y' === $html[ $at + 6 ] ) && 1913 ( 'P' === $html[ $at + 7 ] || 'p' === $html[ $at + 7 ] ) && 1914 ( 'E' === $html[ $at + 8 ] || 'e' === $html[ $at + 8 ] ) 1915 ) { 1916 $closer_at = strpos( $html, '>', $at + 9 ); 1917 if ( false === $closer_at ) { 1918 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 1919 1920 return false; 1921 } 1922 1923 $this->parser_state = self::STATE_DOCTYPE; 1924 $this->token_length = $closer_at + 1 - $this->token_starts_at; 1925 $this->text_starts_at = $this->token_starts_at + 9; 1926 $this->text_length = $closer_at - $this->text_starts_at; 1927 $this->bytes_already_parsed = $closer_at + 1; 1928 return true; 1929 } 1930 1931 if ( 1932 'html' !== $this->parsing_namespace && 1933 strlen( $html ) > $at + 8 && 1934 '[' === $html[ $at + 2 ] && 1935 'C' === $html[ $at + 3 ] && 1936 'D' === $html[ $at + 4 ] && 1937 'A' === $html[ $at + 5 ] && 1938 'T' === $html[ $at + 6 ] && 1939 'A' === $html[ $at + 7 ] && 1940 '[' === $html[ $at + 8 ] 1941 ) { 1942 $closer_at = strpos( $html, ']]>', $at + 9 ); 1943 if ( false === $closer_at ) { 1944 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 1945 1946 return false; 1947 } 1948 1949 $this->parser_state = self::STATE_CDATA_NODE; 1950 $this->text_starts_at = $at + 9; 1951 $this->text_length = $closer_at - $this->text_starts_at; 1952 $this->token_length = $closer_at + 3 - $this->token_starts_at; 1953 $this->bytes_already_parsed = $closer_at + 3; 1954 return true; 1955 } 1956 1957 /* 1958 * Anything else here is an incorrectly-opened comment and transitions 1959 * to the bogus comment state - skip to the nearest >. If no closer is 1960 * found then the HTML was truncated inside the markup declaration. 1961 */ 1962 $closer_at = strpos( $html, '>', $at + 1 ); 1963 if ( false === $closer_at ) { 1964 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 1965 1966 return false; 1967 } 1968 1969 $this->parser_state = self::STATE_COMMENT; 1970 $this->comment_type = self::COMMENT_AS_INVALID_HTML; 1971 $this->token_length = $closer_at + 1 - $this->token_starts_at; 1972 $this->text_starts_at = $this->token_starts_at + 2; 1973 $this->text_length = $closer_at - $this->text_starts_at; 1974 $this->bytes_already_parsed = $closer_at + 1; 1975 1976 /* 1977 * Identify nodes that would be CDATA if HTML had CDATA sections. 1978 * 1979 * This section must occur after identifying the bogus comment end 1980 * because in an HTML parser it will span to the nearest `>`, even 1981 * if there's no `]]>` as would be required in an XML document. It 1982 * is therefore not possible to parse a CDATA section containing 1983 * a `>` in the HTML syntax. 1984 * 1985 * Inside foreign elements there is a discrepancy between browsers 1986 * and the specification on this. 1987 * 1988 * @todo Track whether the Tag Processor is inside a foreign element 1989 * and require the proper closing `]]>` in those cases. 1990 */ 1991 if ( 1992 $this->token_length >= 10 && 1993 '[' === $html[ $this->token_starts_at + 2 ] && 1994 'C' === $html[ $this->token_starts_at + 3 ] && 1995 'D' === $html[ $this->token_starts_at + 4 ] && 1996 'A' === $html[ $this->token_starts_at + 5 ] && 1997 'T' === $html[ $this->token_starts_at + 6 ] && 1998 'A' === $html[ $this->token_starts_at + 7 ] && 1999 '[' === $html[ $this->token_starts_at + 8 ] && 2000 ']' === $html[ $closer_at - 1 ] && 2001 ']' === $html[ $closer_at - 2 ] 2002 ) { 2003 $this->parser_state = self::STATE_COMMENT; 2004 $this->comment_type = self::COMMENT_AS_CDATA_LOOKALIKE; 2005 $this->text_starts_at += 7; 2006 $this->text_length -= 9; 2007 } 2008 2009 return true; 2010 } 2011 2012 /* 2013 * </> is a missing end tag name, which is ignored. 2014 * 2015 * This was also known as the "presumptuous empty tag" 2016 * in early discussions as it was proposed to close 2017 * the nearest previous opening tag. 2018 * 2019 * See https://html.spec.whatwg.org/#parse-error-missing-end-tag-name 2020 */ 2021 if ( '>' === $html[ $at + 1 ] ) { 2022 // `<>` is interpreted as plaintext. 2023 if ( ! $this->is_closing_tag ) { 2024 ++$at; 2025 continue; 2026 } 2027 2028 $this->parser_state = self::STATE_PRESUMPTUOUS_TAG; 2029 $this->token_length = $at + 2 - $this->token_starts_at; 2030 $this->bytes_already_parsed = $at + 2; 2031 return true; 2032 } 2033 2034 /** 2035 * `<?` transitions to the processing instruction open state. 2036 * 2037 * A processing instruction whose target starts with an ASCII letter or `_`, 2038 * continues with ASCII alphanumerics, `-`, or `_`, and is not an ASCII 2039 * case-insensitive match for `xml` or `xml-stylesheet` produces a processing 2040 * instruction node. Anything else transitions to the bogus comment state. 2041 * 2042 * Both forms end at the nearest `>`; a processing instruction cannot 2043 * contain one in the HTML syntax. 2044 * 2045 * @link https://html.spec.whatwg.org/multipage/parsing.html#processing-instruction-open-state 2046 */ 2047 if ( ! $this->is_closing_tag && '?' === $html[ $at + 1 ] ) { 2048 $closer_at = strpos( $html, '>', $at + 2 ); 2049 if ( false === $closer_at ) { 2050 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 2051 2052 return false; 2053 } 2054 2055 $target_at = $at + 2; 2056 $target_length = 0; 2057 $first_char = $html[ $target_at ]; 2058 if ( 2059 ( 'a' <= $first_char && 'z' >= $first_char ) || 2060 ( 'A' <= $first_char && 'Z' >= $first_char ) || 2061 '_' === $first_char 2062 ) { 2063 $target_length = 1 + strspn( $html, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-', $target_at + 1 ); 2064 } 2065 2066 /* 2067 * In the processing instruction target state, only whitespace, `?`, 2068 * or `>` may terminate the target; any other character converts the 2069 * token into a bogus comment. 2070 * 2071 * The `xml` and `xml-stylesheet` targets are reserved and disallowed; 2072 * they also convert the token into a bogus comment. 2073 */ 2074 $is_valid_pi = ( 2075 0 !== $target_length && 2076 str_contains( " \t\f\r\n?>", $html[ $target_at + $target_length ] ) && 2077 ! ( 3 === $target_length && 0 === substr_compare( $html, 'xml', $target_at, 3, true ) ) && 2078 ! ( 14 === $target_length && 0 === substr_compare( $html, 'xml-stylesheet', $target_at, 14, true ) ) 2079 ); 2080 2081 if ( $is_valid_pi ) { 2082 /* 2083 * The processing instruction data starts after any whitespace 2084 * following the target and ends at the `>`. When the token is 2085 * closed by `?>`, that final `?` is not part of the data. 2086 */ 2087 $data_at = $target_at + $target_length; 2088 $data_at += strspn( $html, " \t\f\r\n", $data_at ); 2089 2090 $data_length = $closer_at - $data_at; 2091 if ( $data_length > 0 && '?' === $html[ $closer_at - 1 ] ) { 2092 --$data_length; 2093 } 2094 2095 $this->parser_state = self::STATE_PROCESSING_INSTRUCTION; 2096 $this->tag_name_starts_at = $target_at; 2097 $this->tag_name_length = $target_length; 2098 $this->token_length = $closer_at + 1 - $this->token_starts_at; 2099 $this->text_starts_at = $data_at; 2100 $this->text_length = $data_length; 2101 $this->bytes_already_parsed = $closer_at + 1; 2102 return true; 2103 } 2104 2105 $this->parser_state = self::STATE_COMMENT; 2106 $this->comment_type = self::COMMENT_AS_INVALID_HTML; 2107 $this->token_length = $closer_at + 1 - $this->token_starts_at; 2108 $this->text_starts_at = $this->token_starts_at + 2; 2109 $this->text_length = $closer_at - $this->text_starts_at; 2110 $this->bytes_already_parsed = $closer_at + 1; 2111 2112 /* 2113 * Identify an XML-like Processing Instruction node. 2114 * 2115 * HTML and XML processing instructions have different parsing rules. 2116 * The HTML API recognizes XML-like processing instructions that are 2117 * _not_ HTML processing instructions. The HTML standard transforms 2118 * them to "bogus comments," represented by the HTML API as comments 2119 * with the `COMMENT_AS_PI_NODE_LOOKALIKE` type. This includes the 2120 * special targets `xml` and `xml-stylesheet` which are reserved 2121 * targets not allowed in HTML processing instructions. 2122 * 2123 * > NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | 2124 * [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | 2125 * [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | 2126 * [#x10000-#xEFFFF] 2127 * > NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] 2128 * 2129 * @see https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-PITarget 2130 */ 2131 if ( $this->token_length >= 5 && '?' === $html[ $closer_at - 1 ] ) { 2132 $comment_text = substr( $html, $this->token_starts_at + 2, $this->token_length - 4 ); 2133 $pi_target_length = strspn( $comment_text, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:_' ); 2134 2135 if ( 0 < $pi_target_length ) { 2136 $pi_target_length += strspn( $comment_text, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:_-.', $pi_target_length ); 2137 2138 $this->comment_type = self::COMMENT_AS_PI_NODE_LOOKALIKE; 2139 $this->tag_name_starts_at = $this->token_starts_at + 2; 2140 $this->tag_name_length = $pi_target_length; 2141 $this->text_starts_at += $pi_target_length; 2142 $this->text_length -= $pi_target_length + 1; 2143 } 2144 } 2145 2146 return true; 2147 } 2148 2149 /* 2150 * If a non-alpha starts the tag name in a tag closer it's a comment. 2151 * Find the first `>`, which closes the comment. 2152 * 2153 * This parser classifies these particular comments as special "funky comments" 2154 * which are made available for further processing. 2155 * 2156 * See https://html.spec.whatwg.org/#parse-error-invalid-first-character-of-tag-name 2157 */ 2158 if ( $this->is_closing_tag ) { 2159 // No chance of finding a closer. 2160 if ( $at + 3 > $doc_length ) { 2161 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 2162 2163 return false; 2164 } 2165 2166 $closer_at = strpos( $html, '>', $at + 2 ); 2167 if ( false === $closer_at ) { 2168 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 2169 2170 return false; 2171 } 2172 2173 $this->parser_state = self::STATE_FUNKY_COMMENT; 2174 $this->token_length = $closer_at + 1 - $this->token_starts_at; 2175 $this->text_starts_at = $this->token_starts_at + 2; 2176 $this->text_length = $closer_at - $this->text_starts_at; 2177 $this->bytes_already_parsed = $closer_at + 1; 2178 return true; 2179 } 2180 2181 ++$at; 2182 } 2183 2184 /* 2185 * This does not imply an incomplete parse; it indicates that there 2186 * can be nothing left in the document other than a #text node. 2187 */ 2188 $this->parser_state = self::STATE_TEXT_NODE; 2189 $this->token_starts_at = $was_at; 2190 $this->token_length = $doc_length - $was_at; 2191 $this->text_starts_at = $was_at; 2192 $this->text_length = $this->token_length; 2193 $this->bytes_already_parsed = $doc_length; 2194 return true; 2195 } 2196 2197 /** 2198 * Parses the next attribute. 2199 * 2200 * @since 6.2.0 2201 * @ignore 2202 * 2203 * @return bool Whether an attribute was found before the end of the document. 2204 */ 2205 private function parse_next_attribute(): bool { 2206 $doc_length = strlen( $this->html ); 2207 2208 // Skip whitespace and slashes. 2209 $skipped_length = strspn( $this->html, " \t\f\r\n/", $this->bytes_already_parsed ); 2210 $this->bytes_already_parsed += $skipped_length; 2211 if ( $this->bytes_already_parsed >= $doc_length ) { 2212 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 2213 2214 return false; 2215 } 2216 2217 /** 2218 * This block serves two purposes: 2219 * 2220 * - A fast path for common tag-ending `>`. 2221 * - A check for the self-closing flag which must appear as `/>`. 2222 * 2223 * In a tag like `<g attr=/>`, `/` is the attribute value, not a self-closing 2224 * flag. When it appears in this form, the parser has already consumed the 2225 * attribute value, `$skipped_length` is 0, and this checks below correctly 2226 * identify whether there is a self-closing flag. 2227 * 2228 * Note: Both start and end tags may have the self-closing flag. 2229 */ 2230 if ( '>' === $this->html[ $this->bytes_already_parsed ] ) { 2231 if ( $skipped_length > 0 && '/' === $this->html[ $this->bytes_already_parsed - 1 ] ) { 2232 $this->has_self_closing_flag = true; 2233 } 2234 return false; 2235 } 2236 2237 /* 2238 * Treat the equal sign as a part of the attribute 2239 * name if it is the first encountered byte. 2240 * 2241 * @see https://html.spec.whatwg.org/multipage/parsing.html#before-attribute-name-state 2242 */ 2243 $name_length = '=' === $this->html[ $this->bytes_already_parsed ] 2244 ? 1 + strcspn( $this->html, "=/> \t\f\r\n", $this->bytes_already_parsed + 1 ) 2245 : strcspn( $this->html, "=/> \t\f\r\n", $this->bytes_already_parsed ); 2246 2247 // No attribute, just tag closer. 2248 if ( 0 === $name_length || $this->bytes_already_parsed + $name_length >= $doc_length ) { 2249 return false; 2250 } 2251 2252 $attribute_start = $this->bytes_already_parsed; 2253 $attribute_name = substr( $this->html, $attribute_start, $name_length ); 2254 $this->bytes_already_parsed += $name_length; 2255 if ( $this->bytes_already_parsed >= $doc_length ) { 2256 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 2257 2258 return false; 2259 } 2260 2261 $this->skip_whitespace(); 2262 if ( $this->bytes_already_parsed >= $doc_length ) { 2263 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 2264 2265 return false; 2266 } 2267 2268 $has_value = '=' === $this->html[ $this->bytes_already_parsed ]; 2269 if ( $has_value ) { 2270 ++$this->bytes_already_parsed; 2271 $this->skip_whitespace(); 2272 if ( $this->bytes_already_parsed >= $doc_length ) { 2273 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 2274 2275 return false; 2276 } 2277 2278 switch ( $this->html[ $this->bytes_already_parsed ] ) { 2279 case "'": 2280 case '"': 2281 $quote = $this->html[ $this->bytes_already_parsed ]; 2282 $value_start = $this->bytes_already_parsed + 1; 2283 $end_quote_at = strpos( $this->html, $quote, $value_start ); 2284 $end_quote_at = false === $end_quote_at ? $doc_length : $end_quote_at; 2285 $value_length = $end_quote_at - $value_start; 2286 $attribute_end = $end_quote_at + 1; 2287 $this->bytes_already_parsed = $attribute_end; 2288 break; 2289 2290 default: 2291 $value_start = $this->bytes_already_parsed; 2292 $value_length = strcspn( $this->html, "> \t\f\r\n", $value_start ); 2293 $attribute_end = $value_start + $value_length; 2294 $this->bytes_already_parsed = $attribute_end; 2295 } 2296 } else { 2297 $value_start = $this->bytes_already_parsed; 2298 $value_length = 0; 2299 $attribute_end = $attribute_start + $name_length; 2300 } 2301 2302 if ( $attribute_end >= $doc_length ) { 2303 $this->parser_state = self::STATE_INCOMPLETE_INPUT; 2304 2305 return false; 2306 } 2307 2308 if ( $this->is_closing_tag ) { 2309 return true; 2310 } 2311 2312 /* 2313 * > There must never be two or more attributes on 2314 * > the same start tag whose names are an ASCII 2315 * > case-insensitive match for each other. 2316 * - HTML 5 spec 2317 * 2318 * @see https://html.spec.whatwg.org/multipage/syntax.html#attributes-2:ascii-case-insensitive 2319 * 2320 * The tokenizer replaces U+0000 NULL bytes in 2321 * attribute names with U+FFFD. 2322 * 2323 * @see https://html.spec.whatwg.org/#attribute-name-state 2324 */ 2325 $comparable_name = strtolower( str_replace( "\x00", "\u{FFFD}", $attribute_name ) ); 2326 2327 // If an attribute is listed many times, only use the first declaration and ignore the rest. 2328 if ( ! isset( $this->attributes[ $comparable_name ] ) ) { 2329 $this->attributes[ $comparable_name ] = new WP_HTML_Attribute_Token( 2330 $attribute_name, 2331 $value_start, 2332 $value_length, 2333 $attribute_start, 2334 $attribute_end - $attribute_start, 2335 ! $has_value 2336 ); 2337 2338 return true; 2339 } 2340 2341 /* 2342 * Track the duplicate attributes so if we remove it, all disappear together. 2343 * 2344 * While `$this->duplicated_attributes` could always be stored as an `array()`, 2345 * which would simplify the logic here, storing a `null` and only allocating 2346 * an array when encountering duplicates avoids needless allocations in the 2347 * normative case of parsing tags with no duplicate attributes. 2348 */ 2349 $duplicate_span = new WP_HTML_Span( $attribute_start, $attribute_end - $attribute_start ); 2350 if ( null === $this->duplicate_attributes ) { 2351 $this->duplicate_attributes = array( $comparable_name => array( $duplicate_span ) ); 2352 } elseif ( ! isset( $this->duplicate_attributes[ $comparable_name ] ) ) { 2353 $this->duplicate_attributes[ $comparable_name ] = array( $duplicate_span ); 2354 } else { 2355 $this->duplicate_attributes[ $comparable_name ][] = $duplicate_span; 2356 } 2357 2358 return true; 2359 } 2360 2361 /** 2362 * Move the internal cursor past any immediate successive whitespace. 2363 * 2364 * @since 6.2.0 2365 * @ignore 2366 */ 2367 private function skip_whitespace(): void { 2368 $this->bytes_already_parsed += strspn( $this->html, " \t\f\r\n", $this->bytes_already_parsed ); 2369 } 2370 2371 /** 2372 * Applies attribute updates and cleans up once a tag is fully parsed. 2373 * 2374 * @since 6.2.0 2375 * @ignore 2376 */ 2377 private function after_tag(): void { 2378 /* 2379 * There could be lexical updates enqueued for an attribute that 2380 * also exists on the next tag. In order to avoid conflating the 2381 * attributes across the two tags, lexical updates with names 2382 * need to be flushed to raw lexical updates. 2383 */ 2384 $this->class_name_updates_to_attributes_updates(); 2385 2386 /* 2387 * Purge updates if there are too many. The actual count isn't 2388 * scientific, but a few values from 100 to a few thousand were 2389 * tests to find a practically-useful limit. 2390 * 2391 * If the update queue grows too big, then the Tag Processor 2392 * will spend more time iterating through them and lose the 2393 * efficiency gains of deferring applying them. 2394 */ 2395 if ( 1000 < count( $this->lexical_updates ) ) { 2396 $this->get_updated_html(); 2397 } 2398 2399 foreach ( $this->lexical_updates as $name => $update ) { 2400 /* 2401 * Any updates appearing after the cursor should be applied 2402 * before proceeding, otherwise they may be overlooked. 2403 */ 2404 if ( $update->start >= $this->bytes_already_parsed ) { 2405 $this->get_updated_html(); 2406 break; 2407 } 2408 2409 if ( is_int( $name ) ) { 2410 continue; 2411 } 2412 2413 $this->lexical_updates[] = $update; 2414 unset( $this->lexical_updates[ $name ] ); 2415 } 2416 2417 $this->token_starts_at = null; 2418 $this->token_length = null; 2419 $this->has_self_closing_flag = false; 2420 $this->tag_name_starts_at = null; 2421 $this->tag_name_length = null; 2422 $this->text_starts_at = 0; 2423 $this->text_length = 0; 2424 $this->is_closing_tag = null; 2425 $this->attributes = array(); 2426 $this->comment_type = null; 2427 $this->text_node_classification = self::TEXT_IS_GENERIC; 2428 $this->duplicate_attributes = null; 2429 } 2430 2431 /** 2432 * Converts class name updates into tag attributes updates 2433 * (they are accumulated in different data formats for performance). 2434 * 2435 * @since 6.2.0 2436 * @ignore 2437 * 2438 * @see WP_HTML_Tag_Processor::$lexical_updates 2439 * @see WP_HTML_Tag_Processor::$classname_updates 2440 */ 2441 private function class_name_updates_to_attributes_updates(): void { 2442 if ( count( $this->classname_updates ) === 0 ) { 2443 return; 2444 } 2445 2446 $existing_class = $this->get_enqueued_attribute_value( 'class' ); 2447 if ( null === $existing_class || true === $existing_class ) { 2448 $existing_class = ''; 2449 } 2450 2451 if ( false === $existing_class && isset( $this->attributes['class'] ) ) { 2452 $existing_class = $this->get_decoded_attribute_value( $this->attributes['class'] ); 2453 } 2454 2455 if ( false === $existing_class ) { 2456 $existing_class = ''; 2457 } 2458 2459 /** 2460 * Updated "class" attribute value. 2461 * 2462 * This is incrementally built while scanning through the existing class 2463 * attribute, skipping removed classes on the way, and then appending 2464 * added classes at the end. Only when finished processing will the 2465 * value contain the final new value. 2466 2467 * @var string $class 2468 */ 2469 $class = ''; 2470 2471 /** 2472 * Tracks the cursor position in the existing 2473 * class attribute value while parsing. 2474 * 2475 * @var int $at 2476 */ 2477 $at = 0; 2478 2479 /** 2480 * Indicates if there's any need to modify the existing class attribute. 2481 * 2482 * If a call to `add_class()` and `remove_class()` wouldn't impact 2483 * the `class` attribute value then there's no need to rebuild it. 2484 * For example, when adding a class that's already present or 2485 * removing one that isn't. 2486 * 2487 * This flag enables a performance optimization when none of the enqueued 2488 * class updates would impact the `class` attribute; namely, that the 2489 * processor can continue without modifying the input document, as if 2490 * none of the `add_class()` or `remove_class()` calls had been made. 2491 * 2492 * This flag is set upon the first change that requires a string update. 2493 * 2494 * @var bool $modified 2495 */ 2496 $modified = false; 2497 2498 $seen = array(); 2499 $to_remove = array(); 2500 $is_quirks = self::QUIRKS_MODE === $this->compat_mode; 2501 if ( $is_quirks ) { 2502 foreach ( $this->classname_updates as $updated_name => $action ) { 2503 if ( self::REMOVE_CLASS === $action ) { 2504 $to_remove[] = strtolower( $updated_name ); 2505 } 2506 } 2507 } else { 2508 foreach ( $this->classname_updates as $updated_name => $action ) { 2509 if ( self::REMOVE_CLASS === $action ) { 2510 $to_remove[] = $updated_name; 2511 } 2512 } 2513 } 2514 2515 // Remove unwanted classes by only copying the new ones. 2516 $existing_class_length = strlen( $existing_class ); 2517 while ( $at < $existing_class_length ) { 2518 // Skip to the first non-whitespace character. 2519 $ws_at = $at; 2520 $ws_length = strspn( $existing_class, " \t\f\r\n", $ws_at ); 2521 $at += $ws_length; 2522 2523 // Capture the class name – it's everything until the next whitespace. 2524 $name_length = strcspn( $existing_class, " \t\f\r\n", $at ); 2525 if ( 0 === $name_length ) { 2526 // If no more class names are found then that's the end. 2527 break; 2528 } 2529 2530 $name = substr( $existing_class, $at, $name_length ); 2531 $comparable_class_name = $is_quirks ? strtolower( $name ) : $name; 2532 $at += $name_length; 2533 2534 // If this class is marked for removal, remove it and move on to the next one. 2535 if ( in_array( $comparable_class_name, $to_remove, true ) ) { 2536 $modified = true; 2537 continue; 2538 } 2539 2540 // If a class has already been seen then skip it; it should not be added twice. 2541 if ( in_array( $comparable_class_name, $seen, true ) ) { 2542 continue; 2543 } 2544 2545 $seen[] = $comparable_class_name; 2546 2547 /* 2548 * Otherwise, append it to the new "class" attribute value. 2549 * 2550 * There are options for handling whitespace between tags. 2551 * Preserving the existing whitespace produces fewer changes 2552 * to the HTML content and should clarify the before/after 2553 * content when debugging the modified output. 2554 * 2555 * This approach contrasts normalizing the inter-class 2556 * whitespace to a single space, which might appear cleaner 2557 * in the output HTML but produce a noisier change. 2558 */ 2559 if ( '' !== $class ) { 2560 $class .= substr( $existing_class, $ws_at, $ws_length ); 2561 } 2562 $class .= $name; 2563 } 2564 2565 // Add new classes by appending those which haven't already been seen. 2566 foreach ( $this->classname_updates as $name => $operation ) { 2567 $comparable_name = $is_quirks ? strtolower( $name ) : $name; 2568 if ( self::ADD_CLASS === $operation && ! in_array( $comparable_name, $seen, true ) ) { 2569 $modified = true; 2570 2571 $class .= strlen( $class ) > 0 ? ' ' : ''; 2572 $class .= $name; 2573 } 2574 } 2575 2576 $this->classname_updates = array(); 2577 if ( ! $modified ) { 2578 return; 2579 } 2580 2581 if ( strlen( $class ) > 0 ) { 2582 $this->set_attribute( 'class', $class ); 2583 } else { 2584 $this->remove_attribute( 'class' ); 2585 } 2586 } 2587 2588 /** 2589 * Applies attribute updates to HTML document. 2590 * 2591 * @since 6.2.0 2592 * @since 6.2.1 Accumulates shift for internal cursor and passed pointer. 2593 * @since 6.3.0 Invalidate any bookmarks whose targets are overwritten. 2594 * @ignore 2595 * 2596 * @param int $shift_this_point Accumulate and return shift for this position. 2597 * @return int How many bytes the given pointer moved in response to the updates. 2598 */ 2599 private function apply_attributes_updates( int $shift_this_point ): int { 2600 if ( ! count( $this->lexical_updates ) ) { 2601 return 0; 2602 } 2603 2604 $accumulated_shift_for_given_point = 0; 2605 2606 /* 2607 * Attribute updates can be enqueued in any order but updates 2608 * to the document must occur in lexical order; that is, each 2609 * replacement must be made before all others which follow it 2610 * at later string indices in the input document. 2611 * 2612 * Sorting avoids making out-of-order replacements which 2613 * can lead to mangled output, partially-duplicated 2614 * attributes, and overwritten attributes. 2615 */ 2616 usort( $this->lexical_updates, array( self::class, 'sort_start_ascending' ) ); 2617 2618 $bytes_already_copied = 0; 2619 $output_buffer = ''; 2620 foreach ( $this->lexical_updates as $diff ) { 2621 $shift = strlen( $diff->text ) - $diff->length; 2622 2623 // Adjust the cursor position by however much an update affects it. 2624 if ( $diff->start < $this->bytes_already_parsed ) { 2625 $this->bytes_already_parsed += $shift; 2626 } 2627 2628 // Accumulate shift of the given pointer within this function call. 2629 if ( $diff->start < $shift_this_point ) { 2630 $accumulated_shift_for_given_point += $shift; 2631 } 2632 2633 $output_buffer .= substr( $this->html, $bytes_already_copied, $diff->start - $bytes_already_copied ); 2634 $output_buffer .= $diff->text; 2635 $bytes_already_copied = $diff->start + $diff->length; 2636 } 2637 2638 $this->html = $output_buffer . substr( $this->html, $bytes_already_copied ); 2639 2640 /* 2641 * Adjust bookmark locations to account for how the text 2642 * replacements adjust offsets in the input document. 2643 */ 2644 foreach ( $this->bookmarks as $bookmark_name => $bookmark ) { 2645 $bookmark_end = $bookmark->start + $bookmark->length; 2646 2647 /* 2648 * Each lexical update which appears before the bookmark's endpoints 2649 * might shift the offsets for those endpoints. Loop through each change 2650 * and accumulate the total shift for each bookmark, then apply that 2651 * shift after tallying the full delta. 2652 */ 2653 $head_delta = 0; 2654 $tail_delta = 0; 2655 2656 foreach ( $this->lexical_updates as $diff ) { 2657 $diff_end = $diff->start + $diff->length; 2658 2659 if ( $bookmark->start < $diff->start && $bookmark_end < $diff->start ) { 2660 break; 2661 } 2662 2663 if ( $bookmark->start >= $diff->start && $bookmark_end < $diff_end ) { 2664 $this->release_bookmark( $bookmark_name ); 2665 continue 2; 2666 } 2667 2668 $delta = strlen( $diff->text ) - $diff->length; 2669 2670 if ( $bookmark->start >= $diff->start ) { 2671 $head_delta += $delta; 2672 } 2673 2674 if ( $bookmark_end >= $diff_end ) { 2675 $tail_delta += $delta; 2676 } 2677 } 2678 2679 $bookmark->start += $head_delta; 2680 $bookmark->length += $tail_delta - $head_delta; 2681 } 2682 2683 $this->lexical_updates = array(); 2684 2685 return $accumulated_shift_for_given_point; 2686 } 2687 2688 /** 2689 * Checks whether a bookmark with the given name exists. 2690 * 2691 * @since 6.3.0 2692 * 2693 * @param string $bookmark_name Name to identify a bookmark that potentially exists. 2694 * @return bool Whether that bookmark exists. 2695 */ 2696 public function has_bookmark( $bookmark_name ): bool { 2697 return array_key_exists( $bookmark_name, $this->bookmarks ); 2698 } 2699 2700 /** 2701 * Move the internal cursor in the Tag Processor to a given bookmark's location. 2702 * 2703 * In order to prevent accidental infinite loops, there's a 2704 * maximum limit on the number of times seek() can be called. 2705 * 2706 * @since 6.2.0 2707 * 2708 * @param string $bookmark_name Jump to the place in the document identified by this bookmark name. 2709 * @return bool Whether the internal cursor was successfully moved to the bookmark's location. 2710 */ 2711 public function seek( $bookmark_name ): bool { 2712 if ( ! array_key_exists( $bookmark_name, $this->bookmarks ) ) { 2713 _doing_it_wrong( 2714 __METHOD__, 2715 __( 'Unknown bookmark name.' ), 2716 '6.2.0' 2717 ); 2718 return false; 2719 } 2720 2721 $existing_bookmark = $this->bookmarks[ $bookmark_name ]; 2722 2723 if ( 2724 $this->token_starts_at === $existing_bookmark->start && 2725 $this->token_length === $existing_bookmark->length 2726 ) { 2727 return true; 2728 } 2729 2730 if ( ++$this->seek_count > static::MAX_SEEK_OPS ) { 2731 _doing_it_wrong( 2732 __METHOD__, 2733 __( 'Too many calls to seek() - this can lead to performance issues.' ), 2734 '6.2.0' 2735 ); 2736 return false; 2737 } 2738 2739 // Flush out any pending updates to the document. 2740 $this->get_updated_html(); 2741 2742 // Point this tag processor before the sought tag opener and consume it. 2743 $this->bytes_already_parsed = $this->bookmarks[ $bookmark_name ]->start; 2744 $this->parser_state = self::STATE_READY; 2745 return $this->next_token(); 2746 } 2747 2748 /** 2749 * Compare two WP_HTML_Text_Replacement objects. 2750 * 2751 * @since 6.2.0 2752 * @ignore 2753 * 2754 * @param WP_HTML_Text_Replacement $a First attribute update. 2755 * @param WP_HTML_Text_Replacement $b Second attribute update. 2756 * @return int Comparison value for string order. 2757 */ 2758 private static function sort_start_ascending( WP_HTML_Text_Replacement $a, WP_HTML_Text_Replacement $b ): int { 2759 $by_start = $a->start - $b->start; 2760 if ( 0 !== $by_start ) { 2761 return $by_start; 2762 } 2763 2764 $by_text = isset( $a->text, $b->text ) ? strcmp( $a->text, $b->text ) : 0; 2765 if ( 0 !== $by_text ) { 2766 return $by_text; 2767 } 2768 2769 /* 2770 * This code should be unreachable, because it implies the two replacements 2771 * start at the same location and contain the same text. 2772 */ 2773 return $a->length - $b->length; 2774 } 2775 2776 /** 2777 * Return the enqueued value for a given attribute, if one exists. 2778 * 2779 * Enqueued updates can take different data types: 2780 * - If an update is enqueued and is boolean, the return will be `true` 2781 * - If an update is otherwise enqueued, the return will be the string value of that update. 2782 * - If an attribute is enqueued to be removed, the return will be `null` to indicate that. 2783 * - If no updates are enqueued, the return will be `false` to differentiate from "removed." 2784 * 2785 * @since 6.2.0 2786 * @ignore 2787 * 2788 * @param string $comparable_name The attribute name in its comparable form. 2789 * @return string|boolean|null Value of enqueued update if present, otherwise false. 2790 */ 2791 private function get_enqueued_attribute_value( string $comparable_name ) { 2792 if ( self::STATE_MATCHED_TAG !== $this->parser_state ) { 2793 return false; 2794 } 2795 2796 if ( ! isset( $this->lexical_updates[ $comparable_name ] ) ) { 2797 return false; 2798 } 2799 2800 $enqueued_text = $this->lexical_updates[ $comparable_name ]->text; 2801 2802 // Removed attributes erase the entire span. 2803 if ( '' === $enqueued_text ) { 2804 return null; 2805 } 2806 2807 /* 2808 * Boolean attribute updates are just the attribute name without a corresponding value. 2809 * 2810 * This value might differ from the given comparable name in that there could be leading 2811 * or trailing whitespace, and that the casing follows the name given in `set_attribute`. 2812 * 2813 * Example: 2814 * 2815 * $p->set_attribute( 'data-TEST-id', 'update' ); 2816 * 'update' === $p->get_enqueued_attribute_value( 'data-test-id' ); 2817 * 2818 * Detect this difference based on the absence of the `=`, which _must_ exist in any 2819 * attribute containing a value, e.g. `<input type="text" enabled />`. 2820 * ¹ ² 2821 * 1. Attribute with a string value. 2822 * 2. Boolean attribute whose value is `true`. 2823 */ 2824 $equals_at = strpos( $enqueued_text, '=' ); 2825 if ( false === $equals_at ) { 2826 return true; 2827 } 2828 2829 /* 2830 * Finally, a normal update's value will appear after the `=` and 2831 * be double-quoted, as performed incidentally by `set_attribute`. 2832 * 2833 * e.g. `type="text"` 2834 * ¹² ³ 2835 * 1. Equals is here. 2836 * 2. Double-quoting starts one after the equals sign. 2837 * 3. Double-quoting ends at the last character in the update. 2838 */ 2839 $enqueued_value = substr( $enqueued_text, $equals_at + 2, -1 ); 2840 return WP_HTML_Decoder::decode_attribute( $enqueued_value ); 2841 } 2842 2843 /** 2844 * Returns the value of a requested attribute from a matched tag opener if that attribute exists. 2845 * 2846 * Example: 2847 * 2848 * $p = new WP_HTML_Tag_Processor( '<div enabled class="test" data-test-id="14">Test</div>' ); 2849 * $p->next_tag( array( 'class_name' => 'test' ) ) === true; 2850 * $p->get_attribute( 'data-test-id' ) === '14'; 2851 * $p->get_attribute( 'enabled' ) === true; 2852 * $p->get_attribute( 'aria-label' ) === null; 2853 * 2854 * $p->next_tag() === false; 2855 * $p->get_attribute( 'class' ) === null; 2856 * 2857 * @since 6.2.0 2858 * 2859 * @param string $name Name of attribute whose value is requested. 2860 * @return string|true|null Value of attribute or `null` if not available. Boolean attributes return `true`. 2861 */ 2862 public function get_attribute( $name ) { 2863 if ( self::STATE_MATCHED_TAG !== $this->parser_state ) { 2864 return null; 2865 } 2866 2867 $comparable = strtolower( $name ); 2868 2869 /* 2870 * For every attribute other than `class` it's possible to perform a quick check if 2871 * there's an enqueued lexical update whose value takes priority over what's found in 2872 * the input document. 2873 * 2874 * The `class` attribute is special though because of the exposed helpers `add_class` 2875 * and `remove_class`. These form a builder for the `class` attribute, so an additional 2876 * check for enqueued class changes is required in addition to the check for any enqueued 2877 * attribute values. If any exist, those enqueued class changes must first be flushed out 2878 * into an attribute value update. 2879 */ 2880 if ( 'class' === $comparable ) { 2881 $this->class_name_updates_to_attributes_updates(); 2882 } 2883 2884 // Return any enqueued attribute value updates if they exist. 2885 $enqueued_value = $this->get_enqueued_attribute_value( $comparable ); 2886 if ( false !== $enqueued_value ) { 2887 return $enqueued_value; 2888 } 2889 2890 if ( ! isset( $this->attributes[ $comparable ] ) ) { 2891 return null; 2892 } 2893 2894 $attribute = $this->attributes[ $comparable ]; 2895 2896 /* 2897 * This flag distinguishes an attribute with no value 2898 * from an attribute with an empty string value. For 2899 * unquoted attributes this could look very similar. 2900 * It refers to whether an `=` follows the name. 2901 * 2902 * e.g. <div boolean-attribute empty-attribute=></div> 2903 * ¹ ² 2904 * 1. Attribute `boolean-attribute` is `true`. 2905 * 2. Attribute `empty-attribute` is `""`. 2906 */ 2907 if ( true === $attribute->is_true ) { 2908 return true; 2909 } 2910 2911 return $this->get_decoded_attribute_value( $attribute ); 2912 } 2913 2914 /** 2915 * Decode an attribute value from source. 2916 * 2917 * This method applies the following transformations that the processor defers: 2918 * - Normalize newlines (input stream preprocessing) 2919 * - Replace NULL bytes (tokenization) 2920 * - Decode character references (tokenization) 2921 * 2922 * @since 7.1.0 2923 * @ignore 2924 * 2925 * @param WP_HTML_Attribute_Token $attribute Attribute token from the input document. 2926 * @return string Decoded attribute value. 2927 */ 2928 private function get_decoded_attribute_value( WP_HTML_Attribute_Token $attribute ): string { 2929 $raw_value = substr( $this->html, $attribute->value_starts_at, $attribute->value_length ); 2930 $raw_value = str_replace( "\r\n", "\n", $raw_value ); 2931 $raw_value = str_replace( "\r", "\n", $raw_value ); 2932 $raw_value = str_replace( "\x00", "\u{FFFD}", $raw_value ); 2933 return WP_HTML_Decoder::decode_attribute( $raw_value ); 2934 } 2935 2936 /** 2937 * Gets lowercase names of all attributes matching a given prefix in the current tag. 2938 * 2939 * Note that matching is case-insensitive. This is in accordance with the spec: 2940 * 2941 * > There must never be two or more attributes on 2942 * > the same start tag whose names are an ASCII 2943 * > case-insensitive match for each other. 2944 * - HTML 5 spec 2945 * 2946 * Example: 2947 * 2948 * $p = new WP_HTML_Tag_Processor( '<div data-ENABLED class="test" DATA-test-id="14">Test</div>' ); 2949 * $p->next_tag( array( 'class_name' => 'test' ) ) === true; 2950 * $p->get_attribute_names_with_prefix( 'data-' ) === array( 'data-enabled', 'data-test-id' ); 2951 * 2952 * $p->next_tag() === false; 2953 * $p->get_attribute_names_with_prefix( 'data-' ) === null; 2954 * 2955 * @since 6.2.0 2956 * 2957 * @see https://html.spec.whatwg.org/multipage/syntax.html#attributes-2:ascii-case-insensitive 2958 * 2959 * @param string $prefix Prefix of requested attribute names. 2960 * @return array|null List of attribute names, or `null` when no tag opener is matched. 2961 * @phpstan-return list<non-empty-string>|null 2962 */ 2963 public function get_attribute_names_with_prefix( $prefix ): ?array { 2964 if ( 2965 self::STATE_MATCHED_TAG !== $this->parser_state || 2966 $this->is_closing_tag 2967 ) { 2968 return null; 2969 } 2970 2971 $comparable = strtolower( $prefix ); 2972 2973 /* 2974 * For the `class` attribute, ensure that enqueued class changes from 2975 * `add_class` and `remove_class` are flushed into attribute updates. 2976 */ 2977 $has_class = isset( $this->attributes['class'] ); 2978 if ( '' === $comparable || str_starts_with( 'class', $comparable ) ) { 2979 foreach ( $this->classname_updates as $update ) { 2980 if ( 2981 ( $has_class && self::REMOVE_CLASS === $update ) || 2982 ( ! $has_class && self::ADD_CLASS === $update ) 2983 ) { 2984 $this->class_name_updates_to_attributes_updates(); 2985 break; 2986 } 2987 } 2988 } 2989 2990 $additions = array(); 2991 $removals = array(); 2992 foreach ( $this->lexical_updates as $update_name => $update ) { 2993 if ( is_int( $update_name ) || 'modifiable text' === $update_name ) { 2994 continue; 2995 } 2996 2997 if ( '' === $update->text ) { 2998 $removals[ $update_name ] = true; 2999 } elseif ( ! isset( $this->attributes[ $update_name ] ) && str_starts_with( $update_name, $comparable ) ) { 3000 $additions[] = $update_name; 3001 } 3002 } 3003 3004 $matches = array(); 3005 foreach ( array_keys( $this->attributes ) as $attr_name ) { 3006 if ( str_starts_with( $attr_name, $comparable ) && ! isset( $removals[ $attr_name ] ) ) { 3007 $matches[] = $attr_name; 3008 } 3009 } 3010 3011 return empty( $additions ) ? $matches : array_merge( $additions, $matches ); 3012 } 3013 3014 /** 3015 * Returns the namespace of the matched token. 3016 * 3017 * @since 6.7.0 3018 * 3019 * @return string One of 'html', 'math', or 'svg'. 3020 */ 3021 public function get_namespace(): string { 3022 return $this->parsing_namespace; 3023 } 3024 3025 /** 3026 * Returns the uppercase name of the matched tag. 3027 * 3028 * Example: 3029 * 3030 * $p = new WP_HTML_Tag_Processor( '<div class="test">Test</div>' ); 3031 * $p->next_tag() === true; 3032 * $p->get_tag() === 'DIV'; 3033 * 3034 * $p->next_tag() === false; 3035 * $p->get_tag() === null; 3036 * 3037 * @since 6.2.0 3038 * 3039 * @return string|null Name of currently matched tag in input HTML, or `null` if none found. 3040 */ 3041 public function get_tag(): ?string { 3042 if ( null === $this->tag_name_starts_at ) { 3043 return null; 3044 } 3045 3046 $tag_name = str_replace( "\x00", "\u{FFFD}", substr( $this->html, $this->tag_name_starts_at, $this->tag_name_length ) ); 3047 3048 if ( self::STATE_MATCHED_TAG === $this->parser_state ) { 3049 return strtoupper( $tag_name ); 3050 } 3051 3052 /* 3053 * Processing instruction targets are case-sensitive 3054 * and returned as they appear in the input HTML. 3055 */ 3056 if ( self::STATE_PROCESSING_INSTRUCTION === $this->parser_state ) { 3057 return $tag_name; 3058 } 3059 3060 if ( 3061 self::STATE_COMMENT === $this->parser_state && 3062 self::COMMENT_AS_PI_NODE_LOOKALIKE === $this->get_comment_type() 3063 ) { 3064 return $tag_name; 3065 } 3066 3067 return null; 3068 } 3069 3070 /** 3071 * Returns the adjusted tag name for a given token, taking into 3072 * account the current parsing context, whether HTML, SVG, or MathML. 3073 * 3074 * @since 6.7.0 3075 * 3076 * @return string|null Name of current tag name. 3077 */ 3078 public function get_qualified_tag_name(): ?string { 3079 $tag_name = $this->get_tag(); 3080 if ( null === $tag_name ) { 3081 return null; 3082 } 3083 3084 if ( 'html' === $this->get_namespace() ) { 3085 return $tag_name; 3086 } 3087 3088 $lower_tag_name = strtolower( $tag_name ); 3089 if ( 'math' === $this->get_namespace() ) { 3090 return $lower_tag_name; 3091 } 3092 3093 if ( 'svg' === $this->get_namespace() ) { 3094 switch ( $lower_tag_name ) { 3095 case 'altglyph': 3096 return 'altGlyph'; 3097 3098 case 'altglyphdef': 3099 return 'altGlyphDef'; 3100 3101 case 'altglyphitem': 3102 return 'altGlyphItem'; 3103 3104 case 'animatecolor': 3105 return 'animateColor'; 3106 3107 case 'animatemotion': 3108 return 'animateMotion'; 3109 3110 case 'animatetransform': 3111 return 'animateTransform'; 3112 3113 case 'clippath': 3114 return 'clipPath'; 3115 3116 case 'feblend': 3117 return 'feBlend'; 3118 3119 case 'fecolormatrix': 3120 return 'feColorMatrix'; 3121 3122 case 'fecomponenttransfer': 3123 return 'feComponentTransfer'; 3124 3125 case 'fecomposite': 3126 return 'feComposite'; 3127 3128 case 'feconvolvematrix': 3129 return 'feConvolveMatrix'; 3130 3131 case 'fediffuselighting': 3132 return 'feDiffuseLighting'; 3133 3134 case 'fedisplacementmap': 3135 return 'feDisplacementMap'; 3136 3137 case 'fedistantlight': 3138 return 'feDistantLight'; 3139 3140 case 'fedropshadow': 3141 return 'feDropShadow'; 3142 3143 case 'feflood': 3144 return 'feFlood'; 3145 3146 case 'fefunca': 3147 return 'feFuncA'; 3148 3149 case 'fefuncb': 3150 return 'feFuncB'; 3151 3152 case 'fefuncg': 3153 return 'feFuncG'; 3154 3155 case 'fefuncr': 3156 return 'feFuncR'; 3157 3158 case 'fegaussianblur': 3159 return 'feGaussianBlur'; 3160 3161 case 'feimage': 3162 return 'feImage'; 3163 3164 case 'femerge': 3165 return 'feMerge'; 3166 3167 case 'femergenode': 3168 return 'feMergeNode'; 3169 3170 case 'femorphology': 3171 return 'feMorphology'; 3172 3173 case 'feoffset': 3174 return 'feOffset'; 3175 3176 case 'fepointlight': 3177 return 'fePointLight'; 3178 3179 case 'fespecularlighting': 3180 return 'feSpecularLighting'; 3181 3182 case 'fespotlight': 3183 return 'feSpotLight'; 3184 3185 case 'fetile': 3186 return 'feTile'; 3187 3188 case 'feturbulence': 3189 return 'feTurbulence'; 3190 3191 case 'foreignobject': 3192 return 'foreignObject'; 3193 3194 case 'glyphref': 3195 return 'glyphRef'; 3196 3197 case 'lineargradient': 3198 return 'linearGradient'; 3199 3200 case 'radialgradient': 3201 return 'radialGradient'; 3202 3203 case 'textpath': 3204 return 'textPath'; 3205 3206 default: 3207 return $lower_tag_name; 3208 } 3209 } 3210 3211 // This unnecessary return prevents tools from inaccurately reporting type errors. 3212 return $tag_name; 3213 } 3214 3215 /** 3216 * Returns the adjusted attribute name for a given attribute, taking into 3217 * account the current parsing context, whether HTML, SVG, or MathML. 3218 * 3219 * In SVG and MathML contexts, adjusted foreign attributes with a namespace 3220 * prefix use a space between the prefix and local name. For example, 3221 * `xlink:href` is returned as `xlink href`, while the unprefixed `xmlns` 3222 * attribute is returned as `xmlns`. Non-adjusted attributes with a colon in 3223 * their name, such as `foo:bar`, are returned unchanged. 3224 * 3225 * @since 6.7.0 3226 * 3227 * @param string $attribute_name Which attribute to adjust. 3228 * 3229 * @return string|null 3230 */ 3231 public function get_qualified_attribute_name( $attribute_name ): ?string { 3232 if ( self::STATE_MATCHED_TAG !== $this->parser_state ) { 3233 return null; 3234 } 3235 3236 $namespace = $this->get_namespace(); 3237 $lower_name = strtolower( $attribute_name ); 3238 3239 if ( 'math' === $namespace && 'definitionurl' === $lower_name ) { 3240 return 'definitionURL'; 3241 } 3242 3243 if ( 'svg' === $this->get_namespace() ) { 3244 switch ( $lower_name ) { 3245 case 'attributename': 3246 return 'attributeName'; 3247 3248 case 'attributetype': 3249 return 'attributeType'; 3250 3251 case 'basefrequency': 3252 return 'baseFrequency'; 3253 3254 case 'baseprofile': 3255 return 'baseProfile'; 3256 3257 case 'calcmode': 3258 return 'calcMode'; 3259 3260 case 'clippathunits': 3261 return 'clipPathUnits'; 3262 3263 case 'diffuseconstant': 3264 return 'diffuseConstant'; 3265 3266 case 'edgemode': 3267 return 'edgeMode'; 3268 3269 case 'filterunits': 3270 return 'filterUnits'; 3271 3272 case 'glyphref': 3273 return 'glyphRef'; 3274 3275 case 'gradienttransform': 3276 return 'gradientTransform'; 3277 3278 case 'gradientunits': 3279 return 'gradientUnits'; 3280 3281 case 'kernelmatrix': 3282 return 'kernelMatrix'; 3283 3284 case 'kernelunitlength': 3285 return 'kernelUnitLength'; 3286 3287 case 'keypoints': 3288 return 'keyPoints'; 3289 3290 case 'keysplines': 3291 return 'keySplines'; 3292 3293 case 'keytimes': 3294 return 'keyTimes'; 3295 3296 case 'lengthadjust': 3297 return 'lengthAdjust'; 3298 3299 case 'limitingconeangle': 3300 return 'limitingConeAngle'; 3301 3302 case 'markerheight': 3303 return 'markerHeight'; 3304 3305 case 'markerunits': 3306 return 'markerUnits'; 3307 3308 case 'markerwidth': 3309 return 'markerWidth'; 3310 3311 case 'maskcontentunits': 3312 return 'maskContentUnits'; 3313 3314 case 'maskunits': 3315 return 'maskUnits'; 3316 3317 case 'numoctaves': 3318 return 'numOctaves'; 3319 3320 case 'pathlength': 3321 return 'pathLength'; 3322 3323 case 'patterncontentunits': 3324 return 'patternContentUnits'; 3325 3326 case 'patterntransform': 3327 return 'patternTransform'; 3328 3329 case 'patternunits': 3330 return 'patternUnits'; 3331 3332 case 'pointsatx': 3333 return 'pointsAtX'; 3334 3335 case 'pointsaty': 3336 return 'pointsAtY'; 3337 3338 case 'pointsatz': 3339 return 'pointsAtZ'; 3340 3341 case 'preservealpha': 3342 return 'preserveAlpha'; 3343 3344 case 'preserveaspectratio': 3345 return 'preserveAspectRatio'; 3346 3347 case 'primitiveunits': 3348 return 'primitiveUnits'; 3349 3350 case 'refx': 3351 return 'refX'; 3352 3353 case 'refy': 3354 return 'refY'; 3355 3356 case 'repeatcount': 3357 return 'repeatCount'; 3358 3359 case 'repeatdur': 3360 return 'repeatDur'; 3361 3362 case 'requiredextensions': 3363 return 'requiredExtensions'; 3364 3365 case 'requiredfeatures': 3366 return 'requiredFeatures'; 3367 3368 case 'specularconstant': 3369 return 'specularConstant'; 3370 3371 case 'specularexponent': 3372 return 'specularExponent'; 3373 3374 case 'spreadmethod': 3375 return 'spreadMethod'; 3376 3377 case 'startoffset': 3378 return 'startOffset'; 3379 3380 case 'stddeviation': 3381 return 'stdDeviation'; 3382 3383 case 'stitchtiles': 3384 return 'stitchTiles'; 3385 3386 case 'surfacescale': 3387 return 'surfaceScale'; 3388 3389 case 'systemlanguage': 3390 return 'systemLanguage'; 3391 3392 case 'tablevalues': 3393 return 'tableValues'; 3394 3395 case 'targetx': 3396 return 'targetX'; 3397 3398 case 'targety': 3399 return 'targetY'; 3400 3401 case 'textlength': 3402 return 'textLength'; 3403 3404 case 'viewbox': 3405 return 'viewBox'; 3406 3407 case 'viewtarget': 3408 return 'viewTarget'; 3409 3410 case 'xchannelselector': 3411 return 'xChannelSelector'; 3412 3413 case 'ychannelselector': 3414 return 'yChannelSelector'; 3415 3416 case 'zoomandpan': 3417 return 'zoomAndPan'; 3418 } 3419 } 3420 3421 if ( 'html' !== $namespace ) { 3422 switch ( $lower_name ) { 3423 case 'xlink:actuate': 3424 return 'xlink actuate'; 3425 3426 case 'xlink:arcrole': 3427 return 'xlink arcrole'; 3428 3429 case 'xlink:href': 3430 return 'xlink href'; 3431 3432 case 'xlink:role': 3433 return 'xlink role'; 3434 3435 case 'xlink:show': 3436 return 'xlink show'; 3437 3438 case 'xlink:title': 3439 return 'xlink title'; 3440 3441 case 'xlink:type': 3442 return 'xlink type'; 3443 3444 case 'xml:lang': 3445 return 'xml lang'; 3446 3447 case 'xml:space': 3448 return 'xml space'; 3449 3450 case 'xmlns': 3451 return 'xmlns'; 3452 3453 case 'xmlns:xlink': 3454 return 'xmlns xlink'; 3455 } 3456 } 3457 3458 return $attribute_name; 3459 } 3460 3461 /** 3462 * Indicates if the currently matched tag contains the self-closing flag. 3463 * 3464 * No HTML elements ought to have the self-closing flag and for those, the self-closing 3465 * flag will be ignored. For void elements this is benign because they "self close" 3466 * automatically. For non-void HTML elements though problems will appear if someone 3467 * intends to use a self-closing element in place of that element with an empty body. 3468 * For HTML foreign elements and custom elements the self-closing flag determines if 3469 * they self-close or not. 3470 * 3471 * This function does not determine if a tag is self-closing, 3472 * but only if the self-closing flag is present in the syntax. 3473 * 3474 * @since 6.3.0 3475 * 3476 * @return bool Whether the currently matched tag contains the self-closing flag. 3477 */ 3478 public function has_self_closing_flag(): bool { 3479 if ( self::STATE_MATCHED_TAG !== $this->parser_state ) { 3480 return false; 3481 } 3482 3483 return $this->has_self_closing_flag; 3484 } 3485 3486 /** 3487 * Indicates if the current tag token is a tag closer. 3488 * 3489 * Example: 3490 * 3491 * $p = new WP_HTML_Tag_Processor( '<div></div>' ); 3492 * $p->next_tag( array( 'tag_name' => 'div', 'tag_closers' => 'visit' ) ); 3493 * $p->is_tag_closer() === false; 3494 * 3495 * $p->next_tag( array( 'tag_name' => 'div', 'tag_closers' => 'visit' ) ); 3496 * $p->is_tag_closer() === true; 3497 * 3498 * @since 6.2.0 3499 * @since 6.7.0 Reports all BR tags as opening tags. 3500 * 3501 * @return bool Whether the current tag is a tag closer. 3502 */ 3503 public function is_tag_closer(): bool { 3504 return ( 3505 self::STATE_MATCHED_TAG === $this->parser_state && 3506 $this->is_closing_tag && 3507 3508 /* 3509 * The BR tag can only exist as an opening tag. If something like `</br>` 3510 * appears then the HTML parser will treat it as an opening tag with no 3511 * attributes. The BR tag is unique in this way. 3512 * 3513 * @see https://html.spec.whatwg.org/#parsing-main-inbody 3514 */ 3515 'BR' !== $this->get_tag() 3516 ); 3517 } 3518 3519 /** 3520 * Indicates the kind of matched token, if any. 3521 * 3522 * This differs from `get_token_name()` in that it always 3523 * returns a static string indicating the type, whereas 3524 * `get_token_name()` may return values derived from the 3525 * token itself, such as a tag name or processing 3526 * instruction tag. 3527 * 3528 * Possible values: 3529 * - `#tag` when matched on a tag. 3530 * - `#text` when matched on a text node. 3531 * - `#cdata-section` when matched on a CDATA node. 3532 * - `#comment` when matched on a comment. 3533 * - `#doctype` when matched on a DOCTYPE declaration. 3534 * - `#presumptuous-tag` when matched on an empty tag closer. 3535 * - `#funky-comment` when matched on a funky comment. 3536 * - `#processing-instruction` when matched on a processing instruction. 3537 * 3538 * @since 6.5.0 3539 * @since 7.1.0 Recognizes processing instructions. 3540 * 3541 * @return string|null What kind of token is matched, or null. 3542 * @phpstan-return '#tag'|'#text'|'#cdata-section'|'#comment'|'#doctype'|'#presumptuous-tag'|'#funky-comment'|'#processing-instruction'|null 3543 */ 3544 public function get_token_type(): ?string { 3545 switch ( $this->parser_state ) { 3546 case self::STATE_MATCHED_TAG: 3547 return '#tag'; 3548 3549 case self::STATE_DOCTYPE: 3550 return '#doctype'; 3551 3552 default: 3553 return $this->get_token_name(); 3554 } 3555 } 3556 3557 /** 3558 * Returns the node name represented by the token. 3559 * 3560 * This matches the DOM API value `nodeName`. Some values 3561 * are static, such as `#text` for a text node, while others 3562 * are dynamically generated from the token itself. 3563 * 3564 * Dynamic names: 3565 * - Uppercase tag name for tag matches. 3566 * - `html` for DOCTYPE declarations. 3567 * 3568 * Note that if the Tag Processor is not matched on a token 3569 * then this function will return `null`, either because it 3570 * hasn't yet found a token or because it reached the end 3571 * of the document without matching a token. 3572 * 3573 * @since 6.5.0 3574 * 3575 * @return string|null Name of the matched token. 3576 */ 3577 public function get_token_name(): ?string { 3578 switch ( $this->parser_state ) { 3579 case self::STATE_MATCHED_TAG: 3580 return $this->get_tag(); 3581 3582 case self::STATE_TEXT_NODE: 3583 return '#text'; 3584 3585 case self::STATE_CDATA_NODE: 3586 return '#cdata-section'; 3587 3588 case self::STATE_COMMENT: 3589 return '#comment'; 3590 3591 case self::STATE_DOCTYPE: 3592 return 'html'; 3593 3594 case self::STATE_PRESUMPTUOUS_TAG: 3595 return '#presumptuous-tag'; 3596 3597 case self::STATE_FUNKY_COMMENT: 3598 return '#funky-comment'; 3599 3600 case self::STATE_PROCESSING_INSTRUCTION: 3601 return '#processing-instruction'; 3602 } 3603 3604 return null; 3605 } 3606 3607 /** 3608 * Indicates what kind of comment produced the comment node. 3609 * 3610 * Because there are different kinds of HTML syntax which produce 3611 * comments, the Tag Processor tracks and exposes this as a type 3612 * for the comment. Nominally only regular HTML comments exist as 3613 * they are commonly known, but a number of unrelated syntax errors 3614 * also produce comments. 3615 * 3616 * @see self::COMMENT_AS_ABRUPTLY_CLOSED_COMMENT 3617 * @see self::COMMENT_AS_CDATA_LOOKALIKE 3618 * @see self::COMMENT_AS_INVALID_HTML 3619 * @see self::COMMENT_AS_HTML_COMMENT 3620 * @see self::COMMENT_AS_PI_NODE_LOOKALIKE 3621 * 3622 * @since 6.5.0 3623 * 3624 * @return string|null 3625 */ 3626 public function get_comment_type(): ?string { 3627 if ( self::STATE_COMMENT !== $this->parser_state ) { 3628 return null; 3629 } 3630 3631 return $this->comment_type; 3632 } 3633 3634 /** 3635 * Returns the text of a matched comment or null if not on a comment type node. 3636 * 3637 * This method returns the entire text content of a comment node as it 3638 * would appear in the browser. 3639 * 3640 * This differs from {@see ::get_modifiable_text()} in that certain comment 3641 * types in the HTML API cannot allow their entire comment text content to 3642 * be modified. Namely, "bogus comments" of the form `<?xml not allowed in html>` 3643 * will create a comment whose text content starts with `?`. Note that if 3644 * that character were modified, it would be possible to change the node 3645 * type. 3646 * 3647 * @since 6.7.0 3648 * 3649 * @return string|null The comment text as it would appear in the browser or null 3650 * if not on a comment type node. 3651 */ 3652 public function get_full_comment_text(): ?string { 3653 if ( self::STATE_FUNKY_COMMENT === $this->parser_state ) { 3654 return $this->get_modifiable_text(); 3655 } 3656 3657 if ( self::STATE_COMMENT !== $this->parser_state ) { 3658 return null; 3659 } 3660 3661 switch ( $this->get_comment_type() ) { 3662 case self::COMMENT_AS_HTML_COMMENT: 3663 case self::COMMENT_AS_ABRUPTLY_CLOSED_COMMENT: 3664 return $this->get_modifiable_text(); 3665 3666 case self::COMMENT_AS_CDATA_LOOKALIKE: 3667 return "[CDATA[{$this->get_modifiable_text()}]]"; 3668 3669 case self::COMMENT_AS_PI_NODE_LOOKALIKE: 3670 return "?{$this->get_tag()}{$this->get_modifiable_text()}?"; 3671 3672 /* 3673 * This represents "bogus comments state" from HTML tokenization. 3674 * This can be entered by `<?` or `<!`, where `?` is included in 3675 * the comment text but `!` is not. 3676 */ 3677 case self::COMMENT_AS_INVALID_HTML: 3678 $preceding_character = $this->html[ $this->text_starts_at - 1 ]; 3679 $comment_start = '?' === $preceding_character ? '?' : ''; 3680 return "{$comment_start}{$this->get_modifiable_text()}"; 3681 } 3682 3683 return null; 3684 } 3685 3686 /** 3687 * Subdivides a matched text node, splitting NULL byte sequences and decoded whitespace as 3688 * distinct nodes prefixes. 3689 * 3690 * Note that once anything that's neither a NULL byte nor decoded whitespace is 3691 * encountered, then the remainder of the text node is left intact as generic text. 3692 * 3693 * - The HTML Processor uses this to apply distinct rules for different kinds of text. 3694 * - Inter-element whitespace can be detected and skipped with this method. 3695 * 3696 * Text nodes aren't eagerly subdivided because there's no need to split them unless 3697 * decisions are being made on NULL byte sequences or whitespace-only text. 3698 * 3699 * Example: 3700 * 3701 * $processor = new WP_HTML_Tag_Processor( "\x00Apples & Oranges" ); 3702 * true === $processor->next_token(); // Text is "Apples & Oranges". 3703 * true === $processor->subdivide_text_appropriately(); // Text is "". 3704 * true === $processor->next_token(); // Text is "Apples & Oranges". 3705 * false === $processor->subdivide_text_appropriately(); 3706 * 3707 * $processor = new WP_HTML_Tag_Processor( "
 \r\n\tMore" ); 3708 * true === $processor->next_token(); // Text is "␍ ␊␉More". 3709 * true === $processor->subdivide_text_appropriately(); // Text is "␍ ␊␉". 3710 * true === $processor->next_token(); // Text is "More". 3711 * false === $processor->subdivide_text_appropriately(); 3712 * 3713 * @since 6.7.0 3714 * 3715 * @return bool Whether the text node was subdivided. 3716 */ 3717 public function subdivide_text_appropriately(): bool { 3718 if ( self::STATE_TEXT_NODE !== $this->parser_state ) { 3719 return false; 3720 } 3721 3722 $this->text_node_classification = self::TEXT_IS_GENERIC; 3723 3724 /* 3725 * NULL bytes are treated categorically different than numeric character 3726 * references whose number is zero. `�` is not the same as `"\x00"`. 3727 */ 3728 $leading_nulls = strspn( $this->html, "\x00", $this->text_starts_at, $this->text_length ); 3729 if ( $leading_nulls > 0 ) { 3730 $this->token_length = $leading_nulls; 3731 $this->text_length = $leading_nulls; 3732 $this->bytes_already_parsed = $this->token_starts_at + $leading_nulls; 3733 $this->text_node_classification = self::TEXT_IS_NULL_SEQUENCE; 3734 return true; 3735 } 3736 3737 /* 3738 * Start a decoding loop to determine the point at which the 3739 * text subdivides. This entails raw whitespace bytes and any 3740 * character reference that decodes to the same. 3741 */ 3742 $at = $this->text_starts_at; 3743 $end = $this->text_starts_at + $this->text_length; 3744 while ( $at < $end ) { 3745 $skipped = strspn( $this->html, " \t\f\r\n", $at, $end - $at ); 3746 $at += $skipped; 3747 3748 if ( $at < $end && '&' === $this->html[ $at ] ) { 3749 $matched_byte_length = null; 3750 $replacement = WP_HTML_Decoder::read_character_reference( 'data', $this->html, $at, $matched_byte_length ); 3751 if ( isset( $replacement ) && 1 === strspn( $replacement, " \t\f\r\n" ) ) { 3752 $at += $matched_byte_length; 3753 continue; 3754 } 3755 } 3756 3757 break; 3758 } 3759 3760 if ( $at > $this->text_starts_at ) { 3761 $new_length = $at - $this->text_starts_at; 3762 $this->text_length = $new_length; 3763 $this->token_length = $new_length; 3764 $this->bytes_already_parsed = $at; 3765 $this->text_node_classification = self::TEXT_IS_WHITESPACE; 3766 return true; 3767 } 3768 3769 return false; 3770 } 3771 3772 /** 3773 * Returns the modifiable text for a matched token, or an empty string. 3774 * 3775 * Modifiable text is text content that may be read and changed without 3776 * changing the HTML structure of the document around it. This includes 3777 * the contents of `#text` nodes in the HTML as well as the inner 3778 * contents of HTML comments, Processing Instructions, and others, even 3779 * though these nodes aren't part of a parsed DOM tree. They also contain 3780 * the contents of SCRIPT and STYLE tags, of TEXTAREA tags, and of any 3781 * other section in an HTML document which cannot contain HTML markup (DATA). 3782 * 3783 * If a token has no modifiable text then an empty string is returned to 3784 * avoid needless crashing or type errors. An empty string does not mean 3785 * that a token has modifiable text, and a token with modifiable text may 3786 * have an empty string (e.g. a comment with no contents). 3787 * 3788 * Limitations: 3789 * 3790 * - This function will not strip the leading newline appropriately 3791 * after seeking into a LISTING or PRE element. To ensure that the 3792 * newline is treated properly, seek to the LISTING or PRE opening 3793 * tag instead of to the first text node inside the element. 3794 * 3795 * @since 6.5.0 3796 * @since 6.7.0 Replaces NULL bytes (U+0000) and newlines appropriately. 3797 * 3798 * @return string 3799 */ 3800 public function get_modifiable_text(): string { 3801 $has_enqueued_update = isset( $this->lexical_updates['modifiable text'] ); 3802 3803 if ( ! $has_enqueued_update && ( null === $this->text_starts_at || 0 === $this->text_length ) ) { 3804 return ''; 3805 } 3806 3807 $text = $has_enqueued_update 3808 ? $this->lexical_updates['modifiable text']->text 3809 : substr( $this->html, $this->text_starts_at, $this->text_length ); 3810 3811 /* 3812 * An enqueued processing instruction update holds normalized raw 3813 * syntax spanning from the end of the target through the end of 3814 * the token: a separating space, the data, and the `?>` closer. 3815 * The data is found by skipping the leading whitespace and 3816 * dropping the two bytes of the closer. 3817 * 3818 * @see WP_HTML_Tag_Processor::set_modifiable_text() 3819 */ 3820 if ( $has_enqueued_update && self::STATE_PROCESSING_INSTRUCTION === $this->parser_state ) { 3821 $text = substr( $text, strspn( $text, " \t\f\r\n" ), -2 ); 3822 } 3823 3824 /* 3825 * Pre-processing the input stream would normally happen before 3826 * any parsing is done, but deferring it means it's possible to 3827 * skip in most cases. When getting the modifiable text, however 3828 * it's important to apply the pre-processing steps, which is 3829 * normalizing newlines. 3830 * 3831 * @see https://html.spec.whatwg.org/#preprocessing-the-input-stream 3832 * @see https://infra.spec.whatwg.org/#normalize-newlines 3833 */ 3834 $text = str_replace( "\r\n", "\n", $text ); 3835 $text = str_replace( "\r", "\n", $text ); 3836 3837 // Comment and processing instruction data is not decoded. 3838 if ( 3839 self::STATE_CDATA_NODE === $this->parser_state || 3840 self::STATE_COMMENT === $this->parser_state || 3841 self::STATE_DOCTYPE === $this->parser_state || 3842 self::STATE_FUNKY_COMMENT === $this->parser_state || 3843 self::STATE_PROCESSING_INSTRUCTION === $this->parser_state 3844 ) { 3845 return str_replace( "\x00", "\u{FFFD}", $text ); 3846 } 3847 3848 $tag_name = $this->get_token_name(); 3849 if ( 3850 // Script data is not decoded. 3851 'SCRIPT' === $tag_name || 3852 3853 // RAWTEXT data is not decoded. 3854 'IFRAME' === $tag_name || 3855 'NOEMBED' === $tag_name || 3856 'NOFRAMES' === $tag_name || 3857 'STYLE' === $tag_name || 3858 'XMP' === $tag_name 3859 ) { 3860 return str_replace( "\x00", "\u{FFFD}", $text ); 3861 } 3862 3863 $decoded = WP_HTML_Decoder::decode_text_node( $text ); 3864 3865 /* 3866 * Skip the first line feed after LISTING, PRE, and TEXTAREA opening tags. 3867 * 3868 * Note that this first newline may come in the form of a character 3869 * reference, such as `
`, and so it's important to perform 3870 * this transformation only after decoding the raw text content. 3871 */ 3872 if ( 3873 ( "\n" === ( $decoded[0] ?? '' ) ) && 3874 ( ( $this->skip_newline_at === $this->token_starts_at && '#text' === $tag_name ) || 'TEXTAREA' === $tag_name ) 3875 ) { 3876 $decoded = substr( $decoded, 1 ); 3877 } 3878 3879 /* 3880 * Only in normative text nodes does the NULL byte (U+0000) get removed. 3881 * In all other contexts it's replaced by the replacement character (U+FFFD) 3882 * for security reasons (to avoid joining together strings that were safe 3883 * when separated, but not when joined). 3884 * 3885 * @todo Inside HTML integration points and MathML integration points, the 3886 * text is processed according to the insertion mode, not according 3887 * to the foreign content rules. This should strip the NULL bytes. 3888 */ 3889 return ( '#text' === $tag_name && 'html' === $this->get_namespace() ) 3890 ? str_replace( "\x00", '', $decoded ) 3891 : str_replace( "\x00", "\u{FFFD}", $decoded ); 3892 } 3893 3894 /** 3895 * Sets the modifiable text for the matched token, if matched. 3896 * 3897 * Modifiable text is text content that may be read and changed without 3898 * changing the HTML structure of the document around it. This includes 3899 * the contents of `#text` nodes in the HTML as well as the inner 3900 * contents of HTML comments, Processing Instructions, and others, even 3901 * though these nodes aren't part of a parsed DOM tree. They also contain 3902 * the contents of SCRIPT and STYLE tags, of TEXTAREA tags, and of any 3903 * other section in an HTML document which cannot contain HTML markup (DATA). 3904 * 3905 * Not all modifiable text may be set by this method, and not all content 3906 * may be set as modifiable text. In the case that this fails it will return 3907 * `false` indicating as much. For instance, if the contents of a SCRIPT 3908 * element are neither JavaScript nor JSON, it’s not possible to guarantee 3909 * that escaping strings like `</script>` won’t break the script; in these 3910 * cases, updates will be rejected and it’s up to calling code to perform 3911 * language-specific escaping or workarounds. Similarly, it will not allow 3912 * setting content into a comment which would prematurely terminate the comment, 3913 * or processing instruction data which cannot be represented: data containing 3914 * a `>`, which would prematurely terminate the processing instruction, or data 3915 * with leading whitespace, which is indistinguishable from the whitespace 3916 * separating the data from its target. 3917 * 3918 * Example: 3919 * 3920 * // Add a preface to all STYLE contents. 3921 * while ( $processor->next_tag( 'STYLE' ) ) { 3922 * $style = $processor->get_modifiable_text(); 3923 * $processor->set_modifiable_text( "// Made with love on the World Wide Web\n{$style}" ); 3924 * } 3925 * 3926 * // Replace smiley text with Emoji smilies. 3927 * while ( $processor->next_token() ) { 3928 * if ( '#text' !== $processor->get_token_name() ) { 3929 * continue; 3930 * } 3931 * 3932 * $chunk = $processor->get_modifiable_text(); 3933 * if ( ! str_contains( $chunk, ':)' ) ) { 3934 * continue; 3935 * } 3936 * 3937 * $processor->set_modifiable_text( str_replace( ':)', '🙂', $chunk ) ); 3938 * } 3939 * 3940 * This function handles all necessary HTML encoding. Provide normal, unescaped string values. 3941 * The HTML API will encode the strings appropriately so that the browser will interpret them 3942 * as the intended value. 3943 * 3944 * Example: 3945 * 3946 * // Renders as “Eggs & Milk” in a browser, encoded as `<p>Eggs & Milk</p>`. 3947 * $processor->set_modifiable_text( 'Eggs & Milk' ); 3948 * 3949 * // Renders as “Eggs & Milk” in a browser, encoded as `<p>Eggs &amp; Milk</p>`. 3950 * $processor->set_modifiable_text( 'Eggs & Milk' ); 3951 * 3952 * @since 6.7.0 3953 * @since 6.9.0 Escapes all character references instead of trying to avoid double-escaping. 3954 * @since 7.1.0 Supports setting processing instruction data. 3955 * 3956 * @param string $plaintext_content New text content to represent in the matched token. 3957 * @return bool Whether the text was able to update. 3958 */ 3959 public function set_modifiable_text( string $plaintext_content ): bool { 3960 if ( self::STATE_TEXT_NODE === $this->parser_state ) { 3961 $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement( 3962 $this->text_starts_at, 3963 $this->text_length, 3964 strtr( 3965 $plaintext_content, 3966 array( 3967 '<' => '<', 3968 '>' => '>', 3969 '&' => '&', 3970 '"' => '"', 3971 "'" => ''', 3972 ) 3973 ) 3974 ); 3975 3976 return true; 3977 } 3978 3979 // Comment data is not encoded. 3980 if ( 3981 self::STATE_COMMENT === $this->parser_state && 3982 self::COMMENT_AS_HTML_COMMENT === $this->comment_type 3983 ) { 3984 // Check if the text could close the comment. 3985 if ( 1 === preg_match( '/--!?>/', $plaintext_content ) ) { 3986 _doing_it_wrong( 3987 __METHOD__, 3988 __( 'Comment text cannot contain a comment closer.' ), 3989 '7.1.0' 3990 ); 3991 return false; 3992 } 3993 3994 $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement( 3995 $this->text_starts_at, 3996 $this->text_length, 3997 $plaintext_content 3998 ); 3999 4000 return true; 4001 } 4002 4003 // Processing instruction data is not encoded. 4004 if ( self::STATE_PROCESSING_INSTRUCTION === $this->parser_state ) { 4005 /* 4006 * A processing instruction ends at the first `>` in its 4007 * raw syntax: data containing one cannot be represented. 4008 */ 4009 if ( str_contains( $plaintext_content, '>' ) ) { 4010 _doing_it_wrong( 4011 __METHOD__, 4012 __( 'Processing instruction data cannot contain ">".' ), 4013 '7.1.0' 4014 ); 4015 return false; 4016 } 4017 4018 /* 4019 * All whitespace between the target and the data is skipped when 4020 * parsing: data with leading whitespace cannot be represented. 4021 */ 4022 if ( 0 !== strspn( $plaintext_content, " \t\f\r\n" ) ) { 4023 _doing_it_wrong( 4024 __METHOD__, 4025 __( 'Processing instruction data cannot start with whitespace. Try ltrim( $plaintext_content, " \t\f\r\n" ).' ), 4026 '7.1.0' 4027 ); 4028 return false; 4029 } 4030 4031 /** 4032 * A single replacement spans from the end of the target through 4033 * the end of the token, normalizing the raw syntax for that 4034 * region into a fixed form: a separating space, the data, and 4035 * the `?>` closer. 4036 * 4037 * {@see self::get_modifiable_text()} performs necessary parsing to 4038 * return the correct processing instruction data based 4039 * on the modifiable text lexical update. 4040 */ 4041 $data_at = $this->tag_name_starts_at + $this->tag_name_length; 4042 4043 $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement( 4044 $data_at, 4045 $this->token_starts_at + $this->token_length - $data_at, 4046 " {$plaintext_content}?>" 4047 ); 4048 4049 return true; 4050 } 4051 4052 /* 4053 * The rest of this function handles modifiable text for special "atomic" HTML elements. 4054 * Only tags in the HTML namespace should be processed. 4055 */ 4056 if ( 4057 self::STATE_MATCHED_TAG !== $this->parser_state || 4058 'html' !== $this->get_namespace() 4059 ) { 4060 _doing_it_wrong( 4061 __METHOD__, 4062 __( 'This token does not support setting modifiable text.' ), 4063 '7.1.0' 4064 ); 4065 return false; 4066 } 4067 4068 switch ( $this->get_tag() ) { 4069 case 'SCRIPT': 4070 $script_content_type = $this->get_script_content_type(); 4071 4072 switch ( $script_content_type ) { 4073 case 'javascript': 4074 case 'json': 4075 $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement( 4076 $this->text_starts_at, 4077 $this->text_length, 4078 self::escape_javascript_script_contents( $plaintext_content ) 4079 ); 4080 return true; 4081 } 4082 4083 /* 4084 * If the script’s content type isn’t recognized and understandable then it’s 4085 * impossible to guarantee that escaping the content won’t cause runtime breakage. 4086 * For instance, if the script content type were PHP code then escaping with 4087 * `\u0073` would not be met by unescaping; rather, it could result in corrupted 4088 * data or even syntax errors. 4089 * 4090 * Because of this, content which could potentially modify the SCRIPT tag’s 4091 * HTML structure is rejected here. It’s the responsibility of calling code to 4092 * perform whatever semantic escaping is necessary to avoid problematic strings. 4093 */ 4094 if ( 4095 false !== stripos( $plaintext_content, '<script' ) || 4096 false !== stripos( $plaintext_content, '</script' ) 4097 ) { 4098 _doing_it_wrong( 4099 __METHOD__, 4100 __( 'SCRIPT text with an unrecognized content type cannot contain a SCRIPT tag. Apply the escaping appropriate for the content type.' ), 4101 '7.1.0' 4102 ); 4103 return false; 4104 } 4105 $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement( 4106 $this->text_starts_at, 4107 $this->text_length, 4108 $plaintext_content 4109 ); 4110 return true; 4111 4112 case 'IFRAME': 4113 case 'NOEMBED': 4114 case 'NOFRAMES': 4115 case 'XMP': 4116 $tag_name = $this->get_tag(); 4117 if ( false !== stripos( $plaintext_content, "</{$tag_name}" ) ) { 4118 _doing_it_wrong( 4119 __METHOD__, 4120 sprintf( 4121 /* translators: %s: HTML tag name. */ 4122 __( '%s text cannot contain its own closing tag.' ), 4123 $tag_name 4124 ), 4125 '7.1.0' 4126 ); 4127 return false; 4128 } 4129 4130 $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement( 4131 $this->text_starts_at, 4132 $this->text_length, 4133 $plaintext_content 4134 ); 4135 4136 return true; 4137 4138 case 'STYLE': 4139 $plaintext_content = preg_replace_callback( 4140 '~</(?P<TAG_NAME>style)~i', 4141 static function ( $tag_match ) { 4142 return "\\3c\\2f{$tag_match['TAG_NAME']}"; 4143 }, 4144 $plaintext_content 4145 ); 4146 4147 $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement( 4148 $this->text_starts_at, 4149 $this->text_length, 4150 $plaintext_content 4151 ); 4152 4153 return true; 4154 4155 case 'TEXTAREA': 4156 case 'TITLE': 4157 $plaintext_content = preg_replace_callback( 4158 "~</(?P<TAG_NAME>{$this->get_tag()})~i", 4159 static function ( $tag_match ) { 4160 return "</{$tag_match['TAG_NAME']}"; 4161 }, 4162 $plaintext_content 4163 ); 4164 4165 /* 4166 * HTML ignores a single leading newline in this context. If a leading newline 4167 * is intended, preserve it by adding an extra newline. 4168 */ 4169 if ( 4170 'TEXTAREA' === $this->get_tag() && 4171 1 === strspn( $plaintext_content, "\n\r", 0, 1 ) 4172 ) { 4173 $plaintext_content = "\n{$plaintext_content}"; 4174 } 4175 4176 /* 4177 * These don't _need_ to be escaped, but since they are decoded it's 4178 * safe to leave them escaped and this can prevent other code from 4179 * naively detecting tags within the contents. 4180 * 4181 * @todo It would be useful to prefix a multiline replacement text 4182 * with a newline, but not necessary. This is for aesthetics. 4183 */ 4184 $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement( 4185 $this->text_starts_at, 4186 $this->text_length, 4187 $plaintext_content 4188 ); 4189 4190 return true; 4191 } 4192 4193 _doing_it_wrong( 4194 __METHOD__, 4195 __( 'This tag does not support setting modifiable text.' ), 4196 '7.1.0' 4197 ); 4198 return false; 4199 } 4200 4201 /** 4202 * Returns the content type of the currently-matched HTML SCRIPT tag, if matched and 4203 * recognized, otherwise returns `null` to indicate an unrecognized content type. 4204 * 4205 * An HTML SCRIPT tag is a normal SCRIPT tag, but there can be SCRIPT elements inside 4206 * SVG and MathML elements as well, and these have different parsing rules than those 4207 * in general HTML. For this reason, no content-type inference is performed on those. 4208 * 4209 * Note! This concept is related but distinct from the MIME type of the script. 4210 * Parsing MUST match the specific algorithm in the HTML specification, which 4211 * relies on exact string comparison in some cases. MIME type decoding may be 4212 * performed on SVG or MathML SCRIPT tags. 4213 * 4214 * Only 'javascript' and 'json' content types are currently recognized. 4215 * 4216 * @see https://html.spec.whatwg.org/multipage/scripting.html#prepare-the-script-element 4217 * 4218 * @since 7.0.0 4219 * @ignore 4220 * 4221 * @return 'javascript'|'json'|null Type of script element content if matched and recognized. 4222 */ 4223 private function get_script_content_type(): ?string { 4224 // SVG and MathML SCRIPT elements are not recognized. 4225 if ( 'SCRIPT' !== $this->get_tag() || $this->get_namespace() !== 'html' ) { 4226 return null; 4227 } 4228 4229 /* 4230 * > If any of the following are true: 4231 * > - el has a type attribute whose value is the empty string; 4232 * > - el has no type attribute but it has a language attribute and that attribute's 4233 * > value is the empty string; or 4234 * > - el has neither a type attribute nor a language attribute, 4235 * > then let the script block's type string for this script element be "text/javascript". 4236 */ 4237 $type = $this->get_attribute( 'type' ); 4238 $lang = $this->get_attribute( 'language' ); 4239 4240 if ( true === $type || '' === $type ) { 4241 return 'javascript'; 4242 } 4243 4244 if ( null === $type && ( null === $lang || true === $lang || '' === $lang ) ) { 4245 return 'javascript'; 4246 } 4247 4248 /* 4249 * > Otherwise, if el has a type attribute, then let the script block's type string be 4250 * > the value of that attribute with leading and trailing ASCII whitespace stripped. 4251 * > Otherwise, el has a non-empty language attribute; let the script block's type string 4252 * > be the concatenation of "text/" and the value of el's language attribute. 4253 */ 4254 $type_string = is_string( $type ) ? trim( $type, " \t\f\r\n" ) : "text/{$lang}"; 4255 4256 // All matches are ASCII case-insensitive; eagerly lower-case for comparison. 4257 $type_string = strtolower( $type_string ); 4258 4259 /* 4260 * > If the script block's type string is a JavaScript MIME type essence match, then 4261 * > set el's type to "classic". 4262 * 4263 * > A string is a JavaScript MIME type essence match if it is an ASCII case-insensitive 4264 * > match for one of the JavaScript MIME type essence strings. 4265 * 4266 * > A JavaScript MIME type is any MIME type whose essence is one of the following: 4267 * > 4268 * > - application/ecmascript 4269 * > - application/javascript 4270 * > - application/x-ecmascript 4271 * > - application/x-javascript 4272 * > - text/ecmascript 4273 * > - text/javascript 4274 * > - text/javascript1.0 4275 * > - text/javascript1.1 4276 * > - text/javascript1.2 4277 * > - text/javascript1.3 4278 * > - text/javascript1.4 4279 * > - text/javascript1.5 4280 * > - text/jscript 4281 * > - text/livescript 4282 * > - text/x-ecmascript 4283 * > - text/x-javascript 4284 * 4285 * @see https://mimesniff.spec.whatwg.org/#javascript-mime-type-essence-match 4286 * @see https://mimesniff.spec.whatwg.org/#javascript-mime-type 4287 */ 4288 switch ( $type_string ) { 4289 case 'application/ecmascript': 4290 case 'application/javascript': 4291 case 'application/x-ecmascript': 4292 case 'application/x-javascript': 4293 case 'text/ecmascript': 4294 case 'text/javascript': 4295 case 'text/javascript1.0': 4296 case 'text/javascript1.1': 4297 case 'text/javascript1.2': 4298 case 'text/javascript1.3': 4299 case 'text/javascript1.4': 4300 case 'text/javascript1.5': 4301 case 'text/jscript': 4302 case 'text/livescript': 4303 case 'text/x-ecmascript': 4304 case 'text/x-javascript': 4305 return 'javascript'; 4306 4307 /* 4308 * > Otherwise, if the script block's type string is an ASCII case-insensitive match for 4309 * > the string "module", then set el's type to "module". 4310 * 4311 * A module is evaluated as JavaScript. 4312 */ 4313 case 'module': 4314 return 'javascript'; 4315 4316 /* 4317 * > Otherwise, if the script block's type string is an ASCII case-insensitive match for the string "importmap", then set el's type to "importmap". 4318 * > Otherwise, if the script block's type string is an ASCII case-insensitive match for the string "speculationrules", then set el's type to "speculationrules". 4319 * 4320 * These conditions indicate JSON content. 4321 */ 4322 case 'importmap': 4323 case 'speculationrules': 4324 return 'json'; 4325 4326 /** @todo Rely on a full MIME parser for determining JSON content. */ 4327 case 'application/json': 4328 case 'text/json': 4329 return 'json'; 4330 } 4331 4332 /* 4333 * > Otherwise, return. (No script is executed, and el's type is left as null.) 4334 */ 4335 return null; 4336 } 4337 4338 /** 4339 * Escape JavaScript and JSON script tag contents. 4340 * 4341 * Ensure that the script contents cannot modify the HTML structure or break out 4342 * of its containing SCRIPT element. JavaScript and JSON may both be escaped with 4343 * the same rules, even though there are additional escaping measures available 4344 * to JavaScript source code which aren’t applicable to serialized JSON data. 4345 * 4346 * A simple method safely escapes all content except for a few extremely rare and 4347 * unlikely exceptions: prevent the appearance of `<script` and `</script` within 4348 * the contents by replacing the first letter of the tag name with a Unicode escape. 4349 * 4350 * Example: 4351 * 4352 * $plaintext = '<script>document.write( "A </script> closes a script." );</script>'; 4353 * $escaped = '<script>document.write( "A </\u0073cript> closes a script." );</script>'; 4354 * 4355 * This works because of how parsing changes after encountering an opening SCRIPT 4356 * tag. The actual parsing comprises a complicated state machine, the result of 4357 * legacy behaviors and diverse browser support. However, without these two strings 4358 * in the script contents, two key things are ensured: `</script>` cannot appear to 4359 * prematurely close the tag, and the problematic double-escaped state becomes 4360 * unreachable. A JavaScript engine or JSON decoder will then decode the Unicode 4361 * escape (`\u0073`) back into its original plaintext value, but only after having 4362 * been safely extracted from the HTML. 4363 * 4364 * While it may seem tempting to replace the `<` character instead, doing so would 4365 * break JavaScript syntax. The `<` character is used in comparison operators and 4366 * other JavaScript syntax; replacing it would break valid JavaScript. Replacing 4367 * only the `s` in `<script` and `</script` avoids modifying JavaScript syntax. 4368 * 4369 * ### Exceptions 4370 * 4371 * This _should_ work everywhere, but there are some extreme exceptions. 4372 * 4373 * - Comments. 4374 * - Tagged templates, such as `String.raw()`, which provide access to “raw” strings. 4375 * - The `source` property of a RegExp object. 4376 * 4377 * Each of these exceptions appear at the source code level, not at the semantic or 4378 * evaluation level. Normal JavaScript will remain semantically equivalent after escaping, 4379 * but any JavaScript which analyzes the raw source code will see potentially-different 4380 * values. 4381 * 4382 * #### Comments 4383 * 4384 * Comments are never unescaped because they aren’t parsed by the JavaScript engine. 4385 * When viewing the source in a browser’s developer tools, the comments will retain 4386 * their escaped text. 4387 * 4388 * Example: 4389 * 4390 * // A comment: "</script>" 4391 * …becomes… 4392 * // A comment: "</\u0073cript>" 4393 * 4394 * #### Tagged templates. 4395 * 4396 * Tagged templates “enable the embedding of arbitrary string content, where escape 4397 * sequences may follow a different syntax.” For example, they can aid representing 4398 * a RegExp pattern or LaTex snippet within a JavaScript string, where the string 4399 * escape characters might get noisy and distracting. 4400 * 4401 * Example: 4402 * 4403 * console.log( 'A \notin B' ); // Prints a newline because of the "\n". 4404 * console.log( 'A \\notin B' ); // Prints "A \notin B". 4405 * console.log( String.raw`A \notin B` ); // Prints "A \notin B". 4406 * 4407 * This means that if `<script` transforms into `<\u0073cript` _inside_ a raw string 4408 * or tagged template literal which relies on its `.raw` property, the output of the 4409 * code will be different after escaping. 4410 * 4411 * Example: 4412 * 4413 * console.log( String.raw`</script>` ); // Prematurely closes the SCRIPT element. 4414 * console.log( String.raw`</\u0073cript>` ); // Prints "</\u0073cript". 4415 * 4416 * #### RegExp sources. 4417 * 4418 * The RegExp object exposes its raw source in a similar way to how tagged templates and raw 4419 * strings do. Thankfully, because escape sequences are decoded when compiling the pattern, 4420 * escaped RegExp patterns will match the same way as the plaintext sequences would. 4421 * 4422 * Example: 4423 * 4424 * true === /<script>/.test( '<script>' ); 4425 * true === /<\u0073cript>/.test( '<script>' ); 4426 * 4427 * However, as with raw strings, any code which reads the source will see the escaped value 4428 * instead of the decoded one. 4429 * 4430 * Example: 4431 * 4432 * console.log( /<script>/.source ); // Prints "<script>". 4433 * console.log( /<\u0073cript>/.source ); // Prints "<\u0073cript>". 4434 * 4435 * #### Unsupported escaping. 4436 * 4437 * It is not possible to properly represent every possible JavaScript source file 4438 * inside a SCRIPT element. As with CSS stylesheets, SVG images, and MathML, the 4439 * only 100% reliable way to represent all possible inputs is to link to external 4440 * files of the given content-type. 4441 * 4442 * In some cases it’s possible to manually prevent escaping issues. These are not 4443 * automatically handled by this function because doing so would require a full 4444 * JavaScript tokenizer. Consider the following example listing various ways to 4445 * manually escape a closing script tag. 4446 * 4447 * Example: 4448 * 4449 * console.log( String.raw`</script>` ); // !!UNSAFE!! Will be escaped. 4450 * console.log( String.raw`</\u0073cript>` ); // "</\u0073cript>" 4451 * console.log( String.raw`</scr` + String.raw`ipt>` ); // "</script>" 4452 * console.log( String.raw`</${"script"}>` ); // "</script>" 4453 * console.log( '</scr' + 'ipt>' ); // "</script>" 4454 * console.log( "\x3C/script>" ); // "</script>" 4455 * console.log( "<\/script>" ); // "</script>" 4456 * 4457 * The following graph is a simplified interpretation of how HTML interprets the contents 4458 * of a SCRIPT tag and identifies the closing tag. It is useful to understand what text 4459 * is dangerous inside of a SCRIPT tag and why different approaches to escaping work. 4460 * 4461 * Open script 4462 * │ 4463 * ▼ 4464 * ╔═════════════════════════════════════════╗ <!--(…)> 4465 * ║ ║ (all dashes) 4466 * ║ script ╟────────────────╮ 4467 * ║ data ║ │ 4468 * ╭───────────╢ ║ ◀──────────────╯ 4469 * │ ╚═╤═══════════════════════════════════════╝ 4470 * │ │ ▲ ▲ 4471 * │ │ <!-- │ --> ╰─────╮ 4472 * │ ▼ │ │ 4473 * │ ┌─────────────────┴───────────────────────┐ │ 4474 * │ </script¹ │ escaped │ │ 4475 * │ └─┬─────────────────────────────┬─────────┘ │ 4476 * │ │ ▲ │ │ --> 4477 * │ │ </script¹ │ </script¹ │ <script¹ │ 4478 * │ ▼ │ ▼ │ 4479 * │ ╔══════════════╗ │ ┌───────────┐ │ 4480 * │ ║ Close script ║ │ │ double │ │ 4481 * ╰──────────▶║ ║ ╰───────────┤ escaped ├──╯ 4482 * ╚══════════════╝ └───────────┘ 4483 * 4484 * ¹ = Case insensitive 'script' followed by one of ' \t\f\r\n/>', known 4485 * as “tag-name-terminating characters.” This sequence forms the start 4486 * of what could be a SCRIPT opening or closing tag. 4487 * 4488 * @see https://html.spec.whatwg.org/#restrictions-for-contents-of-script-elements 4489 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#specifications 4490 * @see wp_html_api_script_element_escaping_diagram_source() 4491 * 4492 * @since 7.0.0 4493 * @ignore 4494 * 4495 * @param string $sourcecode Raw contents intended to be serialized into an HTML SCRIPT element. 4496 * @return string Escaped form of input contents which will not lead to premature closing of the containing SCRIPT element. 4497 */ 4498 private static function escape_javascript_script_contents( string $sourcecode ): string { 4499 $at = 0; 4500 $was_at = 0; 4501 $end = strlen( $sourcecode ); 4502 $escaped = ''; 4503 4504 /* 4505 * Replace all instances of the ASCII case-insensitive match of "<script" 4506 * and "</script", when followed by whitespace or "/" or ">", by using a 4507 * character replacement for the "s" (or the "S"). 4508 */ 4509 while ( $at < $end ) { 4510 $tag_at = strpos( $sourcecode, '<', $at ); 4511 if ( false === $tag_at ) { 4512 break; 4513 } 4514 4515 $tag_name_at = $tag_at + 1; 4516 $has_closing_slash = $tag_name_at < $end && '/' === $sourcecode[ $tag_name_at ]; 4517 $tag_name_at += $has_closing_slash ? 1 : 0; 4518 4519 if ( 0 !== substr_compare( $sourcecode, 'script', $tag_name_at, 6, true ) ) { 4520 $at = $tag_at + 1; 4521 continue; 4522 } 4523 4524 if ( 1 !== strspn( $sourcecode, " \t\f\r\n/>", $tag_name_at + 6, 1 ) ) { 4525 $at = $tag_name_at + 6; 4526 continue; 4527 } 4528 4529 $escaped .= substr( $sourcecode, $was_at, $tag_name_at - $was_at ); 4530 $escaped .= 's' === $sourcecode[ $tag_name_at ] ? '\u0073' : '\u0053'; 4531 $was_at = $tag_name_at + 1; 4532 $at = $tag_name_at + 7; 4533 } 4534 4535 if ( '' === $escaped ) { 4536 return $sourcecode; 4537 } 4538 4539 if ( $was_at < $end ) { 4540 $escaped .= substr( $sourcecode, $was_at ); 4541 } 4542 4543 return $escaped; 4544 } 4545 4546 /** 4547 * Updates or creates a new attribute on the currently matched tag with the passed value. 4548 * 4549 * This function handles all necessary HTML encoding. Provide normal, unescaped string values. 4550 * The HTML API will encode the strings appropriately so that the browser will interpret them 4551 * as the intended value. 4552 * 4553 * Example: 4554 * 4555 * // Renders “Eggs & Milk” in a browser, encoded as `<abbr title="Eggs & Milk">`. 4556 * $processor->set_attribute( 'title', 'Eggs & Milk' ); 4557 * 4558 * // Renders “Eggs & Milk” in a browser, encoded as `<abbr title="Eggs &amp; Milk">`. 4559 * $processor->set_attribute( 'title', 'Eggs & Milk' ); 4560 * 4561 * // Renders `true` as `<abbr title>`. 4562 * $processor->set_attribute( 'title', true ); 4563 * 4564 * // Renders without the attribute for `false` as `<abbr>`. 4565 * $processor->set_attribute( 'title', false ); 4566 * 4567 * Special handling is provided for boolean attribute values: 4568 * - When `true` is passed as the value, then only the attribute name is added to the tag. 4569 * - When `false` is passed, the attribute gets removed if it existed before. 4570 * 4571 * @since 6.2.0 4572 * @since 6.2.1 Fix: Only create a single update for multiple calls with case-variant attribute names. 4573 * @since 6.9.0 Escapes all character references instead of trying to avoid double-escaping. 4574 * 4575 * @param string $name The attribute name to target. 4576 * @param string|bool $value The new attribute value. 4577 * @return bool Whether an attribute value was set. 4578 */ 4579 public function set_attribute( $name, $value ): bool { 4580 if ( 4581 self::STATE_MATCHED_TAG !== $this->parser_state || 4582 $this->is_closing_tag 4583 ) { 4584 return false; 4585 } 4586 4587 $name_length = strlen( $name ); 4588 4589 /** 4590 * WordPress rejects more characters than are strictly forbidden 4591 * in HTML5. This is to prevent additional security risks deeper 4592 * in the WordPress and plugin stack. Specifically the following 4593 * are not allowed to be set as part of an HTML attribute name: 4594 * 4595 * - greater-than “>” 4596 * - ampersand “&” 4597 * 4598 * @see https://html.spec.whatwg.org/#attributes-2 4599 */ 4600 if ( 4601 0 === $name_length || 4602 // Syntax-like characters. 4603 strcspn( $name, '"\'>&</ =' ) !== $name_length || 4604 // Control characters. 4605 strcspn( 4606 $name, 4607 "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F" . 4608 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F" 4609 ) !== $name_length || 4610 // Unicode noncharacters. 4611 wp_has_noncharacters( $name ) 4612 ) { 4613 _doing_it_wrong( 4614 __METHOD__, 4615 __( 'Invalid attribute name.' ), 4616 '6.2.0' 4617 ); 4618 4619 return false; 4620 } 4621 4622 /* 4623 * > The values "true" and "false" are not allowed on boolean attributes. 4624 * > To represent a false value, the attribute has to be omitted altogether. 4625 * - HTML5 spec, https://html.spec.whatwg.org/#boolean-attributes 4626 */ 4627 if ( false === $value ) { 4628 return $this->remove_attribute( $name ); 4629 } 4630 4631 if ( true === $value ) { 4632 $updated_attribute = $name; 4633 } else { 4634 $comparable_name = strtolower( $name ); 4635 4636 /** 4637 * Escape attribute values appropriately. 4638 * 4639 * @see https://html.spec.whatwg.org/#attributes-3 4640 */ 4641 $escaped_new_value = in_array( $comparable_name, wp_kses_uri_attributes(), true ) 4642 ? esc_url( $value ) 4643 : strtr( 4644 $value, 4645 array( 4646 '<' => '<', 4647 '>' => '>', 4648 '&' => '&', 4649 '"' => '"', 4650 "'" => ''', 4651 ) 4652 ); 4653 4654 // If the escaping functions wiped out the update, reject it and indicate it was rejected. 4655 if ( '' === $escaped_new_value && '' !== $value ) { 4656 return false; 4657 } 4658 4659 $updated_attribute = "{$name}=\"{$escaped_new_value}\""; 4660 } 4661 4662 /* 4663 * > There must never be two or more attributes on 4664 * > the same start tag whose names are an ASCII 4665 * > case-insensitive match for each other. 4666 * - HTML 5 spec 4667 * 4668 * @see https://html.spec.whatwg.org/multipage/syntax.html#attributes-2:ascii-case-insensitive 4669 */ 4670 $comparable_name = strtolower( $name ); 4671 4672 if ( isset( $this->attributes[ $comparable_name ] ) ) { 4673 /* 4674 * Update an existing attribute. 4675 * 4676 * Example – set attribute id to "new" in <div id="initial_id" />: 4677 * 4678 * <div id="initial_id"/> 4679 * ^-------------^ 4680 * start end 4681 * replacement: `id="new"` 4682 * 4683 * Result: <div id="new"/> 4684 */ 4685 $existing_attribute = $this->attributes[ $comparable_name ]; 4686 $this->lexical_updates[ $comparable_name ] = new WP_HTML_Text_Replacement( 4687 $existing_attribute->start, 4688 $existing_attribute->length, 4689 $updated_attribute 4690 ); 4691 } else { 4692 /* 4693 * Create a new attribute at the tag's name end. 4694 * 4695 * Example – add attribute id="new" to <div />: 4696 * 4697 * <div/> 4698 * ^ 4699 * start and end 4700 * replacement: ` id="new"` 4701 * 4702 * Result: <div id="new"/> 4703 */ 4704 $this->lexical_updates[ $comparable_name ] = new WP_HTML_Text_Replacement( 4705 $this->tag_name_starts_at + $this->tag_name_length, 4706 0, 4707 ' ' . $updated_attribute 4708 ); 4709 } 4710 4711 /* 4712 * Any calls to update the `class` attribute directly should wipe out any 4713 * enqueued class changes from `add_class` and `remove_class`. 4714 */ 4715 if ( 'class' === $comparable_name && ! empty( $this->classname_updates ) ) { 4716 $this->classname_updates = array(); 4717 } 4718 4719 return true; 4720 } 4721 4722 /** 4723 * Remove an attribute from the currently-matched tag. 4724 * 4725 * @since 6.2.0 4726 * 4727 * @param string $name The attribute name to remove. 4728 * @return bool Whether an attribute was removed. 4729 */ 4730 public function remove_attribute( $name ): bool { 4731 if ( 4732 self::STATE_MATCHED_TAG !== $this->parser_state || 4733 $this->is_closing_tag 4734 ) { 4735 return false; 4736 } 4737 4738 /* 4739 * > There must never be two or more attributes on 4740 * > the same start tag whose names are an ASCII 4741 * > case-insensitive match for each other. 4742 * - HTML 5 spec 4743 * 4744 * @see https://html.spec.whatwg.org/multipage/syntax.html#attributes-2:ascii-case-insensitive 4745 */ 4746 $name = strtolower( $name ); 4747 4748 /* 4749 * Any calls to update the `class` attribute directly should wipe out any 4750 * enqueued class changes from `add_class` and `remove_class`. 4751 */ 4752 if ( 'class' === $name && count( $this->classname_updates ) !== 0 ) { 4753 $this->classname_updates = array(); 4754 } 4755 4756 /* 4757 * If updating an attribute that didn't exist in the input 4758 * document, then remove the enqueued update and move on. 4759 * 4760 * For example, this might occur when calling `remove_attribute()` 4761 * after calling `set_attribute()` for the same attribute 4762 * and when that attribute wasn't originally present. 4763 */ 4764 if ( ! isset( $this->attributes[ $name ] ) ) { 4765 if ( isset( $this->lexical_updates[ $name ] ) ) { 4766 unset( $this->lexical_updates[ $name ] ); 4767 } 4768 return false; 4769 } 4770 4771 /* 4772 * Removes an existing tag attribute. 4773 * 4774 * Example – remove the attribute id from <div id="main"/>: 4775 * <div id="initial_id"/> 4776 * ^-------------^ 4777 * start end 4778 * replacement: `` 4779 * 4780 * Result: <div /> 4781 */ 4782 $this->lexical_updates[ $name ] = new WP_HTML_Text_Replacement( 4783 $this->attributes[ $name ]->start, 4784 $this->attributes[ $name ]->length, 4785 '' 4786 ); 4787 4788 // Removes any duplicated attributes if they were also present. 4789 foreach ( $this->duplicate_attributes[ $name ] ?? array() as $attribute_token ) { 4790 $this->lexical_updates[] = new WP_HTML_Text_Replacement( 4791 $attribute_token->start, 4792 $attribute_token->length, 4793 '' 4794 ); 4795 } 4796 4797 return true; 4798 } 4799 4800 /** 4801 * Adds a new class name to the currently matched tag. 4802 * 4803 * @since 6.2.0 4804 * 4805 * @param string $class_name The class name to add. 4806 * @return bool Whether the class was set to be added. 4807 */ 4808 public function add_class( $class_name ): bool { 4809 if ( 4810 self::STATE_MATCHED_TAG !== $this->parser_state || 4811 $this->is_closing_tag 4812 ) { 4813 return false; 4814 } 4815 4816 if ( self::QUIRKS_MODE !== $this->compat_mode ) { 4817 $this->classname_updates[ $class_name ] = self::ADD_CLASS; 4818 return true; 4819 } 4820 4821 /* 4822 * Because class names are matched ASCII-case-insensitively in quirks mode, 4823 * this needs to see if a case variant of the given class name is already 4824 * enqueued and update that existing entry, if so. This picks the casing of 4825 * the first-provided class name for all lexical variations. 4826 */ 4827 $class_name_length = strlen( $class_name ); 4828 foreach ( $this->classname_updates as $updated_name => $action ) { 4829 if ( 4830 strlen( $updated_name ) === $class_name_length && 4831 0 === substr_compare( $updated_name, $class_name, 0, $class_name_length, true ) 4832 ) { 4833 $this->classname_updates[ $updated_name ] = self::ADD_CLASS; 4834 return true; 4835 } 4836 } 4837 4838 $this->classname_updates[ $class_name ] = self::ADD_CLASS; 4839 return true; 4840 } 4841 4842 /** 4843 * Removes a class name from the currently matched tag. 4844 * 4845 * @since 6.2.0 4846 * 4847 * @param string $class_name The class name to remove. 4848 * @return bool Whether the class was set to be removed. 4849 */ 4850 public function remove_class( $class_name ): bool { 4851 if ( 4852 self::STATE_MATCHED_TAG !== $this->parser_state || 4853 $this->is_closing_tag 4854 ) { 4855 return false; 4856 } 4857 4858 if ( self::QUIRKS_MODE !== $this->compat_mode ) { 4859 $this->classname_updates[ $class_name ] = self::REMOVE_CLASS; 4860 return true; 4861 } 4862 4863 /* 4864 * Because class names are matched ASCII-case-insensitively in quirks mode, 4865 * this needs to see if a case variant of the given class name is already 4866 * enqueued and update that existing entry, if so. This picks the casing of 4867 * the first-provided class name for all lexical variations. 4868 */ 4869 $class_name_length = strlen( $class_name ); 4870 foreach ( $this->classname_updates as $updated_name => $action ) { 4871 if ( 4872 strlen( $updated_name ) === $class_name_length && 4873 0 === substr_compare( $updated_name, $class_name, 0, $class_name_length, true ) 4874 ) { 4875 $this->classname_updates[ $updated_name ] = self::REMOVE_CLASS; 4876 return true; 4877 } 4878 } 4879 4880 $this->classname_updates[ $class_name ] = self::REMOVE_CLASS; 4881 return true; 4882 } 4883 4884 /** 4885 * Returns the string representation of the HTML Tag Processor. 4886 * 4887 * @since 6.2.0 4888 * 4889 * @see WP_HTML_Tag_Processor::get_updated_html() 4890 * 4891 * @return string The processed HTML. 4892 */ 4893 public function __toString(): string { 4894 return $this->get_updated_html(); 4895 } 4896 4897 /** 4898 * Returns the string representation of the HTML Tag Processor. 4899 * 4900 * @since 6.2.0 4901 * @since 6.2.1 Shifts the internal cursor corresponding to the applied updates. 4902 * @since 6.4.0 No longer calls subclass method `next_tag()` after updating HTML. 4903 * 4904 * @return string The processed HTML. 4905 */ 4906 public function get_updated_html(): string { 4907 $requires_no_updating = 0 === count( $this->classname_updates ) && 0 === count( $this->lexical_updates ); 4908 4909 /* 4910 * When there is nothing more to update and nothing has already been 4911 * updated, return the original document and avoid a string copy. 4912 */ 4913 if ( $requires_no_updating ) { 4914 return $this->html; 4915 } 4916 4917 /* 4918 * Keep track of the position right before the current tag. This will 4919 * be necessary for reparsing the current tag after updating the HTML. 4920 */ 4921 $before_current_tag = $this->token_starts_at ?? 0; 4922 4923 /* 4924 * 1. Apply the enqueued edits and update all the pointers to reflect those changes. 4925 */ 4926 $this->class_name_updates_to_attributes_updates(); 4927 $before_current_tag += $this->apply_attributes_updates( $before_current_tag ); 4928 4929 /* 4930 * 2. Rewind to before the current tag and reparse to get updated attributes. 4931 * 4932 * At this point the internal cursor points to the end of the tag name. 4933 * Rewind before the tag name starts so that it's as if the cursor didn't 4934 * move; a call to `next_tag()` will reparse the recently-updated attributes 4935 * and additional calls to modify the attributes will apply at this same 4936 * location, but in order to avoid issues with subclasses that might add 4937 * behaviors to `next_tag()`, the internal methods should be called here 4938 * instead. 4939 * 4940 * It's important to note that in this specific place there will be no change 4941 * because the processor was already at a tag when this was called and it's 4942 * rewinding only to the beginning of this very tag before reprocessing it 4943 * and its attributes. 4944 * 4945 * <p>Previous HTML<em>More HTML</em></p> 4946 * ↑ │ back up by the length of the tag name plus the opening < 4947 * └←─┘ back up by strlen("em") + 1 ==> 3 4948 */ 4949 $this->bytes_already_parsed = $before_current_tag; 4950 $this->base_class_next_token(); 4951 4952 return $this->html; 4953 } 4954 4955 /** 4956 * Parses tag query input into internal search criteria. 4957 * 4958 * @since 6.2.0 4959 * @ignore 4960 * 4961 * @param array|string|null $query { 4962 * Optional. Which tag name to find, having which class, etc. Default is to find any tag. 4963 * 4964 * @type string|null $tag_name Which tag to find, or `null` for "any tag." 4965 * @type int|null $match_offset Find the Nth tag matching all search criteria. 4966 * 1 for "first" tag, 3 for "third," etc. 4967 * Defaults to first tag. 4968 * @type string|null $class_name Tag must contain this class name to match. 4969 * @type string $tag_closers "visit" or "skip": whether to stop on tag closers, e.g. </div>. 4970 * } 4971 */ 4972 private function parse_query( $query ) { 4973 if ( null !== $query && $query === $this->last_query ) { 4974 return; 4975 } 4976 4977 $this->last_query = $query; 4978 $this->sought_tag_name = null; 4979 $this->sought_class_name = null; 4980 $this->sought_match_offset = 1; 4981 $this->stop_on_tag_closers = false; 4982 4983 // A single string value means "find the tag of this name". 4984 if ( is_string( $query ) ) { 4985 $this->sought_tag_name = $query; 4986 return; 4987 } 4988 4989 // An empty query parameter applies no restrictions on the search. 4990 if ( null === $query ) { 4991 return; 4992 } 4993 4994 // If not using the string interface, an associative array is required. 4995 if ( ! is_array( $query ) ) { 4996 _doing_it_wrong( 4997 __METHOD__, 4998 __( 'The query argument must be an array or a tag name.' ), 4999 '6.2.0' 5000 ); 5001 return; 5002 } 5003 5004 if ( isset( $query['tag_name'] ) && is_string( $query['tag_name'] ) ) { 5005 $this->sought_tag_name = $query['tag_name']; 5006 } 5007 5008 if ( isset( $query['class_name'] ) && is_string( $query['class_name'] ) ) { 5009 $this->sought_class_name = $query['class_name']; 5010 } 5011 5012 if ( isset( $query['match_offset'] ) && is_int( $query['match_offset'] ) && 0 < $query['match_offset'] ) { 5013 $this->sought_match_offset = $query['match_offset']; 5014 } 5015 5016 if ( isset( $query['tag_closers'] ) ) { 5017 $this->stop_on_tag_closers = 'visit' === $query['tag_closers']; 5018 } 5019 } 5020 5021 5022 /** 5023 * Checks whether a given tag and its attributes match the search criteria. 5024 * 5025 * @since 6.2.0 5026 * @ignore 5027 * 5028 * @return bool Whether the given tag and its attribute match the search criteria. 5029 */ 5030 private function matches(): bool { 5031 if ( $this->is_closing_tag && ! $this->stop_on_tag_closers ) { 5032 return false; 5033 } 5034 5035 // Does the tag name match the requested tag name in a case-insensitive manner? 5036 if ( isset( $this->sought_tag_name ) ) { 5037 $tag_name = $this->get_tag(); 5038 if ( 5039 strlen( $this->sought_tag_name ) !== strlen( $tag_name ) || 5040 0 !== substr_compare( $tag_name, $this->sought_tag_name, 0, null, true ) 5041 ) { 5042 return false; 5043 } 5044 } 5045 5046 if ( null !== $this->sought_class_name && ! $this->has_class( $this->sought_class_name ) ) { 5047 return false; 5048 } 5049 5050 return true; 5051 } 5052 5053 /** 5054 * Gets DOCTYPE declaration info from a DOCTYPE token. 5055 * 5056 * DOCTYPE tokens may appear in many places in an HTML document. In most places, they are 5057 * simply ignored. The main parsing functions find the basic shape of DOCTYPE tokens but 5058 * do not perform detailed parsing. 5059 * 5060 * This method can be called to perform a full parse of the DOCTYPE token and retrieve 5061 * its information. 5062 * 5063 * @return WP_HTML_Doctype_Info|null The DOCTYPE declaration information or `null` if not 5064 * currently at a DOCTYPE node. 5065 */ 5066 public function get_doctype_info(): ?WP_HTML_Doctype_Info { 5067 if ( self::STATE_DOCTYPE !== $this->parser_state ) { 5068 return null; 5069 } 5070 5071 return WP_HTML_Doctype_Info::from_doctype_token( substr( $this->html, $this->token_starts_at, $this->token_length ) ); 5072 } 5073 5074 /** 5075 * Parser Ready State. 5076 * 5077 * Indicates that the parser is ready to run and waiting for a state transition. 5078 * It may not have started yet, or it may have just finished parsing a token and 5079 * is ready to find the next one. 5080 * 5081 * @since 6.5.0 5082 * 5083 * @access private 5084 */ 5085 const STATE_READY = 'STATE_READY'; 5086 5087 /** 5088 * Parser Complete State. 5089 * 5090 * Indicates that the parser has reached the end of the document and there is 5091 * nothing left to scan. It finished parsing the last token completely. 5092 * 5093 * @since 6.5.0 5094 * 5095 * @access private 5096 */ 5097 const STATE_COMPLETE = 'STATE_COMPLETE'; 5098 5099 /** 5100 * Parser Incomplete Input State. 5101 * 5102 * Indicates that the parser has reached the end of the document before finishing 5103 * a token. It started parsing a token but there is a possibility that the input 5104 * HTML document was truncated in the middle of a token. 5105 * 5106 * The parser is reset at the start of the incomplete token and has paused. There 5107 * is nothing more than can be scanned unless provided a more complete document. 5108 * 5109 * @since 6.5.0 5110 * 5111 * @access private 5112 */ 5113 const STATE_INCOMPLETE_INPUT = 'STATE_INCOMPLETE_INPUT'; 5114 5115 /** 5116 * Parser Matched Tag State. 5117 * 5118 * Indicates that the parser has found an HTML tag and it's possible to get 5119 * the tag name and read or modify its attributes (if it's not a closing tag). 5120 * 5121 * @since 6.5.0 5122 * 5123 * @access private 5124 */ 5125 const STATE_MATCHED_TAG = 'STATE_MATCHED_TAG'; 5126 5127 /** 5128 * Parser Text Node State. 5129 * 5130 * Indicates that the parser has found a text node and it's possible 5131 * to read and modify that text. 5132 * 5133 * @since 6.5.0 5134 * 5135 * @access private 5136 */ 5137 const STATE_TEXT_NODE = 'STATE_TEXT_NODE'; 5138 5139 /** 5140 * Parser CDATA Node State. 5141 * 5142 * Indicates that the parser has found a CDATA node and it's possible 5143 * to read and modify its modifiable text. Note that in HTML there are 5144 * no CDATA nodes outside of foreign content (SVG and MathML). Outside 5145 * of foreign content, they are treated as HTML comments. 5146 * 5147 * @since 6.5.0 5148 * 5149 * @access private 5150 */ 5151 const STATE_CDATA_NODE = 'STATE_CDATA_NODE'; 5152 5153 /** 5154 * Indicates that the parser has found an HTML comment and it's 5155 * possible to read and modify its modifiable text. 5156 * 5157 * @since 6.5.0 5158 * 5159 * @access private 5160 */ 5161 const STATE_COMMENT = 'STATE_COMMENT'; 5162 5163 /** 5164 * Indicates that the parser has found a DOCTYPE node and it's 5165 * possible to read its DOCTYPE information via `get_doctype_info()`. 5166 * 5167 * @since 6.5.0 5168 * 5169 * @access private 5170 */ 5171 const STATE_DOCTYPE = 'STATE_DOCTYPE'; 5172 5173 /** 5174 * Indicates that the parser has found an empty tag closer `</>`. 5175 * 5176 * Note that in HTML there are no empty tag closers, and they 5177 * are ignored. Nonetheless, the Tag Processor still 5178 * recognizes them as they appear in the HTML stream. 5179 * 5180 * These were historically discussed as a "presumptuous tag 5181 * closer," which would close the nearest open tag, but were 5182 * dismissed in favor of explicitly-closing tags. 5183 * 5184 * @since 6.5.0 5185 * 5186 * @access private 5187 */ 5188 const STATE_PRESUMPTUOUS_TAG = 'STATE_PRESUMPTUOUS_TAG'; 5189 5190 /** 5191 * Indicates that the parser has found a "funky comment" 5192 * and it's possible to read and modify its modifiable text. 5193 * 5194 * Example: 5195 * 5196 * </%url> 5197 * </{"wp-bit":"query/post-author"}> 5198 * </2> 5199 * 5200 * Funky comments are tag closers with invalid tag names. Note 5201 * that in HTML these are turned into bogus comments. Nonetheless, 5202 * the Tag Processor recognizes them in a stream of HTML and 5203 * exposes them for inspection and modification. 5204 * 5205 * @since 6.5.0 5206 * 5207 * @access private 5208 */ 5209 const STATE_FUNKY_COMMENT = 'STATE_WP_FUNKY'; 5210 5211 /** 5212 * Indicates that the parser has found a processing instruction 5213 * and it's possible to read its target and data. 5214 * 5215 * Example: 5216 * 5217 * <?wp-bit {"just": "kidding"}> 5218 * 5219 * Processing instructions with an allowable target are parsed 5220 * into processing instruction nodes. The reserved `xml` and 5221 * `xml-stylesheet` targets, and targets with characters outside 5222 * an ASCII-representable subset, are turned into bogus comments. 5223 * 5224 * @link https://html.spec.whatwg.org/multipage/parsing.html#processing-instruction-open-state 5225 * 5226 * @since 7.1.0 5227 * 5228 * @access private 5229 */ 5230 const STATE_PROCESSING_INSTRUCTION = 'STATE_PROCESSING_INSTRUCTION'; 5231 5232 /** 5233 * Indicates that a comment was created when encountering abruptly-closed HTML comment. 5234 * 5235 * Example: 5236 * 5237 * <!--> 5238 * <!---> 5239 * 5240 * @since 6.5.0 5241 */ 5242 const COMMENT_AS_ABRUPTLY_CLOSED_COMMENT = 'COMMENT_AS_ABRUPTLY_CLOSED_COMMENT'; 5243 5244 /** 5245 * Indicates that a comment would be parsed as a CDATA node, 5246 * were HTML to allow CDATA nodes outside of foreign content. 5247 * 5248 * Example: 5249 * 5250 * <![CDATA[This is a CDATA node.]]> 5251 * 5252 * This is an HTML comment, but it looks like a CDATA node. 5253 * 5254 * @since 6.5.0 5255 */ 5256 const COMMENT_AS_CDATA_LOOKALIKE = 'COMMENT_AS_CDATA_LOOKALIKE'; 5257 5258 /** 5259 * Indicates that a comment was created when encountering 5260 * normative HTML comment syntax. 5261 * 5262 * Example: 5263 * 5264 * <!-- this is a comment --> 5265 * 5266 * @since 6.5.0 5267 */ 5268 const COMMENT_AS_HTML_COMMENT = 'COMMENT_AS_HTML_COMMENT'; 5269 5270 /** 5271 * Indicates that a comment would be parsed as a Processing 5272 * Instruction node, were its target allowed within HTML. 5273 * 5274 * Example: 5275 * 5276 * <?xml version="1.0" ?> 5277 * <?wp.like count=5 ?> 5278 * 5279 * These are HTML comments, but they look like processing 5280 * instructions. HTML parses processing instructions with 5281 * an allowable target into processing instruction nodes, 5282 * but the reserved `xml` and `xml-stylesheet` targets and 5283 * XML-valid targets with characters outside of the allowed 5284 * set become bogus comments instead. 5285 * 5286 * @since 6.5.0 5287 * @since 7.1.0 Only applies to reserved and XML-specific target names; 5288 * other processing instructions produce their own token. 5289 */ 5290 const COMMENT_AS_PI_NODE_LOOKALIKE = 'COMMENT_AS_PI_NODE_LOOKALIKE'; 5291 5292 /** 5293 * Indicates that a comment was created when encountering invalid 5294 * HTML input, a so-called "bogus comment." 5295 * 5296 * Example: 5297 * 5298 * <?= nothing special ?> 5299 * <!{nothing special}> 5300 * 5301 * @since 6.5.0 5302 */ 5303 const COMMENT_AS_INVALID_HTML = 'COMMENT_AS_INVALID_HTML'; 5304 5305 /** 5306 * No-quirks mode document compatibility mode. 5307 * 5308 * > In no-quirks mode, the behavior is (hopefully) the desired behavior 5309 * > described by the modern HTML and CSS specifications. 5310 * 5311 * @see self::$compat_mode 5312 * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Quirks_Mode_and_Standards_Mode 5313 * 5314 * @since 6.7.0 5315 * 5316 * @var string 5317 */ 5318 const NO_QUIRKS_MODE = 'no-quirks-mode'; 5319 5320 /** 5321 * Quirks mode document compatibility mode. 5322 * 5323 * > In quirks mode, layout emulates behavior in Navigator 4 and Internet 5324 * > Explorer 5. This is essential in order to support websites that were 5325 * > built before the widespread adoption of web standards. 5326 * 5327 * @see self::$compat_mode 5328 * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Quirks_Mode_and_Standards_Mode 5329 * 5330 * @since 6.7.0 5331 * 5332 * @var string 5333 */ 5334 const QUIRKS_MODE = 'quirks-mode'; 5335 5336 /** 5337 * Indicates that a span of text may contain any combination of significant 5338 * kinds of characters: NULL bytes, whitespace, and others. 5339 * 5340 * @see self::$text_node_classification 5341 * @see self::subdivide_text_appropriately 5342 * 5343 * @since 6.7.0 5344 */ 5345 const TEXT_IS_GENERIC = 'TEXT_IS_GENERIC'; 5346 5347 /** 5348 * Indicates that a span of text comprises a sequence only of NULL bytes. 5349 * 5350 * @see self::$text_node_classification 5351 * @see self::subdivide_text_appropriately 5352 * 5353 * @since 6.7.0 5354 */ 5355 const TEXT_IS_NULL_SEQUENCE = 'TEXT_IS_NULL_SEQUENCE'; 5356 5357 /** 5358 * Indicates that a span of decoded text comprises only whitespace. 5359 * 5360 * @see self::$text_node_classification 5361 * @see self::subdivide_text_appropriately 5362 * 5363 * @since 6.7.0 5364 */ 5365 const TEXT_IS_WHITESPACE = 'TEXT_IS_WHITESPACE'; 5366 5367 /** 5368 * Wakeup magic method. 5369 * 5370 * @since 6.9.2 5371 */ 5372 public function __wakeup() { 5373 throw new \LogicException( __CLASS__ . ' should never be unserialized' ); 5374 } 5375 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Sun Aug 2 08:20:19 2026 | Cross-referenced by PHPXref |