-
Notifications
You must be signed in to change notification settings - Fork 384
/
Copy pathclass-amp-validation-manager.php
2691 lines (2417 loc) · 88 KB
/
class-amp-validation-manager.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_Validation_Manager
*
* @package AMP
*/
use AmpProject\AmpWP\DevTools\UserAccess;
use AmpProject\AmpWP\Icon;
use AmpProject\AmpWP\Option;
use AmpProject\AmpWP\QueryVar;
use AmpProject\AmpWP\Services;
use AmpProject\Dom\Document;
use AmpProject\Exception\MaxCssByteCountExceeded;
use AmpProject\Html\Attribute;
use AmpProject\Html\Tag;
/**
* Class AMP_Validation_Manager
*
* @since 0.7
* @internal
*/
class AMP_Validation_Manager {
/**
* Query var that triggers validation.
*
* @var string
*/
const VALIDATE_QUERY_VAR = 'amp_validate';
/**
* Key for amp_validate query var array for nonce to authorize validation.
*
* @var string
*/
const VALIDATE_QUERY_VAR_NONCE = 'nonce';
/**
* Key for amp_validate query var array for whether to store the validation results in an amp_validated_url post.
*
* @var string
*/
const VALIDATE_QUERY_VAR_CACHE = 'cache';
/**
* Key for amp_validate query var array for whether to return previously-stored the validation results if an
* amp_validated_url post exists for the URL and it is not stale.
*
* @var string
*/
const VALIDATE_QUERY_VAR_CACHED_IF_FRESH = 'cached_if_fresh';
/**
* Key for amp_validate query var array for whether to omit stylesheets data.
*
* @var string
*/
const VALIDATE_QUERY_VAR_OMIT_STYLESHEETS = 'omit_stylesheets';
/**
* Key for amp_validate query var array to bust the cache.
*
* @var string
*/
const VALIDATE_QUERY_VAR_CACHE_BUST = 'cache_bust';
/**
* Key for amp_validate query var array to force Standard template mode.
*
* @var string
*/
const VALIDATE_QUERY_VAR_FORCE_STANDARD_MODE = 'force_standard_mode';
/**
* Meta capability for validation.
*
* Note that this is mapped to 'manage_options' by default via `AMP_Validation_Manager::map_meta_cap()`. Using a
* meta capability allows a site to customize which users get access to perform validation.
*
* @see AMP_Validation_Manager::map_meta_cap()
* @var string
*/
const VALIDATE_CAPABILITY = 'amp_validate';
/**
* Action name for previewing the status change for invalid markup.
*
* @var string
*/
const MARKUP_STATUS_PREVIEW_ACTION = 'amp_markup_status_preview';
/**
* Query var for passing status preview/update for validation error.
*
* @var string
*/
const VALIDATION_ERROR_TERM_STATUS_QUERY_VAR = 'amp_validation_error_term_status';
/**
* The errors encountered when validating.
*
* @var array[] {
* @type array $error Error data.
* @type bool $sanitized Whether sanitized.
* }
*/
public static $validation_results = [];
/**
* Sources that enqueue (or register) each script.
*
* @var array
*/
public static $enqueued_script_sources = [];
/**
* Sources for script extras that are attached to each dependency.
*
* The keys are the values of the extras being added; the values are an array of the source(s) that caused the extra
* to be added.
*
* @since 1.5
* @var array[]
*/
public static $extra_script_sources = [];
/**
* Sources that enqueue (or register) each style.
*
* @var array
*/
public static $enqueued_style_sources = [];
/**
* Sources for style extras that are attached to each dependency.
*
* The keys are the style handles, and the values are mappings of the inline CSS to the array of sources.
*
* @since 1.5
* @var array[]
*/
public static $extra_style_sources = [];
/**
* Post IDs for posts that have been updated which need to be re-validated.
*
* Keys are post IDs and values are whether the post has been re-validated.
*
* @deprecated In 2.1 the classic editor block validation was removed. This is not removed yet since there is a mini plugin that uses it: https://gist.github.com/westonruter/31ac0e056b8b1278c98f8a9f548fcc1a.
* @var bool[]
*/
public static $posts_pending_frontend_validation = [];
/**
* Current sources gathered for a given hook currently being run.
*
* @see AMP_Validation_Manager::wrap_hook_callbacks()
* @see AMP_Validation_Manager::decorate_filter_source()
* @var array[]
*/
protected static $current_hook_source_stack = [];
/**
* Index for where block appears in a post's content.
*
* @var int
*/
protected static $block_content_index = 0;
/**
* Hook source stack.
*
* This has to be public for the sake of PHP 5.3.
*
* @since 0.7
* @var array[]
*/
public static $hook_source_stack = [];
/**
* Original render_callbacks for blocks at the time of wrapping.
*
* Keys are block names, values are the render_callback callables.
*
* @see AMP_Validation_Manager::wrap_block_callbacks()
* @var array<string, callable>
*/
protected static $original_block_render_callbacks = [];
/**
* Collection of backtraces for when wp_editor() was called.
*
* @var array
*/
protected static $wp_editor_sources = [];
/**
* Whether a validate request is being performed.
*
* When responding to a request to validate a URL, instead of an HTML document being returned, a JSON document is
* returned with any errors that were encountered during validation.
*
* @see AMP_Validation_Manager::get_validate_response_data()
*
* @var bool
*/
protected static $is_validate_request = false;
/**
* Overrides for validation errors.
*
* @var array
*/
public static $validation_error_status_overrides = [];
/**
* Whether the admin bar item was added for AMP.
*
* @var bool
*/
protected static $amp_admin_bar_item_added = false;
/**
* Get dev tools user access service.
*
* @return UserAccess
*/
private static function get_dev_tools_user_access() {
$service = Services::get( 'dev_tools.user_access' );
return $service;
}
/**
* Initialize.
*
* @return void
*/
public static function init() {
add_filter( 'map_meta_cap', [ __CLASS__, 'map_meta_cap' ], 100, 2 );
AMP_Validated_URL_Post_Type::register();
AMP_Validation_Error_Taxonomy::register();
add_action( 'enqueue_block_editor_assets', [ __CLASS__, 'enqueue_block_validation' ] );
add_action( 'admin_bar_menu', [ __CLASS__, 'add_admin_bar_menu_items' ], 101 );
add_action( 'wp', [ __CLASS__, 'maybe_fail_validate_request' ] );
add_action( 'wp', [ __CLASS__, 'maybe_send_cached_validate_response' ], 20 );
add_action( 'wp', [ __CLASS__, 'override_validation_error_statuses' ] );
// Allow query parameter to force a response to be served with Standard mode (AMP-first). This query parameter
// is only honored when doing a validation request or when the user is able to do validation. This is used as
// part of Site Scanning in order to determine if the primary theme is suitable for serving AMP.
if ( ! amp_is_canonical() ) {
$filter_hooks = [
'default_option_' . AMP_Options_Manager::OPTION_NAME,
'option_' . AMP_Options_Manager::OPTION_NAME,
];
foreach ( $filter_hooks as $filter_hook ) {
add_filter( $filter_hook, [ __CLASS__, 'filter_options_when_force_standard_mode_request' ] );
}
}
}
/**
* Filter AMP options to set Standard template mode if it is an AMP-override request.
*
* @param array|false $options Options.
* @return array Filtered options.
*/
public static function filter_options_when_force_standard_mode_request( $options ) {
if ( ! $options ) {
$options = [];
}
if (
self::is_validate_request()
&&
self::get_validate_request_args()[ self::VALIDATE_QUERY_VAR_FORCE_STANDARD_MODE ]
) {
$options[ Option::THEME_SUPPORT ] = AMP_Theme_Support::STANDARD_MODE_SLUG;
$options[ Option::ALL_TEMPLATES_SUPPORTED ] = true;
}
return $options;
}
/**
* Determine if a post supports AMP validation.
*
* @since 1.2
*
* @param WP_Post|int $post Post.
* @return bool Whether post supports AMP validation.
*/
public static function post_supports_validation( $post ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
return (
// Skip if the post type is not viewable on the frontend, since we need a permalink to validate.
in_array( $post->post_type, AMP_Post_Type_Support::get_eligible_post_types(), true )
&&
! wp_is_post_autosave( $post )
&&
! wp_is_post_revision( $post )
&&
'auto-draft' !== $post->post_status
&&
'trash' !== $post->post_status
&&
amp_is_post_supported( $post )
);
}
/**
* Return whether sanitization is initially accepted (by default) for newly encountered validation errors.
*
* To reject all new validation errors by default, a filter can be used like so:
*
* add_filter( 'amp_validation_error_default_sanitized', '__return_false' );
*
* Whether or not a validation error is then actually sanitized is the ultimately determined by the
* `amp_validation_error_sanitized` filter.
*
* @since 1.0
* @see AMP_Validation_Error_Taxonomy::is_validation_error_sanitized()
* @see AMP_Validation_Error_Taxonomy::get_validation_error_sanitization()
*
* @param array $error Optional. Validation error. Will query the general status if no error provided.
* @return bool Whether sanitization is forcibly accepted.
*/
public static function is_sanitization_auto_accepted( $error = null ) {
if ( $error && amp_is_canonical() ) {
// Excessive CSS on AMP-first sites must not be removed by default since removing CSS can severely break a site.
$accepted = AMP_Style_Sanitizer::STYLESHEET_TOO_LONG !== $error['code'];
} else {
$accepted = true;
}
/**
* Filters whether sanitization is accepted for a newly-encountered validation error .
*
* This only applies to validation errors that have not been encountered before. To override the sanitization
* status of existing validation errors, use the `amp_validation_error_sanitized` filter.
*
* @since 1.4
* @see AMP_Validation_Error_Taxonomy::get_validation_error_sanitization()
*
* @param bool $accepted Default accepted.
* @param array|null $error Validation error. May be null when asking if accepting sanitization is enabled by default.
*/
return apply_filters( 'amp_validation_error_default_sanitized', $accepted, $error );
}
/**
* Add menu items to admin bar for AMP.
*
* When on a non-AMP response (transitional mode), then the admin bar item should include:
* - Icon: LINK SYMBOL when AMP not known to be invalid and sanitization is not forced, or CROSS MARK when AMP is known to be valid.
* - Parent admin item and first submenu item: link to AMP version.
* - Second submenu item: link to validate the URL.
*
* When on transitional AMP response:
* - Icon: CHECK MARK if no unaccepted validation errors on page, or WARNING SIGN if there are unaccepted validation errors which are being forcibly sanitized.
* Otherwise, if there are unsanitized validation errors then a redirect to the non-AMP version will be done.
* - Parent admin item and first submenu item: link to non-AMP version.
* - Second submenu item: link to validate the URL.
*
* When on AMP-first response:
* - Icon: CHECK MARK if no unaccepted validation errors on page, or WARNING SIGN if there are unaccepted validation errors.
* - Parent admin and first submenu item: link to validate the URL.
*
* @see AMP_Validation_Manager::finalize_validation() Where the emoji is updated.
* @see amp_add_admin_bar_view_link() Where an admin bar item may have been added already for Reader/Transitional modes.
*
* @param WP_Admin_Bar $wp_admin_bar Admin bar.
*/
public static function add_admin_bar_menu_items( $wp_admin_bar ) {
if ( is_admin() || ! self::get_dev_tools_user_access()->is_user_enabled() || ! amp_is_available() ) {
self::$amp_admin_bar_item_added = false;
return;
}
$is_amp_request = amp_is_request();
$current_url = remove_query_arg(
array_merge( wp_removable_query_args(), [ QueryVar::NOAMP ] ),
amp_get_current_url()
);
if ( amp_is_canonical() ) {
$amp_url = $current_url;
$non_amp_url = add_query_arg(
QueryVar::NOAMP,
QueryVar::NOAMP_AVAILABLE,
$current_url
);
} elseif ( $is_amp_request ) {
$amp_url = $current_url;
$non_amp_url = add_query_arg(
QueryVar::NOAMP,
QueryVar::NOAMP_MOBILE,
amp_remove_paired_endpoint( $current_url )
);
} else {
$amp_url = amp_add_paired_endpoint( $current_url );
$non_amp_url = $current_url;
}
$validate_url = AMP_Validated_URL_Post_Type::get_recheck_url( AMP_Validated_URL_Post_Type::get_invalid_url_post( $amp_url ) ?: $amp_url );
// Construct the parent admin bar item.
if ( $is_amp_request ) {
$icon = Icon::valid(); // This will get overridden in AMP_Validation_Manager::finalize_validation() if there are unaccepted errors.
$href = $validate_url;
} else {
$icon = Icon::link();
$href = $amp_url;
}
$icon_html = $icon->to_html(
[
'id' => 'amp-admin-bar-item-status-icon',
'class' => 'ab-icon',
]
);
$validate_url_title = __( 'Validate URL', 'amp' );
$parent = [
'id' => 'amp',
'title' => sprintf(
'%s %s',
$icon_html,
esc_html__( 'AMP', 'amp' )
),
'href' => esc_url( $href ),
'meta' => [
'title' => esc_attr( $is_amp_request ? $validate_url_title : __( 'View AMP version', 'amp' ) ),
],
];
// Construct admin bar item for validation.
$validate_item = [
'parent' => 'amp',
'id' => 'amp-validity',
'title' => esc_html( $validate_url_title ),
'href' => esc_url( $validate_url ),
];
// Construct admin bar item to link to AMP version or non-AMP version.
$wp_admin_bar->remove_node( 'amp-view' ); // Remove so we can re-add in the right position.
$link_item = [
'parent' => 'amp',
'id' => 'amp-view',
'href' => esc_url( $is_amp_request ? $non_amp_url : $amp_url ),
];
if ( amp_is_canonical() ) {
$link_item['title'] = esc_html__( 'View with AMP disabled', 'amp' );
} else {
$link_item['title'] = esc_html( $is_amp_request ? __( 'View non-AMP version', 'amp' ) : __( 'View AMP version', 'amp' ) );
}
// Add top-level menu item. Note that this will correctly merge/amend any existing AMP nav menu item added in amp_add_admin_bar_view_link().
$wp_admin_bar->add_node( $parent );
if ( $is_amp_request ) {
$wp_admin_bar->add_node( $validate_item );
$wp_admin_bar->add_node( $link_item );
} else {
$wp_admin_bar->add_node( $link_item );
$wp_admin_bar->add_node( $validate_item );
}
// Add settings link to admin bar.
if ( current_user_can( 'manage_options' ) ) {
$wp_admin_bar->add_node(
[
'parent' => 'amp',
'id' => 'amp-settings',
'title' => esc_html__( 'Settings', 'amp' ),
'href' => esc_url( admin_url( add_query_arg( 'page', AMP_Options_Manager::OPTION_NAME, 'admin.php' ) ) ),
]
);
}
self::$amp_admin_bar_item_added = true;
}
/**
* Override validation error statuses (when requested).
*
* When a query var is present along with the required nonce, override the status of the invalid markup
* as requested.
*
* @since 1.5.0
*/
public static function override_validation_error_statuses() {
$override_validation_error_statuses = (
isset( $_REQUEST['preview'] )
&&
! empty( $_REQUEST[ AMP_Validated_URL_Post_Type::VALIDATION_ERRORS_INPUT_KEY ] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
&&
is_array( $_REQUEST[ AMP_Validated_URL_Post_Type::VALIDATION_ERRORS_INPUT_KEY ] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
);
if ( ! $override_validation_error_statuses ) {
return;
}
if ( ! isset( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST['_wpnonce'] ), self::MARKUP_STATUS_PREVIEW_ACTION ) ) {
wp_die(
esc_html__( 'Preview link expired. Please try again.', 'amp' ),
esc_html__( 'Error', 'amp' ),
[ 'response' => 401 ]
);
}
/*
* This can't just easily add an amp_validation_error_sanitized filter because the the filter_sanitizer_args() method
* currently needs to obtain the list of overrides to create a parsed_cache_variant.
*/
foreach ( $_REQUEST[ AMP_Validated_URL_Post_Type::VALIDATION_ERRORS_INPUT_KEY ] as $slug => $data ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
if ( ! isset( $data[ self::VALIDATION_ERROR_TERM_STATUS_QUERY_VAR ] ) ) {
continue;
}
$slug = sanitize_key( $slug );
$status = (int) $data[ self::VALIDATION_ERROR_TERM_STATUS_QUERY_VAR ];
self::$validation_error_status_overrides[ $slug ] = $status;
ksort( self::$validation_error_status_overrides );
}
}
/**
* Short-circuit validation requests which are for URLs that are not AMP pages.
*
* @since 2.1
*/
public static function maybe_fail_validate_request() {
if ( ! self::is_validate_request() || amp_is_request() ) {
return;
}
if ( ! amp_is_available() ) {
$code = 'AMP_NOT_AVAILABLE';
$message = __( 'The requested URL is not an AMP page. AMP may have been disabled for the URL. If so, you can forget the Validated URL.', 'amp' );
} else {
$code = 'AMP_NOT_REQUESTED';
$message = __( 'The requested URL is not an AMP page.', 'amp' );
}
wp_send_json( compact( 'code', 'message' ), 400 );
}
/**
* Whether a validate request is being performed.
*
* When responding to a request to validate a URL, instead of an HTML document being returned, a JSON document is
* returned with any errors that were encountered during validation.
*
* @see AMP_Validation_Manager::get_validate_response_data()
*
* @return bool
*/
public static function is_validate_request() {
return self::$is_validate_request;
}
/**
* Get validate request args.
*
* @return array {
* Args.
*
* @type string|null $nonce None to authorize validate request or null if none was supplied.
* @type bool $cache Whether to store results in amp_validated_url post.
* @type bool $cached_if_fresh Whether to return previously-stored results if not stale.
* @type bool $omit_stylesheets Whether to omit stylesheet data in the validate response.
* }
*/
private static function get_validate_request_args() {
$defaults = [
self::VALIDATE_QUERY_VAR_NONCE => null,
self::VALIDATE_QUERY_VAR_CACHE => false,
self::VALIDATE_QUERY_VAR_CACHED_IF_FRESH => false,
self::VALIDATE_QUERY_VAR_OMIT_STYLESHEETS => false,
self::VALIDATE_QUERY_VAR_FORCE_STANDARD_MODE => false,
];
if ( ! isset( $_GET[ self::VALIDATE_QUERY_VAR ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
return $defaults;
}
$unsanitized_values = $_GET[ self::VALIDATE_QUERY_VAR ]; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
if ( is_string( $unsanitized_values ) ) {
$unsanitized_values = [
self::VALIDATE_QUERY_VAR_NONCE => $unsanitized_values,
];
} elseif ( ! is_array( $unsanitized_values ) ) {
return $defaults;
}
$args = $defaults;
foreach ( $unsanitized_values as $key => $unsanitized_value ) {
switch ( $key ) {
case self::VALIDATE_QUERY_VAR_NONCE:
$args[ $key ] = sanitize_key( $unsanitized_value );
break;
default:
$args[ $key ] = rest_sanitize_boolean( $unsanitized_value );
}
}
return $args;
}
/**
* Initialize a validate request.
*
* This function is called as early as possible, at the plugins_loaded action, to see if the current request is to
* validate the response. If the validate query arg is absent, then this does nothing. If the query arg is present,
* but the value is not a valid auth key, then wp_send_json() is invoked to short-circuit with a failure. Otherwise,
* the static $is_validate_request variable is set to true.
*
* @since 1.5
*/
public static function init_validate_request() {
$should_validate_response = self::should_validate_response();
if ( true === $should_validate_response ) {
self::add_validation_error_sourcing();
self::$is_validate_request = true;
if ( '1' === (string) ini_get( 'display_errors' ) ) {
// Suppress the display of fatal errors that may arise during validation so that they will not be counted
// as actual validation errors.
ini_set( 'display_errors', 0 ); // phpcs:ignore WordPress.PHP.IniSet.display_errors_Blacklisted
}
} else {
self::$is_validate_request = false;
// Short-circuit validation requests that are unauthorized.
if ( $should_validate_response instanceof WP_Error ) {
wp_send_json(
[
'code' => $should_validate_response->get_error_code(),
'message' => $should_validate_response->get_error_message(),
],
401
);
}
}
}
/**
* Add hooks for doing determining sources for validation errors during preprocessing/sanitizing.
*/
public static function add_validation_error_sourcing() {
add_action( 'wp', [ __CLASS__, 'wrap_widget_callbacks' ] );
$int_min = defined( 'PHP_INT_MIN' ) ? PHP_INT_MIN : ~PHP_INT_MAX; // phpcs:ignore PHPCompatibility.Constants.NewConstants.php_int_minFound
add_filter( 'register_block_type_args', [ __CLASS__, 'wrap_block_callbacks' ], $int_min );
add_action( 'all', [ __CLASS__, 'wrap_hook_callbacks' ] );
$wrapped_filters = [ 'the_content', 'the_excerpt' ];
foreach ( $wrapped_filters as $wrapped_filter ) {
add_filter( $wrapped_filter, [ __CLASS__, 'decorate_filter_source' ], PHP_INT_MAX );
}
add_filter( 'do_shortcode_tag', [ __CLASS__, 'decorate_shortcode_source' ], PHP_INT_MAX, 2 );
add_filter( 'embed_oembed_html', [ __CLASS__, 'decorate_embed_source' ], PHP_INT_MAX, 3 );
// The `WP_Block_Type_Registry` class was added in WordPress 5.0.0. Because of that it sometimes caused issues
// on the AMP Validated URL screen when on WordPress 4.9.
if ( class_exists( 'WP_Block_Type_Registry' ) ) {
add_filter(
'the_content',
[
__CLASS__,
'add_block_source_comments',
],
8
); // The do_blocks() function runs at priority 9.
}
add_filter( 'the_editor', [ __CLASS__, 'filter_the_editor_to_detect_sources' ] );
}
/**
* Filter `the_editor` to detect the theme/plugin responsible for calling it `wp_editor()`.
*
* @since 2.2
* @see wp_editor()
*
* @param string $output Editor's HTML markup.
* @return string Editor's HTML markup (unchanged).
*/
public static function filter_the_editor_to_detect_sources( $output ) {
$file_reflection = Services::get( 'dev_tools.file_reflection' );
// Find the first plugin/theme in the call stack.
$backtrace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace -- Only way to find theme/plugin responsible for calling.
foreach ( $backtrace as $call ) {
if (
! empty( $call['function'] )
&&
! empty( $call['file'] )
&&
'wp_editor' === $call['function']
) {
$source = $file_reflection->get_file_source( $call['file'] );
if ( $source ) {
self::$wp_editor_sources[] = $source;
}
break;
}
}
return $output;
}
/**
* Handle save_post action to queue re-validation of the post on the frontend.
*
* This is intended to only apply to post edits made in the classic editor.
*
* @deprecated In 2.1 the classic editor block validation was removed.
* @codeCoverageIgnore
*/
public static function handle_save_post_prompting_validation() {
_deprecated_function( __METHOD__, '2.1' );
}
/**
* Validate the posts pending frontend validation.
*
* @see AMP_Validation_Manager::handle_save_post_prompting_validation()
*
* @deprecated In 2.1 the classic editor block validation was removed.
* @codeCoverageIgnore
*/
public static function validate_queued_posts_on_frontend() {
_deprecated_function( __METHOD__, '2.1' );
}
/**
* Map the amp_validate meta capability to the primitive manage_options capability.
*
* Using a meta capability allows a site to customize which users get access to perform validation.
*
* @param string[] $caps Array of the user's capabilities.
* @param string $cap Capability name.
* @return string[] Filtered primitive capabilities.
*/
public static function map_meta_cap( $caps, $cap ) {
if ( self::VALIDATE_CAPABILITY === $cap ) {
// Note that $caps most likely only contains a single item anyway, but only swapping out the one meta
// capability with the primitive capability allows a site to add additional required capabilities.
$position = array_search( $cap, $caps, true );
if ( false !== $position ) {
$caps[ $position ] = 'manage_options';
}
}
return $caps;
}
/**
* Whether the user has the required capability to validate.
*
* Checks for permissions before validating.
*
* @param int|WP_User|null $user User to check for the capability. If null, the current user is used.
* @return boolean $has_cap Whether the current user has the capability.
*/
public static function has_cap( $user = null ) {
if ( null === $user ) {
$user = wp_get_current_user();
}
return user_can( $user, self::VALIDATE_CAPABILITY );
}
/**
* Add validation error.
*
* @param array $error Error info, especially code.
* @param array $data Additional data, including the node.
*
* @return bool Whether the validation error should result in sanitization.
*/
public static function add_validation_error( array $error, array $data = [] ) {
$node = null;
$sources = null;
if ( isset( $data['node'] ) && $data['node'] instanceof DOMNode ) {
$node = $data['node'];
}
if ( self::is_validate_request() ) {
if ( ! empty( $error['sources'] ) ) {
$sources = $error['sources'];
} elseif ( $node ) {
$sources = self::locate_sources( $node );
}
}
unset( $error['sources'] );
if ( ! isset( $error['code'] ) ) {
$error['code'] = 'unknown';
}
/**
* Filters the validation error array.
*
* This allows plugins to add amend additional properties which can help with
* more accurately identifying a validation error beyond the name of the parent
* node and the element's attributes. The $sources are also omitted because
* these are only available during an explicit validation request and so they
* are not suitable for plugins to vary sanitization by. If looking to force a
* validation error to be ignored, use the 'amp_validation_error_sanitized'
* filter instead of attempting to return an empty value with this filter (as
* that is not supported).
*
* @since 1.0
*
* @param array $error Validation error to be printed.
* @param array $context {
* Context data for validation error sanitization.
*
* @type DOMNode $node Node for which the validation error is being reported. May be null.
* }
*/
$error = apply_filters( 'amp_validation_error', $error, compact( 'node' ) );
$sanitization = AMP_Validation_Error_Taxonomy::get_validation_error_sanitization( $error );
$sanitized = (
AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_ACCEPTED_STATUS === $sanitization['status']
||
AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_ACCEPTED_STATUS === $sanitization['status']
);
/*
* Ignore validation errors which are forcibly sanitized by filter. This includes errors accepted via
* AMP_Validation_Error_Taxonomy::accept_validation_errors(), such as the acceptable_errors in core themes.
* This was introduced in <https://github.com/ampproject/amp-wp/pull/1413> to prevent forcibly-sanitized
* validation errors from being reported, to avoid noise and wasted storage. It was inadvertently
* reverted in de7b04b but then restored as part of <https://github.com/ampproject/amp-wp/pull/1413>.
*/
if ( $sanitized && 'with_filter' === $sanitization['forced'] ) {
return true;
}
// Add sources back into the $error for referencing later. @todo It may be cleaner to store sources separately to avoid having to re-remove later during storage.
$error = array_merge( $error, compact( 'sources' ) );
self::$validation_results[] = compact( 'error', 'sanitized' );
return $sanitized;
}
/**
* Reset the stored removed nodes and attributes.
*
* After testing if the markup is valid,
* these static values will remain.
* So reset them in case another test is needed.
*
* @return void
*/
public static function reset_validation_results() {
self::$validation_results = [];
self::$enqueued_style_sources = [];
self::$enqueued_script_sources = [];
self::$extra_script_sources = [];
self::$extra_style_sources = [];
self::$original_block_render_callbacks = [];
self::$wp_editor_sources = [];
}
/**
* Checks the AMP validity of the post content.
*
* If it's not valid AMP, it displays an error message above the 'Classic' editor.
*
* This is essentially a PHP implementation of ampBlockValidation.handleValidationErrorsStateChange() in JS.
*
* @deprecated In 2.1 the classic editor block validation was removed.
* @codeCoverageIgnore
* @return void
*/
public static function print_edit_form_validation_status() {
_deprecated_function( __METHOD__, '2.1' );
}
/**
* Get source start comment.
*
* @param array $source Source data.
* @param bool $is_start Whether the comment is the start or end.
* @return string HTML Comment.
*/
public static function get_source_comment( array $source, $is_start = true ) {
unset( $source['reflection'] );
return sprintf(
'<!--%samp-source-stack %s-->',
$is_start ? '' : '/',
str_replace( '--', '', wp_json_encode( $source ) )
);
}
/**
* Parse source comment.
*
* @param DOMComment $comment Comment.
* @return array|null Parsed source or null if not a source comment.
*/
public static function parse_source_comment( DOMComment $comment ) {
if ( ! preg_match( '#^\s*(?P<closing>/)?amp-source-stack\s+(?P<args>{.+})\s*$#s', $comment->nodeValue, $matches ) ) {
return null;
}
$source = json_decode( $matches['args'], true );
$closing = ! empty( $matches['closing'] );
return compact( 'source', 'closing' );
}
/**
* Recursively determine if a given dependency depends on another.
*
* @since 1.3
*
* @param WP_Dependencies $dependencies Dependencies.
* @param string $current_handle Current handle.
* @param string $dependency_handle Dependency handle.
* @return bool Whether the current handle is a dependency of the dependency handle.
*/
protected static function has_dependency( WP_Dependencies $dependencies, $current_handle, $dependency_handle ) {
if ( $current_handle === $dependency_handle ) {
return true;
}
if ( ! isset( $dependencies->registered[ $current_handle ] ) ) {
return false;
}
foreach ( $dependencies->registered[ $current_handle ]->deps as $handle ) {
if ( self::has_dependency( $dependencies, $handle, $dependency_handle ) ) {
return true;
}
}
return false;
}
/**
* Determine if a script element matches a given script handle.
*
* @param DOMElement $element Element.
* @param string $script_handle Script handle.
* @return bool
*/
protected static function is_matching_script( DOMElement $element, $script_handle ) {
// Use the ID attribute which was added to printed scripts after WP ?.?.
if ( $element->getAttribute( Attribute::ID ) === "{$script_handle}-js" ) {
return true;
}
if ( ! isset( wp_scripts()->registered[ $script_handle ] ) ) {
return false;
}
$script_dependency = wp_scripts()->registered[ $script_handle ];
if ( empty( $script_dependency->src ) ) {
return false;
}
// Script src attribute is haystack because includes protocol and may include query args (like ver).
return false !== strpos(
$element->getAttribute( 'src' ),
preg_replace( '#^https?:(?=//)#', '', $script_dependency->src )
);
}
/**
* Walk back tree to find the open sources.
*
* @todo This method and others for sourcing could be moved to a separate class.
*
* @param DOMNode $node Node to look for.
* @return array[][] {
* The data of the removed sources (theme, plugin, or mu-plugin).
*
* @type string $name The name of the source.
* @type string $type The type of the source.
* }
*/
public static function locate_sources( DOMNode $node ) {
$dom = Document::fromNode( $node );
$comments = $dom->xpath->query( 'preceding::comment()[ starts-with( ., "amp-source-stack" ) or starts-with( ., "/amp-source-stack" ) ]', $node );
$sources = [];
$matches = [];