-
Notifications
You must be signed in to change notification settings - Fork 385
/
class-amp-style-sanitizer.php
3240 lines (2909 loc) · 111 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 Amp\AmpWP\Dom\Document;
use Sabberworm\CSS\RuleSet\DeclarationBlock;
use Sabberworm\CSS\CSSList\CSSList;
use Sabberworm\CSS\Property\Selector;
use Sabberworm\CSS\RuleSet\RuleSet;
use Sabberworm\CSS\Property\AtRule;
use Sabberworm\CSS\Rule\Rule;
use Sabberworm\CSS\CSSList\KeyFrame;
use Sabberworm\CSS\RuleSet\AtRuleSet;
use Sabberworm\CSS\Property\Import;
use Sabberworm\CSS\CSSList\AtRuleBlockList;
use Sabberworm\CSS\Value\RuleValueList;
use Sabberworm\CSS\Value\URL;
use Sabberworm\CSS\CSSList\Document as CSSDocument;
/**
* Class AMP_Style_Sanitizer
*
* Collects inline styles and outputs them in the amp-custom stylesheet.
*/
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;
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 STYLESHEET_TOO_LONG = 'STYLESHEET_TOO_LONG';
const STYLESHEET_INVALID_FILE_URL = 'STYLESHEET_INVALID_FILE_URL';
// 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 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 bool $allow_dirty_styles Allow dirty styles. This short-circuits the sanitize logic; it is used primarily in Customizer preview.
* @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.
* }
*/
protected $args;
/**
* Default args.
*
* @var array
*/
protected $DEFAULT_ARGS = [
'dynamic_element_selectors' => [
'amp-list',
'amp-live-list',
'[submit-error]',
'[submit-success]',
'amp-script',
],
'should_locate_sources' => false,
'parsed_cache_variant' => null,
'focus_within_classes' => [ 'focus' ],
'low_priority_plugins' => [ 'query-monitor' ],
];
/**
* 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
*/
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
*/
private $used_tag_names;
/**
* Current node being processed.
*
* @var DOMElement|DOMAttr
*/
private $current_node;
/**
* Current sources for a given node.
*
* @var array
*/
private $current_sources;
/**
* Log of the stylesheet URLs that have been imported to guard against infinite loops.
*
* @var array
*/
private $processed_imported_stylesheet_urls = [];
/**
* List of font stylesheets that were @import'ed which should have been <link>'ed to instead.
*
* These font URLs will be cached with the parsed CSS and then converted into stylesheet links.
*
* @var array
*/
private $imported_font_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-gfycat',
'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',
];
/**
* 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_IMPORTANT,
self::CSS_SYNTAX_INVALID_PROPERTY,
self::CSS_SYNTAX_INVALID_PROPERTY_NOLIST,
self::CSS_SYNTAX_PARSE_ERROR,
self::STYLESHEET_INVALID_FILE_URL,
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() {
$has_required_methods = (
method_exists( 'Sabberworm\CSS\CSSList\Document', 'splice' )
&&
method_exists( 'Sabberworm\CSS\CSSList\Document', 'replace' )
);
if ( ! $has_required_methods ) {
return false;
}
$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;
}
/**
* Get list of CSS styles in HTML content of Dom\Document ($this->dom).
*
* @since 0.4
* @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/master/spec/amp-css-classes.md#input-mode-classes>.
'amp-mode-touch',
'amp-mode-mouse',
'amp-mode-keyboard-active',
];
$classes = ' ';
foreach ( $this->dom->xpath->query( '//*/@class' ) as $class_attribute ) {
$classes .= ' ' . $class_attribute->nodeValue;
}
// Find all [class] attributes and capture the contents of any single- or double-quoted strings.
foreach ( $this->dom->xpath->query( '//*/@' . Document::AMP_BIND_DATA_ATTR_PREFIX . 'class' ) as $bound_class_attribute ) {
if ( preg_match_all( '/([\'"])([^\1]*?)\1/', $bound_class_attribute->nodeValue, $matches ) ) {
$classes .= ' ' . implode( ' ', $matches[2] );
}
}
$class_names = array_merge(
$dynamic_class_names,
array_unique( array_filter( preg_split( '/\s+/', trim( $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]
)
);
}
}
$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://github.com/ampproject/amphtml/blob/master/extensions/amp-video-docking/amp-video-docking.md#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;
}
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;
}
}
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;
}
if ( ! $this->used_attributes[ $attribute_name ] ) {
return false;
}
}
return 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 ) {
parent::init( $sanitizers );
foreach ( $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.
$this->args['dynamic_element_selectors'] = array_merge(
$this->args['dynamic_element_selectors'],
$this->selector_mappings[ $html_selectors ]
);
}
}
}
/**
* Sanitize CSS styles within the HTML contained in this instance's Dom\Document.
*
* @since 0.4
*/
public function sanitize() {
$elements = [];
// @todo Instead of short-circuiting, this actually needs to turn off tree-shaking.
// Do nothing if inline styles are allowed. Note, a better alternative to this is AMP dev mode.
if ( ! empty( $this->args['allow_dirty_styles'] ) ) {
return;
}
$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.
*/
$dev_mode_predicate = '';
if ( $this->is_document_in_dev_mode() ) {
$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.
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 ) {
$this->process_link_element( $element );
// If the element is still in the document, it is a font stylesheet; make sure it gets moved to the head as required.
if ( $element->parentNode && 'head' !== $element->parentNode->nodeName ) {
$this->dom->head->appendChild( $element->parentNode->removeChild( $element ) );
}
}
}
$elements = [];
foreach ( $this->dom->xpath->query( "//*[ @style $dev_mode_predicate ]" ) as $element ) {
$elements[] = $element;
}
foreach ( $elements as $element ) {
$this->collect_inline_styles( $element );
}
$this->finalize_styles();
$this->did_convert_elements = true;
$parse_css_duration = 0.0;
$shake_css_duration = 0.0;
foreach ( $this->pending_stylesheets as $pending_stylesheet ) {
if ( ! $pending_stylesheet['cached'] ) {
$parse_css_duration += $pending_stylesheet['parse_time'];
}
$shake_css_duration += $pending_stylesheet['shake_time'];
}
AMP_HTTP::send_server_timing( 'amp_parse_css', $parse_css_duration, 'AMP Parse CSS' );
AMP_HTTP::send_server_timing( 'amp_shake_css', $shake_css_duration, 'AMP Tree-Shake CSS' );
}
/**
* Get the priority of the stylesheet associated with the given element.
*
* As with hooks, lower priorities mean they should be included first.
* The higher the priority value, the more likely it will be that the
* stylesheet will be among those excluded due to STYLESHEET_TOO_LONG when
* concatenated CSS reaches 50KB.
*
* @todo This will eventually need to be abstracted to not be CMS-specific, allowing for the prioritization scheme to be defined by configuration.
*
* @param DOMNode|DOMElement|DOMAttr $node Node.
* @return int Priority.
*/
private function get_stylesheet_priority( DOMNode $node ) {
$print_priority_base = 100;
$admin_bar_priority = 200;
$remove_url_scheme = static function( $url ) {
return preg_replace( '/^https?:/', '', $url );
};
if ( $node instanceof DOMElement && 'link' === $node->nodeName ) {
$element_id = (string) $node->getAttribute( 'id' );
$schemeless_href = $remove_url_scheme( $node->getAttribute( 'href' ) );
$plugin = null;
if ( preg_match(
sprintf(
'#^(?:%s|%s)(?<plugin>[^/]+)#i',
preg_quote( $remove_url_scheme( trailingslashit( WP_PLUGIN_URL ) ), '#' ),
preg_quote( $remove_url_scheme( trailingslashit( WPMU_PLUGIN_URL ) ), '#' )
),
$schemeless_href,
$matches
) ) {
$plugin = $matches['plugin'];
}
$style_handle = null;
if ( preg_match( '/^(.+)-css$/', $element_id, $matches ) ) {
$style_handle = $matches[1];
}
$core_frontend_handles = [
'wp-block-library',
'wp-block-library-theme',
];
$non_amp_handles = [
'mediaelement',
'wp-mediaelement',
'thickbox',
];
if ( in_array( $style_handle, $non_amp_handles, true ) ) {
// Styles are for non-AMP JS only so not be used in AMP at all.
$priority = 1000;
} elseif ( 'admin-bar' === $style_handle ) {
// Admin bar has lowest priority. If it gets excluded, then the entire admin bar should be removed.
$priority = $admin_bar_priority;
} elseif ( 'dashicons' === $style_handle ) {
// Dashicons could be used by the theme, but low priority compared to other styles.
$priority = 90;
} elseif ( false !== strpos( $schemeless_href, $remove_url_scheme( trailingslashit( get_template_directory_uri() ) ) ) ) {
// Highest priority are parent theme styles.
$priority = 1;
} elseif ( false !== strpos( $schemeless_href, $remove_url_scheme( trailingslashit( get_stylesheet_directory_uri() ) ) ) ) {
// Penultimate highest priority are child theme styles.
$priority = 10;
} elseif ( in_array( $style_handle, $core_frontend_handles, true ) ) {
// Styles from wp-includes which are enqueued for themes are next highest priority.
$priority = 20;
} elseif ( $plugin ) {
// Styles from plugins are next-highest priority, unless they are in the list of low-priority plugins.
$priority = in_array( $plugin, $this->args['low_priority_plugins'], true ) ? 150 : 30;
} elseif ( 0 === strpos( $schemeless_href, $remove_url_scheme( includes_url() ) ) ) {
// Other styles from wp-includes come next.
$priority = 40;
} else {
// Everything else, perhaps wp-admin styles or stylesheets from remote servers.
$priority = 50;
}
if ( 'print' === $node->getAttribute( 'media' ) ) {
$priority += $print_priority_base;
}
} elseif ( $node instanceof DOMElement && 'style' === $node->nodeName && $node->hasAttribute( 'id' ) ) {
$id = $node->getAttribute( 'id' );
$is_theme_inline_css = preg_match( '/^(?<handle>.+)-inline-css$/', $id, $matches ) && wp_style_is( $matches['handle'], 'registered' );
if ( $is_theme_inline_css && 0 === strpos( wp_styles()->registered[ $matches['handle'] ]->src, get_template_directory_uri() ) ) {
// Parent theme inline style.
$priority = 2;
} elseif ( $is_theme_inline_css && get_stylesheet() !== get_template() && 0 === strpos( wp_styles()->registered[ $matches['handle'] ]->src, get_stylesheet_directory_uri() ) ) {
// Child theme inline style.
$priority = 12;
} elseif ( 'admin-bar-inline-css' === $id ) {
$priority = $admin_bar_priority;
} elseif ( 'wp-custom-css' === $id ) {
// Additional CSS from Customizer.
$priority = 60;
} else {
// Other style elements, including from Recent Comments widget.
$priority = 70;
}
if ( 'print' === $node->getAttribute( 'media' ) ) {
$priority += $print_priority_base;
}
} else {
// Style attribute.