[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/html-api/ -> class-wp-html-tag-processor.php (source)

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


Generated : Sat Aug 29 08:20:24 2026 Cross-referenced by PHPXref