-
Notifications
You must be signed in to change notification settings - Fork 0
/
class-wp-html-processor.php
2008 lines (1842 loc) · 63.5 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 following list specifies the HTML tags that _are_ supported:
*
* - Containers: ADDRESS, BLOCKQUOTE, DETAILS, DIALOG, DIV, FOOTER, HEADER, MAIN, MENU, SPAN, SUMMARY.
* - Custom elements: All custom elements are supported. :)
* - Form elements: BUTTON, DATALIST, FIELDSET, INPUT, LABEL, LEGEND, METER, PROGRESS, SEARCH.
* - Formatting elements: B, BIG, CODE, EM, FONT, I, PRE, SMALL, STRIKE, STRONG, TT, U, WBR.
* - Heading elements: H1, H2, H3, H4, H5, H6, HGROUP.
* - Links: A.
* - Lists: DD, DL, DT, LI, OL, UL.
* - Media elements: AUDIO, CANVAS, EMBED, FIGCAPTION, FIGURE, IMG, MAP, PICTURE, SOURCE, TRACK, VIDEO.
* - Paragraph: BR, P.
* - Phrasing elements: ABBR, AREA, BDI, BDO, CITE, DATA, DEL, DFN, INS, MARK, OUTPUT, Q, SAMP, SUB, SUP, TIME, VAR.
* - Sectioning elements: ARTICLE, ASIDE, HR, NAV, SECTION.
* - Templating elements: SLOT.
* - Text decoration: RUBY.
* - Deprecated elements: ACRONYM, BLINK, CENTER, DIR, ISINDEX, KEYGEN, LISTING, MULTICOL, NEXTID, PARAM, SPACER.
*
* ### 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 specifies HTML markup that _is_ supported:
*
* - Markup involving only those tags listed above.
* - Fully-balanced and non-overlapping tags.
* - HTML with unexpected tag closers.
* - Some unbalanced or overlapping tags.
* - P tags after unclosed P tags.
* - BUTTON tags after unclosed BUTTON tags.
* - A tags after unclosed A tags that don't involve any active formatting elements.
*
* @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 = null;
/**
* 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;
/**
* 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
*/
private $release_internal_bookmark_on_destruct = 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
*
* @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 WP_HTML_Processor|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;
}
$processor = new self( $html, self::CONSTRUCTOR_UNLOCK_CODE );
$processor->state->context_node = array( 'BODY', array() );
$processor->state->insertion_mode = WP_HTML_Processor_State::INSERTION_MODE_IN_BODY;
// @todo Create "fake" bookmarks for non-existent but implied nodes.
$processor->bookmarks['root-node'] = new WP_HTML_Span( 0, 0 );
$processor->bookmarks['context-node'] = new WP_HTML_Span( 0, 0 );
$processor->state->stack_of_open_elements->push(
new WP_HTML_Token(
'root-node',
'HTML',
false
)
);
$processor->state->stack_of_open_elements->push(
new WP_HTML_Token(
'context-node',
$processor->state->context_node[0],
false
)
);
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();
/*
* 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 ( $name ) {
parent::release_bookmark( $name );
};
}
/**
* 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() {
return $this->last_error;
}
/**
* Finds the next tag matching the $query.
*
* @todo Support matching the class name and tag name.
*
* @since 6.4.0
*
* @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 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 ) {
if ( null === $query ) {
while ( $this->step() ) {
if ( '#tag' !== $this->get_token_type() ) {
continue;
}
if ( ! $this->is_tag_closer() ) {
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;
}
$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->step() ) {
if ( '#tag' !== $this->get_token_type() ) {
continue;
}
if ( isset( $needs_class ) && ! $this->has_class( $needs_class ) ) {
continue;
}
if ( ! $this->is_tag_closer() ) {
return true;
}
}
return false;
}
if ( isset( $query['tag_closers'] ) && 'visit' === $query['tag_closers'] ) {
_doing_it_wrong(
__METHOD__,
__( 'Cannot visit tag closers in HTML Processor.' ),
'6.4.0'
);
return false;
}
$breadcrumbs = $query['breadcrumbs'];
$match_offset = isset( $query['match_offset'] ) ? (int) $query['match_offset'] : 1;
while ( $match_offset > 0 && $this->step() ) {
if ( '#tag' !== $this->get_token_type() ) {
continue;
}
if ( isset( $needs_class ) && ! $this->has_class( $needs_class ) ) {
continue;
}
if ( $this->matches_breadcrumbs( $breadcrumbs ) && 0 === --$match_offset ) {
return true;
}
}
return false;
}
/**
* 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.
*
* @since 6.5.0 Added for internal support; do not use.
*
* @access private
*
* @return bool
*/
public function next_token() {
return $this->step();
}
/**
* 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 ) {
// 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;
}
foreach ( $this->state->stack_of_open_elements->walk_up() as $node ) {
$crumb = strtoupper( current( $breadcrumbs ) );
if ( '*' !== $crumb && $node->node_name !== $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
*
* @todo When adding support for foreign content, ensure that
* this returns false for self-closing elements in the
* SVG and MathML namespace.
*
* @return bool Whether to expect a closer for the currently-matched node,
* or `null` if not matched on any token.
*/
public function expects_closer() {
$token_name = $this->get_token_name();
if ( ! isset( $token_name ) ) {
return null;
}
return ! (
// Comments, text nodes, and other atomic tokens.
'#' === $token_name[0] ||
// Doctype declarations.
'html' === $token_name ||
// Void elements.
self::is_void( $token_name ) ||
// Special atomic elements.
in_array( $token_name, array( 'IFRAME', 'NOEMBED', 'NOFRAMES', 'SCRIPT', 'STYLE', 'TEXTAREA', 'TITLE', 'XMP' ), true )
);
}
/**
* 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 ) {
// 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.
*
* @todo Once self-closing foreign elements and BGSOUND are supported,
* they must also be implicitly closed here too. BGSOUND is
* special since it's only self-closing if the self-closing flag
* is provided in the opening tag, otherwise it expects a tag closer.
*/
$top_node = $this->state->stack_of_open_elements->current_node();
if (
$top_node && (
// Void elements.
self::is_void( $top_node->node_name ) ||
// Comments, text nodes, and other atomic tokens.
'#' === $top_node->node_name[0] ||
// Doctype declarations.
'html' === $top_node->node_name
)
) {
$this->state->stack_of_open_elements->pop();
}
}
if ( self::PROCESS_NEXT_NODE === $node_to_process ) {
parent::next_token();
}
// Finish stepping when there are no more tokens in the document.
if (
WP_HTML_Tag_Processor::STATE_INCOMPLETE_INPUT === $this->parser_state ||
WP_HTML_Tag_Processor::STATE_COMPLETE === $this->parser_state
) {
return false;
}
$this->state->current_token = new WP_HTML_Token(
$this->bookmark_token(),
$this->get_token_name(),
$this->has_self_closing_flag(),
$this->release_internal_bookmark_on_destruct
);
try {
switch ( $this->state->insertion_mode ) {
case WP_HTML_Processor_State::INSERTION_MODE_IN_BODY:
return $this->step_in_body();
default:
$this->last_error = self::ERROR_UNSUPPORTED;
throw new WP_HTML_Unsupported_Exception( "No support for parsing in the '{$this->state->insertion_mode}' state." );
}
} catch ( WP_HTML_Unsupported_Exception $e ) {
/*
* Exceptions are used in this class to escape deep call stacks that
* otherwise might involve messier calling and return conventions.
*/
return false;
}
}
/**
* Computes the HTML breadcrumbs for the currently-matched node, if matched.
*
* Breadcrumbs start at the outermost parent and descend toward the matched element.
* They always include the entire path from the root HTML node to the matched element.
*
* @todo It could be more efficient to expose a generator-based version of this function
* to avoid creating the array copy on tag iteration. If this is done, it would likely
* be more useful to walk up the stack when yielding instead of starting at the top.
*
* Example
*
* $processor = WP_HTML_Processor::create_fragment( '<p><strong><em><img></em></strong></p>' );
* $processor->next_tag( 'IMG' );
* $processor->get_breadcrumbs() === array( 'HTML', 'BODY', 'P', 'STRONG', 'EM', 'IMG' );
*
* @since 6.4.0
*
* @return string[]|null Array of tag names representing path to matched node, if matched, otherwise NULL.
*/
public function get_breadcrumbs() {
$breadcrumbs = array();
foreach ( $this->state->stack_of_open_elements->walk_down() as $stack_item ) {
$breadcrumbs[] = $stack_item->node_name;
}
return $breadcrumbs;
}
/**
* Returns the nesting depth of the current location in the document.
*
* Example:
*
* $processor = WP_HTML_Processor::create_fragment( '<div><p></p></div>' );
* // The processor starts in the BODY context, meaning it has depth from the start: HTML > BODY.
* 2 === $processor->get_current_depth();
*
* // Opening the DIV element increases the depth.
* $processor->next_token();
* 3 === $processor->get_current_depth();
*
* // Opening the P element increases the depth.
* $processor->next_token();
* 4 === $processor->get_current_depth();
*
* // The P element is closed during `next_token()` so the depth is decreased to reflect that.
* $processor->next_token();
* 3 === $processor->get_current_depth();
*
* @since 6.6.0
*
* @return int Nesting-depth of current location in the document.
*/
public function get_current_depth() {
return $this->state->stack_of_open_elements->count();
}
/**
* Parses next element in the 'in body' insertion mode.
*
* This internal function performs the 'in body' insertion mode
* logic for the generalized WP_HTML_Processor::step() function.
*
* @since 6.4.0
*
* @throws WP_HTML_Unsupported_Exception When encountering unsupported HTML input.
*
* @see https://html.spec.whatwg.org/#parsing-main-inbody
* @see WP_HTML_Processor::step
*
* @return bool Whether an element was found.
*/
private function step_in_body() {
$token_name = $this->get_token_name();
$token_type = $this->get_token_type();
$op_sigil = '#tag' === $token_type ? ( $this->is_tag_closer() ? '-' : '+' ) : '';
$op = "{$op_sigil}{$token_name}";
switch ( $op ) {
case '#comment':
case '#funky-comment':
case '#presumptuous-tag':
$this->insert_html_element( $this->state->current_token );
return true;
case '#text':
$this->reconstruct_active_formatting_elements();
$current_token = $this->bookmarks[ $this->state->current_token->bookmark_name ];
/*
* > A character token that is U+0000 NULL
*
* Any successive sequence of NULL bytes is ignored and won't
* trigger active format reconstruction. Therefore, if the text
* only comprises NULL bytes then the token should be ignored
* here, but if there are any other characters in the stream
* the active formats should be reconstructed.
*/
if (
1 <= $current_token->length &&
"\x00" === $this->html[ $current_token->start ] &&
strspn( $this->html, "\x00", $current_token->start, $current_token->length ) === $current_token->length
) {
// Parse error: ignore the token.
return $this->step();
}
/*
* Whitespace-only text does not affect the frameset-ok flag.
* It is probably inter-element whitespace, but it may also
* contain character references which decode only to whitespace.
*/
$text = $this->get_modifiable_text();
if ( strlen( $text ) !== strspn( $text, " \t\n\f\r" ) ) {
$this->state->frameset_ok = false;
}
$this->insert_html_element( $this->state->current_token );
return true;
case 'html':
/*
* > A DOCTYPE token
* > Parse error. Ignore the token.
*/
return $this->step();
/*
* > A start tag whose tag name is "button"
*/
case '+BUTTON':
if ( $this->state->stack_of_open_elements->has_element_in_scope( 'BUTTON' ) ) {
// @todo Indicate a parse error once it's possible. This error does not impact the logic here.
$this->generate_implied_end_tags();
$this->state->stack_of_open_elements->pop_until( 'BUTTON' );
}
$this->reconstruct_active_formatting_elements();
$this->insert_html_element( $this->state->current_token );
$this->state->frameset_ok = false;
return true;
/*
* > A start tag whose tag name is one of: "address", "article", "aside",
* > "blockquote", "center", "details", "dialog", "dir", "div", "dl",
* > "fieldset", "figcaption", "figure", "footer", "header", "hgroup",
* > "main", "menu", "nav", "ol", "p", "search", "section", "summary", "ul"
*/
case '+ADDRESS':
case '+ARTICLE':
case '+ASIDE':
case '+BLOCKQUOTE':
case '+CENTER':
case '+DETAILS':
case '+DIALOG':
case '+DIR':
case '+DIV':
case '+DL':
case '+FIELDSET':
case '+FIGCAPTION':
case '+FIGURE':
case '+FOOTER':
case '+HEADER':
case '+HGROUP':
case '+MAIN':
case '+MENU':
case '+NAV':
case '+OL':
case '+P':
case '+SEARCH':
case '+SECTION':
case '+SUMMARY':
case '+UL':
if ( $this->state->stack_of_open_elements->has_p_in_button_scope() ) {
$this->close_a_p_element();
}
$this->insert_html_element( $this->state->current_token );
return true;
/*
* > An end tag whose tag name is one of: "address", "article", "aside", "blockquote",
* > "button", "center", "details", "dialog", "dir", "div", "dl", "fieldset",
* > "figcaption", "figure", "footer", "header", "hgroup", "listing", "main",
* > "menu", "nav", "ol", "pre", "search", "section", "summary", "ul"
*/
case '-ADDRESS':
case '-ARTICLE':
case '-ASIDE':
case '-BLOCKQUOTE':
case '-BUTTON':
case '-CENTER':
case '-DETAILS':
case '-DIALOG':
case '-DIR':
case '-DIV':
case '-DL':
case '-FIELDSET':
case '-FIGCAPTION':
case '-FIGURE':
case '-FOOTER':
case '-HEADER':
case '-HGROUP':
case '-LISTING':
case '-MAIN':
case '-MENU':
case '-NAV':
case '-OL':
case '-PRE':
case '-SEARCH':
case '-SECTION':
case '-SUMMARY':
case '-UL':
if ( ! $this->state->stack_of_open_elements->has_element_in_scope( $token_name ) ) {
// @todo Report parse error.
// Ignore the token.
return $this->step();
}
$this->generate_implied_end_tags();
if ( $this->state->stack_of_open_elements->current_node()->node_name !== $token_name ) {
// @todo Record parse error: this error doesn't impact parsing.
}
$this->state->stack_of_open_elements->pop_until( $token_name );
return true;
/*
* > A start tag whose tag name is one of: "h1", "h2", "h3", "h4", "h5", "h6"
*/
case '+H1':
case '+H2':
case '+H3':
case '+H4':
case '+H5':
case '+H6':
if ( $this->state->stack_of_open_elements->has_p_in_button_scope() ) {
$this->close_a_p_element();
}
if (
in_array(
$this->state->stack_of_open_elements->current_node()->node_name,
array( 'H1', 'H2', 'H3', 'H4', 'H5', 'H6' ),
true
)
) {
// @todo Indicate a parse error once it's possible.
$this->state->stack_of_open_elements->pop();
}
$this->insert_html_element( $this->state->current_token );
return true;
/*
* > A start tag whose tag name is one of: "pre", "listing"
*/
case '+PRE':
case '+LISTING':
if ( $this->state->stack_of_open_elements->has_p_in_button_scope() ) {
$this->close_a_p_element();
}
$this->insert_html_element( $this->state->current_token );
$this->state->frameset_ok = false;
return true;
/*
* > An end tag whose tag name is one of: "h1", "h2", "h3", "h4", "h5", "h6"
*/
case '-H1':
case '-H2':
case '-H3':
case '-H4':
case '-H5':
case '-H6':
if ( ! $this->state->stack_of_open_elements->has_element_in_scope( '(internal: H1 through H6 - do not use)' ) ) {
/*
* This is a parse error; ignore the token.
*
* @todo Indicate a parse error once it's possible.
*/
return $this->step();
}
$this->generate_implied_end_tags();
if ( $this->state->stack_of_open_elements->current_node()->node_name !== $token_name ) {
// @todo Record parse error: this error doesn't impact parsing.
}
$this->state->stack_of_open_elements->pop_until( '(internal: H1 through H6 - do not use)' );
return true;
/*
* > A start tag whose tag name is "li"
* > A start tag whose tag name is one of: "dd", "dt"
*/
case '+DD':
case '+DT':
case '+LI':
$this->state->frameset_ok = false;
$node = $this->state->stack_of_open_elements->current_node();
$is_li = 'LI' === $token_name;
in_body_list_loop:
/*
* The logic for LI and DT/DD is the same except for one point: LI elements _only_
* close other LI elements, but a DT or DD element closes _any_ open DT or DD element.
*/
if ( $is_li ? 'LI' === $node->node_name : ( 'DD' === $node->node_name || 'DT' === $node->node_name ) ) {
$node_name = $is_li ? 'LI' : $node->node_name;
$this->generate_implied_end_tags( $node_name );
if ( $node_name !== $this->state->stack_of_open_elements->current_node()->node_name ) {
// @todo Indicate a parse error once it's possible. This error does not impact the logic here.
}
$this->state->stack_of_open_elements->pop_until( $node_name );
goto in_body_list_done;
}
if (
'ADDRESS' !== $node->node_name &&
'DIV' !== $node->node_name &&
'P' !== $node->node_name &&
$this->is_special( $node->node_name )
) {
/*
* > If node is in the special category, but is not an address, div,
* > or p element, then jump to the step labeled done below.
*/
goto in_body_list_done;
} else {
/*
* > Otherwise, set node to the previous entry in the stack of open elements
* > and return to the step labeled loop.
*/
foreach ( $this->state->stack_of_open_elements->walk_up( $node ) as $item ) {
$node = $item;
break;
}
goto in_body_list_loop;
}
in_body_list_done:
if ( $this->state->stack_of_open_elements->has_p_in_button_scope() ) {
$this->close_a_p_element();
}
$this->insert_html_element( $this->state->current_token );
return true;
/*
* > An end tag whose tag name is "li"
* > An end tag whose tag name is one of: "dd", "dt"
*/
case '-DD':
case '-DT':
case '-LI':
if (
/*
* An end tag whose tag name is "li":
* If the stack of open elements does not have an li element in list item scope,
* then this is a parse error; ignore the token.
*/