-
Notifications
You must be signed in to change notification settings - Fork 385
/
class-amp-style-sanitizer.php
3852 lines (3460 loc) · 137 KB
/
class-amp-style-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_Style_Sanitizer
*
* @package AMP
*/
use AmpProject\Amp;
use AmpProject\AmpWP\Icon;
use AmpProject\AmpWP\Option;
use AmpProject\AmpWP\RemoteRequest\CachedRemoteGetRequest;
use AmpProject\AmpWP\RemoteRequest\WpHttpRemoteGetRequest;
use AmpProject\AmpWP\ValidationExemption;
use AmpProject\DevMode;
use AmpProject\Dom\Document;
use AmpProject\Dom\Element;
use AmpProject\Exception\FailedToGetFromRemoteUrl;
use AmpProject\Html\Attribute;
use AmpProject\Html\RequestDestination;
use AmpProject\Html\Tag;
use AmpProject\RemoteGetRequest;
use Sabberworm\CSS\CSSList\AtRuleBlockList;
use Sabberworm\CSS\CSSList\CSSList;
use Sabberworm\CSS\CSSList\Document as CSSDocument;
use Sabberworm\CSS\CSSList\KeyFrame;
use Sabberworm\CSS\OutputFormat;
use Sabberworm\CSS\Parsing\SourceException;
use Sabberworm\CSS\Property\AtRule;
use Sabberworm\CSS\Property\Import;
use Sabberworm\CSS\Property\Selector;
use Sabberworm\CSS\RuleSet\AtRuleSet;
use Sabberworm\CSS\RuleSet\DeclarationBlock;
use Sabberworm\CSS\RuleSet\RuleSet;
use Sabberworm\CSS\Rule\Rule;
use Sabberworm\CSS\Value\CSSFunction;
use Sabberworm\CSS\Value\RuleValueList;
use Sabberworm\CSS\Value\URL;
use Sabberworm\CSS\Value\Value;
/**
* Class AMP_Style_Sanitizer
*
* Collects inline styles and outputs them in the amp-custom stylesheet.
*
* @internal
*/
class AMP_Style_Sanitizer extends AMP_Base_Sanitizer {
const STYLE_AMP_CUSTOM_SPEC_NAME = 'style amp-custom';
const STYLE_AMP_KEYFRAMES_SPEC_NAME = 'style[amp-keyframes]';
const ORIGINAL_STYLE_ATTRIBUTE_NAME = 'data-amp-original-style';
const STYLE_AMP_CUSTOM_GROUP_INDEX = 0;
const STYLE_AMP_KEYFRAMES_GROUP_INDEX = 1;
// Error codes raised during parsing CSS. See get_css_parser_validation_error_codes.
const CSS_SYNTAX_INVALID_AT_RULE = 'CSS_SYNTAX_INVALID_AT_RULE';
const CSS_SYNTAX_INVALID_DECLARATION = 'CSS_SYNTAX_INVALID_DECLARATION';
const CSS_SYNTAX_INVALID_PROPERTY = 'CSS_SYNTAX_INVALID_PROPERTY';
const CSS_SYNTAX_INVALID_PROPERTY_NOLIST = 'CSS_SYNTAX_INVALID_PROPERTY_NOLIST';
const CSS_SYNTAX_INVALID_IMPORTANT = 'CSS_SYNTAX_INVALID_IMPORTANT';
const CSS_SYNTAX_PARSE_ERROR = 'CSS_SYNTAX_PARSE_ERROR';
const CSS_DISALLOWED_SELECTOR = 'CSS_DISALLOWED_SELECTOR';
const STYLESHEET_FETCH_ERROR = 'STYLESHEET_FETCH_ERROR';
const STYLESHEET_TOO_LONG = 'STYLESHEET_TOO_LONG';
// Error code when encountering 'i-amphtml-' prefixing a class name in an HTML class attribute.
const DISALLOWED_ATTR_CLASS_NAME = 'DISALLOWED_ATTR_CLASS_NAME';
// These are internal to the sanitizer and not exposed as validation error codes.
const STYLESHEET_DISALLOWED_FILE_EXT = 'STYLESHEET_DISALLOWED_FILE_EXT';
const STYLESHEET_EXTERNAL_FILE_URL = 'STYLESHEET_EXTERNAL_FILE_URL';
const STYLESHEET_FILE_PATH_NOT_FOUND = 'STYLESHEET_FILE_PATH_NOT_FOUND';
const STYLESHEET_FILE_PATH_NOT_ALLOWED = 'STYLESHEET_FILE_PATH_NOT_ALLOWED';
const STYLESHEET_URL_SYNTAX_ERROR = 'STYLESHEET_URL_SYNTAX_ERROR';
const STYLESHEET_INVALID_RELATIVE_PATH = 'STYLESHEET_INVALID_RELATIVE_PATH';
/**
* Percentage at which the used CSS budget becomes a warning.
*
* @var int
*/
const CSS_BUDGET_WARNING_PERCENTAGE = 80;
/**
* Inline style selector's specificity multiplier, i.e. used to generate the number of ':not(#_)' placeholders.
*
* @var int
*/
const INLINE_SPECIFICITY_MULTIPLIER = 5; // @todo The correctness of using "5" should be validated.
/**
* Array index for tag names extracted from a selector.
*
* @private
* @since 1.1
* @see \AMP_Style_Sanitizer::parse_stylesheet()
*/
const SELECTOR_EXTRACTED_TAGS = 0;
/**
* Array index for class names extracted from a selector.
*
* @private
* @since 1.1
* @see \AMP_Style_Sanitizer::parse_stylesheet()
*/
const SELECTOR_EXTRACTED_CLASSES = 1;
/**
* Array index for IDs extracted from a selector.
*
* @private
* @since 1.1
* @see \AMP_Style_Sanitizer::parse_stylesheet()
*/
const SELECTOR_EXTRACTED_IDS = 2;
/**
* Array index for attributes extracted from a selector.
*
* @private
* @since 1.1
* @see \AMP_Style_Sanitizer::parse_stylesheet()
*/
const SELECTOR_EXTRACTED_ATTRIBUTES = 3;
/**
* Array of flags used to control sanitization.
*
* @var array {
* @type bool $disable_style_processing Whether arbitrary styles should be allowed. When enabled, external stylesheet links, style elements, and style attributes will all be unprocessed and marked as PX-verified.
* @type string[] $dynamic_element_selectors Selectors for elements (or their ancestors) which contain dynamic content; selectors containing these will not be filtered.
* @type bool $use_document_element Whether the root of the document should be used rather than the body.
* @type bool $require_https_src Require HTTPS URLs.
* @type callable $validation_error_callback Function to call when a validation error is encountered.
* @type bool $should_locate_sources Whether to locate the sources when reporting validation errors.
* @type string $parsed_cache_variant Additional value by which to vary parsed cache.
* @type string[] $focus_within_classes Class names in selectors that should be replaced with :focus-within pseudo classes.
* @type string[] $low_priority_plugins Plugin slugs of the plugins to deprioritize when hitting the CSS limit.
* @type bool $allow_transient_caching Whether to allow caching parsed CSS in transients. This may need to be disabled when there is highly-variable CSS content.
* @type bool $skip_tree_shaking Whether tree shaking should be skipped.
* @type bool $allow_excessive_css Whether to allow CSS to exceed the allowed max bytes (without raising validation errors).
* @type bool $transform_important_qualifiers Whether !important rules should be transformed. This also necessarily transform inline style attributes.
* @type string[] $font_face_display_overrides Array of the font family names and the font-display value they should each have.
* }
*/
protected $args;
/**
* Default args.
*
* @var array
*/
protected $DEFAULT_ARGS = [
'disable_style_processing' => false,
'dynamic_element_selectors' => [
'amp-img',
'amp-anim',
'amp-list',
'amp-live-list',
'[submit-error]',
'[submit-success]',
'amp-script',
'amp-story-captions',
],
'should_locate_sources' => false,
'parsed_cache_variant' => null,
'focus_within_classes' => [ 'focus' ],
'low_priority_plugins' => [ 'query-monitor' ],
'allow_transient_caching' => true,
'skip_tree_shaking' => false,
'allow_excessive_css' => false,
'transform_important_qualifiers' => true,
'font_face_display_overrides' => [
'NonBreakingSpaceOverride' => 'optional',
'Inter var' => 'optional',
'Genericons' => 'block',
],
];
/**
* List of stylesheet parts prior to selector/rule removal (tree shaking).
*
* Keys are MD5 hashes of stylesheets.
*
* @since 1.0
* @var array[] {
* @type int $group Either STYLE_AMP_CUSTOM_GROUP_INDEX or STYLE_AMP_KEYFRAMES_GROUP_INDEX.
* @type int $original_size The byte size of the stylesheet prior to parsing and tree shaking.
* @type int $final_size The byte size of the stylesheet after parsing and tree shaking.
* @type DOMElement|DOMAttr $element Origin element for the styles.
* @type string $origin Either 'style_element', 'style_attribute', or 'link_element'.
* @type array $sources Source stack.
* @type int $priority Priority of the stylesheet.
* @type array|null $tokens Stylesheet tokens, with declaration blocks being represented as arrays. Null after shaking occurs.
* @type array|null $shaken_tokens Shaken stylesheet tokens, where first array index of each array item is whether the token is included. Null until shaking occurs.
* @type string $serialized Stylesheet tokens serialized into CSS.
* @type string $hash MD5 hash of the parsed stylesheet tokens, prior to tree-shaking.
* @type array $sources Sources for the node.
* @type bool $keyframes Whether an amp-keyframes.
* @type float $parse_time The time duration it took to parse the stylesheet, in milliseconds.
* @type bool $cached Whether the parsed stylesheet was retrieved from cache.
* }
*/
private $pending_stylesheets = [];
/**
* Spec for style[amp-custom] cdata.
*
* @since 1.0
* @var array
*/
private $style_custom_cdata_spec;
/**
* The style[amp-custom] element.
*
* @var DOMElement
*/
private $amp_custom_style_element;
/**
* Spec for style[amp-keyframes] cdata.
*
* @since 1.0
* @var array
*/
private $style_keyframes_cdata_spec;
/**
* Regex for allowed font stylesheet URL.
*
* @var string
*/
private $allowed_font_src_regex;
/**
* Base URL for styles.
*
* Full URL with trailing slash.
*
* @var string
*/
private $base_url;
/**
* URL of the content directory.
*
* @var string
*/
private $content_url;
/**
* Class names used in document.
*
* This list includes all class names that AMP can dynamically add.
*
* @link https://www.ampproject.org/docs/reference/components/amp-dynamic-css-classes
* @since 1.0
* @var array|null
*/
private $used_class_names;
/**
* Regular expression pattern to match focus class names in selectors.
*
* The computed pattern is cached to prevent re-constructing for each processed selector.
*
* @var string|null
*/
private $focus_class_name_selector_pattern;
/**
* Attributes used in the document.
*
* This is initially populated with boolean attributes which can be mutated by AMP at runtime,
* since they can by dynamically added at any time.
*
* @todo With the exception of 'hidden' (which can be on any element), the values here could be removed in favor of
* checking to see if any of the related elements exist in the page in `\AMP_Style_Sanitizer::has_used_attributes()`.
* Nevertheless, selectors mentioning these attributes are very numerous, so tree-shaking improvements will be marginal.
*
* @see \AMP_Style_Sanitizer::has_used_attributes()
*
* @since 1.1
* @var array
*/
private $used_attributes = [
'autofocus' => true,
'checked' => true,
'controls' => true,
'disabled' => true,
'hidden' => true,
'loop' => true,
'multiple' => true,
'readonly' => true,
'required' => true,
'selected' => true,
];
/**
* Tag names used in document.
*
* @since 1.0
* @var array|null
*/
private $used_tag_names;
/**
* Current node being processed.
*
* @var DOMElement|DOMAttr
*/
private $current_node;
/**
* Current sources for a given node.
*
* @var array|null
*/
private $current_sources;
/**
* Log of the stylesheet URLs that have been imported to guard against infinite loops.
*
* @var array
*/
private $processed_imported_stylesheet_urls = [];
/**
* Mapping of HTML element selectors to AMP selector elements.
*
* @var array
*/
private $selector_mappings = [];
/**
* Elements in extensions which use the video-manager, and thus the video-autoplay.css.
*
* @var array
*/
private $video_autoplay_elements = [
'amp-3q-player',
'amp-brid-player',
'amp-brightcove',
'amp-dailymotion',
'amp-delight-player',
'amp-ima-video',
'amp-mowplayer',
'amp-nexxtv-player',
'amp-ooyala-player',
'amp-powr-player',
'amp-story-auto-ads',
'amp-video',
'amp-video-iframe',
'amp-vimeo',
'amp-viqeo-player',
'amp-wistia-player',
'amp-youtube',
];
/**
* Remote request instance.
*
* @var RemoteGetRequest
*/
private $remote_request;
/**
* All current sanitizers.
*
* @see AMP_Style_Sanitizer::init()
* @var AMP_Base_Sanitizer[]
*/
private $sanitizers = [];
/**
* Get error codes that can be raised during parsing of CSS.
*
* This is used to determine which validation errors should be taken into account
* when determining which validation errors should vary the parse cache.
*
* @return array
*/
public static function get_css_parser_validation_error_codes() {
return [
self::CSS_SYNTAX_INVALID_AT_RULE,
self::CSS_SYNTAX_INVALID_DECLARATION,
self::CSS_SYNTAX_INVALID_PROPERTY,
self::CSS_SYNTAX_INVALID_PROPERTY_NOLIST,
self::CSS_SYNTAX_INVALID_IMPORTANT,
self::CSS_SYNTAX_PARSE_ERROR,
self::CSS_DISALLOWED_SELECTOR,
self::STYLESHEET_FETCH_ERROR,
self::STYLESHEET_TOO_LONG,
];
}
/**
* Determine whether the version of PHP-CSS-Parser loaded has all required features for tree shaking and CSS processing.
*
* @since 1.0.2
*
* @return bool Returns true if the plugin's forked version of PHP-CSS-Parser is loaded by Composer.
*/
public static function has_required_php_css_parser() {
$reflection = new ReflectionClass( 'Sabberworm\CSS\OutputFormat' );
$has_output_format_extensions = (
$reflection->hasProperty( 'sBeforeAtRuleBlock' )
&&
$reflection->hasProperty( 'sAfterAtRuleBlock' )
&&
$reflection->hasProperty( 'sBeforeDeclarationBlock' )
&&
$reflection->hasProperty( 'sAfterDeclarationBlockSelectors' )
&&
$reflection->hasProperty( 'sAfterDeclarationBlock' )
);
if ( ! $has_output_format_extensions ) {
return false;
}
return true;
}
/**
* AMP_Base_Sanitizer constructor.
*
* @since 0.7
*
* @param Document $dom Represents the HTML document to sanitize.
* @param array $args Args.
*/
public function __construct( $dom, array $args = [] ) {
parent::__construct( $dom, $args );
foreach ( AMP_Allowed_Tags_Generated::get_allowed_tag( 'style' ) as $spec_rule ) {
if ( ! isset( $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) ) {
continue;
}
if ( self::STYLE_AMP_KEYFRAMES_SPEC_NAME === $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) {
$this->style_keyframes_cdata_spec = $spec_rule[ AMP_Rule_Spec::CDATA ];
} elseif ( self::STYLE_AMP_CUSTOM_SPEC_NAME === $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) {
$this->style_custom_cdata_spec = $spec_rule[ AMP_Rule_Spec::CDATA ];
}
}
$spec_name = 'link rel=stylesheet for fonts'; // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
foreach ( AMP_Allowed_Tags_Generated::get_allowed_tag( 'link' ) as $spec_rule ) {
if ( isset( $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) && $spec_name === $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) {
$this->allowed_font_src_regex = '/^(' . $spec_rule[ AMP_Rule_Spec::ATTR_SPEC_LIST ]['href']['value_regex'] . ')$/';
break;
}
}
$guessurl = site_url();
if ( ! $guessurl ) {
$guessurl = wp_guess_url();
}
$this->base_url = untrailingslashit( $guessurl );
$this->content_url = WP_CONTENT_URL;
$this->remote_request = new CachedRemoteGetRequest( new WpHttpRemoteGetRequest() );
}
/**
* Get list of CSS styles in HTML content of Dom\Document ($this->dom).
*
* @since 0.4
* @codeCoverageIgnore
* @deprecated As of 1.0, use get_stylesheets().
*
* @return array[] Mapping CSS selectors to array of properties, or mapping of keys starting with 'stylesheet:' with value being the stylesheet.
*/
public function get_styles() {
return [];
}
/**
* Get stylesheets for amp-custom.
*
* @since 0.7
* @return array Values are the CSS stylesheets.
*/
public function get_stylesheets() {
return wp_list_pluck(
array_filter(
$this->pending_stylesheets,
static function( $pending_stylesheet ) {
return $pending_stylesheet['included'] && self::STYLE_AMP_CUSTOM_GROUP_INDEX === $pending_stylesheet['group'];
}
),
'serialized'
);
}
/**
* Get list of all the class names used in the document, including those used in [class] attributes.
*
* @since 1.0
* @return array Used class names.
*/
private function get_used_class_names() {
if ( isset( $this->used_class_names ) ) {
return $this->used_class_names;
}
$dynamic_class_names = [
/*
* See <https://www.ampproject.org/docs/reference/components/amp-dynamic-css-classes>.
* Note that amp-referrer-* class names are handled in has_used_class_name() below.
*/
'amp-viewer',
// Classes added based on input mode. See <https://github.com/ampproject/amphtml/blob/bd29b0eb1b28d900d4abed2c1883c6980f18db8e/spec/amp-css-classes.md#input-mode-classes>.
'amp-mode-touch',
'amp-mode-mouse',
'amp-mode-keyboard-active',
];
$classes = [];
$i_amphtml_prefix = 'i-amphtml-';
$i_amphtml_prefix_length = 10;
foreach ( $this->dom->xpath->query( '//*/@class' ) as $class_attribute ) {
/** @var DOMAttr $class_attribute */
$mutated = false;
$element_classes = [];
foreach ( array_filter( preg_split( '/\s+/', trim( $class_attribute->nodeValue ) ) ) as $class_name ) {
if ( substr( $class_name, 0, $i_amphtml_prefix_length ) === $i_amphtml_prefix ) {
$error = [
'code' => self::DISALLOWED_ATTR_CLASS_NAME,
'type' => AMP_Validation_Error_Taxonomy::HTML_ATTRIBUTE_ERROR_TYPE,
'class_name' => $class_name,
];
$sanitized = $this->should_sanitize_validation_error( $error, [ 'node' => $class_attribute ] );
if ( $sanitized ) {
$mutated = true;
continue;
} else {
ValidationExemption::mark_node_as_amp_unvalidated( $class_attribute );
}
}
$element_classes[] = $class_name;
}
if ( $mutated ) {
$class_attribute->nodeValue = implode( ' ', $element_classes );
}
$classes = array_merge( $classes, $element_classes );
}
// Find all [class] attributes and capture the contents of any single- or double-quoted strings.
foreach ( $this->dom->xpath->query( '//*/@' . Amp::BIND_DATA_ATTR_PREFIX . 'class' ) as $bound_class_attribute ) {
if ( preg_match_all( '/([\'"])([^\1]*?)\1/', $bound_class_attribute->nodeValue, $matches ) ) {
$classes = array_merge(
$classes,
preg_split( '/\s+/', trim( implode( ' ', $matches[2] ) ) )
);
}
}
$class_names = array_merge(
$dynamic_class_names,
array_unique( array_filter( $classes ) )
);
// Find all instances of the toggleClass() action to prevent the class name from being tree-shaken.
foreach ( $this->dom->xpath->query( '//*/@on[ contains( ., "toggleClass" ) ]' ) as $on_attribute ) {
if ( preg_match_all( '/\.\s*toggleClass\s*\(\s*class\s*=\s*(([\'"])([^\1]*?)\2|[a-zA-Z0-9_\-]+)/', $on_attribute->nodeValue, $matches ) ) {
$class_names = array_merge(
$class_names,
array_map(
static function ( $match ) {
return trim( $match, '"\'' );
},
$matches[1]
)
);
}
}
// If using the toggleTheme component, get the theme's dark mode class.
// See usage of toggleTheme in <https://github.com/ampproject/amphtml/pull/36958>.
$dark_mode_class = $this->dom->body->getAttribute( 'data-prefers-dark-mode-class' );
// Prevent dark mode class from being tree-shaken.
if ( $dark_mode_class ) {
$class_names[] = $dark_mode_class;
} else {
$class_names[] = 'amp-dark-mode';
}
$this->used_class_names = array_fill_keys( $class_names, true );
return $this->used_class_names;
}
/**
* Determine if all the supplied class names are used.
*
* @since 1.1
*
* @param string[] $class_names Class names.
* @return bool All used.
*/
private function has_used_class_name( $class_names ) {
if ( empty( $this->used_class_names ) ) {
$this->get_used_class_names();
}
foreach ( $class_names as $class_name ) {
// Bail early with a common case scenario.
if ( isset( $this->used_class_names[ $class_name ] ) ) {
continue;
}
// Check exact matches first, as they are faster.
switch ( $class_name ) {
/*
* Common class names used for amp-user-notification and amp-live-list.
* See <https://www.ampproject.org/docs/reference/components/amp-user-notification#styling>.
* See <https://www.ampproject.org/docs/reference/components/amp-live-list#styling>.
*/
case 'amp-active':
case 'amp-hidden':
if ( ! $this->has_used_tag_names( [ 'amp-live-list', 'amp-user-notification' ] ) ) {
return false;
}
continue 2;
// Class names for amp-image-lightbox, see <https://www.ampproject.org/docs/reference/components/amp-image-lightbox#styling>.
case 'amp-image-lightbox-caption':
if ( ! $this->has_used_tag_names( [ 'amp-image-lightbox' ] ) ) {
return false;
}
continue 2;
// Class names for amp-form, see <https://www.ampproject.org/docs/reference/components/amp-form#classes-and-css-hooks>.
case 'user-valid':
case 'user-invalid':
if ( ! $this->has_used_tag_names( [ 'form' ] ) ) {
return false;
}
continue 2;
}
// Only do AMP element-specific checks on an AMP components with the corresponding prefix.
if ( 'amp-' === substr( $class_name, 0, 4 ) ) {
// Class names for amp-geo, see <https://www.ampproject.org/docs/reference/components/amp-geo#generated-css-classes>.
if ( 'amp-geo-' === substr( $class_name, 0, 8 ) ) {
if ( ! $this->has_used_tag_names( [ 'amp-geo' ] ) ) {
return false;
}
continue;
}
// Class names for amp-form, see <https://www.ampproject.org/docs/reference/components/amp-form#classes-and-css-hooks>.
if ( 'amp-form-' === substr( $class_name, 0, 9 ) ) {
if ( ! $this->has_used_tag_names( [ 'form' ] ) ) {
return false;
}
continue;
}
// Class names for extensions which use the video-manager, and thus video-autoplay.css.
if ( 'amp-video-' === substr( $class_name, 0, 10 ) ) {
foreach ( $this->video_autoplay_elements as $video_autoplay_element ) {
if ( $this->has_used_tag_names( [ $video_autoplay_element ] ) ) {
continue 2;
}
}
return false;
}
switch ( substr( $class_name, 0, 11 ) ) {
/*
* Class names for amp-access and amp-access-laterpay.
* See <https://www.ampproject.org/docs/reference/components/amp-access>.
* See <https://www.ampproject.org/docs/reference/components/amp-access-laterpay#styling>
*/
case 'amp-access-':
if ( ! $this->has_used_attributes( [ 'amp-access' ] ) ) {
return false;
}
continue 2;
// Class names for amp-video-docking, see <https://amp.dev/documentation/components/amp-video-docking/#styling>.
case 'amp-docked-':
if ( ! $this->has_used_attributes( [ 'dock' ] ) ) {
return false;
}
continue 2;
}
// Class names for amp-sidebar, see <https://www.ampproject.org/docs/reference/components/amp-sidebar#styling-toolbar>.
if ( 'amp-sidebar-' === substr( $class_name, 0, 12 ) ) {
if ( ! $this->has_used_tag_names( [ 'amp-sidebar' ] ) ) {
return false;
}
continue;
}
switch ( substr( $class_name, 0, 13 ) ) {
// Class names for amp-dynamic-css-classes, see <https://www.ampproject.org/docs/reference/components/amp-dynamic-css-classes>.
case 'amp-referrer-':
continue 2;
// Class names for amp-carousel, see <https://www.ampproject.org/docs/reference/components/amp-carousel#styling>.
case 'amp-carousel-':
if ( ! $this->has_used_tag_names( [ 'amp-carousel' ] ) ) {
return false;
}
continue 2;
}
switch ( substr( $class_name, 0, 14 ) ) {
// Class names for amp-sticky-ad, see <https://www.ampproject.org/docs/reference/components/amp-sticky-ad#styling>.
case 'amp-sticky-ad-':
if ( ! $this->has_used_tag_names( [ 'amp-sticky-ad' ] ) ) {
return false;
}
continue 2;
// Class names for amp-live-list, see <https://www.ampproject.org/docs/reference/components/amp-live-list#styling>.
case 'amp-live-list-':
if ( ! $this->has_used_tag_names( [ 'amp-live-list' ] ) ) {
return false;
}
continue 2;
// Class names for amp-next-page, see <https://amp.dev/documentation/components/amp-next-page/#styling>.
case 'amp-next-page-':
if ( ! $this->has_used_tag_names( [ 'amp-next-page' ] ) ) {
return false;
}
continue 2;
}
switch ( substr( $class_name, 0, 16 ) ) {
// Class names for amp-date-picker, see <https://www.ampproject.org/docs/reference/components/amp-date-picker>.
case 'amp-date-picker-':
if ( ! $this->has_used_tag_names( [ 'amp-date-picker' ] ) ) {
return false;
}
continue 2;
// Class names for amp-geo, see <https://www.ampproject.org/docs/reference/components/amp-geo#generated-css-classes>.
case 'amp-iso-country-':
if ( ! $this->has_used_tag_names( [ 'amp-geo' ] ) ) {
return false;
}
continue 2;
}
} elseif ( ctype_upper( $class_name[0] ) && $this->has_used_tag_names( [ 'amp-date-picker' ] ) && $this->is_class_allowed_in_amp_date_picker( $class_name ) ) {
// If the document has an amp-date-picker tag, check if this class is an allowed child of it.
// That component's child classes won't be present yet in the document, so prevent tree-shaking valid classes.
// The ctype_upper() check is an optimization since we know up front that all class names in React Dates are
// in CamelCase form, thus we can short-circut if the first character of the class name is not upper-case.
continue;
}
if ( ! isset( $this->used_class_names[ $class_name ] ) ) {
return false;
}
}
return true;
}
/**
* Get list of all the tag names used in the document.
*
* @since 1.0
* @return array Used tag names.
*/
private function get_used_tag_names() {
if ( ! isset( $this->used_tag_names ) ) {
$this->used_tag_names = [];
foreach ( $this->dom->getElementsByTagName( '*' ) as $el ) {
$this->used_tag_names[ $el->tagName ] = true;
}
}
return $this->used_tag_names;
}
/**
* Determine if all the supplied tag names are used.
*
* @since 1.1
*
* @param string[] $tag_names Tag names.
* @return bool All used.
*/
private function has_used_tag_names( $tag_names ) {
if ( empty( $this->used_tag_names ) ) {
$this->get_used_tag_names();
}
foreach ( $tag_names as $tag_name ) {
if ( ! isset( $this->used_tag_names[ $tag_name ] ) ) {
return false;
}
}
return true;
}
/**
* Check whether the attributes exist.
*
* @since 1.1
* @todo Make $attribute_names into $attributes as an associative array and implement lookups of specific values. Since attribute values can vary (e.g. with amp-bind), this may not be feasible.
*
* @param string[] $attribute_names Attribute names.
* @return bool Whether all supplied attributes are used.
*/
private function has_used_attributes( $attribute_names ) {
foreach ( $attribute_names as $attribute_name ) {
if ( ! isset( $this->used_attributes[ $attribute_name ] ) ) {
$expression = sprintf( '(//@%s)[1]', $attribute_name );
$this->used_attributes[ $attribute_name ] = ( 0 !== $this->dom->xpath->query( $expression )->length );
}
// Attributes for amp-accordion, see <https://amp.dev/documentation/components/amp-accordion/#styling>.
if ( 'expanded' === $attribute_name ) {
if ( ! $this->has_used_tag_names( [ 'amp-accordion' ] ) ) {
return false;
}
continue;
}
// Attributes for amp-sidebar, see <https://amp.dev/documentation/components/amp-sidebar/#styling>.
if ( 'open' === $attribute_name ) {
// The 'open' attribute is also used by the HTML5 <details> attribute.
if ( ! $this->has_used_tag_names( [ 'amp-sidebar' ] ) && ! $this->has_used_tag_names( [ 'details' ] ) ) {
return false;
}
continue;
}
// Attributes for amp-live-list, see <https://amp.dev/documentation/components/amp-live-list/#styling>.
if ( 'data-tombstone' === $attribute_name ) {
if ( ! $this->has_used_tag_names( [ 'amp-live-list' ] ) ) {
return false;
}
continue;
}
// Attributes for amp-experiment begin with 'amp-x-', see <https://amp.dev/documentation/examples/components/amp-experiment/>.
if ( 'amp-x-' === substr( $attribute_name, 0, 6 ) ) {
if ( ! $this->has_used_tag_names( [ 'amp-experiment' ] ) ) {
return false;
}
continue;
}
if ( ! $this->used_attributes[ $attribute_name ] ) {
return false;
}
}
return true;
}
/**
* Whether a given class is allowed to be styled in <amp-date-picker>.
*
* That component has child classes that won't be present in the document yet.
* So get whether a class is an allowed child.
*
* @since 1.5.0
* @link https://github.com/airbnb/react-dates/tree/05356/src/components
*
* @param string $class The name of the class to evaluate.
* @return bool Whether the class is allowed as a child of <amp-date-picker>.
*/
private function is_class_allowed_in_amp_date_picker( $class ) {
static $class_prefixes = [
'CalendarDay',
'CalendarMonth',
'CalendarMonthGrid',
'DayPicker',
'DayPickerKeyboardShortcuts',
'DayPickerNavigation',
'KeyboardShortcutRow',
];
return in_array( strtok( $class, '_' ), $class_prefixes, true );
}
/**
* Run logic before any sanitizers are run.
*
* After the sanitizers are instantiated but before calling sanitize on each of them, this
* method is called with list of all the instantiated sanitizers.
*
* @param AMP_Base_Sanitizer[] $sanitizers Sanitizers.
*/
public function init( $sanitizers ) {
$this->sanitizers = $sanitizers;
}
/**
* Sanitize CSS styles within the HTML contained in this instance's Dom\Document.
*
* @since 0.4
*/
public function sanitize() {
// When style processing is disabled, simply mark all the CSS elements/attributes as PX-verified.
if ( $this->args['disable_style_processing'] ) {
foreach ( $this->dom->xpath->query( '//link[ @rel = "stylesheet" and @href ] | //style | //*/@style' ) as $node ) {
ValidationExemption::mark_node_as_px_verified( $node );
// Since stylesheet links are allowed in the HEAD if they are for fonts, mark the href specifically as being the exempted attribute.
if ( $node instanceof Element && Tag::LINK === $node->tagName ) {
ValidationExemption::mark_node_as_px_verified( $node->getAttributeNode( Attribute::HREF ) );
ValidationExemption::mark_node_as_px_verified( $node->getAttributeNode( Attribute::REL ) );
}
}
return;
}
// Capture the selector conversion mappings from the other sanitizers.
foreach ( $this->sanitizers as $sanitizer ) {
foreach ( $sanitizer->get_selector_conversion_mapping() as $html_selectors => $amp_selectors ) {
if ( ! isset( $this->selector_mappings[ $html_selectors ] ) ) {
$this->selector_mappings[ $html_selectors ] = $amp_selectors;
} else {
$this->selector_mappings[ $html_selectors ] = array_unique(
array_merge( $this->selector_mappings[ $html_selectors ], $amp_selectors )
);
}
// Prevent selectors like `amp-img img` getting deleted since `img` does not occur in the DOM.
if ( $sanitizer->has_light_shadow_dom() ) {
$this->args['dynamic_element_selectors'] = array_merge(
$this->args['dynamic_element_selectors'],
$this->selector_mappings[ $html_selectors ]
);
}
}
}
$elements = [];
$this->focus_class_name_selector_pattern = (
! empty( $this->args['focus_within_classes'] ) ?
self::get_class_name_selector_pattern( $this->args['focus_within_classes'] ) :
null
);
/*
* Note that xpath is used to query the DOM so that the link and style elements will be
* in document order. DOMNode::compareDocumentPosition() is not yet implemented.
*/
// @todo Also consider skipping the processing of link and style elements that have data-px-verified-tag.
$dev_mode_predicate = '';
if ( DevMode::isActiveForDocument( $this->dom ) ) {
$dev_mode_predicate = sprintf( ' and not ( @%s )', AMP_Rule_Spec::DEV_MODE_ATTRIBUTE );
}
$lower_case = 'translate( %s, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz" )'; // In XPath 2.0 this is lower-case().
$predicates = [
sprintf( '( self::style and not( @amp-boilerplate ) and ( not( @type ) or %s = "text/css" ) %s )', sprintf( $lower_case, '@type' ), $dev_mode_predicate ),
sprintf( '( self::link and @href and %s = "stylesheet" %s )', sprintf( $lower_case, '@rel' ), $dev_mode_predicate ),
];
foreach ( $this->dom->xpath->query( '//*[ ' . implode( ' or ', $predicates ) . ' ]' ) as $element ) {
$elements[] = $element;
}
// If 'width' attribute is present for 'col' tag, convert to proper CSS rule.
// @todo The width attribute on the <col> tag is probably something that should just be allowed in AMP.
foreach ( $this->dom->getElementsByTagName( 'col' ) as $col ) {
/**
* Col element.
*
* @var DOMElement $col
*/
$width_attr = $col->getAttribute( 'width' );
if ( ! empty( $width_attr ) && ( false === strpos( $width_attr, '*' ) ) ) {
$width_style = 'width: ' . $width_attr;
if ( is_numeric( $width_attr ) ) {
$width_style .= 'px';
}
if ( $col->hasAttribute( 'style' ) ) {
$col->setAttribute( 'style', $width_style . ';' . $col->getAttribute( 'style' ) );
} else {
$col->setAttribute( 'style', $width_style );
}
$col->removeAttribute( 'width' );
}
}
/**
* Element.
*
* @var DOMElement $element
*/
foreach ( $elements as $element ) {
$node_name = strtolower( $element->nodeName );
if ( 'style' === $node_name ) {
$this->process_style_element( $element );
} elseif ( 'link' === $node_name ) {