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


Generated : Sun Oct 25 08:20:35 2026 Cross-referenced by PHPXref