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