mirrored from git://develop.git.wordpress.org/
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathclass-wp-html-processor.php
6622 lines (5965 loc) · 207 KB
/
class-wp-html-processor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* HTML API: WP_HTML_Processor class
*
* @package WordPress
* @subpackage HTML-API
* @since 6.4.0
*/
/**
* Core class used to safely parse and modify an HTML document.
*
* The HTML Processor class properly parses and modifies HTML5 documents.
*
* It supports a subset of the HTML5 specification, and when it encounters
* unsupported markup, it aborts early to avoid unintentionally breaking
* the document. The HTML Processor should never break an HTML document.
*
* While the `WP_HTML_Tag_Processor` is a valuable tool for modifying
* attributes on individual HTML tags, the HTML Processor is more capable
* and useful for the following operations:
*
* - Querying based on nested HTML structure.
*
* Eventually the HTML Processor will also support:
* - Wrapping a tag in surrounding HTML.
* - Unwrapping a tag by removing its parent.
* - Inserting and removing nodes.
* - Reading and changing inner content.
* - Navigating up or around HTML structure.
*
* ## Usage
*
* Use of this class requires three steps:
*
* 1. Call a static creator method with your input HTML document.
* 2. Find the location in the document you are looking for.
* 3. Request changes to the document at that location.
*
* Example:
*
* $processor = WP_HTML_Processor::create_fragment( $html );
* if ( $processor->next_tag( array( 'breadcrumbs' => array( 'DIV', 'FIGURE', 'IMG' ) ) ) ) {
* $processor->add_class( 'responsive-image' );
* }
*
* #### Breadcrumbs
*
* Breadcrumbs represent the stack of open elements from the root
* of the document or fragment down to the currently-matched node,
* if one is currently selected. Call WP_HTML_Processor::get_breadcrumbs()
* to inspect the breadcrumbs for a matched tag.
*
* Breadcrumbs can specify nested HTML structure and are equivalent
* to a CSS selector comprising tag names separated by the child
* combinator, such as "DIV > FIGURE > IMG".
*
* Since all elements find themselves inside a full HTML document
* when parsed, the return value from `get_breadcrumbs()` will always
* contain any implicit outermost elements. For example, when parsing
* with `create_fragment()` in the `BODY` context (the default), any
* tag in the given HTML document will contain `array( 'HTML', 'BODY', … )`
* in its breadcrumbs.
*
* Despite containing the implied outermost elements in their breadcrumbs,
* tags may be found with the shortest-matching breadcrumb query. That is,
* `array( 'IMG' )` matches all IMG elements and `array( 'P', 'IMG' )`
* matches all IMG elements directly inside a P element. To ensure that no
* partial matches erroneously match it's possible to specify in a query
* the full breadcrumb match all the way down from the root HTML element.
*
* Example:
*
* $html = '<figure><img><figcaption>A <em>lovely</em> day outside</figcaption></figure>';
* // ----- Matches here.
* $processor->next_tag( array( 'breadcrumbs' => array( 'FIGURE', 'IMG' ) ) );
*
* $html = '<figure><img><figcaption>A <em>lovely</em> day outside</figcaption></figure>';
* // ---- Matches here.
* $processor->next_tag( array( 'breadcrumbs' => array( 'FIGURE', 'FIGCAPTION', 'EM' ) ) );
*
* $html = '<div><img></div><img>';
* // ----- Matches here, because IMG must be a direct child of the implicit BODY.
* $processor->next_tag( array( 'breadcrumbs' => array( 'BODY', 'IMG' ) ) );
*
* ## HTML Support
*
* This class implements a small part of the HTML5 specification.
* It's designed to operate within its support and abort early whenever
* encountering circumstances it can't properly handle. This is
* the principle way in which this class remains as simple as possible
* without cutting corners and breaking compliance.
*
* ### Supported elements
*
* If any unsupported element appears in the HTML input the HTML Processor
* will abort early and stop all processing. This draconian measure ensures
* that the HTML Processor won't break any HTML it doesn't fully understand.
*
* The HTML Processor supports all elements other than a specific set:
*
* - Any element inside a TABLE.
* - Any element inside foreign content, including SVG and MATH.
* - Any element outside the IN BODY insertion mode, e.g. doctype declarations, meta, links.
*
* ### Supported markup
*
* Some kinds of non-normative HTML involve reconstruction of formatting elements and
* re-parenting of mis-nested elements. For example, a DIV tag found inside a TABLE
* may in fact belong _before_ the table in the DOM. If the HTML Processor encounters
* such a case it will stop processing.
*
* The following list illustrates some common examples of unexpected HTML inputs that
* the HTML Processor properly parses and represents:
*
* - HTML with optional tags omitted, e.g. `<p>one<p>two`.
* - HTML with unexpected tag closers, e.g. `<p>one </span> more</p>`.
* - Non-void tags with self-closing flag, e.g. `<div/>the DIV is still open.</div>`.
* - Heading elements which close open heading elements of another level, e.g. `<h1>Closed by </h2>`.
* - Elements containing text that looks like other tags but isn't, e.g. `<title>The <img> is plaintext</title>`.
* - SCRIPT and STYLE tags containing text that looks like HTML but isn't, e.g. `<script>document.write('<p>Hi</p>');</script>`.
* - SCRIPT content which has been escaped, e.g. `<script><!-- document.write('<script>console.log("hi")</script>') --></script>`.
*
* ### Unsupported Features
*
* This parser does not report parse errors.
*
* Normally, when additional HTML or BODY tags are encountered in a document, if there
* are any additional attributes on them that aren't found on the previous elements,
* the existing HTML and BODY elements adopt those missing attribute values. This
* parser does not add those additional attributes.
*
* In certain situations, elements are moved to a different part of the document in
* a process called "adoption" and "fostering." Because the nodes move to a location
* in the document that the parser had already processed, this parser does not support
* these situations and will bail.
*
* @since 6.4.0
*
* @see WP_HTML_Tag_Processor
* @see https://html.spec.whatwg.org/
*/
class WP_HTML_Processor extends WP_HTML_Tag_Processor {
/**
* The maximum number of bookmarks allowed to exist at any given time.
*
* HTML processing requires more bookmarks than basic tag processing,
* so this class constant from the Tag Processor is overwritten.
*
* @since 6.4.0
*
* @var int
*/
const MAX_BOOKMARKS = 100;
/**
* Holds the working state of the parser, including the stack of
* open elements and the stack of active formatting elements.
*
* Initialized in the constructor.
*
* @since 6.4.0
*
* @var WP_HTML_Processor_State
*/
private $state;
/**
* Used to create unique bookmark names.
*
* This class sets a bookmark for every tag in the HTML document that it encounters.
* The bookmark name is auto-generated and increments, starting with `1`. These are
* internal bookmarks and are automatically released when the referring WP_HTML_Token
* goes out of scope and is garbage-collected.
*
* @since 6.4.0
*
* @see WP_HTML_Processor::$release_internal_bookmark_on_destruct
*
* @var int
*/
private $bookmark_counter = 0;
/**
* Stores an explanation for why something failed, if it did.
*
* @see self::get_last_error
*
* @since 6.4.0
*
* @var string|null
*/
private $last_error = null;
/**
* Stores context for why the parser bailed on unsupported HTML, if it did.
*
* @see self::get_unsupported_exception
*
* @since 6.7.0
*
* @var WP_HTML_Unsupported_Exception|null
*/
private $unsupported_exception = null;
/**
* Releases a bookmark when PHP garbage-collects its wrapping WP_HTML_Token instance.
*
* This function is created inside the class constructor so that it can be passed to
* the stack of open elements and the stack of active formatting elements without
* exposing it as a public method on the class.
*
* @since 6.4.0
*
* @var Closure|null
*/
private $release_internal_bookmark_on_destruct = null;
/**
* Stores stack events which arise during parsing of the
* HTML document, which will then supply the "match" events.
*
* @since 6.6.0
*
* @var WP_HTML_Stack_Event[]
*/
private $element_queue = array();
/**
* Stores the current breadcrumbs.
*
* @since 6.7.0
*
* @var string[]
*/
private $breadcrumbs = array();
/**
* Current stack event, if set, representing a matched token.
*
* Because the parser may internally point to a place further along in a document
* than the nodes which have already been processed (some "virtual" nodes may have
* appeared while scanning the HTML document), this will point at the "current" node
* being processed. It comes from the front of the element queue.
*
* @since 6.6.0
*
* @var WP_HTML_Stack_Event|null
*/
private $current_element = null;
/**
* Context node if created as a fragment parser.
*
* @var WP_HTML_Token|null
*/
private $context_node = null;
/*
* Public Interface Functions
*/
/**
* Creates an HTML processor in the fragment parsing mode.
*
* Use this for cases where you are processing chunks of HTML that
* will be found within a bigger HTML document, such as rendered
* block output that exists within a post, `the_content` inside a
* rendered site layout.
*
* Fragment parsing occurs within a context, which is an HTML element
* that the document will eventually be placed in. It becomes important
* when special elements have different rules than others, such as inside
* a TEXTAREA or a TITLE tag where things that look like tags are text,
* or inside a SCRIPT tag where things that look like HTML syntax are JS.
*
* The context value should be a representation of the tag into which the
* HTML is found. For most cases this will be the body element. The HTML
* form is provided because a context element may have attributes that
* impact the parse, such as with a SCRIPT tag and its `type` attribute.
*
* ## Current HTML Support
*
* - The only supported context is `<body>`, which is the default value.
* - The only supported document encoding is `UTF-8`, which is the default value.
*
* @since 6.4.0
* @since 6.6.0 Returns `static` instead of `self` so it can create subclass instances.
*
* @param string $html Input HTML fragment to process.
* @param string $context Context element for the fragment, must be default of `<body>`.
* @param string $encoding Text encoding of the document; must be default of 'UTF-8'.
* @return static|null The created processor if successful, otherwise null.
*/
public static function create_fragment( $html, $context = '<body>', $encoding = 'UTF-8' ) {
if ( '<body>' !== $context || 'UTF-8' !== $encoding ) {
return null;
}
$context_processor = static::create_full_parser( "<!DOCTYPE html>{$context}", $encoding );
if ( null === $context_processor ) {
return null;
}
while ( $context_processor->next_tag() ) {
if ( ! $context_processor->is_virtual() ) {
$context_processor->set_bookmark( 'final_node' );
}
}
if (
! $context_processor->has_bookmark( 'final_node' ) ||
! $context_processor->seek( 'final_node' )
) {
_doing_it_wrong( __METHOD__, __( 'No valid context element was detected.' ), '6.8.0' );
return null;
}
return $context_processor->create_fragment_at_current_node( $html );
}
/**
* Creates an HTML processor in the full parsing mode.
*
* It's likely that a fragment parser is more appropriate, unless sending an
* entire HTML document from start to finish. Consider a fragment parser with
* a context node of `<body>`.
*
* UTF-8 is the only allowed encoding. If working with a document that
* isn't UTF-8, first convert the document to UTF-8, then pass in the
* converted HTML.
*
* @param string $html Input HTML document to process.
* @param string|null $known_definite_encoding Optional. If provided, specifies the charset used
* in the input byte stream. Currently must be UTF-8.
* @return static|null The created processor if successful, otherwise null.
*/
public static function create_full_parser( $html, $known_definite_encoding = 'UTF-8' ) {
if ( 'UTF-8' !== $known_definite_encoding ) {
return null;
}
$processor = new static( $html, self::CONSTRUCTOR_UNLOCK_CODE );
$processor->state->encoding = $known_definite_encoding;
$processor->state->encoding_confidence = 'certain';
return $processor;
}
/**
* Constructor.
*
* Do not use this method. Use the static creator methods instead.
*
* @access private
*
* @since 6.4.0
*
* @see WP_HTML_Processor::create_fragment()
*
* @param string $html HTML to process.
* @param string|null $use_the_static_create_methods_instead This constructor should not be called manually.
*/
public function __construct( $html, $use_the_static_create_methods_instead = null ) {
parent::__construct( $html );
if ( self::CONSTRUCTOR_UNLOCK_CODE !== $use_the_static_create_methods_instead ) {
_doing_it_wrong(
__METHOD__,
sprintf(
/* translators: %s: WP_HTML_Processor::create_fragment(). */
__( 'Call %s to create an HTML Processor instead of calling the constructor directly.' ),
'<code>WP_HTML_Processor::create_fragment()</code>'
),
'6.4.0'
);
}
$this->state = new WP_HTML_Processor_State();
$this->state->stack_of_open_elements->set_push_handler(
function ( WP_HTML_Token $token ): void {
$is_virtual = ! isset( $this->state->current_token ) || $this->is_tag_closer();
$same_node = isset( $this->state->current_token ) && $token->node_name === $this->state->current_token->node_name;
$provenance = ( ! $same_node || $is_virtual ) ? 'virtual' : 'real';
$this->element_queue[] = new WP_HTML_Stack_Event( $token, WP_HTML_Stack_Event::PUSH, $provenance );
$this->change_parsing_namespace( $token->integration_node_type ? 'html' : $token->namespace );
}
);
$this->state->stack_of_open_elements->set_pop_handler(
function ( WP_HTML_Token $token ): void {
$is_virtual = ! isset( $this->state->current_token ) || ! $this->is_tag_closer();
$same_node = isset( $this->state->current_token ) && $token->node_name === $this->state->current_token->node_name;
$provenance = ( ! $same_node || $is_virtual ) ? 'virtual' : 'real';
$this->element_queue[] = new WP_HTML_Stack_Event( $token, WP_HTML_Stack_Event::POP, $provenance );
$adjusted_current_node = $this->get_adjusted_current_node();
if ( $adjusted_current_node ) {
$this->change_parsing_namespace( $adjusted_current_node->integration_node_type ? 'html' : $adjusted_current_node->namespace );
} else {
$this->change_parsing_namespace( 'html' );
}
}
);
/*
* Create this wrapper so that it's possible to pass
* a private method into WP_HTML_Token classes without
* exposing it to any public API.
*/
$this->release_internal_bookmark_on_destruct = function ( string $name ): void {
parent::release_bookmark( $name );
};
}
/**
* Creates a fragment processor at the current node.
*
* HTML Fragment parsing always happens with a context node. HTML Fragment Processors can be
* instantiated with a `BODY` context node via `WP_HTML_Processor::create_fragment( $html )`.
*
* The context node may impact how a fragment of HTML is parsed. For example, consider the HTML
* fragment `<td />Inside TD?</td>`.
*
* A BODY context node will produce the following tree:
*
* └─#text Inside TD?
*
* Notice that the `<td>` tags are completely ignored.
*
* Compare that with an SVG context node that produces the following tree:
*
* ├─svg:td
* └─#text Inside TD?
*
* Here, a `td` node in the `svg` namespace is created, and its self-closing flag is respected.
* This is a peculiarity of parsing HTML in foreign content like SVG.
*
* Finally, consider the tree produced with a TABLE context node:
*
* └─TBODY
* └─TR
* └─TD
* └─#text Inside TD?
*
* These examples demonstrate how important the context node may be when processing an HTML
* fragment. Special care must be taken when processing fragments that are expected to appear
* in specific contexts. SVG and TABLE are good examples, but there are others.
*
* @see https://html.spec.whatwg.org/multipage/parsing.html#html-fragment-parsing-algorithm
*
* @since 6.8.0
*
* @param string $html Input HTML fragment to process.
* @return static|null The created processor if successful, otherwise null.
*/
private function create_fragment_at_current_node( string $html ) {
if ( $this->get_token_type() !== '#tag' || $this->is_tag_closer() ) {
_doing_it_wrong(
__METHOD__,
__( 'The context element must be a start tag.' ),
'6.8.0'
);
return null;
}
$tag_name = $this->current_element->token->node_name;
$namespace = $this->current_element->token->namespace;
if ( 'html' === $namespace && self::is_void( $tag_name ) ) {
_doing_it_wrong(
__METHOD__,
sprintf(
// translators: %s: A tag name like INPUT or BR.
__( 'The context element cannot be a void element, found "%s".' ),
$tag_name
),
'6.8.0'
);
return null;
}
/*
* Prevent creating fragments at nodes that require a special tokenizer state.
* This is unsupported by the HTML Processor.
*/
if (
'html' === $namespace &&
in_array( $tag_name, array( 'IFRAME', 'NOEMBED', 'NOFRAMES', 'SCRIPT', 'STYLE', 'TEXTAREA', 'TITLE', 'XMP', 'PLAINTEXT' ), true )
) {
_doing_it_wrong(
__METHOD__,
sprintf(
// translators: %s: A tag name like IFRAME or TEXTAREA.
__( 'The context element "%s" is not supported.' ),
$tag_name
),
'6.8.0'
);
return null;
}
$fragment_processor = new static( $html, self::CONSTRUCTOR_UNLOCK_CODE );
$fragment_processor->compat_mode = $this->compat_mode;
// @todo Create "fake" bookmarks for non-existent but implied nodes.
$fragment_processor->bookmarks['root-node'] = new WP_HTML_Span( 0, 0 );
$root_node = new WP_HTML_Token(
'root-node',
'HTML',
false
);
$fragment_processor->state->stack_of_open_elements->push( $root_node );
$fragment_processor->bookmarks['context-node'] = new WP_HTML_Span( 0, 0 );
$fragment_processor->context_node = clone $this->current_element->token;
$fragment_processor->context_node->bookmark_name = 'context-node';
$fragment_processor->context_node->on_destroy = null;
$fragment_processor->breadcrumbs = array( 'HTML', $fragment_processor->context_node->node_name );
if ( 'TEMPLATE' === $fragment_processor->context_node->node_name ) {
$fragment_processor->state->stack_of_template_insertion_modes[] = WP_HTML_Processor_State::INSERTION_MODE_IN_TEMPLATE;
}
$fragment_processor->reset_insertion_mode_appropriately();
/*
* > Set the parser's form element pointer to the nearest node to the context element that
* > is a form element (going straight up the ancestor chain, and including the element
* > itself, if it is a form element), if any. (If there is no such form element, the
* > form element pointer keeps its initial value, null.)
*/
foreach ( $this->state->stack_of_open_elements->walk_up() as $element ) {
if ( 'FORM' === $element->node_name && 'html' === $element->namespace ) {
$fragment_processor->state->form_element = clone $element;
$fragment_processor->state->form_element->bookmark_name = null;
$fragment_processor->state->form_element->on_destroy = null;
break;
}
}
$fragment_processor->state->encoding_confidence = 'irrelevant';
/*
* Update the parsing namespace near the end of the process.
* This is important so that any push/pop from the stack of open
* elements does not change the parsing namespace.
*/
$fragment_processor->change_parsing_namespace(
$this->current_element->token->integration_node_type ? 'html' : $namespace
);
return $fragment_processor;
}
/**
* Stops the parser and terminates its execution when encountering unsupported markup.
*
* @throws WP_HTML_Unsupported_Exception Halts execution of the parser.
*
* @since 6.7.0
*
* @param string $message Explains support is missing in order to parse the current node.
*/
private function bail( string $message ) {
$here = $this->bookmarks[ $this->state->current_token->bookmark_name ];
$token = substr( $this->html, $here->start, $here->length );
$open_elements = array();
foreach ( $this->state->stack_of_open_elements->stack as $item ) {
$open_elements[] = $item->node_name;
}
$active_formats = array();
foreach ( $this->state->active_formatting_elements->walk_down() as $item ) {
$active_formats[] = $item->node_name;
}
$this->last_error = self::ERROR_UNSUPPORTED;
$this->unsupported_exception = new WP_HTML_Unsupported_Exception(
$message,
$this->state->current_token->node_name,
$here->start,
$token,
$open_elements,
$active_formats
);
throw $this->unsupported_exception;
}
/**
* Returns the last error, if any.
*
* Various situations lead to parsing failure but this class will
* return `false` in all those cases. To determine why something
* failed it's possible to request the last error. This can be
* helpful to know to distinguish whether a given tag couldn't
* be found or if content in the document caused the processor
* to give up and abort processing.
*
* Example
*
* $processor = WP_HTML_Processor::create_fragment( '<template><strong><button><em><p><em>' );
* false === $processor->next_tag();
* WP_HTML_Processor::ERROR_UNSUPPORTED === $processor->get_last_error();
*
* @since 6.4.0
*
* @see self::ERROR_UNSUPPORTED
* @see self::ERROR_EXCEEDED_MAX_BOOKMARKS
*
* @return string|null The last error, if one exists, otherwise null.
*/
public function get_last_error(): ?string {
return $this->last_error;
}
/**
* Returns context for why the parser aborted due to unsupported HTML, if it did.
*
* This is meant for debugging purposes, not for production use.
*
* @since 6.7.0
*
* @see self::$unsupported_exception
*
* @return WP_HTML_Unsupported_Exception|null
*/
public function get_unsupported_exception() {
return $this->unsupported_exception;
}
/**
* Finds the next tag matching the $query.
*
* @todo Support matching the class name and tag name.
*
* @since 6.4.0
* @since 6.6.0 Visits all tokens, including virtual ones.
*
* @throws Exception When unable to allocate a bookmark for the next token in the input HTML document.
*
* @param array|string|null $query {
* Optional. Which tag name to find, having which class, etc. Default is to find any tag.
*
* @type string|null $tag_name Which tag to find, or `null` for "any tag."
* @type string $tag_closers 'visit' to pause at tag closers, 'skip' or unset to only visit openers.
* @type int|null $match_offset Find the Nth tag matching all search criteria.
* 1 for "first" tag, 3 for "third," etc.
* Defaults to first tag.
* @type string|null $class_name Tag must contain this whole class name to match.
* @type string[] $breadcrumbs DOM sub-path at which element is found, e.g. `array( 'FIGURE', 'IMG' )`.
* May also contain the wildcard `*` which matches a single element, e.g. `array( 'SECTION', '*' )`.
* }
* @return bool Whether a tag was matched.
*/
public function next_tag( $query = null ): bool {
$visit_closers = isset( $query['tag_closers'] ) && 'visit' === $query['tag_closers'];
if ( null === $query ) {
while ( $this->next_token() ) {
if ( '#tag' !== $this->get_token_type() ) {
continue;
}
if ( ! $this->is_tag_closer() || $visit_closers ) {
return true;
}
}
return false;
}
if ( is_string( $query ) ) {
$query = array( 'breadcrumbs' => array( $query ) );
}
if ( ! is_array( $query ) ) {
_doing_it_wrong(
__METHOD__,
__( 'Please pass a query array to this function.' ),
'6.4.0'
);
return false;
}
if ( isset( $query['tag_name'] ) ) {
$query['tag_name'] = strtoupper( $query['tag_name'] );
}
$needs_class = ( isset( $query['class_name'] ) && is_string( $query['class_name'] ) )
? $query['class_name']
: null;
if ( ! ( array_key_exists( 'breadcrumbs', $query ) && is_array( $query['breadcrumbs'] ) ) ) {
while ( $this->next_token() ) {
if ( '#tag' !== $this->get_token_type() ) {
continue;
}
if ( isset( $query['tag_name'] ) && $query['tag_name'] !== $this->get_token_name() ) {
continue;
}
if ( isset( $needs_class ) && ! $this->has_class( $needs_class ) ) {
continue;
}
if ( ! $this->is_tag_closer() || $visit_closers ) {
return true;
}
}
return false;
}
$breadcrumbs = $query['breadcrumbs'];
$match_offset = isset( $query['match_offset'] ) ? (int) $query['match_offset'] : 1;
while ( $match_offset > 0 && $this->next_token() ) {
if ( '#tag' !== $this->get_token_type() || $this->is_tag_closer() ) {
continue;
}
if ( isset( $needs_class ) && ! $this->has_class( $needs_class ) ) {
continue;
}
if ( $this->matches_breadcrumbs( $breadcrumbs ) && 0 === --$match_offset ) {
return true;
}
}
return false;
}
/**
* Finds the next token in the HTML document.
*
* This doesn't currently have a way to represent non-tags and doesn't process
* semantic rules for text nodes. For access to the raw tokens consider using
* WP_HTML_Tag_Processor instead.
*
* @since 6.5.0 Added for internal support; do not use.
* @since 6.7.2 Refactored so subclasses may extend.
*
* @return bool Whether a token was parsed.
*/
public function next_token(): bool {
return $this->next_visitable_token();
}
/**
* Ensures internal accounting is maintained for HTML semantic rules while
* the underlying Tag Processor class is seeking to a bookmark.
*
* This doesn't currently have a way to represent non-tags and doesn't process
* semantic rules for text nodes. For access to the raw tokens consider using
* WP_HTML_Tag_Processor instead.
*
* Note that this method may call itself recursively. This is why it is not
* implemented as {@see WP_HTML_Processor::next_token()}, which instead calls
* this method similarly to how {@see WP_HTML_Tag_Processor::next_token()}
* calls the {@see WP_HTML_Tag_Processor::base_class_next_token()} method.
*
* @since 6.7.2 Added for internal support.
*
* @access private
*
* @return bool
*/
private function next_visitable_token(): bool {
$this->current_element = null;
if ( isset( $this->last_error ) ) {
return false;
}
/*
* Prime the events if there are none.
*
* @todo In some cases, probably related to the adoption agency
* algorithm, this call to step() doesn't create any new
* events. Calling it again creates them. Figure out why
* this is and if it's inherent or if it's a bug. Looping
* until there are events or until there are no more
* tokens works in the meantime and isn't obviously wrong.
*/
if ( empty( $this->element_queue ) && $this->step() ) {
return $this->next_visitable_token();
}
// Process the next event on the queue.
$this->current_element = array_shift( $this->element_queue );
if ( ! isset( $this->current_element ) ) {
// There are no tokens left, so close all remaining open elements.
while ( $this->state->stack_of_open_elements->pop() ) {
continue;
}
return empty( $this->element_queue ) ? false : $this->next_visitable_token();
}
$is_pop = WP_HTML_Stack_Event::POP === $this->current_element->operation;
/*
* The root node only exists in the fragment parser, and closing it
* indicates that the parse is complete. Stop before popping it from
* the breadcrumbs.
*/
if ( 'root-node' === $this->current_element->token->bookmark_name ) {
return $this->next_visitable_token();
}
// Adjust the breadcrumbs for this event.
if ( $is_pop ) {
array_pop( $this->breadcrumbs );
} else {
$this->breadcrumbs[] = $this->current_element->token->node_name;
}
// Avoid sending close events for elements which don't expect a closing.
if ( $is_pop && ! $this->expects_closer( $this->current_element->token ) ) {
return $this->next_visitable_token();
}
return true;
}
/**
* Indicates if the current tag token is a tag closer.
*
* Example:
*
* $p = WP_HTML_Processor::create_fragment( '<div></div>' );
* $p->next_tag( array( 'tag_name' => 'div', 'tag_closers' => 'visit' ) );
* $p->is_tag_closer() === false;
*
* $p->next_tag( array( 'tag_name' => 'div', 'tag_closers' => 'visit' ) );
* $p->is_tag_closer() === true;
*
* @since 6.6.0 Subclassed for HTML Processor.
*
* @return bool Whether the current tag is a tag closer.
*/
public function is_tag_closer(): bool {
return $this->is_virtual()
? ( WP_HTML_Stack_Event::POP === $this->current_element->operation && '#tag' === $this->get_token_type() )
: parent::is_tag_closer();
}
/**
* Indicates if the currently-matched token is virtual, created by a stack operation
* while processing HTML, rather than a token found in the HTML text itself.
*
* @since 6.6.0
*
* @return bool Whether the current token is virtual.
*/
private function is_virtual(): bool {
return (
isset( $this->current_element->provenance ) &&
'virtual' === $this->current_element->provenance
);
}
/**
* Indicates if the currently-matched tag matches the given breadcrumbs.
*
* A "*" represents a single tag wildcard, where any tag matches, but not no tags.
*
* At some point this function _may_ support a `**` syntax for matching any number
* of unspecified tags in the breadcrumb stack. This has been intentionally left
* out, however, to keep this function simple and to avoid introducing backtracking,
* which could open up surprising performance breakdowns.
*
* Example:
*
* $processor = WP_HTML_Processor::create_fragment( '<div><span><figure><img></figure></span></div>' );
* $processor->next_tag( 'img' );
* true === $processor->matches_breadcrumbs( array( 'figure', 'img' ) );
* true === $processor->matches_breadcrumbs( array( 'span', 'figure', 'img' ) );
* false === $processor->matches_breadcrumbs( array( 'span', 'img' ) );
* true === $processor->matches_breadcrumbs( array( 'span', '*', 'img' ) );
*
* @since 6.4.0
*
* @param string[] $breadcrumbs DOM sub-path at which element is found, e.g. `array( 'FIGURE', 'IMG' )`.
* May also contain the wildcard `*` which matches a single element, e.g. `array( 'SECTION', '*' )`.
* @return bool Whether the currently-matched tag is found at the given nested structure.
*/
public function matches_breadcrumbs( $breadcrumbs ): bool {
// Everything matches when there are zero constraints.
if ( 0 === count( $breadcrumbs ) ) {
return true;
}
// Start at the last crumb.
$crumb = end( $breadcrumbs );
if ( '*' !== $crumb && $this->get_tag() !== strtoupper( $crumb ) ) {
return false;
}
for ( $i = count( $this->breadcrumbs ) - 1; $i >= 0; $i-- ) {
$node = $this->breadcrumbs[ $i ];
$crumb = strtoupper( current( $breadcrumbs ) );
if ( '*' !== $crumb && $node !== $crumb ) {
return false;
}
if ( false === prev( $breadcrumbs ) ) {
return true;
}
}
return false;
}
/**
* Indicates if the currently-matched node expects a closing
* token, or if it will self-close on the next step.
*
* Most HTML elements expect a closer, such as a P element or
* a DIV element. Others, like an IMG element are void and don't
* have a closing tag. Special elements, such as SCRIPT and STYLE,
* are treated just like void tags. Text nodes and self-closing
* foreign content will also act just like a void tag, immediately
* closing as soon as the processor advances to the next token.
*
* @since 6.6.0
*
* @param WP_HTML_Token|null $node Optional. Node to examine, if provided.
* Default is to examine current node.
* @return bool|null Whether to expect a closer for the currently-matched node,
* or `null` if not matched on any token.
*/
public function expects_closer( ?WP_HTML_Token $node = null ): ?bool {
$token_name = $node->node_name ?? $this->get_token_name();
if ( ! isset( $token_name ) ) {
return null;
}
$token_namespace = $node->namespace ?? $this->get_namespace();
$token_has_self_closing = $node->has_self_closing_flag ?? $this->has_self_closing_flag();
return ! (
// Comments, text nodes, and other atomic tokens.
'#' === $token_name[0] ||
// Doctype declarations.
'html' === $token_name ||
// Void elements.
( 'html' === $token_namespace && self::is_void( $token_name ) ) ||
// Special atomic elements.
( 'html' === $token_namespace && in_array( $token_name, array( 'IFRAME', 'NOEMBED', 'NOFRAMES', 'SCRIPT', 'STYLE', 'TEXTAREA', 'TITLE', 'XMP' ), true ) ) ||
// Self-closing elements in foreign content.
( 'html' !== $token_namespace && $token_has_self_closing )
);
}
/**
* Steps through the HTML document and stop at the next tag, if any.
*
* @since 6.4.0
*
* @throws Exception When unable to allocate a bookmark for the next token in the input HTML document.
*
* @see self::PROCESS_NEXT_NODE
* @see self::REPROCESS_CURRENT_NODE
*
* @param string $node_to_process Whether to parse the next node or reprocess the current node.
* @return bool Whether a tag was matched.
*/
public function step( $node_to_process = self::PROCESS_NEXT_NODE ): bool {
// Refuse to proceed if there was a previous error.
if ( null !== $this->last_error ) {
return false;
}
if ( self::REPROCESS_CURRENT_NODE !== $node_to_process ) {
/*
* Void elements still hop onto the stack of open elements even though
* there's no corresponding closing tag. This is important for managing
* stack-based operations such as "navigate to parent node" or checking
* on an element's breadcrumbs.
*
* When moving on to the next node, therefore, if the bottom-most element
* on the stack is a void element, it must be closed.
*/
$top_node = $this->state->stack_of_open_elements->current_node();
if ( isset( $top_node ) && ! $this->expects_closer( $top_node ) ) {