-
Notifications
You must be signed in to change notification settings - Fork 384
/
class-amp-style-sanitizer.php
2795 lines (2514 loc) · 93.2 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 \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;
/**
* Class AMP_Style_Sanitizer
*
* Collects inline styles and outputs them in the amp-custom stylesheet.
*/
class AMP_Style_Sanitizer extends AMP_Base_Sanitizer {
/**
* Error code for tree shaking.
*
* @var string
*/
const TREE_SHAKING_ERROR_CODE = 'removed_unused_css_rules';
/**
* Error code for illegal at-rule.
*
* @var string
*/
const ILLEGAL_AT_RULE_ERROR_CODE = 'illegal_css_at_rule';
/**
* 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::prepare_stylesheet()
*/
const SELECTOR_EXTRACTED_TAGS = 0;
/**
* Array index for class names extracted from a selector.
*
* @private
* @since 1.1
* @see \AMP_Style_Sanitizer::prepare_stylesheet()
*/
const SELECTOR_EXTRACTED_CLASSES = 1;
/**
* Array index for IDs extracted from a selector.
*
* @private
* @since 1.1
* @see \AMP_Style_Sanitizer::prepare_stylesheet()
*/
const SELECTOR_EXTRACTED_IDS = 2;
/**
* Array index for attributes extracted from a selector.
*
* @private
* @since 1.1
* @see \AMP_Style_Sanitizer::prepare_stylesheet()
*/
const SELECTOR_EXTRACTED_ATTRIBUTES = 3;
/**
* Array of flags used to control sanitization.
*
* @var array {
* @type string $remove_unused_rules Enum 'never', 'sometimes' (default), 'always'. If total CSS is greater than max_bytes, whether to strip selectors (and then empty rules) when they are not found to be used in doc. A validation error will be emitted when stripping happens since it is not completely safe in the case of dynamic content.
* @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 bool $accept_tree_shaking Whether to accept tree-shaking by default and bypass a validation error.
* @type string $include_manifest_comment Whether to show the manifest HTML comment in the response before the style[amp-custom] element. Can be 'always', 'never', or 'when_excessive'.
* }
*/
protected $args;
/**
* Default args.
*
* @var array
*/
protected $DEFAULT_ARGS = array(
'remove_unused_rules' => 'sometimes',
'dynamic_element_selectors' => array(
'amp-list',
'amp-live-list',
'[submit-error]',
'[submit-success]',
),
'should_locate_sources' => false,
'parsed_cache_variant' => null,
'accept_tree_shaking' => false,
'include_manifest_comment' => 'always',
);
/**
* Stylesheets.
*
* Values are the CSS stylesheets. Keys are MD5 hashes of the stylesheets,
*
* @since 0.7
* @var string[]
*/
private $stylesheets = array();
/**
* List of stylesheet parts prior to selector/rule removal (tree shaking).
*
* Keys are MD5 hashes of stylesheets.
*
* @since 1.0
* @var array[] {
* @type array $stylesheet Array of stylesheet chunked, with declaration blocks being represented as arrays.
* @type DOMElement|DOMAttr $node Origin for styles.
* @type array $sources Sources for the node.
* @type bool $keyframes Whether an amp-keyframes.
* }
*/
private $pending_stylesheets = array();
/**
* 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;
/**
* 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.
*
* @since 1.1
* @var array
*/
private $used_attributes = array(
'autofocus' => true,
'checked' => true,
'controls' => true,
'disabled' => true,
'hidden' => true,
'loop' => true,
'multiple' => true,
'open' => true,
'readonly' => true,
'required' => true,
'selected' => true,
);
/**
* Tag names used in document.
*
* @since 1.0
* @var array
*/
private $used_tag_names;
/**
* XPath.
*
* @since 1.0
* @var DOMXPath
*/
private $xpath;
/**
* Amount of time that was spent parsing CSS.
*
* @since 1.0
* @var float
*/
private $parse_css_duration = 0.0;
/**
* THe HEAD element.
*
* @var DOMElement
*/
private $head;
/**
* 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 = array();
/**
* 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 = array();
/**
* Mapping of HTML element selectors to AMP selector elements.
*
* @var array
*/
private $selector_mappings = array();
/**
* 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 array(
'css_parse_error',
'excessive_css',
self::ILLEGAL_AT_RULE_ERROR_CODE,
'illegal_css_important',
'illegal_css_property',
self::TREE_SHAKING_ERROR_CODE,
'unrecognized_css',
'disallowed_file_extension',
'file_path_not_found',
);
}
/**
* 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 DOMDocument $dom Represents the HTML document to sanitize.
* @param array $args Args.
*/
public function __construct( DOMDocument $dom, array $args = array() ) {
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 ( 'style[amp-keyframes]' === $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) {
$this->style_keyframes_cdata_spec = $spec_rule[ AMP_Rule_Spec::CDATA ];
} elseif ( 'style amp-custom' === $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->xpath = new DOMXPath( $dom );
}
/**
* Get list of CSS styles in HTML content of DOMDocument ($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 array();
}
/**
* Get stylesheets.
*
* @since 0.7
* @returns array Values are the CSS stylesheets. Keys are MD5 hashes of the stylesheets.
*/
public function get_stylesheets() {
return $this->stylesheets;
}
/**
* 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 = array(
/*
* 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 = ' ';
foreach ( $this->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->xpath->query( '//*/@' . AMP_DOM_Utils::get_amp_bind_placeholder_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 ) ) ) )
);
$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 ) {
// Class names for amp-dynamic-css-classes, see <https://www.ampproject.org/docs/reference/components/amp-dynamic-css-classes>.
if ( 'amp-referrer-' === substr( $class_name, 0, 13 ) ) {
continue;
}
/*
* 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>.
*/
if ( 'amp-active' === $class_name || 'amp-hidden' === $class_name ) {
if ( ! $this->has_used_tag_names( array( 'amp-live-list' ) ) && ! $this->has_used_tag_names( array( 'amp-user-notification' ) ) ) {
return false;
}
continue;
}
// Class names for amp-carousel, see <https://www.ampproject.org/docs/reference/components/amp-carousel#styling>.
if ( 'amp-carousel-' === substr( $class_name, 0, 13 ) ) {
if ( ! $this->has_used_tag_names( array( 'amp-carousel' ) ) ) {
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 ) || 'user-valid' === $class_name || 'user-invalid' === $class_name ) {
if ( ! $this->has_used_tag_names( array( 'form' ) ) ) {
return false;
}
continue;
}
/*
* 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>
*/
if ( 'amp-access-' === substr( $class_name, 0, 11 ) ) {
if ( ! $this->has_used_attributes( array( 'amp-access' ) ) ) {
return false;
}
continue;
}
// 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 ) || 'amp-iso-country-' === substr( $class_name, 0, 16 ) ) {
if ( ! $this->has_used_tag_names( array( 'amp-geo' ) ) ) {
return false;
}
continue;
}
// Class names for amp-image-lightbox, see <https://www.ampproject.org/docs/reference/components/amp-image-lightbox#styling>.
if ( 'amp-image-lightbox-caption' === $class_name ) {
if ( ! $this->has_used_tag_names( array( 'amp-image-lightbox' ) ) ) {
return false;
}
continue;
}
// Class names for amp-live-list, see <https://www.ampproject.org/docs/reference/components/amp-live-list#styling>.
if ( 'amp-live-list-' === substr( $class_name, 0, 14 ) ) {
if ( ! $this->has_used_tag_names( array( 'amp-live-list' ) ) ) {
return false;
}
continue;
}
// 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( array( 'amp-sidebar' ) ) ) {
return false;
}
continue;
}
// Class names for amp-sticky-ad, see <https://www.ampproject.org/docs/reference/components/amp-sticky-ad#styling>.
if ( 'amp-sticky-ad-' === substr( $class_name, 0, 14 ) ) {
if ( ! $this->has_used_tag_names( array( 'amp-sticky-ad' ) ) ) {
return false;
}
continue;
}
// Class names for amp-video-docking, see <https://github.com/ampproject/amphtml/blob/master/extensions/amp-video-docking/amp-video-docking.md#styling>.
if ( 'amp-docked-' === substr( $class_name, 0, 11 ) ) {
if ( ! $this->has_used_attributes( array( 'dock' ) ) ) {
return false;
}
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 = array();
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->xpath->query( $expression )->length );
}
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 DOMDocument.
*
* @since 0.4
*/
public function sanitize() {
$elements = array();
// Do nothing if inline styles are allowed.
if ( ! empty( $this->args['allow_dirty_styles'] ) ) {
return;
}
$this->head = $this->dom->getElementsByTagName( 'head' )->item( 0 );
if ( ! $this->head ) {
$this->head = $this->dom->createElement( 'head' );
$this->dom->documentElement->insertBefore( $this->head, $this->dom->documentElement->firstChild );
}
$this->parse_css_duration = 0.0;
/*
* 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.
*/
$xpath = $this->xpath;
$lower_case = 'translate( %s, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz" )'; // In XPath 2.0 this is lower-case().
$predicates = array(
sprintf( '( self::style and not( @amp-boilerplate ) and ( not( @type ) or %s = "text/css" ) )', sprintf( $lower_case, '@type' ) ),
sprintf( '( self::link and @href and %s = "stylesheet" )', sprintf( $lower_case, '@rel' ) ),
);
foreach ( $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 );
}
}
$elements = array();
foreach ( $xpath->query( '//*[ @style ]' ) as $element ) {
$elements[] = $element;
}
foreach ( $elements as $element ) {
$this->collect_inline_styles( $element );
}
$this->finalize_styles();
$this->did_convert_elements = true;
if ( $this->parse_css_duration > 0.0 ) {
AMP_HTTP::send_server_timing( 'amp_parse_css', $this->parse_css_duration, 'AMP Parse CSS' );
}
}
/**
* Eliminate relative segments (../ and ./) from a path.
*
* @param string $path Path with relative segments. This is not a URL, so no host and no query string.
* @return string|WP_Error Unrelativized path or WP_Error if there is too much relativity.
*/
private function unrelativize_path( $path ) {
// Eliminate current directory relative paths, like <foo/./bar/./baz.css> => <foo/bar/baz.css>.
do {
$path = preg_replace(
'#/\./#',
'/',
$path,
-1,
$count
);
} while ( 0 !== $count );
// Collapse relative paths, like <foo/bar/../../baz.css> => <baz.css>.
do {
$path = preg_replace(
'#(?<=/)(?!\.\./)[^/]+/\.\./#',
'',
$path,
1,
$count
);
} while ( 0 !== $count );
if ( preg_match( '#(^|/)\.+/#', $path ) ) {
/* translators: %s is the path with the remaining relative segments. */
return new WP_Error( 'remaining_relativity', sprintf( __( 'There are remaining relative path segments: %s', 'amp' ), $path ) );
}
return $path;
}
/**
* Construct a URL from a parsed one.
*
* @param array $parsed_url Parsed URL.
* @return string Reconstructed URL.
*/
private function reconstruct_url( $parsed_url ) {
$url = '';
if ( ! empty( $parsed_url['host'] ) ) {
if ( ! empty( $parsed_url['scheme'] ) ) {
$url .= $parsed_url['scheme'] . ':';
}
$url .= '//';
$url .= $parsed_url['host'];
if ( ! empty( $parsed_url['port'] ) ) {
$url .= ':' . $parsed_url['port'];
}
}
if ( ! empty( $parsed_url['path'] ) ) {
$url .= $parsed_url['path'];
}
if ( ! empty( $parsed_url['query'] ) ) {
$url .= '?' . $parsed_url['query'];
}
if ( ! empty( $parsed_url['fragment'] ) ) {
$url .= '#' . $parsed_url['fragment'];
}
return $url;
}
/**
* Generate a URL's fully-qualified file path.
*
* @since 0.7
* @see WP_Styles::_css_href()
*
* @param string $url The file URL.
* @param string[] $allowed_extensions Allowed file extensions for local files.
* @return string|WP_Error Style's absolute validated filesystem path, or WP_Error when error.
*/
public function get_validated_url_file_path( $url, $allowed_extensions = array() ) {
if ( ! is_string( $url ) ) {
return new WP_Error( 'url_not_string' );
}
$needs_base_url = (
! preg_match( '|^(https?:)?//|', $url )
&&
! ( $this->content_url && 0 === strpos( $url, $this->content_url ) )
);
if ( $needs_base_url ) {
$url = $this->base_url . '/' . ltrim( $url, '/' );
}
$parsed_url = wp_parse_url( $url );
if ( empty( $parsed_url['host'] ) ) {
/* translators: %s is the original URL */
return new WP_Error( 'no_url_host', sprintf( __( 'URL is missing host: %s', 'amp' ), $url ) );
}
if ( empty( $parsed_url['path'] ) ) {
/* translators: %s is the original URL */
return new WP_Error( 'no_url_path', sprintf( __( 'URL is missing path: %s', 'amp' ), $url ) );
}
$path = $this->unrelativize_path( $parsed_url['path'] );
if ( is_wp_error( $path ) ) {
return $path;
}
$parsed_url['path'] = $path;
$remove_url_scheme = function( $schemed_url ) {
return preg_replace( '#^\w+:(?=//)#', '', $schemed_url );
};
unset( $parsed_url['scheme'], $parsed_url['query'], $parsed_url['fragment'] );
$url = $this->reconstruct_url( $parsed_url );
$includes_url = $remove_url_scheme( includes_url( '/' ) );
$content_url = $remove_url_scheme( content_url( '/' ) );
$admin_url = $remove_url_scheme( get_admin_url( null, '/' ) );
$site_url = $remove_url_scheme( site_url( '/' ) );
$allowed_hosts = array(
wp_parse_url( $includes_url, PHP_URL_HOST ),
wp_parse_url( $content_url, PHP_URL_HOST ),
wp_parse_url( $admin_url, PHP_URL_HOST ),
);
// Validate file extensions.
if ( ! empty( $allowed_extensions ) ) {
$pattern = sprintf( '/\.(%s)$/i', implode( '|', $allowed_extensions ) );
if ( ! preg_match( $pattern, $url ) ) {
/* translators: %s: the file URL. */
return new WP_Error( 'disallowed_file_extension', sprintf( __( 'File does not have an allowed file extension for filesystem access (%s).', 'amp' ), $url ) );
}
}
if ( ! in_array( $parsed_url['host'], $allowed_hosts, true ) ) {
/* translators: %s: the file URL */
return new WP_Error( 'external_file_url', sprintf( __( 'URL is located on an external domain: %s.', 'amp' ), $parsed_url['host'] ) );
}
$base_path = null;
$file_path = null;
$wp_content = 'wp-content';
if ( 0 === strpos( $url, $content_url ) ) {
$base_path = WP_CONTENT_DIR;
$file_path = substr( $url, strlen( $content_url ) - 1 );
} elseif ( 0 === strpos( $url, $includes_url ) ) {
$base_path = ABSPATH . WPINC;
$file_path = substr( $url, strlen( $includes_url ) - 1 );
} elseif ( 0 === strpos( $url, $admin_url ) ) {
$base_path = ABSPATH . 'wp-admin';
$file_path = substr( $url, strlen( $admin_url ) - 1 );
} elseif ( 0 === strpos( $url, $site_url . trailingslashit( $wp_content ) ) ) {
// Account for loading content from original wp-content directory not WP_CONTENT_DIR which can happen via register_theme_directory().
$base_path = ABSPATH . $wp_content;
$file_path = substr( $url, strlen( $site_url ) + strlen( $wp_content ) );
}
if ( ! $file_path || false !== strpos( $file_path, '../' ) || false !== strpos( $file_path, '..\\' ) ) {
/* translators: %s: the file URL. */
return new WP_Error( 'file_path_not_allowed', sprintf( __( 'Disallowed URL filesystem path for %s.', 'amp' ), $url ) );
}
if ( ! file_exists( $base_path . $file_path ) ) {
/* translators: %s: the file URL. */
return new WP_Error( 'file_path_not_found', sprintf( __( 'Unable to locate filesystem path for %s.', 'amp' ), $url ) );
}
return $base_path . $file_path;
}
/**
* Set the current node (and its sources when required).
*
* @since 1.0
* @param DOMElement|DOMAttr|null $node Current node, or null to reset.
*/
private function set_current_node( $node ) {
if ( $this->current_node === $node ) {
return;
}
$this->current_node = $node;
if ( empty( $node ) ) {
$this->current_sources = null;
} elseif ( ! empty( $this->args['should_locate_sources'] ) ) {
$this->current_sources = AMP_Validation_Manager::locate_sources( $node );
}
}
/**
* Process style element.
*
* @param DOMElement $element Style element.
*/
private function process_style_element( DOMElement $element ) {
$this->set_current_node( $element ); // And sources when needing to be located.
// @todo Any @keyframes rules could be removed from amp-custom and instead added to amp-keyframes.
$is_keyframes = $element->hasAttribute( 'amp-keyframes' );
$stylesheet = trim( $element->textContent );
$cdata_spec = $is_keyframes ? $this->style_keyframes_cdata_spec : $this->style_custom_cdata_spec;
// Honor the style's media attribute.
$media = $element->getAttribute( 'media' );
if ( $media && 'all' !== $media ) {
$stylesheet = sprintf( '@media %s { %s }', $media, $stylesheet );
}
$processed = $this->process_stylesheet(
$stylesheet,
array(
'allowed_at_rules' => $cdata_spec['css_spec']['allowed_at_rules'],
'property_whitelist' => $cdata_spec['css_spec']['declaration'],
'validate_keyframes' => $cdata_spec['css_spec']['validate_keyframes'],
)
);
$this->pending_stylesheets[] = array_merge(
array(
'keyframes' => $is_keyframes,
'node' => $element,
'sources' => $this->current_sources,
),
wp_array_slice_assoc( $processed, array( 'stylesheet', 'imported_font_urls' ) )
);
if ( $element->hasAttribute( 'amp-custom' ) ) {
if ( ! $this->amp_custom_style_element ) {
$this->amp_custom_style_element = $element;
} else {
$element->parentNode->removeChild( $element ); // There can only be one. #highlander.
}
} else {
// Remove from DOM since we'll be adding it to amp-custom.
$element->parentNode->removeChild( $element );
}
$this->set_current_node( null );
}
/**
* Process link element.
*
* @param DOMElement $element Link element.
*/
private function process_link_element( DOMElement $element ) {
$href = $element->getAttribute( 'href' );
// Allow font URLs, including protocol-less URLs and recognized URLs that use HTTP instead of HTTPS.