-
Notifications
You must be signed in to change notification settings - Fork 385
/
class-amp-tag-and-attribute-sanitizer.php
2747 lines (2499 loc) · 102 KB
/
class-amp-tag-and-attribute-sanitizer.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
/**
* Class AMP_Tag_And_Attribute_Sanitizer
*
* Also referred to the "Validating Sanitizer".
*
* @package AMP
*/
use AmpProject\Amp;
use AmpProject\AmpWP\ValidationExemption;
use AmpProject\CssLength;
use AmpProject\DevMode;
use AmpProject\Dom\Document;
use AmpProject\Dom\Element;
use AmpProject\Extension;
use AmpProject\Html\Attribute;
use AmpProject\Html\Tag;
use AmpProject\Layout;
/**
* Strips the tags and attributes from the content that are not allowed by the AMP spec.
*
* Allowed tags array is generated from this protocol buffer:
*
* https://github.com/ampproject/amphtml/blob/bd29b0eb1b28d900d4abed2c1883c6980f18db8e/validator/validator-main.protoascii
* by the python script in amp-wp/bin/amp_wp_build.py. See the comment at the top
* of that file for instructions to generate class-amp-allowed-tags-generated.php.
*
* @todo Need to check the following items that are not yet checked by this sanitizer:
*
* - `also_requires_attr` - if one attribute is present, this requires another.
* - `ChildTagSpec` - Places restrictions on the number and type of child tags.
* - `if_value_regex` - if one attribute value matches, this places a restriction
* on another attribute/value.
*
* @internal
*/
class AMP_Tag_And_Attribute_Sanitizer extends AMP_Base_Sanitizer {
const ATTR_REQUIRED_BUT_MISSING = 'ATTR_REQUIRED_BUT_MISSING';
const CDATA_TOO_LONG = 'CDATA_TOO_LONG';
const CDATA_VIOLATES_DENYLIST = 'CDATA_VIOLATES_DENYLIST';
const DISALLOWED_ATTR = 'DISALLOWED_ATTR';
const DISALLOWED_CHILD_TAG = 'DISALLOWED_CHILD_TAG';
const DISALLOWED_DESCENDANT_TAG = 'DISALLOWED_DESCENDANT_TAG';
const DISALLOWED_FIRST_CHILD_TAG = 'DISALLOWED_FIRST_CHILD_TAG';
const DISALLOWED_SIBLING_TAG = 'DISALLOWED_SIBLING_TAG';
const DISALLOWED_PROCESSING_INSTRUCTION = 'DISALLOWED_PROCESSING_INSTRUCTION';
const DISALLOWED_PROPERTY_IN_ATTR_VALUE = 'DISALLOWED_PROPERTY_IN_ATTR_VALUE';
const DISALLOWED_RELATIVE_URL = 'DISALLOWED_RELATIVE_URL';
const DISALLOWED_TAG = 'DISALLOWED_TAG';
const DISALLOWED_TAG_ANCESTOR = 'DISALLOWED_TAG_ANCESTOR';
const DUPLICATE_DIMENSIONS = 'DUPLICATE_DIMENSIONS';
const DUPLICATE_ONEOF_ATTRS = 'DUPLICATE_ONEOF_ATTRS';
const DUPLICATE_UNIQUE_TAG = 'DUPLICATE_UNIQUE_TAG';
const IMPLIED_LAYOUT_INVALID = 'IMPLIED_LAYOUT_INVALID';
const INCORRECT_MIN_NUM_CHILD_TAGS = 'INCORRECT_MIN_NUM_CHILD_TAGS';
const INCORRECT_NUM_CHILD_TAGS = 'INCORRECT_NUM_CHILD_TAGS';
const INVALID_ATTR_VALUE = 'INVALID_ATTR_VALUE';
const INVALID_ATTR_VALUE_CASEI = 'INVALID_ATTR_VALUE_CASEI';
const INVALID_ATTR_VALUE_REGEX = 'INVALID_ATTR_VALUE_REGEX';
const INVALID_ATTR_VALUE_REGEX_CASEI = 'INVALID_ATTR_VALUE_REGEX_CASEI';
const INVALID_DISALLOWED_VALUE_REGEX = 'INVALID_DISALLOWED_VALUE_REGEX';
const INVALID_CDATA_CONTENTS = 'INVALID_CDATA_CONTENTS';
const INVALID_CDATA_CSS_I_AMPHTML_NAME = 'INVALID_CDATA_CSS_I_AMPHTML_NAME';
const INVALID_CDATA_CSS_IMPORTANT = 'INVALID_CDATA_CSS_IMPORTANT';
const INVALID_CDATA_HTML_COMMENTS = 'INVALID_CDATA_HTML_COMMENTS';
const INVALID_LAYOUT_AUTO_HEIGHT = 'INVALID_LAYOUT_AUTO_HEIGHT';
const INVALID_LAYOUT_AUTO_WIDTH = 'INVALID_LAYOUT_AUTO_WIDTH';
const INVALID_LAYOUT_FIXED_HEIGHT = 'INVALID_LAYOUT_FIXED_HEIGHT';
const INVALID_LAYOUT_HEIGHT = 'INVALID_LAYOUT_HEIGHT';
const INVALID_LAYOUT_HEIGHTS = 'INVALID_LAYOUT_HEIGHTS';
const INVALID_LAYOUT_NO_HEIGHT = 'INVALID_LAYOUT_NO_HEIGHT';
const INVALID_LAYOUT_UNIT_DIMENSIONS = 'INVALID_LAYOUT_UNIT_DIMENSIONS';
const INVALID_LAYOUT_WIDTH = 'INVALID_LAYOUT_WIDTH';
const INVALID_URL = 'INVALID_URL';
const INVALID_URL_PROTOCOL = 'INVALID_URL_PROTOCOL';
const JSON_ERROR_CTRL_CHAR = 'JSON_ERROR_CTRL_CHAR';
const JSON_ERROR_DEPTH = 'JSON_ERROR_DEPTH';
const JSON_ERROR_EMPTY = 'JSON_ERROR_EMPTY';
const JSON_ERROR_STATE_MISMATCH = 'JSON_ERROR_STATE_MISMATCH';
const JSON_ERROR_SYNTAX = 'JSON_ERROR_SYNTAX';
const JSON_ERROR_UTF8 = 'JSON_ERROR_UTF8';
const MANDATORY_ANYOF_ATTR_MISSING = 'MANDATORY_ANYOF_ATTR_MISSING';
const MANDATORY_CDATA_MISSING_OR_INCORRECT = 'MANDATORY_CDATA_MISSING_OR_INCORRECT';
const MANDATORY_ONEOF_ATTR_MISSING = 'MANDATORY_ONEOF_ATTR_MISSING';
const MANDATORY_TAG_ANCESTOR = 'MANDATORY_TAG_ANCESTOR';
const MISSING_LAYOUT_ATTRIBUTES = 'MISSING_LAYOUT_ATTRIBUTES';
const MISSING_MANDATORY_PROPERTY = 'MISSING_MANDATORY_PROPERTY';
const MISSING_REQUIRED_PROPERTY_VALUE = 'MISSING_REQUIRED_PROPERTY_VALUE';
const MISSING_URL = 'MISSING_URL';
const SPECIFIED_LAYOUT_INVALID = 'SPECIFIED_LAYOUT_INVALID';
const WRONG_PARENT_TAG = 'WRONG_PARENT_TAG';
/**
* Key for localhost.
*
* @var string
*/
const LOCALHOST = 'localhost';
/**
* Allowed tags.
*
* @since 0.5
*
* @var array
*/
protected $allowed_tags;
/**
* Globally-allowed attributes.
*
* @since 0.5
*
* @var array[][]
*/
protected $globally_allowed_attributes;
/**
* Layout-allowed attributes.
*
* @since 0.5
*
* @var string[]
*/
protected $layout_allowed_attributes;
/**
* Mapping of alternative names back to their primary names.
*
* @since 0.7
* @var array
*/
protected $rev_alternate_attr_name_lookup = [];
/**
* Mapping of JSON-serialized tag spec to the number of instances encountered in the document.
*
* @var array
*/
protected $visited_unique_tag_specs = [];
/**
* Default args.
*
* @since 0.5
*
* @var array
*/
protected $DEFAULT_ARGS = [];
/**
* AMP script components that are discovered being required through sanitization.
*
* @var string[]
*/
protected $script_components = [];
/**
* Keep track of nodes that should not be replaced to prevent duplicated validation errors since sanitization is rejected.
*
* @var array
*/
protected $should_not_replace_nodes = [];
/**
* Keep track of the elements that are currently open.
*
* This is used to determine whether a node exists inside of a given element tree, speeding up has_ancestor checks
* as well as disabling attribute validation inside of templates.
*
* @see \AMP_Tag_And_Attribute_Sanitizer::has_ancestor()
* @since 1.3
* @var array
*/
protected $open_elements = [];
/**
* AMP_Tag_And_Attribute_Sanitizer constructor.
*
* @since 0.5
*
* @param Document $dom DOM.
* @param array $args Args.
*/
public function __construct( $dom, $args = [] ) {
// @todo It is pointless to have this DEFAULT_ARGS copying the array values. We should only get the data from AMP_Allowed_Tags_Generated.
$this->DEFAULT_ARGS = [
'amp_allowed_tags' => AMP_Allowed_Tags_Generated::get_allowed_tags(),
'amp_globally_allowed_attributes' => AMP_Allowed_Tags_Generated::get_allowed_attributes(),
'amp_layout_allowed_attributes' => AMP_Allowed_Tags_Generated::get_layout_attributes(),
'allow_localhost_http_protocol' => false,
];
parent::__construct( $dom, $args );
// Prepare allowlists.
$this->allowed_tags = $this->args['amp_allowed_tags'];
foreach ( AMP_Rule_Spec::$additional_allowed_tags as $tag_name => $tag_rule_spec ) {
$this->allowed_tags[ $tag_name ][] = $tag_rule_spec;
}
// @todo Do the same for body when !use_document_element?
if ( ! empty( $this->args['use_document_element'] ) ) {
foreach ( $this->allowed_tags['html'] as &$rule_spec ) {
unset( $rule_spec[ AMP_Rule_Spec::TAG_SPEC ][ AMP_Rule_Spec::MANDATORY_PARENT ] );
}
unset( $rule_spec );
}
foreach ( $this->allowed_tags as &$tag_specs ) {
foreach ( $tag_specs as &$tag_spec ) {
if ( isset( $tag_spec[ AMP_Rule_Spec::ATTR_SPEC_LIST ] ) ) {
$tag_spec[ AMP_Rule_Spec::ATTR_SPEC_LIST ] = $this->process_alternate_names( $tag_spec[ AMP_Rule_Spec::ATTR_SPEC_LIST ] );
}
}
unset( $tag_spec );
}
unset( $tag_specs );
$this->globally_allowed_attributes = $this->process_alternate_names( $this->args['amp_globally_allowed_attributes'] );
$this->layout_allowed_attributes = $this->process_alternate_names( $this->args['amp_layout_allowed_attributes'] );
}
/**
* Return array of values that would be valid as an HTML `script` element.
*
* Array keys are AMP element names and array values are their respective
* Javascript URLs from https://cdn.ampproject.org
*
* @since 0.7
* @see amp_register_default_scripts()
*
* @return array Returns component name as array key and true as value (or JavaScript URL string),
* respectively. When true then the default component script URL will be used.
* Will return an empty array if sanitization has yet to be run
* or if it did not find any HTML elements to convert to AMP equivalents.
*/
public function get_scripts() {
return array_fill_keys( array_unique( $this->script_components ), true );
}
/**
* Process alternative names in attribute spec list.
*
* @since 0.7
*
* @param array $attr_spec_list Attribute spec list.
* @return array Modified attribute spec list.
*/
private function process_alternate_names( $attr_spec_list ) {
foreach ( $attr_spec_list as $attr_name => &$attr_spec ) {
// Save all alternative names in lookup to improve performance.
if ( isset( $attr_spec[ AMP_Rule_Spec::ALTERNATIVE_NAMES ] ) ) {
foreach ( $attr_spec[ AMP_Rule_Spec::ALTERNATIVE_NAMES ] as $alternative_name ) {
$this->rev_alternate_attr_name_lookup[ $alternative_name ] = $attr_name;
}
}
}
return $attr_spec_list;
}
/**
* Sanitize the elements from the HTML contained in this instance's Dom\Document.
*
* @since 0.5
*/
public function sanitize() {
$result = $this->sanitize_element( $this->root_element );
if ( is_array( $result ) ) {
$this->script_components = $result;
}
}
/**
* Sanitize element.
*
* Walk the DOM tree with depth first search (DFS) with post order traversal (LRN).
*
* @param DOMElement $element Element.
* @return string[]|null Required component scripts from sanitizing an element tree, or null if the element was removed.
*/
private function sanitize_element( DOMElement $element ) {
if ( ! isset( $this->open_elements[ $element->nodeName ] ) ) {
$this->open_elements[ $element->nodeName ] = 0;
}
$this->open_elements[ $element->nodeName ]++;
$script_components = [];
// First recurse into children to sanitize descendants.
// The check for $element->parentNode at each iteration is to make sure an invalid child didn't bubble up removed
// ancestor nodes in AMP_Tag_And_Attribute_Sanitizer::remove_node().
$this_child = $element->firstChild;
while ( $this_child && $element->parentNode ) {
$prev_child = $this_child->previousSibling;
$next_child = $this_child->nextSibling;
if ( $this_child instanceof DOMElement ) {
$result = $this->sanitize_element( $this_child );
if ( is_array( $result ) ) {
$script_components = array_merge(
$script_components,
$result
);
}
} elseif ( $this_child instanceof DOMProcessingInstruction ) {
$this->remove_invalid_child( $this_child, [ 'code' => self::DISALLOWED_PROCESSING_INSTRUCTION ] );
}
if ( ! $this_child->parentNode ) {
// Handle case where this child is replaced with children.
$this_child = $prev_child ? $prev_child->nextSibling : $element->firstChild;
} else {
$this_child = $next_child;
}
}
// If the element is still in the tree, process it.
// The element can currently be removed from the tree when processing children via AMP_Tag_And_Attribute_Sanitizer::remove_node().
$was_removed = false;
if ( $element->parentNode ) {
$result = $this->process_node( $element );
if ( is_array( $result ) ) {
$script_components = array_merge( $script_components, $result );
} else {
$was_removed = true;
}
}
$this->open_elements[ $element->nodeName ]--;
if ( $was_removed ) {
return null;
}
return $script_components;
}
/**
* Augment rule spec for validation.
*
* @since 1.0
*
* @param DOMElement $node Node.
* @param array $rule_spec Rule spec.
* @return array Augmented rule spec.
*/
private function get_rule_spec_list_to_validate( DOMElement $node, $rule_spec ) {
// Expand extension_spec into a set of attr_spec_list.
if ( isset( $rule_spec[ AMP_Rule_Spec::TAG_SPEC ]['extension_spec'] ) ) {
$extension_spec = $rule_spec[ AMP_Rule_Spec::TAG_SPEC ]['extension_spec'];
// This could also be derived from the extension_type in the extension_spec.
$custom_attr = 'amp-mustache' === $extension_spec['name'] ? 'custom-template' : 'custom-element';
$rule_spec[ AMP_Rule_Spec::ATTR_SPEC_LIST ][ $custom_attr ] = [
AMP_Rule_Spec::VALUE => $extension_spec['name'],
AMP_Rule_Spec::MANDATORY => true,
];
$rule_spec[ AMP_Rule_Spec::ATTR_SPEC_LIST ]['src'] = [
AMP_Rule_Spec::VALUE_REGEX => implode(
'',
[
'^',
preg_quote( 'https://cdn.ampproject.org/v0/' . $extension_spec['name'] . '-', '/' ),
'(' . implode( '|', array_merge( $extension_spec['version'], [ 'latest' ] ) ) . ')',
'\.js$',
]
),
];
}
// Augment the attribute list according to the parent's reference points, if it has them.
if ( ! empty( $node->parentNode ) && isset( $this->allowed_tags[ $node->parentNode->nodeName ] ) ) {
foreach ( $this->allowed_tags[ $node->parentNode->nodeName ] as $parent_rule_spec ) {
if ( empty( $parent_rule_spec[ AMP_Rule_Spec::TAG_SPEC ]['reference_points'] ) ) {
continue;
}
foreach ( $parent_rule_spec[ AMP_Rule_Spec::TAG_SPEC ]['reference_points'] as $reference_point_spec_name => $reference_point_spec_instance_attrs ) {
$reference_point = AMP_Allowed_Tags_Generated::get_reference_point_spec( $reference_point_spec_name );
if ( empty( $reference_point[ AMP_Rule_Spec::ATTR_SPEC_LIST ] ) ) {
/*
* See special case for amp-selector in AMP_Tag_And_Attribute_Sanitizer::is_amp_allowed_attribute()
* where its reference point applies to any descendant elements, not just direct children.
*/
continue;
}
foreach ( $reference_point[ AMP_Rule_Spec::ATTR_SPEC_LIST ] as $attr_name => $reference_point_spec_attr ) {
$reference_point_spec_attr = array_merge(
$reference_point_spec_attr,
$reference_point_spec_instance_attrs
);
/*
* Ignore mandatory constraint for now since this would end up causing other sibling children
* getting removed due to missing a mandatory attribute. To sanitize this it would require
* higher-level processing to look at an element's surrounding context, similar to how the
* sanitizer does not yet handle the mandatory_oneof constraint.
*/
unset( $reference_point_spec_attr['mandatory'] );
$rule_spec[ AMP_Rule_Spec::ATTR_SPEC_LIST ][ $attr_name ] = $reference_point_spec_attr;
}
}
}
}
return $rule_spec;
}
/**
* Process a node by checking if an element and its attributes are valid, and removing them when invalid.
*
* Attributes which are not valid are removed. Elements which are not allowed are also removed,
* including elements which miss mandatory attributes.
*
* @param DOMElement $node Node.
* @return string[]|null Required scripts, or null if the element was removed.
*/
private function process_node( DOMElement $node ) {
// Remove nodes with tags that have not been put in the allowlist.
if ( ! $this->is_amp_allowed_tag( $node ) ) {
// If it's not an allowed tag, replace the node with it's children.
$this->replace_node_with_children( $node );
// Return early since we don't know anything about this node to validate it.
return null;
}
/*
* Compile a list of rule_specs to validate for this node
* based on tag name of the node.
*/
$rule_spec_list_to_validate = [];
$validation_errors = [];
$rule_spec_list = $this->allowed_tags[ $node->nodeName ];
foreach ( $rule_spec_list as $id => $rule_spec ) {
$validity = $this->validate_tag_spec_for_node( $node, $rule_spec[ AMP_Rule_Spec::TAG_SPEC ] );
if ( true === $validity ) {
$rule_spec_list_to_validate[ $id ] = $this->get_rule_spec_list_to_validate( $node, $rule_spec );
} else {
$validation_errors[] = array_merge(
$validity,
[ 'spec_name' => $this->get_spec_name( $node, $rule_spec[ AMP_Rule_Spec::TAG_SPEC ] ) ]
);
}
}
// If no valid rule_specs exist, then remove this node and return.
if ( empty( $rule_spec_list_to_validate ) ) {
if ( 1 === count( $validation_errors ) ) {
// If there was only one tag spec candidate that failed, use its error code for removing the node,
// since we know it is the specific reason for why the node had to be removed.
// This is the normal case.
$this->remove_invalid_child(
$node,
$validation_errors[0]
);
} else {
$spec_names = wp_list_pluck( $validation_errors, 'spec_name' );
$unique_validation_error_count = count(
array_unique(
array_map(
static function ( $validation_error ) {
unset(
$validation_error['spec_name'],
// Remove other keys that may make the error unique.
$validation_error['required_parent_name'],
$validation_error['required_ancestor_name'],
$validation_error['required_child_count'],
$validation_error['required_min_child_count'],
$validation_error['required_attr_value']
);
return $validation_error;
},
$validation_errors
),
SORT_REGULAR
)
);
if ( 1 === $unique_validation_error_count ) {
// If all of the validation errors are the same except for the spec_name, use the common error code.
$validation_error = $validation_errors[0];
unset( $validation_error['spec_name'] );
$this->remove_invalid_child(
$node,
array_merge(
$validation_error,
compact( 'spec_names' )
)
);
} else {
// Otherwise, we have a rare condition where multiple tag specs fail for different reasons.
foreach ( $validation_errors as $validation_error ) {
if ( true === $this->remove_invalid_child( $node, $validation_error ) ) {
break; // Once removed, ignore remaining errors.
}
}
}
}
return null;
}
// The remaining validations all have to do with attributes.
$attr_spec_list = [];
$tag_spec = [];
$cdata = [];
/*
* If we have exactly one rule_spec, use it's attr_spec_list
* to validate the node's attributes.
*/
if ( 1 === count( $rule_spec_list_to_validate ) ) {
$rule_spec = array_pop( $rule_spec_list_to_validate );
$attr_spec_list = $rule_spec[ AMP_Rule_Spec::ATTR_SPEC_LIST ];
$tag_spec = $rule_spec[ AMP_Rule_Spec::TAG_SPEC ];
if ( isset( $rule_spec[ AMP_Rule_Spec::CDATA ] ) ) {
$cdata = $rule_spec[ AMP_Rule_Spec::CDATA ];
}
} else {
/*
* If there is more than one valid rule_spec for this node,
* then try to deduce which one is intended by inspecting
* the node's attributes.
*/
/*
* Get a score from each attr_spec_list by seeing how many
* attributes and values match the node.
*/
$attr_spec_scores = [];
foreach ( $rule_spec_list_to_validate as $spec_id => $rule_spec ) {
$attr_spec_scores[ $spec_id ] = $this->validate_attr_spec_list_for_node( $node, $rule_spec[ AMP_Rule_Spec::ATTR_SPEC_LIST ] );
}
// Remove all spec lists that didn't match.
$attr_spec_scores = array_filter( $attr_spec_scores );
// If no attribute spec lists match, then the element must be removed.
if ( empty( $attr_spec_scores ) ) {
$this->remove_node( $node );
return null;
}
// Get the key(s) to the highest score(s).
$spec_ids_sorted = array_keys( $attr_spec_scores, max( $attr_spec_scores ), true );
// If there is exactly one attr_spec with a max score, use that one.
if ( 1 === count( $spec_ids_sorted ) ) {
$attr_spec_list = $rule_spec_list_to_validate[ $spec_ids_sorted[0] ][ AMP_Rule_Spec::ATTR_SPEC_LIST ];
$tag_spec = $rule_spec_list_to_validate[ $spec_ids_sorted[0] ][ AMP_Rule_Spec::TAG_SPEC ];
if ( isset( $rule_spec_list_to_validate[ $spec_ids_sorted[0] ][ AMP_Rule_Spec::CDATA ] ) ) {
$cdata = $rule_spec_list_to_validate[ $spec_ids_sorted[0] ][ AMP_Rule_Spec::CDATA ];
}
} else {
// This should not happen very often, but...
// If we're here, then we're not sure which spec should
// be used. Let's use the top scoring ones.
foreach ( $spec_ids_sorted as $id ) {
$attr_spec_list = array_merge(
$attr_spec_list,
$rule_spec_list_to_validate[ $id ][ AMP_Rule_Spec::ATTR_SPEC_LIST ]
);
$tag_spec = array_merge(
$tag_spec,
$rule_spec_list_to_validate[ $id ][ AMP_Rule_Spec::TAG_SPEC ]
);
if ( isset( $rule_spec_list_to_validate[ $id ][ AMP_Rule_Spec::CDATA ] ) ) {
$cdata = array_merge( $cdata, $rule_spec_list_to_validate[ $id ][ AMP_Rule_Spec::CDATA ] );
}
}
$first_spec = reset( $rule_spec_list_to_validate );
if ( empty( $attr_spec_list ) && isset( $first_spec[ AMP_Rule_Spec::ATTR_SPEC_LIST ] ) ) {
$attr_spec_list = $first_spec[ AMP_Rule_Spec::ATTR_SPEC_LIST ];
}
}
}
$attr_spec_list = array_merge(
$this->globally_allowed_attributes,
$attr_spec_list
);
// Remove element if it has illegal CDATA.
if ( ! empty( $cdata ) ) {
$validity = $this->validate_cdata_for_node( $node, $cdata );
if ( true !== $validity ) {
$sanitized = $this->remove_invalid_child(
$node,
array_merge(
$validity,
[ 'spec_name' => $this->get_spec_name( $node, $tag_spec ) ]
)
);
return $sanitized ? null : $this->get_required_script_components( $node, $tag_spec, $attr_spec_list );
}
}
// Amend spec list with layout.
if ( isset( $tag_spec['amp_layout'] ) ) {
$attr_spec_list = array_merge( $attr_spec_list, $this->layout_allowed_attributes );
if ( isset( $tag_spec['amp_layout']['supported_layouts'] ) ) {
$layouts = wp_array_slice_assoc( Layout::FROM_SPEC, $tag_spec['amp_layout']['supported_layouts'] );
$attr_spec_list['layout'][ AMP_Rule_Spec::VALUE_REGEX_CASEI ] = '(' . implode( '|', $layouts ) . ')';
}
}
// Enforce unique constraint.
if ( ! empty( $tag_spec['unique'] ) ) {
$removed = false;
$tag_spec_key = wp_json_encode( $tag_spec );
if ( ! empty( $this->visited_unique_tag_specs[ $node->nodeName ][ $tag_spec_key ] ) ) {
$removed = $this->remove_invalid_child(
$node,
[
'code' => self::DUPLICATE_UNIQUE_TAG,
'spec_name' => $this->get_spec_name( $node, $tag_spec ),
]
);
}
$this->visited_unique_tag_specs[ $node->nodeName ][ $tag_spec_key ] = true;
if ( $removed ) {
return null;
}
}
// Remove the element if it is has an invalid layout.
$layout_validity = $this->is_valid_layout( $tag_spec, $node );
if ( true !== $layout_validity ) {
$sanitized = $this->remove_invalid_child( $node, $layout_validity );
return $sanitized ? null : $this->get_required_script_components( $node, $tag_spec, $attr_spec_list );
}
// Identify attribute values that don't conform to the attr_spec.
$disallowed_attributes = $this->sanitize_disallowed_attribute_values_in_node( $node, $attr_spec_list );
// Remove all invalid attributes.
if ( ! empty( $disallowed_attributes ) ) {
/*
* Capture all element attributes up front so that differing validation errors result when
* one invalid attribute is accepted but the others are still rejected.
*/
$element_attributes = [];
foreach ( $node->attributes as $attribute ) {
$element_attributes[ $attribute->nodeName ] = $attribute->nodeValue;
}
$removed_attributes = [];
foreach ( $disallowed_attributes as $disallowed_attribute ) {
/**
* Returned vars.
*
* @var DOMAttr $attr_node
* @var string $error_code
* @var array $error_data
*/
list( $attr_node, $error_code, $error_data ) = $disallowed_attribute;
$validation_error = [
'code' => $error_code,
'element_attributes' => $element_attributes,
];
if ( self::DISALLOWED_PROPERTY_IN_ATTR_VALUE === $error_code ) {
$properties = $this->parse_properties_attribute( $attr_node->nodeValue );
$validation_error['meta_property_name'] = $error_data['name'];
if ( ! $this->is_empty_attribute_value( $properties[ $error_data['name'] ] ) ) {
$validation_error['meta_property_value'] = $properties[ $error_data['name'] ];
}
if ( $this->should_sanitize_validation_error( $validation_error, [ 'node' => $attr_node ] ) ) {
unset( $properties[ $error_data['name'] ] );
$node->setAttribute( $attr_node->nodeName, $this->serialize_properties_attribute( $properties ) );
}
} elseif ( self::MISSING_REQUIRED_PROPERTY_VALUE === $error_code ) {
$validation_error['meta_property_name'] = $error_data['name'];
$validation_error['meta_property_value'] = $error_data['value'];
$validation_error['meta_property_required_value'] = $error_data['required_value'];
if ( $this->should_sanitize_validation_error( $validation_error, [ 'node' => $attr_node ] ) ) {
$properties = $this->parse_properties_attribute( $attr_node->nodeValue );
if ( ! empty( $attr_spec_list[ $attr_node->nodeName ]['value_properties'][ $error_data['name'] ]['mandatory'] ) ) {
$properties[ $error_data['name'] ] = $error_data['required_value'];
} else {
unset( $properties[ $error_data['name'] ] );
}
$node->setAttribute( $attr_node->nodeName, $this->serialize_properties_attribute( $properties ) );
}
} elseif ( self::MISSING_MANDATORY_PROPERTY === $error_code ) {
$validation_error['meta_property_name'] = $error_data['name'];
$validation_error['meta_property_required_value'] = $error_data['required_value'];
if ( $this->should_sanitize_validation_error( $validation_error, [ 'node' => $attr_node ] ) ) {
$properties = array_merge(
$this->parse_properties_attribute( $attr_node->nodeValue ),
[ $error_data['name'] => $error_data['required_value'] ]
);
$node->setAttribute( $attr_node->nodeName, $this->serialize_properties_attribute( $properties ) );
}
} else {
$attr_spec = isset( $attr_spec_list[ $attr_node->nodeName ] ) ? $attr_spec_list[ $attr_node->nodeName ] : [];
if ( $this->remove_invalid_attribute( $node, $attr_node, $validation_error, $attr_spec ) ) {
$removed_attributes[] = $attr_node;
}
}
}
/*
* Only run cleanup after the fact to prevent a scenario where invalid markup is kept and so the attribute
* is actually not removed. This prevents a "DOMException: Not Found Error" from happening when calling
* remove_invalid_attribute() since clean_up_after_attribute_removal() can end up removing invalid link
* attributes (like 'target') when there is an invalid 'href' attribute, but if the 'target' attribute is
* itself invalid, then if clean_up_after_attribute_removal() is called inside of remove_invalid_attribute()
* it can cause a subsequent invocation of remove_invalid_attribute() to try to remove an invalid
* attribute that has already been removed from the DOM.
*/
foreach ( $removed_attributes as $removed_attribute ) {
$this->clean_up_after_attribute_removal( $node, $removed_attribute );
}
}
if ( ! empty( $tag_spec[ AMP_Rule_Spec::DESCENDANT_TAG_LIST ] ) ) {
$allowed_tags = AMP_Allowed_Tags_Generated::get_descendant_tag_list( $tag_spec[ AMP_Rule_Spec::DESCENDANT_TAG_LIST ] );
if ( ! empty( $allowed_tags ) ) {
$this->remove_disallowed_descendants( $node, $allowed_tags, $this->get_spec_name( $node, $tag_spec ) );
}
}
// If the node disallows any siblings, remove them.
if ( ! empty( $tag_spec[ AMP_Rule_Spec::SIBLINGS_DISALLOWED ] ) ) {
$this->remove_disallowed_siblings( $node, $this->get_spec_name( $node, $tag_spec ) );
}
// After attributes have been sanitized (and potentially removed), if mandatory attribute(s) are missing, remove the element.
$missing_mandatory_attributes = $this->get_missing_mandatory_attributes( $attr_spec_list, $node );
if ( ! empty( $missing_mandatory_attributes ) ) {
$sanitized = $this->remove_invalid_child(
$node,
[
'code' => self::ATTR_REQUIRED_BUT_MISSING,
'attributes' => $missing_mandatory_attributes,
'spec_name' => $this->get_spec_name( $node, $tag_spec ),
]
);
return $sanitized ? null : $this->get_required_script_components( $node, $tag_spec, $attr_spec_list );
}
if ( ! empty( $tag_spec[ AMP_Rule_Spec::MANDATORY_ANYOF ] ) ) {
$anyof_attributes = $this->get_element_attribute_intersection( $node, $tag_spec[ AMP_Rule_Spec::MANDATORY_ANYOF ] );
if ( 0 === count( $anyof_attributes ) ) {
$sanitized = $this->remove_invalid_child(
$node,
[
'code' => self::MANDATORY_ANYOF_ATTR_MISSING,
'mandatory_anyof_attrs' => $tag_spec[ AMP_Rule_Spec::MANDATORY_ANYOF ], // @todo Temporary as value can be looked up via spec name. See https://github.com/ampproject/amp-wp/pull/3817.
'spec_name' => $this->get_spec_name( $node, $tag_spec ),
]
);
return $sanitized ? null : $this->get_required_script_components( $node, $tag_spec, $attr_spec_list );
}
}
if ( ! empty( $tag_spec[ AMP_Rule_Spec::MANDATORY_ONEOF ] ) ) {
$oneof_attributes = $this->get_element_attribute_intersection( $node, $tag_spec[ AMP_Rule_Spec::MANDATORY_ONEOF ] );
if ( 0 === count( $oneof_attributes ) ) {
$sanitized = $this->remove_invalid_child(
$node,
[
'code' => self::MANDATORY_ONEOF_ATTR_MISSING,
'mandatory_oneof_attrs' => $tag_spec[ AMP_Rule_Spec::MANDATORY_ONEOF ], // @todo Temporary as value can be looked up via spec name. See https://github.com/ampproject/amp-wp/pull/3817.
'spec_name' => $this->get_spec_name( $node, $tag_spec ),
]
);
return $sanitized ? null : $this->get_required_script_components( $node, $tag_spec, $attr_spec_list );
} elseif ( count( $oneof_attributes ) > 1 ) {
$sanitized = $this->remove_invalid_child(
$node,
[
'code' => self::DUPLICATE_ONEOF_ATTRS,
'duplicate_oneof_attrs' => $oneof_attributes,
'spec_name' => $this->get_spec_name( $node, $tag_spec ),
]
);
return $sanitized ? null : $this->get_required_script_components( $node, $tag_spec, $attr_spec_list );
}
}
return $this->get_required_script_components( $node, $tag_spec, $attr_spec_list );
}
/**
* Get required AMP component scripts.
*
* @param DOMElement $node Element.
* @param array $tag_spec Tag spec.
* @param array $attr_spec_list Attribute spec list.
* @return string[] Script component handles.
*/
private function get_required_script_components( DOMElement $node, $tag_spec, $attr_spec_list ) {
$script_components = [];
if ( ! empty( $tag_spec['requires_extension'] ) ) {
$script_components = array_merge( $script_components, $tag_spec['requires_extension'] );
}
// Add required AMP components for attributes.
foreach ( $node->attributes as $attribute ) {
if ( isset( $attr_spec_list[ $attribute->nodeName ]['requires_extension'] ) ) {
$script_components = array_merge(
$script_components,
$attr_spec_list[ $attribute->nodeName ]['requires_extension']
);
}
}
// Manually add components for attributes; this is hard-coded because attributes do not have requires_extension like tags do. See <https://github.com/ampproject/amp-wp/issues/1808>.
if ( $node->hasAttribute( 'lightbox' ) ) {
$script_components[] = 'amp-lightbox-gallery';
}
// Check if element needs amp-bind component.
if ( ! in_array( 'amp-bind', $this->script_components, true ) ) {
foreach ( $node->attributes as $name => $value ) {
if ( Amp::BIND_DATA_ATTR_PREFIX === substr( $name, 0, 14 ) ) {
$script_components[] = 'amp-bind';
break;
}
}
}
return $script_components;
}
/**
* Whether a node is missing a mandatory attribute.
*
* @param array $attr_spec The attribute specification.
* @param DOMElement $node The DOMElement of the node to check.
* @return bool $is_missing boolean Whether a required attribute is missing.
*/
public function is_missing_mandatory_attribute( $attr_spec, DOMElement $node ) {
return 0 !== count( $this->get_missing_mandatory_attributes( $attr_spec, $node ) );
}
/**
* Get list of mandatory missing mandatory attributes.
*
* @param array $attr_spec The attribute specification.
* @param DOMElement $node The DOMElement of the node to check.
* @return string[] Names of missing attributes.
*/
private function get_missing_mandatory_attributes( $attr_spec, DOMElement $node ) {
$missing_attributes = [];
foreach ( $attr_spec as $attr_name => $attr_spec_rule_value ) {
if ( empty( $attr_spec_rule_value[ AMP_Rule_Spec::MANDATORY ] ) ) {
continue;
}
if ( '\u' === substr( $attr_name, 0, 2 ) ) {
$attr_name = html_entity_decode( '&#x' . substr( $attr_name, 2 ) . ';' ); // Probably ⚡.
}
if ( ! $node->hasAttribute( $attr_name ) && AMP_Rule_Spec::FAIL === $this->check_attr_spec_rule_mandatory( $node, $attr_name, $attr_spec_rule_value ) ) {
$missing_attributes[] = $attr_name;
}
}
return $missing_attributes;
}
/**
* Validate element for its CDATA.
*
* @since 0.7
*
* @param DOMElement $element Element.
* @param array $cdata_spec CDATA.
* @return true|array True when valid or error data when invalid.
*/
private function validate_cdata_for_node( DOMElement $element, $cdata_spec ) {
if (
isset( $cdata_spec['max_bytes'] ) && strlen( $element->textContent ) > $cdata_spec['max_bytes']
&&
// Skip the <style amp-custom> tag, as we want to display it even with an excessive size if it passed the style sanitizer.
// This would mean that AMP was disabled to not break the styling.
! ( 'style' === $element->nodeName && $element->hasAttribute( 'amp-custom' ) )
) {
return [
'code' => self::CDATA_TOO_LONG,
];
}
if ( isset( $cdata_spec['disallowed_cdata_regex'] ) ) {
foreach ( $cdata_spec['disallowed_cdata_regex'] as $disallowed_cdata_regex ) {
if ( preg_match( '@' . $disallowed_cdata_regex['regex'] . '@u', $element->textContent ) ) {
if ( isset( $disallowed_cdata_regex['error_message'] ) ) {
// There are only a few error messages, so map them to error codes.
switch ( $disallowed_cdata_regex['error_message'] ) {
case 'CSS i-amphtml- name prefix':
// The prefix used in selectors is handled by style sanitizer.
return [ 'code' => self::INVALID_CDATA_CSS_I_AMPHTML_NAME ];
case 'contents':
return [ 'code' => self::INVALID_CDATA_CONTENTS ];
case 'html comments':
return [ 'code' => self::INVALID_CDATA_HTML_COMMENTS ];
}
}
// Note: This fallback case is not currently reachable because all error messages are accounted for in the switch statement.
return [ 'code' => self::CDATA_VIOLATES_DENYLIST ];
}
}
} elseif ( isset( $cdata_spec['cdata_regex'] ) ) {
$delimiter = false === strpos( $cdata_spec['cdata_regex'], '@' ) ? '@' : '#';
if ( ! preg_match( $delimiter . $cdata_spec['cdata_regex'] . $delimiter . 'u', $element->textContent ) ) {
return [ 'code' => self::MANDATORY_CDATA_MISSING_OR_INCORRECT ];
}
} elseif ( isset( $cdata_spec['mandatory_cdata'] ) && $cdata_spec['mandatory_cdata'] !== $element->textContent ) {
return [ 'code' => self::MANDATORY_CDATA_MISSING_OR_INCORRECT ];
}
// When the CDATA is expected to be JSON, ensure it's valid JSON.
if ( 'script' === $element->nodeName && 'application/json' === $element->getAttribute( 'type' ) ) {
if ( '' === trim( $element->textContent ) ) {
return [ 'code' => self::JSON_ERROR_EMPTY ];
}
json_decode( $element->textContent );
$json_last_error = json_last_error();
if ( JSON_ERROR_NONE !== $json_last_error ) {
return [ 'code' => $this->get_json_error_code( $json_last_error ) ];
}
}
return true;
}
/**
* Gets the JSON error code for the last error.
*
* @link https://www.php.net/manual/en/function.json-last-error.php#refsect1-function.json-last-error-returnvalues
*
* @param int $json_last_error The last JSON error code.
* @return string The error code for the last JSON error.
*/
private function get_json_error_code( $json_last_error ) {
static $possible_json_errors = [
'JSON_ERROR_CTRL_CHAR',
'JSON_ERROR_DEPTH',
'JSON_ERROR_STATE_MISMATCH',
'JSON_ERROR_SYNTAX',
'JSON_ERROR_UTF8',
];
foreach ( $possible_json_errors as $possible_error ) {
if ( constant( $possible_error ) === $json_last_error ) {
return $possible_error;
}
}
return 'JSON_ERROR_SYNTAX';
}
/**
* Determines is a node is currently valid per its tag specification.
*
* Checks to see if a node's placement with the DOM is be valid for the
* given tag_spec. If there are restrictions placed on the type of node
* that can be an immediate parent or an ancestor of this node, then make
* sure those restrictions are met.
*
* This method has no side effects. It should not sanitize the DOM. It is purely to see if the spec matches.
*
* @since 0.5
*
* @param DOMElement $node The node to validate.
* @param array $tag_spec The specification.
* @return true|array True if node is valid for spec, or error data array if otherwise.
*/
private function validate_tag_spec_for_node( DOMElement $node, $tag_spec ) {
if ( ! empty( $tag_spec[ AMP_Rule_Spec::MANDATORY_PARENT ] ) ) {
$missing_required_parent = false;
if ( 'subscriptions-section content swg_amp_cache_nonce' === $tag_spec[ AMP_Rule_Spec::MANDATORY_PARENT ] ) {
// Special case for mandatory parent name which doesn't follow the pattern where mandatory_parent is just a tag name.
if ( ! (
$this->has_parent( $node, 'section' )
&&