[ 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       *
3237       * @return string|null
3238       */
3239  	public function get_qualified_attribute_name( $attribute_name ): ?string {
3240          if ( self::STATE_MATCHED_TAG !== $this->parser_state ) {
3241              return null;
3242          }
3243  
3244          $namespace  = $this->get_namespace();
3245          $lower_name = strtolower( $attribute_name );
3246  
3247          if ( 'math' === $namespace && 'definitionurl' === $lower_name ) {
3248              return 'definitionURL';
3249          }
3250  
3251          if ( 'svg' === $this->get_namespace() ) {
3252              switch ( $lower_name ) {
3253                  case 'attributename':
3254                      return 'attributeName';
3255  
3256                  case 'attributetype':
3257                      return 'attributeType';
3258  
3259                  case 'basefrequency':
3260                      return 'baseFrequency';
3261  
3262                  case 'baseprofile':
3263                      return 'baseProfile';
3264  
3265                  case 'calcmode':
3266                      return 'calcMode';
3267  
3268                  case 'clippathunits':
3269                      return 'clipPathUnits';
3270  
3271                  case 'diffuseconstant':
3272                      return 'diffuseConstant';
3273  
3274                  case 'edgemode':
3275                      return 'edgeMode';
3276  
3277                  case 'filterunits':
3278                      return 'filterUnits';
3279  
3280                  case 'glyphref':
3281                      return 'glyphRef';
3282  
3283                  case 'gradienttransform':
3284                      return 'gradientTransform';
3285  
3286                  case 'gradientunits':
3287                      return 'gradientUnits';
3288  
3289                  case 'kernelmatrix':
3290                      return 'kernelMatrix';
3291  
3292                  case 'kernelunitlength':
3293                      return 'kernelUnitLength';
3294  
3295                  case 'keypoints':
3296                      return 'keyPoints';
3297  
3298                  case 'keysplines':
3299                      return 'keySplines';
3300  
3301                  case 'keytimes':
3302                      return 'keyTimes';
3303  
3304                  case 'lengthadjust':
3305                      return 'lengthAdjust';
3306  
3307                  case 'limitingconeangle':
3308                      return 'limitingConeAngle';
3309  
3310                  case 'markerheight':
3311                      return 'markerHeight';
3312  
3313                  case 'markerunits':
3314                      return 'markerUnits';
3315  
3316                  case 'markerwidth':
3317                      return 'markerWidth';
3318  
3319                  case 'maskcontentunits':
3320                      return 'maskContentUnits';
3321  
3322                  case 'maskunits':
3323                      return 'maskUnits';
3324  
3325                  case 'numoctaves':
3326                      return 'numOctaves';
3327  
3328                  case 'pathlength':
3329                      return 'pathLength';
3330  
3331                  case 'patterncontentunits':
3332                      return 'patternContentUnits';
3333  
3334                  case 'patterntransform':
3335                      return 'patternTransform';
3336  
3337                  case 'patternunits':
3338                      return 'patternUnits';
3339  
3340                  case 'pointsatx':
3341                      return 'pointsAtX';
3342  
3343                  case 'pointsaty':
3344                      return 'pointsAtY';
3345  
3346                  case 'pointsatz':
3347                      return 'pointsAtZ';
3348  
3349                  case 'preservealpha':
3350                      return 'preserveAlpha';
3351  
3352                  case 'preserveaspectratio':
3353                      return 'preserveAspectRatio';
3354  
3355                  case 'primitiveunits':
3356                      return 'primitiveUnits';
3357  
3358                  case 'refx':
3359                      return 'refX';
3360  
3361                  case 'refy':
3362                      return 'refY';
3363  
3364                  case 'repeatcount':
3365                      return 'repeatCount';
3366  
3367                  case 'repeatdur':
3368                      return 'repeatDur';
3369  
3370                  case 'requiredextensions':
3371                      return 'requiredExtensions';
3372  
3373                  case 'requiredfeatures':
3374                      return 'requiredFeatures';
3375  
3376                  case 'specularconstant':
3377                      return 'specularConstant';
3378  
3379                  case 'specularexponent':
3380                      return 'specularExponent';
3381  
3382                  case 'spreadmethod':
3383                      return 'spreadMethod';
3384  
3385                  case 'startoffset':
3386                      return 'startOffset';
3387  
3388                  case 'stddeviation':
3389                      return 'stdDeviation';
3390  
3391                  case 'stitchtiles':
3392                      return 'stitchTiles';
3393  
3394                  case 'surfacescale':
3395                      return 'surfaceScale';
3396  
3397                  case 'systemlanguage':
3398                      return 'systemLanguage';
3399  
3400                  case 'tablevalues':
3401                      return 'tableValues';
3402  
3403                  case 'targetx':
3404                      return 'targetX';
3405  
3406                  case 'targety':
3407                      return 'targetY';
3408  
3409                  case 'textlength':
3410                      return 'textLength';
3411  
3412                  case 'viewbox':
3413                      return 'viewBox';
3414  
3415                  case 'viewtarget':
3416                      return 'viewTarget';
3417  
3418                  case 'xchannelselector':
3419                      return 'xChannelSelector';
3420  
3421                  case 'ychannelselector':
3422                      return 'yChannelSelector';
3423  
3424                  case 'zoomandpan':
3425                      return 'zoomAndPan';
3426              }
3427          }
3428  
3429          if ( 'html' !== $namespace ) {
3430              switch ( $lower_name ) {
3431                  case 'xlink:actuate':
3432                      return 'xlink actuate';
3433  
3434                  case 'xlink:arcrole':
3435                      return 'xlink arcrole';
3436  
3437                  case 'xlink:href':
3438                      return 'xlink href';
3439  
3440                  case 'xlink:role':
3441                      return 'xlink role';
3442  
3443                  case 'xlink:show':
3444                      return 'xlink show';
3445  
3446                  case 'xlink:title':
3447                      return 'xlink title';
3448  
3449                  case 'xlink:type':
3450                      return 'xlink type';
3451  
3452                  case 'xml:lang':
3453                      return 'xml lang';
3454  
3455                  case 'xml:space':
3456                      return 'xml space';
3457  
3458                  case 'xmlns':
3459                      return 'xmlns';
3460  
3461                  case 'xmlns:xlink':
3462                      return 'xmlns xlink';
3463              }
3464          }
3465  
3466          return $attribute_name;
3467      }
3468  
3469      /**
3470       * Indicates if the currently matched tag contains the self-closing flag.
3471       *
3472       * No HTML elements ought to have the self-closing flag and for those, the self-closing
3473       * flag will be ignored. For void elements this is benign because they "self close"
3474       * automatically. For non-void HTML elements though problems will appear if someone
3475       * intends to use a self-closing element in place of that element with an empty body.
3476       * For HTML foreign elements and custom elements the self-closing flag determines if
3477       * they self-close or not.
3478       *
3479       * This function does not determine if a tag is self-closing,
3480       * but only if the self-closing flag is present in the syntax.
3481       *
3482       * @since 6.3.0
3483       *
3484       * @return bool Whether the currently matched tag contains the self-closing flag.
3485       */
3486  	public function has_self_closing_flag(): bool {
3487          if ( self::STATE_MATCHED_TAG !== $this->parser_state ) {
3488              return false;
3489          }
3490  
3491          return $this->has_self_closing_flag;
3492      }
3493  
3494      /**
3495       * Indicates if the current tag token is a tag closer.
3496       *
3497       * Example:
3498       *
3499       *     $p = new WP_HTML_Tag_Processor( '<div></div>' );
3500       *     $p->next_tag( array( 'tag_name' => 'div', 'tag_closers' => 'visit' ) );
3501       *     $p->is_tag_closer() === false;
3502       *
3503       *     $p->next_tag( array( 'tag_name' => 'div', 'tag_closers' => 'visit' ) );
3504       *     $p->is_tag_closer() === true;
3505       *
3506       * @since 6.2.0
3507       * @since 6.7.0 Reports all BR tags as opening tags.
3508       *
3509       * @return bool Whether the current tag is a tag closer.
3510       */
3511  	public function is_tag_closer(): bool {
3512          return (
3513              self::STATE_MATCHED_TAG === $this->parser_state &&
3514              $this->is_closing_tag &&
3515  
3516              /*
3517               * The BR tag can only exist as an opening tag. If something like `</br>`
3518               * appears then the HTML parser will treat it as an opening tag with no
3519               * attributes. The BR tag is unique in this way.
3520               *
3521               * @see https://html.spec.whatwg.org/#parsing-main-inbody
3522               */
3523              'BR' !== $this->get_tag()
3524          );
3525      }
3526  
3527      /**
3528       * Indicates the kind of matched token, if any.
3529       *
3530       * This differs from `get_token_name()` in that it always
3531       * returns a static string indicating the type, whereas
3532       * `get_token_name()` may return values derived from the
3533       * token itself, such as a tag name or processing
3534       * instruction tag.
3535       *
3536       * Possible values:
3537       *  - `#tag` when matched on a tag.
3538       *  - `#text` when matched on a text node.
3539       *  - `#cdata-section` when matched on a CDATA node.
3540       *  - `#comment` when matched on a comment.
3541       *  - `#doctype` when matched on a DOCTYPE declaration.
3542       *  - `#presumptuous-tag` when matched on an empty tag closer.
3543       *  - `#funky-comment` when matched on a funky comment.
3544       *  - `#processing-instruction` when matched on a processing instruction.
3545       *
3546       * @since 6.5.0
3547       * @since 7.1.0 Recognizes processing instructions.
3548       *
3549       * @return string|null What kind of token is matched, or null.
3550       * @phpstan-return '#tag'|'#text'|'#cdata-section'|'#comment'|'#doctype'|'#presumptuous-tag'|'#funky-comment'|'#processing-instruction'|null
3551       */
3552  	public function get_token_type(): ?string {
3553          switch ( $this->parser_state ) {
3554              case self::STATE_MATCHED_TAG:
3555                  return '#tag';
3556  
3557              case self::STATE_DOCTYPE:
3558                  return '#doctype';
3559  
3560              default:
3561                  return $this->get_token_name();
3562          }
3563      }
3564  
3565      /**
3566       * Returns the node name represented by the token.
3567       *
3568       * This matches the DOM API value `nodeName`. Some values
3569       * are static, such as `#text` for a text node, while others
3570       * are dynamically generated from the token itself.
3571       *
3572       * Dynamic names:
3573       *  - Uppercase tag name for tag matches.
3574       *  - `html` for DOCTYPE declarations.
3575       *
3576       * Note that if the Tag Processor is not matched on a token
3577       * then this function will return `null`, either because it
3578       * hasn't yet found a token or because it reached the end
3579       * of the document without matching a token.
3580       *
3581       * @since 6.5.0
3582       *
3583       * @return string|null Name of the matched token.
3584       */
3585  	public function get_token_name(): ?string {
3586          switch ( $this->parser_state ) {
3587              case self::STATE_MATCHED_TAG:
3588                  return $this->get_tag();
3589  
3590              case self::STATE_TEXT_NODE:
3591                  return '#text';
3592  
3593              case self::STATE_CDATA_NODE:
3594                  return '#cdata-section';
3595  
3596              case self::STATE_COMMENT:
3597                  return '#comment';
3598  
3599              case self::STATE_DOCTYPE:
3600                  return 'html';
3601  
3602              case self::STATE_PRESUMPTUOUS_TAG:
3603                  return '#presumptuous-tag';
3604  
3605              case self::STATE_FUNKY_COMMENT:
3606                  return '#funky-comment';
3607  
3608              case self::STATE_PROCESSING_INSTRUCTION:
3609                  return '#processing-instruction';
3610          }
3611  
3612          return null;
3613      }
3614  
3615      /**
3616       * Indicates what kind of comment produced the comment node.
3617       *
3618       * Because there are different kinds of HTML syntax which produce
3619       * comments, the Tag Processor tracks and exposes this as a type
3620       * for the comment. Nominally only regular HTML comments exist as
3621       * they are commonly known, but a number of unrelated syntax errors
3622       * also produce comments.
3623       *
3624       * @see self::COMMENT_AS_ABRUPTLY_CLOSED_COMMENT
3625       * @see self::COMMENT_AS_CDATA_LOOKALIKE
3626       * @see self::COMMENT_AS_INVALID_HTML
3627       * @see self::COMMENT_AS_HTML_COMMENT
3628       * @see self::COMMENT_AS_PI_NODE_LOOKALIKE
3629       *
3630       * @since 6.5.0
3631       *
3632       * @return string|null
3633       */
3634  	public function get_comment_type(): ?string {
3635          if ( self::STATE_COMMENT !== $this->parser_state ) {
3636              return null;
3637          }
3638  
3639          return $this->comment_type;
3640      }
3641  
3642      /**
3643       * Returns the text of a matched comment or null if not on a comment type node.
3644       *
3645       * This method returns the entire text content of a comment node as it
3646       * would appear in the browser.
3647       *
3648       * This differs from {@see ::get_modifiable_text()} in that certain comment
3649       * types in the HTML API cannot allow their entire comment text content to
3650       * be modified. Namely, "bogus comments" of the form `<?xml not allowed in html>`
3651       * will create a comment whose text content starts with `?`. Note that if
3652       * that character were modified, it would be possible to change the node
3653       * type.
3654       *
3655       * @since 6.7.0
3656       *
3657       * @return string|null The comment text as it would appear in the browser or null
3658       *                     if not on a comment type node.
3659       */
3660  	public function get_full_comment_text(): ?string {
3661          if ( self::STATE_FUNKY_COMMENT === $this->parser_state ) {
3662              return $this->get_modifiable_text();
3663          }
3664  
3665          if ( self::STATE_COMMENT !== $this->parser_state ) {
3666              return null;
3667          }
3668  
3669          switch ( $this->get_comment_type() ) {
3670              case self::COMMENT_AS_HTML_COMMENT:
3671              case self::COMMENT_AS_ABRUPTLY_CLOSED_COMMENT:
3672                  return $this->get_modifiable_text();
3673  
3674              case self::COMMENT_AS_CDATA_LOOKALIKE:
3675                  return "[CDATA[{$this->get_modifiable_text()}]]";
3676  
3677              case self::COMMENT_AS_PI_NODE_LOOKALIKE:
3678                  return "?{$this->get_tag()}{$this->get_modifiable_text()}?";
3679  
3680              /*
3681               * This represents "bogus comments state" from HTML tokenization.
3682               * This can be entered by `<?` or `<!`, where `?` is included in
3683               * the comment text but `!` is not.
3684               */
3685              case self::COMMENT_AS_INVALID_HTML:
3686                  $preceding_character = $this->html[ $this->text_starts_at - 1 ];
3687                  $comment_start       = '?' === $preceding_character ? '?' : '';
3688                  return "{$comment_start}{$this->get_modifiable_text()}";
3689          }
3690  
3691          return null;
3692      }
3693  
3694      /**
3695       * Subdivides a matched text node, splitting NULL byte sequences and decoded whitespace as
3696       * distinct nodes prefixes.
3697       *
3698       * Note that once anything that's neither a NULL byte nor decoded whitespace is
3699       * encountered, then the remainder of the text node is left intact as generic text.
3700       *
3701       *  - The HTML Processor uses this to apply distinct rules for different kinds of text.
3702       *  - Inter-element whitespace can be detected and skipped with this method.
3703       *
3704       * Text nodes aren't eagerly subdivided because there's no need to split them unless
3705       * decisions are being made on NULL byte sequences or whitespace-only text.
3706       *
3707       * Example:
3708       *
3709       *     $processor = new WP_HTML_Tag_Processor( "\x00Apples & Oranges" );
3710       *     true  === $processor->next_token();                   // Text is "Apples & Oranges".
3711       *     true  === $processor->subdivide_text_appropriately(); // Text is "".
3712       *     true  === $processor->next_token();                   // Text is "Apples & Oranges".
3713       *     false === $processor->subdivide_text_appropriately();
3714       *
3715       *     $processor = new WP_HTML_Tag_Processor( "&#xD; \r\n\tMore" );
3716       *     true  === $processor->next_token();                   // Text is "␍ ␊␉More".
3717       *     true  === $processor->subdivide_text_appropriately(); // Text is "␍ ␊␉".
3718       *     true  === $processor->next_token();                   // Text is "More".
3719       *     false === $processor->subdivide_text_appropriately();
3720       *
3721       * @since 6.7.0
3722       *
3723       * @return bool Whether the text node was subdivided.
3724       */
3725  	public function subdivide_text_appropriately(): bool {
3726          if ( self::STATE_TEXT_NODE !== $this->parser_state ) {
3727              return false;
3728          }
3729  
3730          $this->text_node_classification = self::TEXT_IS_GENERIC;
3731  
3732          /*
3733           * NULL bytes are treated categorically different than numeric character
3734           * references whose number is zero. `&#x00;` is not the same as `"\x00"`.
3735           */
3736          $leading_nulls = strspn( $this->html, "\x00", $this->text_starts_at, $this->text_length );
3737          if ( $leading_nulls > 0 ) {
3738              $this->token_length             = $leading_nulls;
3739              $this->text_length              = $leading_nulls;
3740              $this->bytes_already_parsed     = $this->token_starts_at + $leading_nulls;
3741              $this->text_node_classification = self::TEXT_IS_NULL_SEQUENCE;
3742              return true;
3743          }
3744  
3745          /*
3746           * Start a decoding loop to determine the point at which the
3747           * text subdivides. This entails raw whitespace bytes and any
3748           * character reference that decodes to the same.
3749           */
3750          $at  = $this->text_starts_at;
3751          $end = $this->text_starts_at + $this->text_length;
3752          while ( $at < $end ) {
3753              $skipped = strspn( $this->html, " \t\f\r\n", $at, $end - $at );
3754              $at     += $skipped;
3755  
3756              if ( $at < $end && '&' === $this->html[ $at ] ) {
3757                  $matched_byte_length = null;
3758                  $replacement         = WP_HTML_Decoder::read_character_reference( 'data', $this->html, $at, $matched_byte_length );
3759                  if ( isset( $replacement ) && 1 === strspn( $replacement, " \t\f\r\n" ) ) {
3760                      $at += $matched_byte_length;
3761                      continue;
3762                  }
3763              }
3764  
3765              break;
3766          }
3767  
3768          if ( $at > $this->text_starts_at ) {
3769              $new_length                     = $at - $this->text_starts_at;
3770              $this->text_length              = $new_length;
3771              $this->token_length             = $new_length;
3772              $this->bytes_already_parsed     = $at;
3773              $this->text_node_classification = self::TEXT_IS_WHITESPACE;
3774              return true;
3775          }
3776  
3777          return false;
3778      }
3779  
3780      /**
3781       * Returns the modifiable text for a matched token, or an empty string.
3782       *
3783       * Modifiable text is text content that may be read and changed without
3784       * changing the HTML structure of the document around it. This includes
3785       * the contents of `#text` nodes in the HTML as well as the inner
3786       * contents of HTML comments, Processing Instructions, and others, even
3787       * though these nodes aren't part of a parsed DOM tree. They also contain
3788       * the contents of SCRIPT and STYLE tags, of TEXTAREA tags, and of any
3789       * other section in an HTML document which cannot contain HTML markup (DATA).
3790       *
3791       * If a token has no modifiable text then an empty string is returned to
3792       * avoid needless crashing or type errors. An empty string does not mean
3793       * that a token has modifiable text, and a token with modifiable text may
3794       * have an empty string (e.g. a comment with no contents).
3795       *
3796       * Limitations:
3797       *
3798       *  - This function will not strip the leading newline appropriately
3799       *    after seeking into a LISTING or PRE element. To ensure that the
3800       *    newline is treated properly, seek to the LISTING or PRE opening
3801       *    tag instead of to the first text node inside the element.
3802       *
3803       * @since 6.5.0
3804       * @since 6.7.0 Replaces NULL bytes (U+0000) and newlines appropriately.
3805       *
3806       * @return string
3807       */
3808  	public function get_modifiable_text(): string {
3809          $has_enqueued_update = isset( $this->lexical_updates['modifiable text'] );
3810  
3811          if ( ! $has_enqueued_update && ( null === $this->text_starts_at || 0 === $this->text_length ) ) {
3812              return '';
3813          }
3814  
3815          $text = $has_enqueued_update
3816              ? $this->lexical_updates['modifiable text']->text
3817              : substr( $this->html, $this->text_starts_at, $this->text_length );
3818  
3819          /*
3820           * An enqueued processing instruction update holds normalized raw
3821           * syntax spanning from the end of the target through the end of
3822           * the token: a separating space, the data, and the `?>` closer.
3823           * The data is found by skipping the leading whitespace and
3824           * dropping the two bytes of the closer.
3825           *
3826           * @see WP_HTML_Tag_Processor::set_modifiable_text()
3827           */
3828          if ( $has_enqueued_update && self::STATE_PROCESSING_INSTRUCTION === $this->parser_state ) {
3829              $text = substr( $text, strspn( $text, " \t\f\r\n" ), -2 );
3830          }
3831  
3832          /*
3833           * Pre-processing the input stream would normally happen before
3834           * any parsing is done, but deferring it means it's possible to
3835           * skip in most cases. When getting the modifiable text, however
3836           * it's important to apply the pre-processing steps, which is
3837           * normalizing newlines.
3838           *
3839           * @see https://html.spec.whatwg.org/#preprocessing-the-input-stream
3840           * @see https://infra.spec.whatwg.org/#normalize-newlines
3841           */
3842          $text = str_replace( "\r\n", "\n", $text );
3843          $text = str_replace( "\r", "\n", $text );
3844  
3845          // Comment and processing instruction data is not decoded.
3846          if (
3847              self::STATE_CDATA_NODE === $this->parser_state ||
3848              self::STATE_COMMENT === $this->parser_state ||
3849              self::STATE_DOCTYPE === $this->parser_state ||
3850              self::STATE_FUNKY_COMMENT === $this->parser_state ||
3851              self::STATE_PROCESSING_INSTRUCTION === $this->parser_state
3852          ) {
3853              return str_replace( "\x00", "\u{FFFD}", $text );
3854          }
3855  
3856          $tag_name = $this->get_token_name();
3857          if (
3858              // Script data is not decoded.
3859              'SCRIPT' === $tag_name ||
3860  
3861              // RAWTEXT data is not decoded.
3862              'IFRAME' === $tag_name ||
3863              'NOEMBED' === $tag_name ||
3864              'NOFRAMES' === $tag_name ||
3865              'STYLE' === $tag_name ||
3866              'XMP' === $tag_name
3867          ) {
3868              return str_replace( "\x00", "\u{FFFD}", $text );
3869          }
3870  
3871          $decoded = WP_HTML_Decoder::decode_text_node( $text );
3872  
3873          /*
3874           * Skip the first line feed after LISTING, PRE, and TEXTAREA opening tags.
3875           *
3876           * Note that this first newline may come in the form of a character
3877           * reference, such as `&#x0a;`, and so it's important to perform
3878           * this transformation only after decoding the raw text content.
3879           */
3880          if (
3881              ( "\n" === ( $decoded[0] ?? '' ) ) &&
3882              ( ( $this->skip_newline_at === $this->token_starts_at && '#text' === $tag_name ) || 'TEXTAREA' === $tag_name )
3883          ) {
3884              $decoded = substr( $decoded, 1 );
3885          }
3886  
3887          /*
3888           * Only in normative text nodes does the NULL byte (U+0000) get removed.
3889           * In all other contexts it's replaced by the replacement character (U+FFFD)
3890           * for security reasons (to avoid joining together strings that were safe
3891           * when separated, but not when joined).
3892           *
3893           * @todo Inside HTML integration points and MathML integration points, the
3894           *       text is processed according to the insertion mode, not according
3895           *       to the foreign content rules. This should strip the NULL bytes.
3896           */
3897          return ( '#text' === $tag_name && 'html' === $this->get_namespace() )
3898              ? str_replace( "\x00", '', $decoded )
3899              : str_replace( "\x00", "\u{FFFD}", $decoded );
3900      }
3901  
3902      /**
3903       * Sets the modifiable text for the matched token, if matched.
3904       *
3905       * Modifiable text is text content that may be read and changed without
3906       * changing the HTML structure of the document around it. This includes
3907       * the contents of `#text` nodes in the HTML as well as the inner
3908       * contents of HTML comments, Processing Instructions, and others, even
3909       * though these nodes aren't part of a parsed DOM tree. They also contain
3910       * the contents of SCRIPT and STYLE tags, of TEXTAREA tags, and of any
3911       * other section in an HTML document which cannot contain HTML markup (DATA).
3912       *
3913       * Not all modifiable text may be set by this method, and not all content
3914       * may be set as modifiable text. In the case that this fails it will return
3915       * `false` indicating as much. For instance, if the contents of a SCRIPT
3916       * element are neither JavaScript nor JSON, it’s not possible to guarantee
3917       * that escaping strings like `</script>` won’t break the script; in these
3918       * cases, updates will be rejected and it’s up to calling code to perform
3919       * language-specific escaping or workarounds. Similarly, it will not allow
3920       * setting content into a comment which would prematurely terminate the comment,
3921       * or processing instruction data which cannot be represented: data containing
3922       * a `>`, which would prematurely terminate the processing instruction, or data
3923       * with leading whitespace, which is indistinguishable from the whitespace
3924       * separating the data from its target.
3925       *
3926       * Example:
3927       *
3928       *     // Add a preface to all STYLE contents.
3929       *     while ( $processor->next_tag( 'STYLE' ) ) {
3930       *         $style = $processor->get_modifiable_text();
3931       *         $processor->set_modifiable_text( "// Made with love on the World Wide Web\n{$style}" );
3932       *     }
3933       *
3934       *     // Replace smiley text with Emoji smilies.
3935       *     while ( $processor->next_token() ) {
3936       *         if ( '#text' !== $processor->get_token_name() ) {
3937       *             continue;
3938       *         }
3939       *
3940       *         $chunk = $processor->get_modifiable_text();
3941       *         if ( ! str_contains( $chunk, ':)' ) ) {
3942       *             continue;
3943       *         }
3944       *
3945       *         $processor->set_modifiable_text( str_replace( ':)', '🙂', $chunk ) );
3946       *     }
3947       *
3948       * This function handles all necessary HTML encoding. Provide normal, unescaped string values.
3949       * The HTML API will encode the strings appropriately so that the browser will interpret them
3950       * as the intended value.
3951       *
3952       * Example:
3953       *
3954       *     // Renders as “Eggs & Milk” in a browser, encoded as `<p>Eggs &amp; Milk</p>`.
3955       *     $processor->set_modifiable_text( 'Eggs & Milk' );
3956       *
3957       *     // Renders as “Eggs &amp; Milk” in a browser, encoded as `<p>Eggs &amp;amp; Milk</p>`.
3958       *     $processor->set_modifiable_text( 'Eggs &amp; Milk' );
3959       *
3960       * @since 6.7.0
3961       * @since 6.9.0 Escapes all character references instead of trying to avoid double-escaping.
3962       * @since 7.1.0 Supports setting processing instruction data.
3963       *
3964       * @param string $plaintext_content New text content to represent in the matched token.
3965       * @return bool Whether the text was able to update.
3966       */
3967  	public function set_modifiable_text( string $plaintext_content ): bool {
3968          if ( self::STATE_TEXT_NODE === $this->parser_state ) {
3969              $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement(
3970                  $this->text_starts_at,
3971                  $this->text_length,
3972                  strtr(
3973                      $plaintext_content,
3974                      array(
3975                          '<' => '&lt;',
3976                          '>' => '&gt;',
3977                          '&' => '&amp;',
3978                          '"' => '&quot;',
3979                          "'" => '&apos;',
3980                      )
3981                  )
3982              );
3983  
3984              return true;
3985          }
3986  
3987          // Comment data is not encoded.
3988          if (
3989              self::STATE_COMMENT === $this->parser_state &&
3990              self::COMMENT_AS_HTML_COMMENT === $this->comment_type
3991          ) {
3992              // Check if the text could close the comment.
3993              if ( 1 === preg_match( '/--!?>/', $plaintext_content ) ) {
3994                  _doing_it_wrong(
3995                      __METHOD__,
3996                      __( 'Comment text cannot contain a comment closer.' ),
3997                      '7.1.0'
3998                  );
3999                  return false;
4000              }
4001  
4002              $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement(
4003                  $this->text_starts_at,
4004                  $this->text_length,
4005                  $plaintext_content
4006              );
4007  
4008              return true;
4009          }
4010  
4011          // Processing instruction data is not encoded.
4012          if ( self::STATE_PROCESSING_INSTRUCTION === $this->parser_state ) {
4013              /*
4014               * A processing instruction ends at the first `>` in its
4015               * raw syntax: data containing one cannot be represented.
4016               */
4017              if ( str_contains( $plaintext_content, '>' ) ) {
4018                  _doing_it_wrong(
4019                      __METHOD__,
4020                      __( 'Processing instruction data cannot contain ">".' ),
4021                      '7.1.0'
4022                  );
4023                  return false;
4024              }
4025  
4026              /*
4027               * All whitespace between the target and the data is skipped when
4028               * parsing: data with leading whitespace cannot be represented.
4029               */
4030              if ( 0 !== strspn( $plaintext_content, " \t\f\r\n" ) ) {
4031                  _doing_it_wrong(
4032                      __METHOD__,
4033                      __( 'Processing instruction data cannot start with whitespace. Try ltrim( $plaintext_content, " \t\f\r\n" ).' ),
4034                      '7.1.0'
4035                  );
4036                  return false;
4037              }
4038  
4039              /**
4040               * A single replacement spans from the end of the target through
4041               * the end of the token, normalizing the raw syntax for that
4042               * region into a fixed form: a separating space, the data, and
4043               * the `?>` closer.
4044               *
4045               * {@see self::get_modifiable_text()} performs necessary parsing to
4046               * return the correct processing instruction data based
4047               * on the modifiable text lexical update.
4048               */
4049              $data_at = $this->tag_name_starts_at + $this->tag_name_length;
4050  
4051              $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement(
4052                  $data_at,
4053                  $this->token_starts_at + $this->token_length - $data_at,
4054                  " {$plaintext_content}?>"
4055              );
4056  
4057              return true;
4058          }
4059  
4060          /*
4061           * The rest of this function handles modifiable text for special "atomic" HTML elements.
4062           * Only tags in the HTML namespace should be processed.
4063           */
4064          if (
4065              self::STATE_MATCHED_TAG !== $this->parser_state ||
4066              'html' !== $this->get_namespace()
4067          ) {
4068              _doing_it_wrong(
4069                  __METHOD__,
4070                  __( 'This token does not support setting modifiable text.' ),
4071                  '7.1.0'
4072              );
4073              return false;
4074          }
4075  
4076          switch ( $this->get_tag() ) {
4077              case 'SCRIPT':
4078                  $script_content_type = $this->get_script_content_type();
4079  
4080                  switch ( $script_content_type ) {
4081                      case 'javascript':
4082                      case 'json':
4083                          $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement(
4084                              $this->text_starts_at,
4085                              $this->text_length,
4086                              self::escape_javascript_script_contents( $plaintext_content )
4087                          );
4088                          return true;
4089                  }
4090  
4091                  /*
4092                   * If the script’s content type isn’t recognized and understandable then it’s
4093                   * impossible to guarantee that escaping the content won’t cause runtime breakage.
4094                   * For instance, if the script content type were PHP code then escaping with
4095                   * `\u0073` would not be met by unescaping; rather, it could result in corrupted
4096                   * data or even syntax errors.
4097                   *
4098                   * Because of this, content which could potentially modify the SCRIPT tag’s
4099                   * HTML structure is rejected here. It’s the responsibility of calling code to
4100                   * perform whatever semantic escaping is necessary to avoid problematic strings.
4101                   */
4102                  if (
4103                      false !== stripos( $plaintext_content, '<script' ) ||
4104                      false !== stripos( $plaintext_content, '</script' )
4105                  ) {
4106                      _doing_it_wrong(
4107                          __METHOD__,
4108                          __( 'SCRIPT text with an unrecognized content type cannot contain a SCRIPT tag. Apply the escaping appropriate for the content type.' ),
4109                          '7.1.0'
4110                      );
4111                      return false;
4112                  }
4113                  $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement(
4114                      $this->text_starts_at,
4115                      $this->text_length,
4116                      $plaintext_content
4117                  );
4118                  return true;
4119  
4120              case 'IFRAME':
4121              case 'NOEMBED':
4122              case 'NOFRAMES':
4123              case 'XMP':
4124                  $tag_name = $this->get_tag();
4125                  if ( false !== stripos( $plaintext_content, "</{$tag_name}" ) ) {
4126                      _doing_it_wrong(
4127                          __METHOD__,
4128                          sprintf(
4129                              /* translators: %s: HTML tag name. */
4130                              __( '%s text cannot contain its own closing tag.' ),
4131                              $tag_name
4132                          ),
4133                          '7.1.0'
4134                      );
4135                      return false;
4136                  }
4137  
4138                  $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement(
4139                      $this->text_starts_at,
4140                      $this->text_length,
4141                      $plaintext_content
4142                  );
4143  
4144                  return true;
4145  
4146              case 'STYLE':
4147                  $plaintext_content = preg_replace_callback(
4148                      '~</(?P<TAG_NAME>style)~i',
4149                      static function ( $tag_match ) {
4150                          return "\\3c\\2f{$tag_match['TAG_NAME']}";
4151                      },
4152                      $plaintext_content
4153                  );
4154  
4155                  $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement(
4156                      $this->text_starts_at,
4157                      $this->text_length,
4158                      $plaintext_content
4159                  );
4160  
4161                  return true;
4162  
4163              case 'TEXTAREA':
4164              case 'TITLE':
4165                  $plaintext_content = preg_replace_callback(
4166                      "~</(?P<TAG_NAME>{$this->get_tag()})~i",
4167                      static function ( $tag_match ) {
4168                          return "&lt;/{$tag_match['TAG_NAME']}";
4169                      },
4170                      $plaintext_content
4171                  );
4172  
4173                  /*
4174                   * HTML ignores a single leading newline in this context. If a leading newline
4175                   * is intended, preserve it by adding an extra newline.
4176                   */
4177                  if (
4178                      'TEXTAREA' === $this->get_tag() &&
4179                      1 === strspn( $plaintext_content, "\n\r", 0, 1 )
4180                  ) {
4181                      $plaintext_content = "\n{$plaintext_content}";
4182                  }
4183  
4184                  /*
4185                   * These don't _need_ to be escaped, but since they are decoded it's
4186                   * safe to leave them escaped and this can prevent other code from
4187                   * naively detecting tags within the contents.
4188                   *
4189                   * @todo It would be useful to prefix a multiline replacement text
4190                   *       with a newline, but not necessary. This is for aesthetics.
4191                   */
4192                  $this->lexical_updates['modifiable text'] = new WP_HTML_Text_Replacement(
4193                      $this->text_starts_at,
4194                      $this->text_length,
4195                      $plaintext_content
4196                  );
4197  
4198                  return true;
4199          }
4200  
4201          _doing_it_wrong(
4202              __METHOD__,
4203              __( 'Only the IFRAME, NOEMBED, NOFRAMES, SCRIPT, STYLE, TEXTAREA, TITLE, and XMP tags support setting modifiable text.' ),
4204              '7.1.0'
4205          );
4206          return false;
4207      }
4208  
4209      /**
4210       * Returns the content type of the currently-matched HTML SCRIPT tag, if matched and
4211       * recognized, otherwise returns `null` to indicate an unrecognized content type.
4212       *
4213       * An HTML SCRIPT tag is a normal SCRIPT tag, but there can be SCRIPT elements inside
4214       * SVG and MathML elements as well, and these have different parsing rules than those
4215       * in general HTML. For this reason, no content-type inference is performed on those.
4216       *
4217       * Note! This concept is related but distinct from the MIME type of the script.
4218       * Parsing MUST match the specific algorithm in the HTML specification, which
4219       * relies on exact string comparison in some cases. MIME type decoding may be
4220       * performed on SVG or MathML SCRIPT tags.
4221       *
4222       * Only 'javascript' and 'json' content types are currently recognized.
4223       *
4224       * @see https://html.spec.whatwg.org/multipage/scripting.html#prepare-the-script-element
4225       *
4226       * @since 7.0.0
4227       * @ignore
4228       *
4229       * @return 'javascript'|'json'|null Type of script element content if matched and recognized.
4230       */
4231  	private function get_script_content_type(): ?string {
4232          // SVG and MathML SCRIPT elements are not recognized.
4233          if ( 'SCRIPT' !== $this->get_tag() || $this->get_namespace() !== 'html' ) {
4234              return null;
4235          }
4236  
4237          /*
4238           * > If any of the following are true:
4239           * >   - el has a type attribute whose value is the empty string;
4240           * >   - el has no type attribute but it has a language attribute and that attribute's
4241           * >     value is the empty string; or
4242           * >   - el has neither a type attribute nor a language attribute,
4243           * > then let the script block's type string for this script element be "text/javascript".
4244           */
4245          $type = $this->get_attribute( 'type' );
4246          $lang = $this->get_attribute( 'language' );
4247  
4248          if ( true === $type || '' === $type ) {
4249              return 'javascript';
4250          }
4251  
4252          if ( null === $type && ( null === $lang || true === $lang || '' === $lang ) ) {
4253              return 'javascript';
4254          }
4255  
4256          /*
4257           * > Otherwise, if el has a type attribute, then let the script block's type string be
4258           * > the value of that attribute with leading and trailing ASCII whitespace stripped.
4259           * > Otherwise, el has a non-empty language attribute; let the script block's type string
4260           * > be the concatenation of "text/" and the value of el's language attribute.
4261           */
4262          $type_string = is_string( $type ) ? trim( $type, " \t\f\r\n" ) : "text/{$lang}";
4263  
4264          // All matches are ASCII case-insensitive; eagerly lower-case for comparison.
4265          $type_string = strtolower( $type_string );
4266  
4267          /*
4268           * > If the script block's type string is a JavaScript MIME type essence match, then
4269           * > set el's type to "classic".
4270           *
4271           * > A string is a JavaScript MIME type essence match if it is an ASCII case-insensitive
4272           * > match for one of the JavaScript MIME type essence strings.
4273           *
4274           * > A JavaScript MIME type is any MIME type whose essence is one of the following:
4275           * >
4276           * > - application/ecmascript
4277           * > - application/javascript
4278           * > - application/x-ecmascript
4279           * > - application/x-javascript
4280           * > - text/ecmascript
4281           * > - text/javascript
4282           * > - text/javascript1.0
4283           * > - text/javascript1.1
4284           * > - text/javascript1.2
4285           * > - text/javascript1.3
4286           * > - text/javascript1.4
4287           * > - text/javascript1.5
4288           * > - text/jscript
4289           * > - text/livescript
4290           * > - text/x-ecmascript
4291           * > - text/x-javascript
4292           *
4293           * @see https://mimesniff.spec.whatwg.org/#javascript-mime-type-essence-match
4294           * @see https://mimesniff.spec.whatwg.org/#javascript-mime-type
4295           */
4296          switch ( $type_string ) {
4297              case 'application/ecmascript':
4298              case 'application/javascript':
4299              case 'application/x-ecmascript':
4300              case 'application/x-javascript':
4301              case 'text/ecmascript':
4302              case 'text/javascript':
4303              case 'text/javascript1.0':
4304              case 'text/javascript1.1':
4305              case 'text/javascript1.2':
4306              case 'text/javascript1.3':
4307              case 'text/javascript1.4':
4308              case 'text/javascript1.5':
4309              case 'text/jscript':
4310              case 'text/livescript':
4311              case 'text/x-ecmascript':
4312              case 'text/x-javascript':
4313                  return 'javascript';
4314  
4315              /*
4316               * > Otherwise, if the script block's type string is an ASCII case-insensitive match for
4317               * > the string "module", then set el's type to "module".
4318               *
4319               * A module is evaluated as JavaScript.
4320               */
4321              case 'module':
4322                  return 'javascript';
4323  
4324              /*
4325               * > 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".
4326               * > 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".
4327               *
4328               * These conditions indicate JSON content.
4329               */
4330              case 'importmap':
4331              case 'speculationrules':
4332                  return 'json';
4333  
4334              /** @todo Rely on a full MIME parser for determining JSON content. */
4335              case 'application/json':
4336              case 'text/json':
4337                  return 'json';
4338          }
4339  
4340          /*
4341           * > Otherwise, return. (No script is executed, and el's type is left as null.)
4342           */
4343          return null;
4344      }
4345  
4346      /**
4347       * Escape JavaScript and JSON script tag contents.
4348       *
4349       * Ensure that the script contents cannot modify the HTML structure or break out
4350       * of its containing SCRIPT element. JavaScript and JSON may both be escaped with
4351       * the same rules, even though there are additional escaping measures available
4352       * to JavaScript source code which aren’t applicable to serialized JSON data.
4353       *
4354       * A simple method safely escapes all content except for a few extremely rare and
4355       * unlikely exceptions: prevent the appearance of `<script` and `</script` within
4356       * the contents by replacing the first letter of the tag name with a Unicode escape.
4357       *
4358       * Example:
4359       *
4360       *     $plaintext = '<script>document.write( "A </script> closes a script." );</script>';
4361       *     $escaped   = '<script>document.write( "A </\u0073cript> closes a script." );</script>';
4362       *
4363       * This works because of how parsing changes after encountering an opening SCRIPT
4364       * tag. The actual parsing comprises a complicated state machine, the result of
4365       * legacy behaviors and diverse browser support. However, without these two strings
4366       * in the script contents, two key things are ensured: `</script>` cannot appear to
4367       * prematurely close the tag, and the problematic double-escaped state becomes
4368       * unreachable. A JavaScript engine or JSON decoder will then decode the Unicode
4369       * escape (`\u0073`) back into its original plaintext value, but only after having
4370       * been safely extracted from the HTML.
4371       *
4372       * While it may seem tempting to replace the `<` character instead, doing so would
4373       * break JavaScript syntax. The `<` character is used in comparison operators and
4374       * other JavaScript syntax; replacing it would break valid JavaScript. Replacing
4375       * only the `s` in `<script` and `</script` avoids modifying JavaScript syntax.
4376       *
4377       * ### Exceptions
4378       *
4379       * This _should_ work everywhere, but there are some extreme exceptions.
4380       *
4381       *  - Comments.
4382       *  - Tagged templates, such as `String.raw()`, which provide access to “raw” strings.
4383       *  - The `source` property of a RegExp object.
4384       *
4385       * Each of these exceptions appear at the source code level, not at the semantic or
4386       * evaluation level. Normal JavaScript will remain semantically equivalent after escaping,
4387       * but any JavaScript which analyzes the raw source code will see potentially-different
4388       * values.
4389       *
4390       * #### Comments
4391       *
4392       * Comments are never unescaped because they aren’t parsed by the JavaScript engine.
4393       * When viewing the source in a browser’s developer tools, the comments will retain
4394       * their escaped text.
4395       *
4396       * Example:
4397       *
4398       *     // A comment: "</script>"
4399       *         …becomes…
4400       *     // A comment: "</\u0073cript>"
4401       *
4402       * #### Tagged templates.
4403       *
4404       * Tagged templates “enable the embedding of arbitrary string content, where escape
4405       * sequences may follow a different syntax.” For example, they can aid representing
4406       * a RegExp pattern or LaTex snippet within a JavaScript string, where the string
4407       * escape characters might get noisy and distracting.
4408       *
4409       * Example:
4410       *
4411       *     console.log( 'A \notin B' );           // Prints a newline because of the "\n".
4412       *     console.log( 'A \\notin B' );          // Prints "A \notin B".
4413       *     console.log( String.raw`A \notin B` ); // Prints "A \notin B".
4414       *
4415       * This means that if `<script` transforms into `<\u0073cript` _inside_ a raw string
4416       * or tagged template literal which relies on its `.raw` property, the output of the
4417       * code will be different after escaping.
4418       *
4419       * Example:
4420       *
4421       *     console.log( String.raw`</script>` );      // Prematurely closes the SCRIPT element.
4422       *     console.log( String.raw`</\u0073cript>` ); // Prints "</\u0073cript".
4423       *
4424       * #### RegExp sources.
4425       *
4426       * The RegExp object exposes its raw source in a similar way to how tagged templates and raw
4427       * strings do. Thankfully, because escape sequences are decoded when compiling the pattern,
4428       * escaped RegExp patterns will match the same way as the plaintext sequences would.
4429       *
4430       * Example:
4431       *
4432       *     true === /<script>/.test( '<script>' );
4433       *     true === /<\u0073cript>/.test( '<script>' );
4434       *
4435       * However, as with raw strings, any code which reads the source will see the escaped value
4436       * instead of the decoded one.
4437       *
4438       * Example:
4439       *
4440       *     console.log( /<script>/.source );      // Prints "<script>".
4441       *     console.log( /<\u0073cript>/.source ); // Prints "<\u0073cript>".
4442       *
4443       * #### Unsupported escaping.
4444       *
4445       * It is not possible to properly represent every possible JavaScript source file
4446       * inside a SCRIPT element. As with CSS stylesheets, SVG images, and MathML, the
4447       * only 100% reliable way to represent all possible inputs is to link to external
4448       * files of the given content-type.
4449       *
4450       * In some cases it’s possible to manually prevent escaping issues. These are not
4451       * automatically handled by this function because doing so would require a full
4452       * JavaScript tokenizer. Consider the following example listing various ways to
4453       * manually escape a closing script tag.
4454       *
4455       * Example:
4456       *
4457       *     console.log( String.raw`</script>` );                // !!UNSAFE!! Will be escaped.
4458       *     console.log( String.raw`</\u0073cript>` );           // "</\u0073cript>"
4459       *     console.log( String.raw`</scr` + String.raw`ipt>` ); // "</script>"
4460       *     console.log( String.raw`</${"script"}>` );           // "</script>"
4461       *     console.log( '</scr' + 'ipt>' );                     // "</script>"
4462       *     console.log( "\x3C/script>" );                       // "</script>"
4463       *     console.log( "<\/script>" );                         // "</script>"
4464       *
4465       * The following graph is a simplified interpretation of how HTML interprets the contents
4466       * of a SCRIPT tag and identifies the closing tag. It is useful to understand what text
4467       * is dangerous inside of a SCRIPT tag and why different approaches to escaping work.
4468       *
4469       *                                 Open script
4470       *                                     │
4471       *                                     ▼
4472       *                  ╔═════════════════════════════════════════╗   <!--(…)>
4473       *                  ║                                         ║   (all dashes)
4474       *                  ║                 script                  ╟────────────────╮
4475       *                  ║                  data                   ║                │
4476       *      ╭───────────╢                                         ║ ◀──────────────╯
4477       *      │           ╚═╤═══════════════════════════════════════╝
4478       *      │             │               ▲                    ▲
4479       *      │             │ <!--          │ -->                ╰─────╮
4480       *      │             ▼               │                          │
4481       *      │           ┌─────────────────┴───────────────────────┐  │
4482       *      │ </script¹ │                 escaped                 │  │
4483       *      │           └─┬─────────────────────────────┬─────────┘  │
4484       *      │             │               ▲             │            │ -->
4485       *      │             │ </script¹     │ </script¹   │ <script¹   │
4486       *      │             ▼               │             ▼            │
4487       *      │           ╔══════════════╗  │           ┌───────────┐  │
4488       *      │           ║ Close script ║  │           │  double   │  │
4489       *      ╰──────────▶║              ║  ╰───────────┤  escaped  ├──╯
4490       *                  ╚══════════════╝              └───────────┘
4491       *
4492       *           ¹ = Case insensitive 'script' followed by one of ' \t\f\r\n/>', known
4493       *               as “tag-name-terminating characters.” This sequence forms the start
4494       *               of what could be a SCRIPT opening or closing tag.
4495       *
4496       * @see https://html.spec.whatwg.org/#restrictions-for-contents-of-script-elements
4497       * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#specifications
4498       * @see wp_html_api_script_element_escaping_diagram_source()
4499       *
4500       * @since 7.0.0
4501       * @ignore
4502       *
4503       * @param string $sourcecode Raw contents intended to be serialized into an HTML SCRIPT element.
4504       * @return string Escaped form of input contents which will not lead to premature closing of the containing SCRIPT element.
4505       */
4506  	private static function escape_javascript_script_contents( string $sourcecode ): string {
4507          $at      = 0;
4508          $was_at  = 0;
4509          $end     = strlen( $sourcecode );
4510          $escaped = '';
4511  
4512          /*
4513           * Replace all instances of the ASCII case-insensitive match of "<script"
4514           * and "</script", when followed by whitespace or "/" or ">", by using a
4515           * character replacement for the "s" (or the "S").
4516           */
4517          while ( $at < $end ) {
4518              $tag_at = strpos( $sourcecode, '<', $at );
4519              if ( false === $tag_at ) {
4520                  break;
4521              }
4522  
4523              $tag_name_at       = $tag_at + 1;
4524              $has_closing_slash = $tag_name_at < $end && '/' === $sourcecode[ $tag_name_at ];
4525              $tag_name_at      += $has_closing_slash ? 1 : 0;
4526  
4527              if ( 0 !== substr_compare( $sourcecode, 'script', $tag_name_at, 6, true ) ) {
4528                  $at = $tag_at + 1;
4529                  continue;
4530              }
4531  
4532              if ( 1 !== strspn( $sourcecode, " \t\f\r\n/>", $tag_name_at + 6, 1 ) ) {
4533                  $at = $tag_name_at + 6;
4534                  continue;
4535              }
4536  
4537              $escaped .= substr( $sourcecode, $was_at, $tag_name_at - $was_at );
4538              $escaped .= 's' === $sourcecode[ $tag_name_at ] ? '\u0073' : '\u0053';
4539              $was_at   = $tag_name_at + 1;
4540              $at       = $tag_name_at + 7;
4541          }
4542  
4543          if ( '' === $escaped ) {
4544              return $sourcecode;
4545          }
4546  
4547          if ( $was_at < $end ) {
4548              $escaped .= substr( $sourcecode, $was_at );
4549          }
4550  
4551          return $escaped;
4552      }
4553  
4554      /**
4555       * Updates or creates a new attribute on the currently matched tag with the passed value.
4556       *
4557       * This function handles all necessary HTML encoding. Provide normal, unescaped string values.
4558       * The HTML API will encode the strings appropriately so that the browser will interpret them
4559       * as the intended value.
4560       *
4561       * Example:
4562       *
4563       *     // Renders “Eggs & Milk” in a browser, encoded as `<abbr title="Eggs &amp; Milk">`.
4564       *     $processor->set_attribute( 'title', 'Eggs & Milk' );
4565       *
4566       *     // Renders “Eggs &amp; Milk” in a browser, encoded as `<abbr title="Eggs &amp;amp; Milk">`.
4567       *     $processor->set_attribute( 'title', 'Eggs &amp; Milk' );
4568       *
4569       *     // Renders `true` as `<abbr title>`.
4570       *     $processor->set_attribute( 'title', true );
4571       *
4572       *     // Renders without the attribute for `false` as `<abbr>`.
4573       *     $processor->set_attribute( 'title', false );
4574       *
4575       * Special handling is provided for boolean attribute values:
4576       *  - When `true` is passed as the value, then only the attribute name is added to the tag.
4577       *  - When `false` is passed, the attribute gets removed if it existed before.
4578       *
4579       * @since 6.2.0
4580       * @since 6.2.1 Fix: Only create a single update for multiple calls with case-variant attribute names.
4581       * @since 6.9.0 Escapes all character references instead of trying to avoid double-escaping.
4582       *
4583       * @param string      $name  The attribute name to target.
4584       * @param string|bool $value The new attribute value.
4585       * @return bool Whether an attribute value was set.
4586       */
4587  	public function set_attribute( $name, $value ): bool {
4588          if (
4589              self::STATE_MATCHED_TAG !== $this->parser_state ||
4590              $this->is_closing_tag
4591          ) {
4592              return false;
4593          }
4594  
4595          $name_length = strlen( $name );
4596  
4597          /**
4598           * WordPress rejects more characters than are strictly forbidden
4599           * in HTML5. This is to prevent additional security risks deeper
4600           * in the WordPress and plugin stack. Specifically the following
4601           * are not allowed to be set as part of an HTML attribute name:
4602           *
4603           *  - greater-than “>”
4604           *  - ampersand “&”
4605           *
4606           * @see https://html.spec.whatwg.org/#attributes-2
4607           */
4608          if (
4609              0 === $name_length ||
4610              // Syntax-like characters.
4611              strcspn( $name, '"\'>&</ =' ) !== $name_length ||
4612              // Control characters.
4613              strcspn(
4614                  $name,
4615                  "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F" .
4616                  "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"
4617              ) !== $name_length ||
4618              // Unicode noncharacters.
4619              wp_has_noncharacters( $name )
4620          ) {
4621              _doing_it_wrong(
4622                  __METHOD__,
4623                  __( 'Invalid attribute name.' ),
4624                  '6.2.0'
4625              );
4626  
4627              return false;
4628          }
4629  
4630          /*
4631           * > The values "true" and "false" are not allowed on boolean attributes.
4632           * > To represent a false value, the attribute has to be omitted altogether.
4633           *     - HTML5 spec, https://html.spec.whatwg.org/#boolean-attributes
4634           */
4635          if ( false === $value ) {
4636              return $this->remove_attribute( $name );
4637          }
4638  
4639          if ( true === $value ) {
4640              $updated_attribute = $name;
4641          } else {
4642              $comparable_name = strtolower( $name );
4643  
4644              /**
4645               * Escape attribute values appropriately.
4646               *
4647               * @see https://html.spec.whatwg.org/#attributes-3
4648               */
4649              $escaped_new_value = in_array( $comparable_name, wp_kses_uri_attributes(), true )
4650                  ? esc_url( $value )
4651                  : strtr(
4652                      $value,
4653                      array(
4654                          '<' => '&lt;',
4655                          '>' => '&gt;',
4656                          '&' => '&amp;',
4657                          '"' => '&quot;',
4658                          "'" => '&apos;',
4659                      )
4660                  );
4661  
4662              // If the escaping functions wiped out the update, reject it and indicate it was rejected.
4663              if ( '' === $escaped_new_value && '' !== $value ) {
4664                  return false;
4665              }
4666  
4667              $updated_attribute = "{$name}=\"{$escaped_new_value}\"";
4668          }
4669  
4670          /*
4671           * > There must never be two or more attributes on
4672           * > the same start tag whose names are an ASCII
4673           * > case-insensitive match for each other.
4674           *     - HTML 5 spec
4675           *
4676           * @see https://html.spec.whatwg.org/multipage/syntax.html#attributes-2:ascii-case-insensitive
4677           */
4678          $comparable_name = strtolower( $name );
4679  
4680          if ( isset( $this->attributes[ $comparable_name ] ) ) {
4681              /*
4682               * Update an existing attribute.
4683               *
4684               * Example – set attribute id to "new" in <div id="initial_id" />:
4685               *
4686               *     <div id="initial_id"/>
4687               *          ^-------------^
4688               *          start         end
4689               *     replacement: `id="new"`
4690               *
4691               *     Result: <div id="new"/>
4692               */
4693              $existing_attribute                        = $this->attributes[ $comparable_name ];
4694              $this->lexical_updates[ $comparable_name ] = new WP_HTML_Text_Replacement(
4695                  $existing_attribute->start,
4696                  $existing_attribute->length,
4697                  $updated_attribute
4698              );
4699          } else {
4700              /*
4701               * Create a new attribute at the tag's name end.
4702               *
4703               * Example – add attribute id="new" to <div />:
4704               *
4705               *     <div/>
4706               *         ^
4707               *         start and end
4708               *     replacement: ` id="new"`
4709               *
4710               *     Result: <div id="new"/>
4711               */
4712              $this->lexical_updates[ $comparable_name ] = new WP_HTML_Text_Replacement(
4713                  $this->tag_name_starts_at + $this->tag_name_length,
4714                  0,
4715                  ' ' . $updated_attribute
4716              );
4717          }
4718  
4719          /*
4720           * Any calls to update the `class` attribute directly should wipe out any
4721           * enqueued class changes from `add_class` and `remove_class`.
4722           */
4723          if ( 'class' === $comparable_name && ! empty( $this->classname_updates ) ) {
4724              $this->classname_updates = array();
4725          }
4726  
4727          return true;
4728      }
4729  
4730      /**
4731       * Remove an attribute from the currently-matched tag.
4732       *
4733       * @since 6.2.0
4734       *
4735       * @param string $name The attribute name to remove.
4736       * @return bool Whether an attribute was removed.
4737       */
4738  	public function remove_attribute( $name ): bool {
4739          if (
4740              self::STATE_MATCHED_TAG !== $this->parser_state ||
4741              $this->is_closing_tag
4742          ) {
4743              return false;
4744          }
4745  
4746          /*
4747           * > There must never be two or more attributes on
4748           * > the same start tag whose names are an ASCII
4749           * > case-insensitive match for each other.
4750           *     - HTML 5 spec
4751           *
4752           * @see https://html.spec.whatwg.org/multipage/syntax.html#attributes-2:ascii-case-insensitive
4753           */
4754          $name = strtolower( $name );
4755  
4756          /*
4757           * Any calls to update the `class` attribute directly should wipe out any
4758           * enqueued class changes from `add_class` and `remove_class`.
4759           */
4760          if ( 'class' === $name && count( $this->classname_updates ) !== 0 ) {
4761              $this->classname_updates = array();
4762          }
4763  
4764          /*
4765           * If updating an attribute that didn't exist in the input
4766           * document, then remove the enqueued update and move on.
4767           *
4768           * For example, this might occur when calling `remove_attribute()`
4769           * after calling `set_attribute()` for the same attribute
4770           * and when that attribute wasn't originally present.
4771           */
4772          if ( ! isset( $this->attributes[ $name ] ) ) {
4773              if ( isset( $this->lexical_updates[ $name ] ) ) {
4774                  unset( $this->lexical_updates[ $name ] );
4775              }
4776              return false;
4777          }
4778  
4779          /*
4780           * Removes an existing tag attribute.
4781           *
4782           * Example – remove the attribute id from <div id="main"/>:
4783           *    <div id="initial_id"/>
4784           *         ^-------------^
4785           *         start         end
4786           *    replacement: ``
4787           *
4788           *    Result: <div />
4789           */
4790          $this->lexical_updates[ $name ] = new WP_HTML_Text_Replacement(
4791              $this->attributes[ $name ]->start,
4792              $this->attributes[ $name ]->length,
4793              ''
4794          );
4795  
4796          // Removes any duplicated attributes if they were also present.
4797          foreach ( $this->duplicate_attributes[ $name ] ?? array() as $attribute_token ) {
4798              $this->lexical_updates[] = new WP_HTML_Text_Replacement(
4799                  $attribute_token->start,
4800                  $attribute_token->length,
4801                  ''
4802              );
4803          }
4804  
4805          return true;
4806      }
4807  
4808      /**
4809       * Adds a new class name to the currently matched tag.
4810       *
4811       * @since 6.2.0
4812       *
4813       * @param string $class_name The class name to add.
4814       * @return bool Whether the class was set to be added.
4815       */
4816  	public function add_class( $class_name ): bool {
4817          if (
4818              self::STATE_MATCHED_TAG !== $this->parser_state ||
4819              $this->is_closing_tag
4820          ) {
4821              return false;
4822          }
4823  
4824          if ( self::QUIRKS_MODE !== $this->compat_mode ) {
4825              $this->classname_updates[ $class_name ] = self::ADD_CLASS;
4826              return true;
4827          }
4828  
4829          /*
4830           * Because class names are matched ASCII-case-insensitively in quirks mode,
4831           * this needs to see if a case variant of the given class name is already
4832           * enqueued and update that existing entry, if so. This picks the casing of
4833           * the first-provided class name for all lexical variations.
4834           */
4835          $class_name_length = strlen( $class_name );
4836          foreach ( $this->classname_updates as $updated_name => $action ) {
4837              if (
4838                  strlen( $updated_name ) === $class_name_length &&
4839                  0 === substr_compare( $updated_name, $class_name, 0, $class_name_length, true )
4840              ) {
4841                  $this->classname_updates[ $updated_name ] = self::ADD_CLASS;
4842                  return true;
4843              }
4844          }
4845  
4846          $this->classname_updates[ $class_name ] = self::ADD_CLASS;
4847          return true;
4848      }
4849  
4850      /**
4851       * Removes a class name from the currently matched tag.
4852       *
4853       * @since 6.2.0
4854       *
4855       * @param string $class_name The class name to remove.
4856       * @return bool Whether the class was set to be removed.
4857       */
4858  	public function remove_class( $class_name ): bool {
4859          if (
4860              self::STATE_MATCHED_TAG !== $this->parser_state ||
4861              $this->is_closing_tag
4862          ) {
4863              return false;
4864          }
4865  
4866          if ( self::QUIRKS_MODE !== $this->compat_mode ) {
4867              $this->classname_updates[ $class_name ] = self::REMOVE_CLASS;
4868              return true;
4869          }
4870  
4871          /*
4872           * Because class names are matched ASCII-case-insensitively in quirks mode,
4873           * this needs to see if a case variant of the given class name is already
4874           * enqueued and update that existing entry, if so. This picks the casing of
4875           * the first-provided class name for all lexical variations.
4876           */
4877          $class_name_length = strlen( $class_name );
4878          foreach ( $this->classname_updates as $updated_name => $action ) {
4879              if (
4880                  strlen( $updated_name ) === $class_name_length &&
4881                  0 === substr_compare( $updated_name, $class_name, 0, $class_name_length, true )
4882              ) {
4883                  $this->classname_updates[ $updated_name ] = self::REMOVE_CLASS;
4884                  return true;
4885              }
4886          }
4887  
4888          $this->classname_updates[ $class_name ] = self::REMOVE_CLASS;
4889          return true;
4890      }
4891  
4892      /**
4893       * Returns the string representation of the HTML Tag Processor.
4894       *
4895       * @since 6.2.0
4896       *
4897       * @see WP_HTML_Tag_Processor::get_updated_html()
4898       *
4899       * @return string The processed HTML.
4900       */
4901  	public function __toString(): string {
4902          return $this->get_updated_html();
4903      }
4904  
4905      /**
4906       * Returns the string representation of the HTML Tag Processor.
4907       *
4908       * @since 6.2.0
4909       * @since 6.2.1 Shifts the internal cursor corresponding to the applied updates.
4910       * @since 6.4.0 No longer calls subclass method `next_tag()` after updating HTML.
4911       *
4912       * @return string The processed HTML.
4913       */
4914  	public function get_updated_html(): string {
4915          $requires_no_updating = 0 === count( $this->classname_updates ) && 0 === count( $this->lexical_updates );
4916  
4917          /*
4918           * When there is nothing more to update and nothing has already been
4919           * updated, return the original document and avoid a string copy.
4920           */
4921          if ( $requires_no_updating ) {
4922              return $this->html;
4923          }
4924  
4925          /*
4926           * Keep track of the position right before the current tag. This will
4927           * be necessary for reparsing the current tag after updating the HTML.
4928           */
4929          $before_current_tag = $this->token_starts_at ?? 0;
4930  
4931          /*
4932           * 1. Apply the enqueued edits and update all the pointers to reflect those changes.
4933           */
4934          $this->class_name_updates_to_attributes_updates();
4935          $before_current_tag += $this->apply_attributes_updates( $before_current_tag );
4936  
4937          /*
4938           * 2. Rewind to before the current tag and reparse to get updated attributes.
4939           *
4940           * At this point the internal cursor points to the end of the tag name.
4941           * Rewind before the tag name starts so that it's as if the cursor didn't
4942           * move; a call to `next_tag()` will reparse the recently-updated attributes
4943           * and additional calls to modify the attributes will apply at this same
4944           * location, but in order to avoid issues with subclasses that might add
4945           * behaviors to `next_tag()`, the internal methods should be called here
4946           * instead.
4947           *
4948           * It's important to note that in this specific place there will be no change
4949           * because the processor was already at a tag when this was called and it's
4950           * rewinding only to the beginning of this very tag before reprocessing it
4951           * and its attributes.
4952           *
4953           * <p>Previous HTML<em>More HTML</em></p>
4954           *                 ↑  │ back up by the length of the tag name plus the opening <
4955           *                 └←─┘ back up by strlen("em") + 1 ==> 3
4956           */
4957          $this->bytes_already_parsed = $before_current_tag;
4958          $this->base_class_next_token();
4959  
4960          return $this->html;
4961      }
4962  
4963      /**
4964       * Parses tag query input into internal search criteria.
4965       *
4966       * @since 6.2.0
4967       * @ignore
4968       *
4969       * @param array|string|null $query {
4970       *     Optional. Which tag name to find, having which class, etc. Default is to find any tag.
4971       *
4972       *     @type string|null $tag_name     Which tag to find, or `null` for "any tag."
4973       *     @type int|null    $match_offset Find the Nth tag matching all search criteria.
4974       *                                     1 for "first" tag, 3 for "third," etc.
4975       *                                     Defaults to first tag.
4976       *     @type string|null $class_name   Tag must contain this class name to match.
4977       *     @type string      $tag_closers  "visit" or "skip": whether to stop on tag closers, e.g. </div>.
4978       * }
4979       */
4980  	private function parse_query( $query ) {
4981          if ( null !== $query && $query === $this->last_query ) {
4982              return;
4983          }
4984  
4985          $this->last_query          = $query;
4986          $this->sought_tag_name     = null;
4987          $this->sought_class_name   = null;
4988          $this->sought_match_offset = 1;
4989          $this->stop_on_tag_closers = false;
4990  
4991          // A single string value means "find the tag of this name".
4992          if ( is_string( $query ) ) {
4993              $this->sought_tag_name = $query;
4994              return;
4995          }
4996  
4997          // An empty query parameter applies no restrictions on the search.
4998          if ( null === $query ) {
4999              return;
5000          }
5001  
5002          // If not using the string interface, an associative array is required.
5003          if ( ! is_array( $query ) ) {
5004              _doing_it_wrong(
5005                  __METHOD__,
5006                  __( 'The query argument must be an array or a tag name.' ),
5007                  '6.2.0'
5008              );
5009              return;
5010          }
5011  
5012          if ( isset( $query['tag_name'] ) && is_string( $query['tag_name'] ) ) {
5013              $this->sought_tag_name = $query['tag_name'];
5014          }
5015  
5016          if ( isset( $query['class_name'] ) && is_string( $query['class_name'] ) ) {
5017              $this->sought_class_name = $query['class_name'];
5018          }
5019  
5020          if ( isset( $query['match_offset'] ) && is_int( $query['match_offset'] ) && 0 < $query['match_offset'] ) {
5021              $this->sought_match_offset = $query['match_offset'];
5022          }
5023  
5024          if ( isset( $query['tag_closers'] ) ) {
5025              $this->stop_on_tag_closers = 'visit' === $query['tag_closers'];
5026          }
5027      }
5028  
5029  
5030      /**
5031       * Checks whether a given tag and its attributes match the search criteria.
5032       *
5033       * @since 6.2.0
5034       * @ignore
5035       *
5036       * @return bool Whether the given tag and its attribute match the search criteria.
5037       */
5038  	private function matches(): bool {
5039          if ( $this->is_closing_tag && ! $this->stop_on_tag_closers ) {
5040              return false;
5041          }
5042  
5043          // Does the tag name match the requested tag name in a case-insensitive manner?
5044          if ( isset( $this->sought_tag_name ) ) {
5045              $tag_name = $this->get_tag();
5046              if (
5047                  strlen( $this->sought_tag_name ) !== strlen( $tag_name ) ||
5048                  0 !== substr_compare( $tag_name, $this->sought_tag_name, 0, null, true )
5049              ) {
5050                  return false;
5051              }
5052          }
5053  
5054          if ( null !== $this->sought_class_name && ! $this->has_class( $this->sought_class_name ) ) {
5055              return false;
5056          }
5057  
5058          return true;
5059      }
5060  
5061      /**
5062       * Gets DOCTYPE declaration info from a DOCTYPE token.
5063       *
5064       * DOCTYPE tokens may appear in many places in an HTML document. In most places, they are
5065       * simply ignored. The main parsing functions find the basic shape of DOCTYPE tokens but
5066       * do not perform detailed parsing.
5067       *
5068       * This method can be called to perform a full parse of the DOCTYPE token and retrieve
5069       * its information.
5070       *
5071       * @return WP_HTML_Doctype_Info|null The DOCTYPE declaration information or `null` if not
5072       *                                   currently at a DOCTYPE node.
5073       */
5074  	public function get_doctype_info(): ?WP_HTML_Doctype_Info {
5075          if ( self::STATE_DOCTYPE !== $this->parser_state ) {
5076              return null;
5077          }
5078  
5079          return WP_HTML_Doctype_Info::from_doctype_token( substr( $this->html, $this->token_starts_at, $this->token_length ) );
5080      }
5081  
5082      /**
5083       * Parser Ready State.
5084       *
5085       * Indicates that the parser is ready to run and waiting for a state transition.
5086       * It may not have started yet, or it may have just finished parsing a token and
5087       * is ready to find the next one.
5088       *
5089       * @since 6.5.0
5090       *
5091       * @access private
5092       */
5093      const STATE_READY = 'STATE_READY';
5094  
5095      /**
5096       * Parser Complete State.
5097       *
5098       * Indicates that the parser has reached the end of the document and there is
5099       * nothing left to scan. It finished parsing the last token completely.
5100       *
5101       * @since 6.5.0
5102       *
5103       * @access private
5104       */
5105      const STATE_COMPLETE = 'STATE_COMPLETE';
5106  
5107      /**
5108       * Parser Incomplete Input State.
5109       *
5110       * Indicates that the parser has reached the end of the document before finishing
5111       * a token. It started parsing a token but there is a possibility that the input
5112       * HTML document was truncated in the middle of a token.
5113       *
5114       * The parser is reset at the start of the incomplete token and has paused. There
5115       * is nothing more than can be scanned unless provided a more complete document.
5116       *
5117       * @since 6.5.0
5118       *
5119       * @access private
5120       */
5121      const STATE_INCOMPLETE_INPUT = 'STATE_INCOMPLETE_INPUT';
5122  
5123      /**
5124       * Parser Matched Tag State.
5125       *
5126       * Indicates that the parser has found an HTML tag and it's possible to get
5127       * the tag name and read or modify its attributes (if it's not a closing tag).
5128       *
5129       * @since 6.5.0
5130       *
5131       * @access private
5132       */
5133      const STATE_MATCHED_TAG = 'STATE_MATCHED_TAG';
5134  
5135      /**
5136       * Parser Text Node State.
5137       *
5138       * Indicates that the parser has found a text node and it's possible
5139       * to read and modify that text.
5140       *
5141       * @since 6.5.0
5142       *
5143       * @access private
5144       */
5145      const STATE_TEXT_NODE = 'STATE_TEXT_NODE';
5146  
5147      /**
5148       * Parser CDATA Node State.
5149       *
5150       * Indicates that the parser has found a CDATA node and it's possible
5151       * to read and modify its modifiable text. Note that in HTML there are
5152       * no CDATA nodes outside of foreign content (SVG and MathML). Outside
5153       * of foreign content, they are treated as HTML comments.
5154       *
5155       * @since 6.5.0
5156       *
5157       * @access private
5158       */
5159      const STATE_CDATA_NODE = 'STATE_CDATA_NODE';
5160  
5161      /**
5162       * Indicates that the parser has found an HTML comment and it's
5163       * possible to read and modify its modifiable text.
5164       *
5165       * @since 6.5.0
5166       *
5167       * @access private
5168       */
5169      const STATE_COMMENT = 'STATE_COMMENT';
5170  
5171      /**
5172       * Indicates that the parser has found a DOCTYPE node and it's
5173       * possible to read its DOCTYPE information via `get_doctype_info()`.
5174       *
5175       * @since 6.5.0
5176       *
5177       * @access private
5178       */
5179      const STATE_DOCTYPE = 'STATE_DOCTYPE';
5180  
5181      /**
5182       * Indicates that the parser has found an empty tag closer `</>`.
5183       *
5184       * Note that in HTML there are no empty tag closers, and they
5185       * are ignored. Nonetheless, the Tag Processor still
5186       * recognizes them as they appear in the HTML stream.
5187       *
5188       * These were historically discussed as a "presumptuous tag
5189       * closer," which would close the nearest open tag, but were
5190       * dismissed in favor of explicitly-closing tags.
5191       *
5192       * @since 6.5.0
5193       *
5194       * @access private
5195       */
5196      const STATE_PRESUMPTUOUS_TAG = 'STATE_PRESUMPTUOUS_TAG';
5197  
5198      /**
5199       * Indicates that the parser has found a "funky comment"
5200       * and it's possible to read and modify its modifiable text.
5201       *
5202       * Example:
5203       *
5204       *     </%url>
5205       *     </{"wp-bit":"query/post-author"}>
5206       *     </2>
5207       *
5208       * Funky comments are tag closers with invalid tag names. Note
5209       * that in HTML these are turned into bogus comments. Nonetheless,
5210       * the Tag Processor recognizes them in a stream of HTML and
5211       * exposes them for inspection and modification.
5212       *
5213       * @since 6.5.0
5214       *
5215       * @access private
5216       */
5217      const STATE_FUNKY_COMMENT = 'STATE_WP_FUNKY';
5218  
5219      /**
5220       * Indicates that the parser has found a processing instruction
5221       * and it's possible to read its target and data.
5222       *
5223       * Example:
5224       *
5225       *     <?wp-bit {"just": "kidding"}>
5226       *
5227       * Processing instructions with an allowable target are parsed
5228       * into processing instruction nodes. The reserved `xml` and
5229       * `xml-stylesheet` targets, and targets with characters outside
5230       * an ASCII-representable subset, are turned into bogus comments.
5231       *
5232       * @link https://html.spec.whatwg.org/multipage/parsing.html#processing-instruction-open-state
5233       *
5234       * @since 7.1.0
5235       *
5236       * @access private
5237       */
5238      const STATE_PROCESSING_INSTRUCTION = 'STATE_PROCESSING_INSTRUCTION';
5239  
5240      /**
5241       * Indicates that a comment was created when encountering abruptly-closed HTML comment.
5242       *
5243       * Example:
5244       *
5245       *     <!-->
5246       *     <!--->
5247       *
5248       * @since 6.5.0
5249       */
5250      const COMMENT_AS_ABRUPTLY_CLOSED_COMMENT = 'COMMENT_AS_ABRUPTLY_CLOSED_COMMENT';
5251  
5252      /**
5253       * Indicates that a comment would be parsed as a CDATA node,
5254       * were HTML to allow CDATA nodes outside of foreign content.
5255       *
5256       * Example:
5257       *
5258       *     <![CDATA[This is a CDATA node.]]>
5259       *
5260       * This is an HTML comment, but it looks like a CDATA node.
5261       *
5262       * @since 6.5.0
5263       */
5264      const COMMENT_AS_CDATA_LOOKALIKE = 'COMMENT_AS_CDATA_LOOKALIKE';
5265  
5266      /**
5267       * Indicates that a comment was created when encountering
5268       * normative HTML comment syntax.
5269       *
5270       * Example:
5271       *
5272       *     <!-- this is a comment -->
5273       *
5274       * @since 6.5.0
5275       */
5276      const COMMENT_AS_HTML_COMMENT = 'COMMENT_AS_HTML_COMMENT';
5277  
5278      /**
5279       * Indicates that a comment would be parsed as a Processing
5280       * Instruction node, were its target allowed within HTML.
5281       *
5282       * Example:
5283       *
5284       *     <?xml version="1.0" ?>
5285       *     <?wp.like count=5 ?>
5286       *
5287       * These are HTML comments, but they look like processing
5288       * instructions. HTML parses processing instructions with
5289       * an allowable target into processing instruction nodes,
5290       * but the reserved `xml` and `xml-stylesheet` targets and
5291       * XML-valid targets with characters outside of the allowed
5292       * set become bogus comments instead.
5293       *
5294       * @since 6.5.0
5295       * @since 7.1.0 Only applies to reserved and XML-specific target names;
5296       *              other processing instructions produce their own token.
5297       */
5298      const COMMENT_AS_PI_NODE_LOOKALIKE = 'COMMENT_AS_PI_NODE_LOOKALIKE';
5299  
5300      /**
5301       * Indicates that a comment was created when encountering invalid
5302       * HTML input, a so-called "bogus comment."
5303       *
5304       * Example:
5305       *
5306       *     <?= nothing special ?>
5307       *     <!{nothing special}>
5308       *
5309       * @since 6.5.0
5310       */
5311      const COMMENT_AS_INVALID_HTML = 'COMMENT_AS_INVALID_HTML';
5312  
5313      /**
5314       * No-quirks mode document compatibility mode.
5315       *
5316       * > In no-quirks mode, the behavior is (hopefully) the desired behavior
5317       * > described by the modern HTML and CSS specifications.
5318       *
5319       * @see self::$compat_mode
5320       * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Quirks_Mode_and_Standards_Mode
5321       *
5322       * @since 6.7.0
5323       *
5324       * @var string
5325       */
5326      const NO_QUIRKS_MODE = 'no-quirks-mode';
5327  
5328      /**
5329       * Quirks mode document compatibility mode.
5330       *
5331       * > In quirks mode, layout emulates behavior in Navigator 4 and Internet
5332       * > Explorer 5. This is essential in order to support websites that were
5333       * > built before the widespread adoption of web standards.
5334       *
5335       * @see self::$compat_mode
5336       * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Quirks_Mode_and_Standards_Mode
5337       *
5338       * @since 6.7.0
5339       *
5340       * @var string
5341       */
5342      const QUIRKS_MODE = 'quirks-mode';
5343  
5344      /**
5345       * Indicates that a span of text may contain any combination of significant
5346       * kinds of characters: NULL bytes, whitespace, and others.
5347       *
5348       * @see self::$text_node_classification
5349       * @see self::subdivide_text_appropriately
5350       *
5351       * @since 6.7.0
5352       */
5353      const TEXT_IS_GENERIC = 'TEXT_IS_GENERIC';
5354  
5355      /**
5356       * Indicates that a span of text comprises a sequence only of NULL bytes.
5357       *
5358       * @see self::$text_node_classification
5359       * @see self::subdivide_text_appropriately
5360       *
5361       * @since 6.7.0
5362       */
5363      const TEXT_IS_NULL_SEQUENCE = 'TEXT_IS_NULL_SEQUENCE';
5364  
5365      /**
5366       * Indicates that a span of decoded text comprises only whitespace.
5367       *
5368       * @see self::$text_node_classification
5369       * @see self::subdivide_text_appropriately
5370       *
5371       * @since 6.7.0
5372       */
5373      const TEXT_IS_WHITESPACE = 'TEXT_IS_WHITESPACE';
5374  
5375      /**
5376       * Wakeup magic method.
5377       *
5378       * @since 6.9.2
5379       */
5380  	public function __wakeup() {
5381          throw new \LogicException( __CLASS__ . ' should never be unserialized' );
5382      }
5383  }


Generated : Sun Aug 16 08:20:24 2026 Cross-referenced by PHPXref