-
Notifications
You must be signed in to change notification settings - Fork 385
/
class-amp-style-sanitizer.php
1332 lines (1194 loc) · 44.4 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\Rule\Rule;
use \Sabberworm\CSS\Property\AtRule;
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;
/**
* Class AMP_Style_Sanitizer
*
* Collects inline styles and outputs them in the amp-custom stylesheet.
*/
class AMP_Style_Sanitizer extends AMP_Base_Sanitizer {
/**
* 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.
* }
*/
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]',
),
);
/**
* 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.
*
* @since 1.0
* @var array
*/
private $used_class_names = array();
/**
* 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;
/**
* 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 = $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.
*
* @since 1.0
* @return array Used class names.
*/
private function get_used_class_names() {
if ( empty( $this->used_class_names ) ) {
$classes = ' ';
foreach ( $this->xpath->query( '//*/@class' ) as $class_attribute ) {
$classes .= ' ' . $class_attribute->nodeValue;
}
$this->used_class_names = array_unique( array_filter( preg_split( '/\s+/', trim( $classes ) ) ) );
}
return $this->used_class_names;
}
/**
* 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->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 ) {
$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_Response_Headers::send_server_timing( 'amp_parse_css', $this->parse_css_duration, 'AMP Parse CSS' );
}
}
/**
* 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.
* @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() ) {
$needs_base_url = (
! is_bool( $url )
&&
! preg_match( '|^(https?:)?//|', $url )
&&
! ( $this->content_url && 0 === strpos( $url, $this->content_url ) )
);
if ( $needs_base_url ) {
$url = $this->base_url . $url;
}
$remove_url_scheme = function( $schemed_url ) {
return preg_replace( '#^\w+:(?=//)#', '', $schemed_url );
};
// Strip URL scheme, query, and fragment.
$url = $remove_url_scheme( preg_replace( ':[\?#].*$:', '', $url ) );
$includes_url = $remove_url_scheme( includes_url( '/' ) );
$content_url = $remove_url_scheme( content_url( '/' ) );
$admin_url = $remove_url_scheme( get_admin_url( null, '/' ) );
$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 ),
);
$url_host = wp_parse_url( $url, PHP_URL_HOST );
if ( ! in_array( $url_host, $allowed_hosts, true ) ) {
/* translators: %s is the file URL */
return new WP_Error( 'disallowed_external_file_url', sprintf( __( 'Skipped file which does not have a recognized local host (%s).', 'amp' ), $url_host ) );
}
// Validate file extensions.
if ( ! empty( $allowed_extensions ) ) {
$pattern = sprintf( '/\.(%s)$/i', implode( '|', $allowed_extensions ) );
if ( ! preg_match( $pattern, $url ) ) {
/* translators: %s is the file URL */
return new WP_Error( 'disallowed_file_extension', sprintf( __( 'Skipped file which does not have an allowed file extension (%s).', 'amp' ), $url ) );
}
}
$file_path = null;
if ( 0 === strpos( $url, $content_url ) ) {
$file_path = WP_CONTENT_DIR . substr( $url, strlen( $content_url ) - 1 );
} elseif ( 0 === strpos( $url, $includes_url ) ) {
$file_path = ABSPATH . WPINC . substr( $url, strlen( $includes_url ) - 1 );
} elseif ( 0 === strpos( $url, $admin_url ) ) {
$file_path = ABSPATH . 'wp-admin' . substr( $url, strlen( $admin_url ) - 1 );
}
if ( ! $file_path || false !== strpos( '../', $file_path ) || 0 !== validate_file( $file_path ) || ! file_exists( $file_path ) ) {
/* translators: %s is file URL */
return new WP_Error( 'file_path_not_found', sprintf( __( 'Unable to locate filesystem path for %s.', 'amp' ), $url ) );
}
return $file_path;
}
/**
* Process style element.
*
* @param DOMElement $element Style element.
*/
private function process_style_element( DOMElement $element ) {
// @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;
if ( $stylesheet ) {
$stylesheet = $this->process_stylesheet( $stylesheet, $element, array(
'allowed_at_rules' => $cdata_spec['css_spec']['allowed_at_rules'],
'property_whitelist' => $cdata_spec['css_spec']['allowed_declarations'],
'validate_keyframes' => $cdata_spec['css_spec']['validate_keyframes'],
) );
$pending_stylesheet = array(
'keyframes' => $is_keyframes,
'stylesheet' => $stylesheet,
'node' => $element,
);
if ( ! empty( $this->args['validation_error_callback'] ) ) {
$pending_stylesheet['sources'] = AMP_Validation_Utils::locate_sources( $element ); // Needed because node is removed below.
}
$this->pending_stylesheets[] = $pending_stylesheet;
}
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 );
}
}
/**
* 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.
$normalized_font_href = preg_replace( '#^(http:)?(?=//)#', 'https:', $href );
if ( $this->allowed_font_src_regex && preg_match( $this->allowed_font_src_regex, $normalized_font_href ) ) {
if ( $href !== $normalized_font_href ) {
$element->setAttribute( 'href', $normalized_font_href );
}
return;
}
$css_file_path = $this->get_validated_url_file_path( $href, array( 'css', 'less', 'scss', 'sass' ) );
if ( is_wp_error( $css_file_path ) ) {
$this->remove_invalid_child( $element, array(
'code' => $css_file_path->get_error_code(),
'message' => $css_file_path->get_error_message(),
) );
return;
}
// Load the CSS from the filesystem.
$stylesheet = file_get_contents( $css_file_path ); // phpcs:ignore -- It's a local filesystem path not a remote request.
if ( false === $stylesheet ) {
$this->remove_invalid_child( $element, array(
'message' => __( 'Unable to load stylesheet from filesystem.', 'amp' ),
) );
return;
}
// Honor the link's media attribute.
$media = $element->getAttribute( 'media' );
if ( $media && 'all' !== $media ) {
$stylesheet = sprintf( '@media %s { %s }', $media, $stylesheet );
}
$stylesheet = $this->process_stylesheet( $stylesheet, $element, array(
'allowed_at_rules' => $this->style_custom_cdata_spec['css_spec']['allowed_at_rules'],
'property_whitelist' => $this->style_custom_cdata_spec['css_spec']['allowed_declarations'],
'stylesheet_url' => $href,
'stylesheet_path' => $css_file_path,
) );
$pending_stylesheet = array(
'keyframes' => false,
'stylesheet' => $stylesheet,
'node' => $element,
);
if ( ! empty( $this->args['validation_error_callback'] ) ) {
$pending_stylesheet['sources'] = AMP_Validation_Utils::locate_sources( $element ); // Needed because node is removed below.
}
$this->pending_stylesheets[] = $pending_stylesheet;
// Remove now that styles have been processed.
$element->parentNode->removeChild( $element );
}
/**
* Process stylesheet.
*
* Sanitized invalid CSS properties and rules, removes rules which do not
* apply to the current document, and compresses the CSS to remove whitespace and comments.
*
* @since 1.0
*
* @param string $stylesheet Stylesheet.
* @param DOMElement|DOMAttr $node Element (link/style) or style attribute where the stylesheet came from.
* @param array $options {
* Options.
*
* @type bool $class_selector_tree_shaking Whether to perform tree shaking to delete rules that reference class names not extant in the current document.
* @type string[] $property_whitelist Exclusively-allowed properties.
* @type string[] $property_blacklist Disallowed properties.
* @type string $stylesheet_url Original URL for stylesheet when originating via link (or @import?).
* @type string $stylesheet_path Original filesystem path for stylesheet when originating via link (or @import?).
* @type array $allowed_at_rules Allowed @-rules.
* @type bool $validate_keyframes Whether keyframes should be validated.
* }
* @return array Processed stylesheet parts.
*/
private function process_stylesheet( $stylesheet, $node, $options = array() ) {
$cache_impacting_options = wp_array_slice_assoc(
$options,
array( 'property_whitelist', 'property_blacklist', 'stylesheet_url', 'allowed_at_rules' )
);
$cache_key = md5( $stylesheet . serialize( $cache_impacting_options ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize
$cache_group = 'amp-parsed-stylesheet-v1';
if ( wp_using_ext_object_cache() ) {
$parsed = wp_cache_get( $cache_key, $cache_group );
} else {
$parsed = get_transient( $cache_key . $cache_group );
}
if ( ! $parsed || ! isset( $parsed['stylesheet'] ) || ! is_array( $parsed['stylesheet'] ) ) {
$parsed = $this->parse_stylesheet( $stylesheet, $options );
if ( wp_using_ext_object_cache() ) {
wp_cache_set( $cache_key, $parsed, $cache_group );
} else {
// The expiration is to ensure transient doesn't stick around forever since no LRU flushing like with external object cache.
set_transient( $cache_key . $cache_group, $parsed, MONTH_IN_SECONDS );
}
}
if ( ! empty( $this->args['validation_error_callback'] ) && ! empty( $parsed['validation_errors'] ) ) {
foreach ( $parsed['validation_errors'] as $validation_error ) {
call_user_func( $this->args['validation_error_callback'], array_merge( $validation_error, compact( 'node' ) ) );
}
}
return $parsed['stylesheet'];
}
/**
* Parse stylesheet.
*
* @since 1.0
*
* @param string $stylesheet_string Stylesheet.
* @param array $options Options. See definition in \AMP_Style_Sanitizer::process_stylesheet().
* @return array {
* Parsed stylesheet.
*
* @type array $stylesheet Stylesheet parts, where arrays are tuples for declaration blocks.
* @type array $validation_errors Validation errors.
* }
*/
private function parse_stylesheet( $stylesheet_string, $options = array() ) {
$start_time = microtime( true );
$options = array_merge(
array(
'allowed_at_rules' => array(),
'property_blacklist' => array(
// See <https://www.ampproject.org/docs/design/responsive/style_pages#disallowed-styles>.
'behavior',
'-moz-binding',
),
'property_whitelist' => array(),
'validate_keyframes' => false,
'stylesheet_url' => null,
'stylesheet_path' => null,
),
$options
);
$stylesheet = array();
$validation_errors = array();
try {
$parser_settings = Sabberworm\CSS\Settings::create();
$css_parser = new Sabberworm\CSS\Parser( $stylesheet_string, $parser_settings );
$css_document = $css_parser->parse();
if ( ! empty( $options['stylesheet_url'] ) ) {
$this->real_path_urls(
array_filter(
$css_document->getAllValues(),
function ( $value ) {
return $value instanceof URL;
}
),
$options['stylesheet_url']
);
}
$validation_errors = $this->process_css_list( $css_document, $options );
$output_format = Sabberworm\CSS\OutputFormat::createCompact();
$before_declaration_block = '/*AMP_WP_BEFORE_DECLARATION_BLOCK*/';
$between_selectors = '/*AMP_WP_BETWEEN_SELECTORS*/';
$after_declaration_block_selectors = '/*AMP_WP_BEFORE_DECLARATION_SELECTORS*/';
$after_declaration_block = '/*AMP_WP_AFTER_DECLARATION*/';
$output_format->set( 'BeforeDeclarationBlock', $before_declaration_block );
$output_format->set( 'SpaceBeforeSelectorSeparator', $between_selectors );
$output_format->set( 'AfterDeclarationBlockSelectors', $after_declaration_block_selectors );
$output_format->set( 'AfterDeclarationBlock', $after_declaration_block );
$stylesheet_string = $css_document->render( $output_format );
$pattern = '#';
$pattern .= '(' . preg_quote( $before_declaration_block, '#' ) . ')';
$pattern .= '(.+?)';
$pattern .= preg_quote( $after_declaration_block_selectors, '#' );
$pattern .= '(.+?)';
$pattern .= preg_quote( $after_declaration_block, '#' );
$pattern .= '#s';
$split_stylesheet = preg_split( $pattern, $stylesheet_string, -1, PREG_SPLIT_DELIM_CAPTURE );
$length = count( $split_stylesheet );
for ( $i = 0; $i < $length; $i++ ) {
if ( $before_declaration_block === $split_stylesheet[ $i ] ) {
$selectors = explode( $between_selectors . ',', $split_stylesheet[ ++$i ] );
$declaration = $split_stylesheet[ ++$i ];
$selectors_parsed = array();
foreach ( $selectors as $selector ) {
$classes = array();
// Remove :not() to eliminate false negatives, such as with `body:not(.title-tagline-hidden) .site-branding-text`.
$reduced_selector = preg_replace( '/:not\(.+?\)/', '', $selector );
// Remove attribute selectors to eliminate false negative, such as with `.social-navigation a[href*="example.com"]:before`.
$reduced_selector = preg_replace( '/\[\w.*?\]/', '', $reduced_selector );
if ( preg_match_all( '/(?<=\.)([a-zA-Z0-9_-]+)/', $reduced_selector, $matches ) ) {
$classes = $matches[0];
}
$selectors_parsed[ $selector ] = $classes;
}
$stylesheet[] = array(
$selectors_parsed,
$declaration,
);
} else {
$stylesheet[] = $split_stylesheet[ $i ];
}
}
} catch ( Exception $exception ) {
$validation_errors[] = array(
'code' => 'css_parse_error',
'message' => $exception->getMessage(),
);
}
$this->parse_css_duration += ( microtime( true ) - $start_time );
return compact( 'stylesheet', 'validation_errors' );
}
/**
* Process CSS list.
*
* @since 1.0
*
* @param CSSList $css_list CSS List.
* @param array $options Options.
* @return array Validation errors.
*/
private function process_css_list( CSSList $css_list, $options ) {
$validation_errors = array();
foreach ( $css_list->getContents() as $css_item ) {
if ( $css_item instanceof DeclarationBlock && empty( $options['validate_keyframes'] ) ) {
$validation_errors = array_merge(
$validation_errors,
$this->process_css_declaration_block( $css_item, $css_list, $options )
);
} elseif ( $css_item instanceof AtRuleBlockList ) {
if ( in_array( $css_item->atRuleName(), $options['allowed_at_rules'], true ) ) {
$validation_errors = array_merge(
$validation_errors,
$this->process_css_list( $css_item, $options )
);
} else {
$validation_errors[] = array(
'code' => 'illegal_css_at_rule',
/* translators: %s is the CSS at-rule name. */
'message' => sprintf( __( 'CSS @%s rules are currently disallowed.', 'amp' ), $css_item->atRuleName() ),
);
$css_list->remove( $css_item );
}
} elseif ( $css_item instanceof Import ) {
$validation_errors[] = array(
'code' => 'illegal_css_import_rule',
'message' => __( 'CSS @import is currently disallowed.', 'amp' ),
);
$css_list->remove( $css_item );
} elseif ( $css_item instanceof AtRuleSet ) {
if ( in_array( $css_item->atRuleName(), $options['allowed_at_rules'], true ) ) {
$validation_errors = array_merge(
$validation_errors,
$this->process_css_declaration_block( $css_item, $css_list, $options )
);
} else {
$validation_errors[] = array(
'code' => 'illegal_css_at_rule',
/* translators: %s is the CSS at-rule name. */
'message' => sprintf( __( 'CSS @%s rules are currently disallowed.', 'amp' ), $css_item->atRuleName() ),
);
$css_list->remove( $css_item );
}
} elseif ( $css_item instanceof KeyFrame ) {
if ( in_array( 'keyframes', $options['allowed_at_rules'], true ) ) {
$validation_errors = array_merge(
$validation_errors,
$this->process_css_keyframes( $css_item, $options )
);
} else {
$validation_errors[] = array(
'code' => 'illegal_css_at_rule',
/* translators: %s is the CSS at-rule name. */
'message' => sprintf( __( 'CSS @%s rules are currently disallowed.', 'amp' ), $css_item->atRuleName() ),
);
}
} elseif ( $css_item instanceof AtRule ) {
$validation_errors[] = array(
'code' => 'illegal_css_at_rule',
/* translators: %s is the CSS at-rule name. */
'message' => sprintf( __( 'CSS @%s rules are currently disallowed.', 'amp' ), $css_item->atRuleName() ),
);
$css_list->remove( $css_item );
} else {
$validation_errors[] = array(
'code' => 'unrecognized_css',
'message' => __( 'Unrecognized CSS removed.', 'amp' ),
);
$css_list->remove( $css_item );
}
}
return $validation_errors;
}
/**
* Convert URLs in to non-relative real-paths.
*
* @param URL[] $urls URLs.
* @param string $stylesheet_url Stylesheet URL.
*/
private function real_path_urls( $urls, $stylesheet_url ) {
$base_url = preg_replace( ':[^/]+(\?.*)?(#.*)?$:', '', $stylesheet_url );
if ( empty( $base_url ) ) {
return;
}
foreach ( $urls as $url ) {
$url_string = $url->getURL()->getString();
if ( 'data:' === substr( $url_string, 0, 5 ) ) {
continue;
}
$parsed_url = wp_parse_url( $url_string );
if ( ! empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) || '/' === substr( $parsed_url['path'], 0, 1 ) ) {
continue;
}
$relative_url = preg_replace( '#^\./#', '', $url->getURL()->getString() );
$real_url = $base_url . $relative_url;
do {
$real_url = preg_replace( '#[^/]+/../#', '', $real_url, -1, $count );
} while ( 0 !== $count );
$url->getURL()->setString( $real_url );
}
}
/**
* Process CSS rule set.
*
* @since 1.0
* @link https://www.ampproject.org/docs/design/responsive/style_pages#disallowed-styles
* @link https://www.ampproject.org/docs/design/responsive/style_pages#restricted-styles
*
* @param RuleSet $ruleset Ruleset.
* @param CSSList $css_list CSS List.
* @param array $options Options.
*
* @return array Validation errors.
*/
private function process_css_declaration_block( RuleSet $ruleset, CSSList $css_list, $options ) {
$validation_errors = array();
// Remove disallowed properties.
if ( ! empty( $options['property_whitelist'] ) ) {
$properties = $ruleset->getRules();
foreach ( $properties as $property ) {
$vendorless_property_name = preg_replace( '/^-\w+-/', '', $property->getRule() );
if ( ! in_array( $vendorless_property_name, $options['property_whitelist'], true ) ) {
$validation_errors[] = array(
'code' => 'illegal_css_property',
'property_name' => $property->getRule(),
'property_value' => $property->getValue(),
);
$ruleset->removeRule( $property->getRule() );
}
}
} else {
foreach ( $options['property_blacklist'] as $illegal_property_name ) {
$properties = $ruleset->getRules( $illegal_property_name );
foreach ( $properties as $property ) {
$validation_errors[] = array(
'code' => 'illegal_css_property',
'property_name' => $property->getRule(),
'property_value' => $property->getValue(),
);
$ruleset->removeRule( $property->getRule() );
}
}
}
if ( $ruleset instanceof AtRuleSet && 'font-face' === $ruleset->atRuleName() ) {
$this->process_font_face_at_rule( $ruleset, $options );
}
$validation_errors = array_merge(
$validation_errors,
$this->transform_important_qualifiers( $ruleset, $css_list )
);
// Remove the ruleset if it is now empty.
if ( 0 === count( $ruleset->getRules() ) ) {
$css_list->remove( $ruleset );
}
// @todo Delete rules with selectors for -amphtml- class and i-amphtml- tags.
return $validation_errors;
}
/**
* Process @font-face by making src URLs non-relative and converting data: URLs into (assumed) file URLs.
*
* @since 1.0
*
* @param AtRuleSet $ruleset Ruleset for @font-face.
* @param array $options Options.
*/
private function process_font_face_at_rule( AtRuleSet $ruleset, $options ) {
$src_properties = $ruleset->getRules( 'src' );
if ( empty( $src_properties ) ) {
return;
}
foreach ( $src_properties as $src_property ) {
$value = $src_property->getValue();
if ( ! ( $value instanceof RuleValueList ) ) {
continue;
}
/*
* The CSS Parser parses a src such as:
*
* url(data:application/font-woff;...) format('woff'),
* url('Genericons.ttf') format('truetype'),
* url('Genericons.svg#genericonsregular') format('svg')
*
* As a list of components consisting of:
*
* URL,
* RuleValueList( CSSFunction, URL ),
* RuleValueList( CSSFunction, URL ),
* CSSFunction
*
* Clearly the components here are not logically grouped. So the first step is to fix the order.
*/
$sources = array();
foreach ( $value->getListComponents() as $component ) {
if ( $component instanceof RuleValueList ) {
$subcomponents = $component->getListComponents();
$subcomponent = array_shift( $subcomponents );
if ( $subcomponent ) {
if ( empty( $sources ) ) {
$sources[] = array( $subcomponent );
} else {
$sources[ count( $sources ) - 1 ][] = $subcomponent;
}
}
foreach ( $subcomponents as $subcomponent ) {
$sources[] = array( $subcomponent );
}
} else {
if ( empty( $sources ) ) {
$sources[] = array( $component );
} else {
$sources[ count( $sources ) - 1 ][] = $component;
}
}
}
/**
* Source URL lists.
*
* @var URL[] $source_file_urls
* @var URL[] $source_data_urls
*/
$source_file_urls = array();
$source_data_urls = array();
foreach ( $sources as $i => $source ) {
if ( $source[0] instanceof URL ) {
if ( 'data:' === substr( $source[0]->getURL()->getString(), 0, 5 ) ) {
$source_data_urls[ $i ] = $source[0];
} else {
$source_file_urls[ $i ] = $source[0];
}
}
}
// Convert data: URLs into regular URLs, assuming there will be a file present (e.g. woff fonts in core themes).
if ( empty( $source_file_urls ) ) {
continue;
}
$source_file_url = current( $source_file_urls );
foreach ( $source_data_urls as $i => $data_url ) {
$mime_type = strtok( substr( $data_url->getURL()->getString(), 5 ), ';' );
if ( ! $mime_type ) {
continue;
}
$extension = preg_replace( ':.+/(.+-)?:', '', $mime_type );
$guessed_url = preg_replace(
':(?<=\.)\w+(\?.*)?(#.*)?$:', // Match the file extension in the URL.
$extension,
$source_file_url->getURL()->getString(),
1,
$count
);
if ( 1 !== $count ) {
continue;
}
// Ensure file exists.
$path = $this->get_validated_url_file_path( $guessed_url );
if ( is_wp_error( $path ) ) {
continue;
}
$data_url->getURL()->setString( $guessed_url );
break;
}
}
}
/**
* Process CSS keyframes.
*
* @since 1.0
* @link https://www.ampproject.org/docs/design/responsive/style_pages#restricted-styles.
* @link https://github.com/ampproject/amphtml/blob/b685a0780a7f59313666225478b2b79b463bcd0b/validator/validator-main.protoascii#L1002-L1043
* @todo Tree shaking could be extended to keyframes, to omit a keyframe if it is not referenced by any rule.
*
* @param KeyFrame $css_list Ruleset.
* @param array $options Options.
* @return array Validation errors.
*/
private function process_css_keyframes( KeyFrame $css_list, $options ) {
$validation_errors = array();
if ( ! empty( $options['property_whitelist'] ) ) {
foreach ( $css_list->getContents() as $rules ) {
if ( ! ( $rules instanceof DeclarationBlock ) ) {
$validation_errors[] = array(
'code' => 'unrecognized_css',
'message' => __( 'Unrecognized CSS removed.', 'amp' ),
);
$css_list->remove( $rules );
continue;
}
$validation_errors = array_merge(
$validation_errors,
$this->transform_important_qualifiers( $rules, $css_list )
);
$properties = $rules->getRules();
foreach ( $properties as $property ) {
$vendorless_property_name = preg_replace( '/^-\w+-/', '', $property->getRule() );
if ( ! in_array( $vendorless_property_name, $options['property_whitelist'], true ) ) {
$validation_errors[] = array(
'code' => 'illegal_css_property',
'property_name' => $property->getRule(),
'property_value' => $property->getValue(),
);
$rules->removeRule( $property->getRule() );
}
}
}
}
return $validation_errors;
}
/**
* Replace !important qualifiers with more specific rules.
*
* @since 1.0
* @see https://www.npmjs.com/package/replace-important