-
Notifications
You must be signed in to change notification settings - Fork 384
/
class-amp-validation-manager.php
2232 lines (2008 loc) · 74.1 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 Amp\AmpWP\Dom\Document;
/**
* Class AMP_Validation_Manager
*
* @since 0.7
*/
class AMP_Validation_Manager {
/**
* Query var that triggers validation.
*
* @var string
*/
const VALIDATE_QUERY_VAR = 'amp_validate';
/**
* Query var for containing the number of validation errors on the frontend after redirection when invalid.
*
* @var string
*/
const VALIDATION_ERRORS_QUERY_VAR = 'amp_validation_errors';
/**
* 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';
/**
* Query var for cache-busting.
*
* @var string
*/
const CACHE_BUST_QUERY_VAR = 'amp_cache_bust';
/**
* Transient key to store validation errors when activating a plugin.
*
* @var string
*/
const PLUGIN_ACTIVATION_VALIDATION_ERRORS_TRANSIENT_KEY = 'amp_plugin_activation_validation_errors';
/**
* The name of the REST API field with the AMP validation results.
*
* @var string
*/
const VALIDITY_REST_FIELD_NAME = 'amp_validity';
/**
* The errors encountered when validating.
*
* @var array[][] {
* @type array $error Error code.
* @type bool $sanitized Whether sanitized.
* @type string $slug Hash of the error.
* }
*/
public static $validation_results = [];
/**
* Sources that enqueue each script.
*
* @var array
*/
public static $enqueued_script_sources = [];
/**
* Sources that enqueue each style.
*
* @var array
*/
public static $enqueued_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.
*
* @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 = [];
/**
* 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
*/
public 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;
/**
* Cached template directory to prevent infinite recursion.
*
* @see get_template_directory()
* @var string
*/
protected static $template_directory;
/**
* Cached template slug to prevent infinite recursion.
*
* @see get_template()
* @var string
*/
protected static $template_slug;
/**
* Cached stylesheet directory to prevent infinite recursion.
*
* @see get_stylesheet_directory()
* @var string
*/
protected static $stylesheet_directory;
/**
* Cached stylesheet slug to prevent infinite recursion.
*
* @see get_stylesheet()
* @var string
*/
protected static $stylesheet_slug;
/**
* Initialize.
*
* @return void
*/
public static function init() {
$should_validate_response = self::should_validate_response();
// 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
);
}
self::$is_validate_request = $should_validate_response;
AMP_Validated_URL_Post_Type::register();
AMP_Validation_Error_Taxonomy::register();
// Short-circuit if AMP is not supported as only the post types should be available.
if ( ! current_theme_supports( AMP_Theme_Support::SLUG ) && ! AMP_Options_Manager::is_stories_experience_enabled() ) {
return;
}
add_action( 'save_post', [ __CLASS__, 'handle_save_post_prompting_validation' ] );
add_action( 'enqueue_block_editor_assets', [ __CLASS__, 'enqueue_block_validation' ] );
add_action( 'edit_form_top', [ __CLASS__, 'print_edit_form_validation_status' ], 10, 2 );
add_action( 'rest_api_init', [ __CLASS__, 'add_rest_api_fields' ] );
// Add actions for checking theme support is present to determine plugin compatibility and show validation links in the admin bar.
if ( AMP_Options_Manager::is_website_experience_enabled() && current_theme_supports( AMP_Theme_Support::SLUG ) ) {
// Actions and filters involved in validation.
add_action(
'activate_plugin',
function() {
if ( ! has_action( 'shutdown', [ __CLASS__, 'validate_after_plugin_activation' ] ) ) {
add_action( 'shutdown', [ __CLASS__, 'validate_after_plugin_activation' ] ); // Shutdown so all plugins will have been activated.
}
}
);
// Prevent query vars from persisting after redirect.
add_filter(
'removable_query_args',
function( $query_vars ) {
$query_vars[] = AMP_Validation_Manager::VALIDATION_ERRORS_QUERY_VAR;
return $query_vars;
}
);
add_action( 'all_admin_notices', [ __CLASS__, 'print_plugin_notice' ] );
add_action( 'admin_bar_menu', [ __CLASS__, 'add_admin_bar_menu_items' ], 101 );
}
add_action( 'wp', [ __CLASS__, 'override_validation_error_statuses' ] );
if ( self::$is_validate_request ) {
self::add_validation_error_sourcing();
}
}
/**
* 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;
}
$supports_validation = (
// Skip if the post type is not viewable on the frontend, since we need a permalink to validate.
is_post_type_viewable( $post->post_type )
&&
! wp_is_post_autosave( $post )
&&
! wp_is_post_revision( $post )
&&
'auto-draft' !== $post->post_status
&&
'trash' !== $post->post_status
);
if ( ! $supports_validation ) {
return false;
}
// Story post type always supports validation.
if ( AMP_Story_Post_Type::POST_TYPE_SLUG === $post->post_type ) {
return AMP_Options_Manager::is_stories_experience_enabled();
}
// Prevent doing post validation in Reader mode or if the Website experience is not enabled.
if ( ! current_theme_supports( AMP_Theme_Support::SLUG ) || ! AMP_Options_Manager::is_website_experience_enabled() ) {
return false;
}
return post_supports_amp( $post );
}
/**
* Determine whether AMP theme support is forced via the amp_validate query param.
*
* @since 1.0
*
* @return bool Whether theme support forced.
*/
public static function is_theme_support_forced() {
return self::$is_validate_request;
}
/**
* 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::has_cap() ) {
self::$amp_admin_bar_item_added = false;
return;
}
$availability = AMP_Theme_Support::get_template_availability();
if ( ! $availability['supported'] ) {
self::$amp_admin_bar_item_added = false;
return;
}
$amp_validated_url_post = null;
$current_url = amp_get_current_url();
$non_amp_url = amp_remove_endpoint( $current_url );
$amp_url = remove_query_arg(
wp_removable_query_args(),
$current_url
);
if ( ! amp_is_canonical() ) {
$amp_url = add_query_arg( amp_get_slug(), '', $amp_url );
}
$error_count = -1;
/*
* If not an AMP response, then obtain the count of validation errors from either the query param supplied after redirecting from AMP
* to non-AMP due to validation errors (see AMP_Theme_Support::prepare_response()), or if there is an amp_validated_url post that already
* is populated with the last-known validation errors. Otherwise, if it *is* an AMP response then the error count is obtained after
* when the response is being prepared by AMP_Validation_Manager::finalize_validation().
*/
if ( ! is_amp_endpoint() ) {
if ( isset( $_GET[ self::VALIDATION_ERRORS_QUERY_VAR ] ) && is_numeric( $_GET[ self::VALIDATION_ERRORS_QUERY_VAR ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$error_count = (int) $_GET[ self::VALIDATION_ERRORS_QUERY_VAR ]; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
}
if ( $error_count < 0 ) {
$amp_validated_url_post = AMP_Validated_URL_Post_Type::get_invalid_url_post( $amp_url );
if ( $amp_validated_url_post ) {
$error_count = 0;
foreach ( AMP_Validated_URL_Post_Type::get_invalid_url_validation_errors( $amp_validated_url_post ) as $error ) {
if ( AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_REJECTED_STATUS === $error['term_status'] || AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_REJECTED_STATUS === $error['term_status'] ) {
$error_count++;
}
}
}
}
}
$user_can_revalidate = $amp_validated_url_post ? current_user_can( 'edit_post', $amp_validated_url_post->ID ) : current_user_can( 'manage_options' );
if ( ! $user_can_revalidate ) {
return;
}
// @todo The amp_validated_url post should probably only be accessible to users who can manage_options, or limit access to a post if the user has the cap to edit the queried object?
$validate_url = AMP_Validated_URL_Post_Type::get_recheck_url( $amp_validated_url_post ?: $amp_url );
// Construct the parent admin bar item.
if ( is_amp_endpoint() ) {
$icon = '✅'; // WHITE HEAVY CHECK MARK. This will get overridden in AMP_Validation_Manager::finalize_validation() if there are unaccepted errors.
$href = $validate_url;
} elseif ( $error_count > 0 ) {
$icon = '❌'; // CROSS MARK.
$href = $validate_url;
} else {
$icon = '🔗'; // LINK SYMBOL.
$href = $amp_url;
}
$parent = [
'id' => 'amp',
'title' => sprintf(
'<span id="amp-admin-bar-item-status-icon">%s</span> %s',
$icon,
esc_html__( 'AMP', 'amp' )
),
'href' => esc_url( $href ),
];
// Construct admin bar item for validation.
$validate_item = [
'parent' => 'amp',
'id' => 'amp-validity',
'href' => esc_url( $validate_url ),
];
if ( $error_count <= 0 ) {
$validate_item['title'] = esc_html__( 'Validate', 'amp' );
} else {
$validate_item['title'] = esc_html(
sprintf(
/* translators: %s is count of validation errors */
_n(
'Review %s validation issue',
'Review %s validation issues',
$error_count,
'amp'
),
number_format_i18n( $error_count )
)
);
}
// Construct admin bar item to link to AMP version or non-AMP version.
$link_item = [
'parent' => 'amp',
'id' => 'amp-view',
'title' => esc_html( is_amp_endpoint() ? __( 'View non-AMP version', 'amp' ) : __( 'View AMP version', 'amp' ) ),
'href' => esc_url( is_amp_endpoint() ? $non_amp_url : $amp_url ),
];
// Add admin bar item to switch between AMP and non-AMP if parent node is also an AMP link.
$is_single_version_available = (
amp_is_canonical()
||
( ! is_amp_endpoint() && $error_count > 0 )
);
// 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 );
/*
* Add submenu items based on whether viewing AMP or not, and whether or not AMP is available.
* When
*/
if ( $is_single_version_available ) {
$wp_admin_bar->add_node( $validate_item );
} elseif ( ! is_amp_endpoint() ) {
$wp_admin_bar->add_node( $link_item );
$wp_admin_bar->add_node( $validate_item );
} else {
$wp_admin_bar->add_node( $validate_item );
$wp_admin_bar->add_node( $link_item );
}
if ( AMP_Theme_Support::is_paired_available() && $error_count <= 0 && amp_is_dev_mode() ) {
// Construct admin bar item to link to paired browsing experience.
$paired_browsing_item = [
'parent' => 'amp',
'id' => 'amp-paired-browsing',
'title' => esc_html__( 'Paired browsing', 'amp' ),
'href' => AMP_Theme_Support::get_paired_browsing_url(),
];
$wp_admin_bar->add_node( $paired_browsing_item );
}
// Scrub the query var from the URL.
if ( ! is_amp_endpoint() && isset( $_GET[ self::VALIDATION_ERRORS_QUERY_VAR ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
add_action(
'wp_before_admin_bar_render',
function() {
?>
<script>
(function( queryVar ) {
var urlParser = document.createElement( 'a' );
urlParser.href = location.href;
urlParser.search = urlParser.search.substr( 1 ).split( /&/ ).filter( function( part ) {
return 0 !== part.indexOf( queryVar + '=' );
} );
if ( urlParser.href !== location.href ) {
history.replaceState( {}, '', urlParser.href );
}
})( <?php echo wp_json_encode( AMP_Validation_Manager::VALIDATION_ERRORS_QUERY_VAR ); ?> );
</script>
<?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 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'] )
&&
isset( $_REQUEST[ self::VALIDATION_ERROR_TERM_STATUS_QUERY_VAR ] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
&&
is_array( $_REQUEST[ self::VALIDATION_ERROR_TERM_STATUS_QUERY_VAR ] ) // 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 ]
);
}
$statuses = $_REQUEST[ self::VALIDATION_ERROR_TERM_STATUS_QUERY_VAR ]; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
/*
* 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 ( $statuses as $slug => $status ) {
$slug = sanitize_key( $slug );
$status = (int) $status;
self::$validation_error_status_overrides[ $slug ] = $status;
ksort( self::$validation_error_status_overrides );
}
}
/**
* Add hooks for doing determining sources for validation errors during preprocessing/sanitizing.
*/
public static function add_validation_error_sourcing() {
self::$template_directory = wp_normalize_path( get_template_directory() );
self::$template_slug = get_template();
self::$stylesheet_directory = wp_normalize_path( get_stylesheet_directory() );
self::$stylesheet_slug = get_stylesheet();
add_action( 'wp', [ __CLASS__, 'wrap_widget_callbacks' ] );
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 );
$do_blocks_priority = has_filter( 'the_content', 'do_blocks' );
$is_gutenberg_active = (
false !== $do_blocks_priority
&&
class_exists( 'WP_Block_Type_Registry' )
);
if ( $is_gutenberg_active ) {
add_filter( 'the_content', [ __CLASS__, 'add_block_source_comments' ], $do_blocks_priority - 1 );
}
}
/**
* 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.
*
* @see AMP_Validation_Manager::get_amp_validity_rest_field() The method responsible for validation post changes via Gutenberg.
* @see AMP_Validation_Manager::validate_queued_posts_on_frontend()
*
* @param int $post_id Post ID.
*/
public static function handle_save_post_prompting_validation( $post_id ) {
global $pagenow;
$post = get_post( $post_id );
$is_classic_editor_post_save = (
isset( $_SERVER['REQUEST_METHOD'] )
&&
'POST' === $_SERVER['REQUEST_METHOD']
&&
'post.php' === $pagenow
&&
isset( $_POST['post_ID'] ) // phpcs:ignore WordPress.Security.NonceVerification.Missing
&&
(int) $_POST['post_ID'] === (int) $post_id // phpcs:ignore WordPress.Security.NonceVerification.Missing
);
$should_validate_post = (
$is_classic_editor_post_save
&&
self::post_supports_validation( $post )
&&
! isset( self::$posts_pending_frontend_validation[ $post_id ] )
);
if ( $should_validate_post ) {
self::$posts_pending_frontend_validation[ $post_id ] = true;
// The reason for shutdown is to ensure that all postmeta changes have been saved, including whether AMP is enabled.
if ( ! has_action( 'shutdown', [ __CLASS__, 'validate_queued_posts_on_frontend' ] ) ) {
add_action( 'shutdown', [ __CLASS__, 'validate_queued_posts_on_frontend' ] );
}
}
}
/**
* Validate the posts pending frontend validation.
*
* @see AMP_Validation_Manager::handle_save_post_prompting_validation()
*
* @return array Mapping of post ID to the result of validating or storing the validation result.
*/
public static function validate_queued_posts_on_frontend() {
$posts = array_filter(
array_map( 'get_post', array_keys( array_filter( self::$posts_pending_frontend_validation ) ) ),
function( $post ) {
return self::post_supports_validation( $post );
}
);
$validation_posts = [];
/*
* It is unlikely that there will be more than one post in the array.
* For the bulk recheck action, see AMP_Validated_URL_Post_Type::handle_bulk_action().
*/
foreach ( $posts as $post ) {
$url = amp_get_permalink( $post->ID );
if ( ! $url ) {
$validation_posts[ $post->ID ] = new WP_Error( 'no_amp_permalink' );
continue;
}
// Prevent re-validating.
self::$posts_pending_frontend_validation[ $post->ID ] = false;
$validity = self::validate_url( $url );
if ( is_wp_error( $validity ) ) {
$validation_posts[ $post->ID ] = $validity;
} else {
$invalid_url_post_id = (int) get_post_meta( $post->ID, '_amp_validated_url_post_id', true );
$validation_posts[ $post->ID ] = AMP_Validated_URL_Post_Type::store_validation_errors(
wp_list_pluck( $validity['results'], 'error' ),
$validity['url'],
array_merge(
[
'invalid_url_post' => $invalid_url_post_id,
],
wp_array_slice_assoc( $validity, [ 'queried_object', 'stylesheets' ] )
)
);
// Remember the amp_validated_url post so that when the slug changes the old amp_validated_url post can be updated.
if ( ! is_wp_error( $validation_posts[ $post->ID ] ) && $invalid_url_post_id !== $validation_posts[ $post->ID ] ) {
update_post_meta( $post->ID, '_amp_validated_url_post_id', $validation_posts[ $post->ID ] );
}
}
}
return $validation_posts;
}
/**
* Adds fields to the REST API responses, in order to display validation errors.
*
* @return void
*/
public static function add_rest_api_fields() {
if ( ! current_theme_supports( AMP_Theme_Support::SLUG ) ) {
$object_types = [ AMP_Story_Post_Type::POST_TYPE_SLUG ]; // Eventually validation should be done in Reader mode as well, but for now, limit to stories.
} elseif ( amp_is_canonical() ) {
$object_types = get_post_types_by_support( 'editor' ); // @todo Shouldn't this actually only be those with 'amp' support, or if if all_templates_supported?
} else {
$object_types = array_intersect(
get_post_types_by_support( 'amp' ),
get_post_types(
[
'show_in_rest' => true,
]
)
);
}
register_rest_field(
$object_types,
self::VALIDITY_REST_FIELD_NAME,
[
'get_callback' => [ __CLASS__, 'get_amp_validity_rest_field' ],
'schema' => [
'description' => __( 'AMP validity status', 'amp' ),
'type' => 'object',
],
]
);
}
/**
* Adds a field to the REST API responses to display the validation status.
*
* First, get existing errors for the post.
* If there are none, validate the post and return any errors.
*
* @param array $post_data Data for the post.
* @param string $field_name The name of the field to add.
* @param WP_REST_Request $request The name of the field to add.
* @return array|null $validation_data Validation data if it's available, or null.
*/
public static function get_amp_validity_rest_field( $post_data, $field_name, $request ) {
if ( ! current_user_can( 'edit_post', $post_data['id'] ) || ! self::has_cap() || ! self::post_supports_validation( $post_data['id'] ) ) {
return null;
}
$post = get_post( $post_data['id'] );
$validation_status_post = null;
if ( in_array( $request->get_method(), [ 'PUT', 'POST' ], true ) ) {
if ( ! isset( self::$posts_pending_frontend_validation[ $post->ID ] ) ) {
self::$posts_pending_frontend_validation[ $post->ID ] = true;
}
$results = self::validate_queued_posts_on_frontend();
if ( isset( $results[ $post->ID ] ) && is_int( $results[ $post->ID ] ) ) {
$validation_status_post = get_post( $results[ $post->ID ] );
}
}
if ( empty( $validation_status_post ) ) {
$validation_status_post = AMP_Validated_URL_Post_Type::get_invalid_url_post( amp_get_permalink( $post->ID ) );
}
$field = [
'results' => [],
'review_link' => null,
];
if ( $validation_status_post ) {
$field['review_link'] = get_edit_post_link( $validation_status_post->ID, 'raw' );
foreach ( AMP_Validated_URL_Post_Type::get_invalid_url_validation_errors( $validation_status_post ) as $result ) {
$field['results'][] = [
'sanitized' => AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_ACCEPTED_STATUS === $result['status'],
'error' => $result['data'],
'status' => $result['status'],
'term_status' => $result['term_status'],
'forced' => $result['forced'],
];
}
}
return $field;
}
/**
* Whether the user has the required capability.
*
* Checks for permissions before validating.
*
* @return boolean $has_cap Whether the current user has the capability.
*/
public static function has_cap() {
return current_user_can( 'edit_posts' );
}
/**
* 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 = [];
}
/**
* 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.
*
* @param WP_Post $post The updated post.
* @return void
*/
public static function print_edit_form_validation_status( $post ) {
if ( ! self::post_supports_validation( $post ) || ! self::has_cap() ) {
return;
}
$invalid_url_post = AMP_Validated_URL_Post_Type::get_invalid_url_post( get_permalink( $post->ID ) );
if ( ! $invalid_url_post ) {
return;
}
// Show all validation errors which have not been explicitly acknowledged as accepted.
$validation_errors = [];
$has_rejected_error = false;
foreach ( AMP_Validated_URL_Post_Type::get_invalid_url_validation_errors( $invalid_url_post ) as $error ) {
$needs_moderation = (
AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_REJECTED_STATUS === $error['status'] || // @todo Show differently since moderated?
AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_REJECTED_STATUS === $error['status'] ||
AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_ACCEPTED_STATUS === $error['status']
);
if ( $needs_moderation ) {
$validation_errors[] = $error['data'];
}
if (
AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_REJECTED_STATUS === $error['status']
||
AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_REJECTED_STATUS === $error['status']
) {
$has_rejected_error = true;
}
}
// No validation errors so abort.
if ( empty( $validation_errors ) ) {
return;
}
echo '<div class="notice notice-warning">';
echo '<p>';
// @todo Check if the error actually occurs in the_content, and if not, consider omitting the warning if the user does not have privileges to manage_options.
esc_html_e( 'There is content which fails AMP validation.', 'amp' );
echo ' ';
// Auto-acceptance is enabled by default but can be overridden by the the `amp_validation_error_default_sanitized` filter.
if ( ! $has_rejected_error ) {
esc_html_e( 'Nevertheless, the invalid markup has been automatically removed.', 'amp' );
} else {
/*
* Even if invalid markup is removed by default, if there are non-accepted errors in non-Standard mode, it will redirect to a non-AMP page.
* For example, the errors could have been stored as 'New Kept' when auto-accept was false, and now auto-accept is true.
* In that case, this will block serving AMP.
* This could also apply if this is in 'Standard' mode and the user has rejected a validation error.
*/
esc_html_e( 'You will have to remove the invalid markup (or allow the plugin to remove it) to serve AMP.', 'amp' );
}
echo sprintf(
' <a href="%s" target="_blank">%s</a>',
esc_url( get_edit_post_link( $invalid_url_post ) ),
esc_html__( 'Review issues', 'amp' )
);
echo '</p>';
$results = AMP_Validation_Error_Taxonomy::summarize_validation_errors( array_unique( $validation_errors, SORT_REGULAR ) );
$removed_sets = [];
if ( ! empty( $results[ AMP_Validation_Error_Taxonomy::REMOVED_ELEMENTS ] ) && is_array( $results[ AMP_Validation_Error_Taxonomy::REMOVED_ELEMENTS ] ) ) {
$removed_sets[] = [
'label' => __( 'Invalid elements:', 'amp' ),
'names' => array_map( 'sanitize_key', $results[ AMP_Validation_Error_Taxonomy::REMOVED_ELEMENTS ] ),
];
}
if ( ! empty( $results[ AMP_Validation_Error_Taxonomy::REMOVED_ATTRIBUTES ] ) && is_array( $results[ AMP_Validation_Error_Taxonomy::REMOVED_ATTRIBUTES ] ) ) {
$removed_sets[] = [
'label' => __( 'Invalid attributes:', 'amp' ),
'names' => array_map( 'sanitize_key', $results[ AMP_Validation_Error_Taxonomy::REMOVED_ATTRIBUTES ] ),
];
}
// @todo There are other kinds of errors other than REMOVED_ELEMENTS and REMOVED_ATTRIBUTES.
foreach ( $removed_sets as $removed_set ) {
printf( '<p>%s ', esc_html( $removed_set['label'] ) );
$items = [];
foreach ( $removed_set['names'] as $name => $count ) {
if ( 1 === (int) $count ) {
$items[] = sprintf( '<code>%s</code>', esc_html( $name ) );
} else {
$items[] = sprintf( '<code>%s</code> (%d)', esc_html( $name ), $count );
}
}