-
Notifications
You must be signed in to change notification settings - Fork 385
/
class-amp-validation-error-taxonomy.php
3507 lines (3200 loc) · 127 KB
/
class-amp-validation-error-taxonomy.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_Error_Taxonomy
*
* @package AMP
*/
use AmpProject\AmpWP\Icon;
use AmpProject\AmpWP\Services;
use AmpProject\AmpWP\Admin\ValidationCounts;
/**
* Class AMP_Validation_Error_Taxonomy
*
* @since 1.0
* @internal
*/
class AMP_Validation_Error_Taxonomy {
/**
* The slug of the taxonomy to store AMP errors.
*
* @var string
*/
const TAXONOMY_SLUG = 'amp_validation_error';
/**
* Acknowledged validation error bit mask.
*
* @var int
*/
const ACKNOWLEDGED_VALIDATION_ERROR_BIT_MASK = 2; // === 0b10.
/**
* Accepted validation error bit mask.
*
* @var int
*/
const ACCEPTED_VALIDATION_ERROR_BIT_MASK = 1; // === 0b01.
/**
* Term group for new validation_error terms which are rejected (not auto-accepted).
*
* @var int
*/
const VALIDATION_ERROR_NEW_REJECTED_STATUS = 0; // == 0b00 == ^ACKNOWLEDGED_VALIDATION_ERROR_BIT_MASK | ^ACCEPTED_VALIDATION_ERROR_BIT_MASK.
/**
* Term group for new validation_error terms which are auto-accepted.
*
* @var int
*/
const VALIDATION_ERROR_NEW_ACCEPTED_STATUS = 1; // == 0b01 == ^ACKNOWLEDGED_VALIDATION_ERROR_BIT_MASK | ACCEPTED_VALIDATION_ERROR_BIT_MASK.
/**
* Term group for validation_error terms that the accepts and thus can be sanitized and does not disable AMP.
*
* @var int
*/
const VALIDATION_ERROR_ACK_ACCEPTED_STATUS = 3; // == 0b11 == ACKNOWLEDGED_VALIDATION_ERROR_BIT_MASK | ACCEPTED_VALIDATION_ERROR_BIT_MASK.
/**
* Term group for validation_error terms that the user flags as being blockers to enabling AMP.
*
* @var int
*/
const VALIDATION_ERROR_ACK_REJECTED_STATUS = 2; // == 0b10 == ACKNOWLEDGED_VALIDATION_ERROR_BIT_MASK | ^ACCEPTED_VALIDATION_ERROR_BIT_MASK.
/**
* Action name for ignoring a validation error.
*
* @var string
*/
const VALIDATION_ERROR_ACKNOWLEDGE_ACTION = 'amp_validation_error_ack';
/**
* Action name for ignoring a validation error.
*
* @var string
*/
const VALIDATION_ERROR_ACCEPT_ACTION = 'amp_validation_error_accept';
/**
* Action name for rejecting a validation error.
*
* @var string
*/
const VALIDATION_ERROR_REJECT_ACTION = 'amp_validation_error_reject';
/**
* Action name for clearing empty validation error terms.
*
* @var string
*/
const VALIDATION_ERROR_CLEAR_EMPTY_ACTION = 'amp_validation_error_terms_clear_empty';
/**
* Query var used when filtering by validation error status or passing updates.
*
* @var string
*/
const VALIDATION_ERROR_STATUS_QUERY_VAR = 'amp_validation_error_status';
/**
* Query var used when filtering for the validation error type.
*
* @var string
*/
const VALIDATION_ERROR_TYPE_QUERY_VAR = 'amp_validation_error_type';
/**
* Query var used for ordering list by error code.
*
* @var string
*/
const VALIDATION_DETAILS_ERROR_CODE_QUERY_VAR = 'amp_validation_code';
/**
* Query var used to indicate how many terms were deleted.
*
* @var string
*/
const VALIDATION_ERRORS_CLEARED_QUERY_VAR = 'amp_validation_errors_cleared';
/**
* The <option> value to not filter at all, like for 'All Statuses'.
*
* This is also used in WP_List_Table, like for the 'Bulk Actions' option.
* When this is present, this ensures that this isn't filtered.
*
* @var string
*/
const NO_FILTER_VALUE = '';
/**
* The 'type' of error for invalid HTML elements, like <frame>.
*
* These usually have the 'code' of AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG.
* Except for AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG errors for a <script>, which have the JS_ERROR_TYPE.
* This allows filtering by type in the taxonomy page, like displaying only HTML element errors, or only CSS errors.
*
* @var string
*/
const HTML_ELEMENT_ERROR_TYPE = 'html_element_error';
/**
* The 'type' of error for invalid HTML attributes.
*
* Banned attributes include i-amp-*.
* But on* attributes, like onclick, have the JS_ERROR_TYPE.
*
* @var string
*/
const HTML_ATTRIBUTE_ERROR_TYPE = 'html_attribute_error';
/**
* The 'type' of error that applies to the error 'code' of AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG when the node is a <script>.
* This applies both when enqueuing a script, and when a <script> is echoed directly.
*
* @var string
*/
const JS_ERROR_TYPE = 'js_error';
/**
* The 'type' of all CSS errors, no matter what the 'code'.
*
* @var string
*/
const CSS_ERROR_TYPE = 'css_error';
/**
* The key for removed elements.
*
* @var string
*/
const REMOVED_ELEMENTS = 'removed_elements';
/**
* The key for found elements and attributes.
*
* @var string
*/
const FOUND_ELEMENTS_AND_ATTRIBUTES = 'found_elements_and_attributes';
/**
* The key for removed attributes.
*
* @var string
*/
const REMOVED_ATTRIBUTES = 'removed_attributes';
/**
* The key in the response for the sources that have invalid output.
*
* @var string
*/
const SOURCES_INVALID_OUTPUT = 'sources_with_invalid_output';
/**
* The key for the error status.
*
* @var string
*/
const ERROR_STATUS = 'error_status';
/**
* Key for the transient storing error index counts.
*
* @var string
*/
const TRANSIENT_KEY_ERROR_INDEX_COUNTS = 'amp_error_index_counts';
/**
* Current row index for the validated URL's validation error being displayed.
*
* @var int
*/
protected static $current_validation_error_row_index = 0;
/**
* Whether the terms_clauses filter should apply to a term query for validation errors to limit to a given status.
*
* This is set to false when calling wp_count_terms() for the admin menu and for the views.
*
* @see AMP_Validation_Manager::get_validation_error_count()
* @var bool
*/
protected static $should_filter_terms_clauses_for_error_validation_status;
/**
* Registers the taxonomy to store the validation errors.
*
* @return void
*/
public static function register() {
$dev_tools_user_access = Services::get( 'dev_tools.user_access' );
// Show in the admin menu if dev tools are enabled for the user or if the user is on any dev tools screen.
$show_in_menu = (
$dev_tools_user_access->is_user_enabled()
||
( isset( $_GET['post_type'] ) && AMP_Validated_URL_Post_Type::POST_TYPE_SLUG === $_GET['post_type'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
||
( isset( $_GET['post'], $_GET['action'] ) && 'edit' === $_GET['action'] && AMP_Validated_URL_Post_Type::POST_TYPE_SLUG === get_post_type( (int) $_GET['post'] ) ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
||
( isset( $_GET['taxonomy'] ) && self::TAXONOMY_SLUG === $_GET['taxonomy'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
||
( isset( $_GET[ self::TAXONOMY_SLUG ] ) ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
);
register_taxonomy(
self::TAXONOMY_SLUG,
AMP_Validated_URL_Post_Type::POST_TYPE_SLUG,
[
'labels' => [
'name' => _x( 'AMP Validation Error Index', 'taxonomy general name', 'amp' ),
'singular_name' => _x( 'AMP Validation Error', 'taxonomy singular name', 'amp' ),
'search_items' => __( 'Search AMP Validation Errors', 'amp' ),
'all_items' => __( 'All AMP Validation Errors', 'amp' ),
'edit_item' => __( 'Edit AMP Validation Error', 'amp' ),
'update_item' => __( 'Update AMP Validation Error', 'amp' ),
'menu_name' => __( 'Error Index', 'amp' ),
'back_to_items' => __( 'Back to AMP Validation Errors', 'amp' ),
'popular_items' => __( 'Frequent Validation Errors', 'amp' ),
'view_item' => __( 'View Validation Error', 'amp' ),
'add_new_item' => __( 'Add New Validation Error', 'amp' ), // Makes no sense.
'new_item_name' => __( 'New Validation Error Hash', 'amp' ), // Makes no sense.
'not_found' => __( 'No validation errors found.', 'amp' ),
'no_terms' => __( 'Validation Error', 'amp' ),
'items_list_navigation' => __( 'Validation errors navigation', 'amp' ),
'items_list' => __( 'Validation errors list', 'amp' ),
/* translators: Tab heading when selecting from the most used terms */
'most_used' => __( 'Most Used Validation Errors', 'amp' ),
],
'public' => false,
'show_ui' => true, // @todo False because we need a custom UI.
'show_tagcloud' => false,
'show_in_quick_edit' => false,
'hierarchical' => false, // Or true? Code could be the parent term?
'show_in_menu' => $show_in_menu,
'meta_box_cb' => false,
'capabilities' => [
'manage_terms' => AMP_Validation_Manager::VALIDATE_CAPABILITY, // Needed to give access to the term list table.
'delete_terms' => AMP_Validation_Manager::VALIDATE_CAPABILITY, // Needed so the checkbox (cb) table column will work.
'assign_terms' => 'do_not_allow', // Block assign_terms since associating terms with posts is done programmatically.
'edit_terms' => 'do_not_allow', // Terms are created (and updated) programmatically.
],
]
);
if ( is_admin() ) {
self::add_admin_hooks();
}
add_action( 'created_' . self::TAXONOMY_SLUG, [ __CLASS__, 'clear_cached_counts' ] );
add_action( 'edited_' . self::TAXONOMY_SLUG, [ __CLASS__, 'clear_cached_counts' ] );
add_action( 'delete_' . self::TAXONOMY_SLUG, [ __CLASS__, 'clear_cached_counts' ] );
}
/**
* Get amp_validation_error taxonomy term by slug or error properties.
*
* @since 1.0
* @see get_term_by()
*
* @param string|array $error Slug for term or array of term data.
* @return WP_Term|false Queried term or false if no match.
*/
public static function get_term( $error ) {
$slug = null;
if ( is_string( $error ) ) {
$slug = $error;
} elseif ( is_array( $error ) ) {
$term_data = self::prepare_validation_error_taxonomy_term( $error );
$slug = $term_data['slug'];
}
if ( ! $slug ) {
_doing_it_wrong( __METHOD__, esc_html__( 'Method must be passed a term slug (string) or error attributes (array).', 'amp' ), '1.0' );
return false;
}
return get_term_by( 'slug', $slug, self::TAXONOMY_SLUG );
}
/**
* Delete all amp_validation_error terms that have zero counts (no amp_validated_url posts associated with them).
*
* @since 1.0
*
* @return int Count of terms that were deleted.
*/
public static function delete_empty_terms() {
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$empty_term_ids = $wpdb->get_col(
$wpdb->prepare( "SELECT term_id FROM $wpdb->term_taxonomy WHERE taxonomy = %s AND count = 0", self::TAXONOMY_SLUG )
);
if ( empty( $empty_term_ids ) ) {
return 0;
}
// Make sure the term counts are still accurate.
wp_update_term_count_now( $empty_term_ids, self::TAXONOMY_SLUG );
$deleted_count = 0;
foreach ( $empty_term_ids as $term_id ) {
if ( true === self::delete_empty_term( $term_id ) ) {
$deleted_count++;
}
}
return $deleted_count;
}
/**
* Delete an amp_validation_error term if it has no amp_validated_url posts associated with it.
*
* @param int $term_id Term ID.
* @return bool True if deleted, false otherwise.
*/
public static function delete_empty_term( $term_id ) {
$term = get_term( (int) $term_id, self::TAXONOMY_SLUG );
// Skip if the term count was not actually 0.
if ( ! $term instanceof WP_Term || 0 !== $term->count ) {
return false;
}
if ( true === wp_delete_term( $term->term_id, self::TAXONOMY_SLUG ) ) {
return true;
}
return false;
}
/**
* Sanitize term status(es).
*
* @param int|int[]|string $status One or more statuses (including comma-delimited string).
* @param array $options {
* Options.
*
* @type bool $multiple Multiple, whether to extract more than one. Default false.
* }
* @return int|int[]|null Returns an integer unless the multiple option is passed. Null if invalid.
*/
public static function sanitize_term_status( $status, $options = [] ) {
$multiple = ! empty( $options['multiple'] );
// Catch case where an empty string is supplied. Prevent casting to 0.
if ( ! is_numeric( $status ) && empty( $status ) ) {
return $multiple ? [] : null;
}
if ( is_string( $status ) ) {
$statuses = wp_parse_id_list( $status );
} else {
$statuses = array_map( 'absint', (array) $status );
}
$statuses = array_intersect(
[
self::VALIDATION_ERROR_NEW_REJECTED_STATUS,
self::VALIDATION_ERROR_NEW_ACCEPTED_STATUS,
self::VALIDATION_ERROR_ACK_ACCEPTED_STATUS,
self::VALIDATION_ERROR_ACK_REJECTED_STATUS,
],
$statuses
);
$statuses = array_values( array_unique( $statuses ) );
if ( ! $multiple ) {
return array_shift( $statuses );
}
return $statuses;
}
/**
* Prepare term_group IN condition for SQL WHERE clause.
*
* @param int[] $groups Term groups.
* @return string SQL.
*/
public static function prepare_term_group_in_sql( $groups ) {
global $wpdb;
return $wpdb->prepare(
'IN ( ' . implode( ', ', array_fill( 0, count( $groups ), '%d' ) ) . ' )',
$groups
);
}
/**
* Prepare a validation error for lookup or insertion as taxonomy term.
*
* @param array $error Validation error.
* @return array Term fields.
*/
public static function prepare_validation_error_taxonomy_term( $error ) {
unset( $error['sources'] );
ksort( $error );
$description = wp_json_encode( $error );
$term_slug = md5( $description );
return [
'slug' => $term_slug,
'name' => $term_slug,
'description' => $description,
];
}
/**
* Determine whether a validation error should be sanitized.
*
* @since 1.0
* @see AMP_Validation_Error_Taxonomy::get_validation_error_sanitization()
* @see AMP_Validation_Manager::is_sanitization_auto_accepted()
*
* @param array $error Validation error.
* @return bool Whether error should be sanitized.
*/
public static function is_validation_error_sanitized( $error ) {
$sanitization = self::get_validation_error_sanitization( $error );
return (
self::VALIDATION_ERROR_ACK_ACCEPTED_STATUS === $sanitization['status']
||
self::VALIDATION_ERROR_NEW_ACCEPTED_STATUS === $sanitization['status']
);
}
/**
* Get the validation error sanitization.
*
* @since 1.0
* @see AMP_Validation_Manager::is_sanitization_auto_accepted()
*
* @param array $error Validation error.
* @return array {
* Validation error sanitization.
*
* @type int $status Validation status.
* @type int $term_status The initial validation status prior to being overridden by previewing, option, or filter.
* @type false|string $forced If and how the status is overridden from its initial term status.
* }
*/
public static function get_validation_error_sanitization( $error ) {
$term_data = self::prepare_validation_error_taxonomy_term( $error );
$term = self::get_term( $term_data['slug'] );
$statuses = [
self::VALIDATION_ERROR_NEW_REJECTED_STATUS,
self::VALIDATION_ERROR_NEW_ACCEPTED_STATUS,
self::VALIDATION_ERROR_ACK_ACCEPTED_STATUS,
self::VALIDATION_ERROR_ACK_REJECTED_STATUS,
];
if ( ! empty( $term ) && in_array( $term->term_group, $statuses, true ) ) {
$term_status = $term->term_group;
} else {
$term_status = AMP_Validation_Manager::is_sanitization_auto_accepted( $error ) ? self::VALIDATION_ERROR_NEW_ACCEPTED_STATUS : self::VALIDATION_ERROR_NEW_REJECTED_STATUS;
}
$forced = false;
$status = $term_status;
// See note in AMP_Validation_Manager::add_validation_error_sourcing() for why amp_validation_error_sanitized filter isn't used.
if ( isset( AMP_Validation_Manager::$validation_error_status_overrides[ $term_data['slug'] ] ) ) {
$status = AMP_Validation_Manager::$validation_error_status_overrides[ $term_data['slug'] ];
$forced = 'with_preview';
}
/**
* Filters whether the validation error should be sanitized.
*
* Returning true this indicates that the validation error is acceptable
* and should not be considered a blocker to render AMP. Returning null
* means that the default status should be used.
*
* Note that the $node is not passed here to ensure that the filter can be
* applied on validation errors that have been stored. Likewise, 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.
*
* @since 1.0
* @see AMP_Validation_Manager::is_sanitization_auto_accepted() Which controls whether an error is initially accepted or rejected for sanitization.
*
* @param null|bool $sanitized Whether sanitized; this is initially null, and changing it to bool causes the validation error to be forced.
* @param array $error Validation error being sanitized.
*/
$sanitized = apply_filters( 'amp_validation_error_sanitized', null, $error );
if ( null !== $sanitized ) {
$forced = 'with_filter';
$status = $sanitized ? self::VALIDATION_ERROR_ACK_ACCEPTED_STATUS : self::VALIDATION_ERROR_ACK_REJECTED_STATUS;
}
return compact( 'status', 'forced', 'term_status' );
}
/**
* Automatically (forcibly) accept validation errors that arise (that is, remove the invalid markup causing the validation errors).
*
* @since 1.0
*
* @param array|true $acceptable_errors Acceptable validation errors, where keys are codes and values are either `true` or sparse array to check as subset. If just true, then all validation errors are accepted.
*/
public static function accept_validation_errors( $acceptable_errors ) {
if ( empty( $acceptable_errors ) ) {
return;
}
add_filter(
'amp_validation_error_sanitized',
static function( $sanitized, $error ) use ( $acceptable_errors ) {
if ( true === $acceptable_errors ) {
return true;
}
if ( isset( $acceptable_errors[ $error['code'] ] ) ) {
if ( true === $acceptable_errors[ $error['code'] ] ) {
return true;
}
foreach ( $acceptable_errors[ $error['code'] ] as $acceptable_error_props ) {
if ( AMP_Validation_Error_Taxonomy::is_array_subset( $error, $acceptable_error_props ) ) {
return true;
}
}
}
return $sanitized;
},
10,
2
);
}
/**
* Check if one array is a sparse subset of another array.
*
* @param array $superset Superset array.
* @param array $subset Subset array.
*
* @return bool Whether subset is contained in superset.
*/
public static function is_array_subset( $superset, $subset ) {
foreach ( $subset as $key => $subset_value ) {
if ( ! isset( $superset[ $key ] ) || gettype( $subset_value ) !== gettype( $superset[ $key ] ) ) {
return false;
}
if ( is_array( $subset_value ) ) {
if ( ! self::is_array_subset( $superset[ $key ], $subset_value ) ) {
return false;
}
} elseif ( $superset[ $key ] !== $subset_value ) {
return false;
}
}
return true;
}
/**
* Get the count of validation error terms, optionally restricted by term group (e.g. accepted or rejected).
*
* @param array $args {
* Args passed into wp_count_terms().
*
* @type int|int[]|string $group Term group(s), including comma-separated ID list.
* }
* @return int Term count.
*/
public static function get_validation_error_count( $args = [] ) {
$args = array_merge(
[
'group' => null,
],
$args
);
$cache_key = wp_json_encode( $args );
$cached_counts = get_transient( self::TRANSIENT_KEY_ERROR_INDEX_COUNTS );
if ( empty( $cached_counts ) ) {
$cached_counts = [];
}
if ( isset( $cached_counts[ $cache_key ] ) ) {
return $cached_counts[ $cache_key ];
}
$groups = null;
if ( isset( $args['group'] ) ) {
$groups = self::sanitize_term_status( $args['group'], [ 'multiple' => true ] );
}
$filter = static function( $clauses ) use ( $groups ) {
$clauses['where'] .= ' AND t.term_group ' . AMP_Validation_Error_Taxonomy::prepare_term_group_in_sql( $groups );
return $clauses;
};
if ( isset( $args['group'] ) ) {
add_filter( 'terms_clauses', $filter );
}
self::$should_filter_terms_clauses_for_error_validation_status = false;
$term_count = wp_count_terms( self::TAXONOMY_SLUG, $args );
self::$should_filter_terms_clauses_for_error_validation_status = true;
if ( isset( $args['group'] ) ) {
remove_filter( 'terms_clauses', $filter );
}
$result = (int) $term_count;
$cached_counts[ $cache_key ] = $result;
set_transient( self::TRANSIENT_KEY_ERROR_INDEX_COUNTS, $cached_counts, DAY_IN_SECONDS );
return $result;
}
/**
* Add support for querying posts by amp_validation_error_status and by error type.
*
* Add recognition of amp_validation_error_status query var for amp_validated_url post queries.
* Also, conditionally filter for error type, like js_error or css_error.
*
* @see WP_Tax_Query::get_sql_for_clause()
*
* @param string $where SQL WHERE clause.
* @param WP_Query $query Query.
* @return string Modified WHERE clause.
*/
public static function filter_posts_where_for_validation_error_status( $where, WP_Query $query ) {
global $wpdb;
// If the post type is not correct, return the $where clause unchanged.
if ( ! in_array( AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, (array) $query->get( 'post_type' ), true ) ) {
return $where;
}
$error_statuses = [];
if ( false !== $query->get( self::VALIDATION_ERROR_STATUS_QUERY_VAR, false ) ) {
$error_statuses = self::sanitize_term_status( $query->get( self::VALIDATION_ERROR_STATUS_QUERY_VAR ), [ 'multiple' => true ] );
}
$error_type = sanitize_key( $query->get( self::VALIDATION_ERROR_TYPE_QUERY_VAR ) );
/*
* Selecting the 'All Statuses' <option> sends a value of '' to indicate that this should not filter.
*/
$is_error_status_present = ! empty( $error_statuses );
$is_error_type_present = in_array( $error_type, self::get_error_types(), true );
// If neither the error status nor the type is present, there is no need to filter the $where clause.
if ( ! $is_error_status_present && ! $is_error_type_present ) {
return $where;
}
$sql_select = $wpdb->prepare(
"
SELECT 1
FROM $wpdb->term_relationships
INNER JOIN $wpdb->term_taxonomy ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
INNER JOIN $wpdb->terms ON $wpdb->terms.term_id = $wpdb->term_taxonomy.term_id
WHERE
$wpdb->term_taxonomy.taxonomy = %s
AND
$wpdb->term_relationships.object_id = $wpdb->posts.ID
",
self::TAXONOMY_SLUG
);
if ( $is_error_status_present ) {
$sql_select .= " AND $wpdb->terms.term_group " . self::prepare_term_group_in_sql( $error_statuses );
}
if ( $is_error_type_present ) {
$sql_select .= $wpdb->prepare(
" AND $wpdb->term_taxonomy.description LIKE %s ",
'%"type":"' . $wpdb->esc_like( $error_type ) . '"%'
);
}
$sql_select .= ' LIMIT 1 ';
$where .= " AND ( $sql_select ) ";
return $where;
}
/**
* Gets the AMP validation response.
*
* Returns the current validation errors the sanitizers found in rendering the page.
*
* @param array $validation_errors Validation errors.
* @return array The AMP validity of the markup.
*/
public static function summarize_validation_errors( $validation_errors ) {
$results = [];
$removed_elements = [];
$removed_attributes = [];
$removed_pis = [];
$sources = [];
foreach ( $validation_errors as $validation_error ) {
$code = isset( $validation_error['code'] ) ? $validation_error['code'] : null;
if ( AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG === $code ) {
if ( ! isset( $removed_elements[ $validation_error['node_name'] ] ) ) {
$removed_elements[ $validation_error['node_name'] ] = 0;
}
++$removed_elements[ $validation_error['node_name'] ];
} elseif ( AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR === $code ) {
if ( ! isset( $removed_attributes[ $validation_error['node_name'] ] ) ) {
$removed_attributes[ $validation_error['node_name'] ] = 0;
}
++$removed_attributes[ $validation_error['node_name'] ];
} elseif ( AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_PROCESSING_INSTRUCTION === $code ) {
if ( ! isset( $removed_pis[ $validation_error['node_name'] ] ) ) {
$removed_pis[ $validation_error['node_name'] ] = 0;
}
++$removed_pis[ $validation_error['node_name'] ];
}
if ( ! empty( $validation_error['sources'] ) ) {
$sources = array_merge( $sources, $validation_error['sources'] );
}
}
$results = array_merge(
[
self::SOURCES_INVALID_OUTPUT => self::summarize_sources( $sources ),
],
compact(
'removed_elements',
'removed_attributes',
'removed_pis'
),
$results
);
return $results;
}
/**
* Summarize sources.
*
* @param array $sources Sources.
* @return array Summarized (de-duped) sources.
*/
public static function summarize_sources( $sources ) {
$summarized_sources = [];
foreach ( $sources as $source ) {
if ( isset( $source['hook'] ) ) {
$summarized_sources['hook'] = $source['hook'];
}
if ( isset( $source['type'], $source['name'] ) ) {
$summarized_sources[ $source['type'] ][] = $source['name'];
} elseif ( isset( $source['embed'] ) ) {
$summarized_sources['embed'] = true;
}
if ( isset( $source['block_name'] ) ) {
$summarized_sources['blocks'][] = $source['block_name'];
}
}
// Remove core if there is a plugin or theme.
if ( isset( $summarized_sources['core'] ) && ( isset( $summarized_sources['theme'] ) || isset( $summarized_sources['plugin'] ) ) ) {
unset( $summarized_sources['core'] );
}
return $summarized_sources;
}
/**
* Add admin hooks.
*/
public static function add_admin_hooks() {
add_filter( 'redirect_term_location', [ __CLASS__, 'add_term_filter_query_var' ], 10, 2 );
add_action( 'load-edit-tags.php', [ __CLASS__, 'add_group_terms_clauses_filter' ] );
add_action( 'load-edit-tags.php', [ __CLASS__, 'add_error_type_clauses_filter' ] );
add_action( 'load-post.php', [ __CLASS__, 'add_error_type_clauses_filter' ] );
add_action( 'load-edit-tags.php', [ __CLASS__, 'add_order_clauses_from_description_json' ] );
add_action( 'load-post.php', [ __CLASS__, 'add_order_clauses_from_description_json' ] );
add_action( sprintf( 'after-%s-table', self::TAXONOMY_SLUG ), [ __CLASS__, 'render_taxonomy_filters' ] );
add_action( sprintf( 'after-%s-table', self::TAXONOMY_SLUG ), [ __CLASS__, 'render_link_to_invalid_urls_screen' ] );
add_filter( 'terms_clauses', [ __CLASS__, 'filter_terms_clauses_for_description_search' ], 10, 3 );
add_action( 'admin_notices', [ __CLASS__, 'add_admin_notices' ] );
add_filter( self::TAXONOMY_SLUG . '_row_actions', [ __CLASS__, 'filter_tag_row_actions' ], PHP_INT_MAX, 2 );
if ( get_taxonomy( self::TAXONOMY_SLUG )->show_in_menu ) {
add_action( 'admin_menu', [ __CLASS__, 'add_admin_menu_validation_error_item' ] );
}
add_filter( 'manage_' . self::TAXONOMY_SLUG . '_custom_column', [ __CLASS__, 'filter_manage_custom_columns' ], 10, 3 );
add_filter( 'manage_' . AMP_Validated_URL_Post_Type::POST_TYPE_SLUG . '_sortable_columns', [ __CLASS__, 'add_single_post_sortable_columns' ] );
add_filter( 'posts_where', [ __CLASS__, 'filter_posts_where_for_validation_error_status' ], 10, 2 );
add_filter( 'post_action_' . self::VALIDATION_ERROR_REJECT_ACTION, [ __CLASS__, 'handle_single_url_page_bulk_and_inline_actions' ] );
add_filter( 'post_action_' . self::VALIDATION_ERROR_ACCEPT_ACTION, [ __CLASS__, 'handle_single_url_page_bulk_and_inline_actions' ] );
add_filter( 'handle_bulk_actions-edit-' . self::TAXONOMY_SLUG, [ __CLASS__, 'handle_validation_error_update' ], 10, 3 );
add_action( 'load-edit-tags.php', [ __CLASS__, 'handle_inline_edit_request' ] );
add_action( 'load-edit-tags.php', [ __CLASS__, 'handle_clear_empty_terms_request' ] );
add_action( 'load-edit.php', [ __CLASS__, 'handle_inline_edit_request' ] );
// Prevent query vars from persisting after redirect.
add_filter(
'removable_query_args',
static function( $query_vars ) {
$query_vars[] = 'amp_actioned';
$query_vars[] = 'amp_actioned_count';
$query_vars[] = 'amp_validation_errors_not_deleted';
$query_vars[] = AMP_Validation_Error_Taxonomy::VALIDATION_ERRORS_CLEARED_QUERY_VAR;
return $query_vars;
}
);
// Add recognition of amp_validation_error_status and type query vars (which will only apply in admin since post type is not publicly_queryable).
add_filter(
'query_vars',
static function( $query_vars ) {
$query_vars[] = AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_STATUS_QUERY_VAR;
$query_vars[] = AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_TYPE_QUERY_VAR;
return $query_vars;
}
);
// Default ordering terms by ID descending so that new terms appear at the top.
add_filter(
'get_terms_defaults',
static function( $args, $taxonomies ) {
if ( [ AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG ] === $taxonomies ) {
$args['orderby'] = 'term_id';
$args['order'] = 'DESC';
}
return $args;
},
10,
2
);
// Remove bulk actions.
add_filter( 'bulk_actions-edit-' . self::TAXONOMY_SLUG, '__return_empty_array' );
// Override the columns displayed for the validation error terms.
add_filter(
'manage_edit-' . self::TAXONOMY_SLUG . '_columns',
static function() {
return [
'error_code' => esc_html__( 'Error', 'amp' ),
'status' => sprintf(
'%s<span class="dashicons dashicons-editor-help tooltip-button" tabindex="0"></span><div class="tooltip" hidden data-content="%s"></div>',
esc_html__( 'Markup Status', 'amp' ),
esc_attr(
sprintf(
'<h3>%s</h3><p>%s</p>',
esc_html__( 'Markup Status', 'amp' ),
__( 'When invalid markup is removed it will not block a URL from being served as AMP; the validation error will be sanitized, where the offending markup is stripped from the response to ensure AMP validity. If invalid AMP markup is kept, then URLs is occurs on will not be served as AMP pages.', 'amp' )
)
)
),
'details' => sprintf(
'%s<span class="dashicons dashicons-editor-help tooltip-button" tabindex="0"></span><div class="tooltip" hidden data-content="%s"></div>',
esc_html__( 'Context', 'amp' ),
esc_attr(
sprintf(
'<h3>%s</h3><p>%s</p>',
esc_html__( 'Context', 'amp' ),
esc_html__( 'The parent element of where the error occurred.', 'amp' )
)
)
),
'error_type' => esc_html__( 'Type', 'amp' ),
'created_date_gmt' => esc_html__( 'Last Seen', 'amp' ),
'posts' => esc_html__( 'URLs', 'amp' ),
];
}
);
// Let the created date column sort by term ID.
add_filter(
'manage_edit-' . self::TAXONOMY_SLUG . '_sortable_columns',
static function( $sortable_columns ) {
$sortable_columns['created_date_gmt'] = 'term_id';
$sortable_columns['error_type'] = AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_TYPE_QUERY_VAR;
$sortable_columns['error_code'] = AMP_Validation_Error_Taxonomy::VALIDATION_DETAILS_ERROR_CODE_QUERY_VAR;
return $sortable_columns;
}
);
// Hide empty term addition form.
add_action(
'admin_enqueue_scripts',
static function() {
$current_screen = get_current_screen();
if ( ! $current_screen ) {
return;
}
if ( AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG === $current_screen->taxonomy ) {
wp_add_inline_style(
'common',
'
#col-left { display: none; }
#col-right { float:none; width: auto; }
/* Improve column widths */
td.column-details pre, td.column-sources pre { overflow:auto; }
th.column-created_date_gmt { width:15%; }
th.column-status { width:15%; }
'
);
wp_register_style(
'amp-validation-tooltips',
amp_get_asset_url( 'css/amp-validation-tooltips.css' ),
[ 'wp-pointer' ],
AMP__VERSION
);
wp_styles()->add_data( 'amp-validation-tooltips', 'rtl', 'replace' );
$asset_file = AMP__DIR__ . '/assets/js/amp-validation-tooltips.asset.php';
$asset = require $asset_file;
$dependencies = $asset['dependencies'];
$version = $asset['version'];
wp_register_script(
'amp-validation-tooltips',
amp_get_asset_url( 'js/amp-validation-tooltips.js' ),
$dependencies,
$version,
true
);
wp_enqueue_style(
'amp-validation-error-taxonomy',
amp_get_asset_url( 'css/amp-validation-error-taxonomy.css' ),
[ 'common', 'amp-validation-tooltips', 'amp-icons' ],
AMP__VERSION
);
wp_styles()->add_data( 'amp-validation-error-taxonomy', 'rtl', 'replace' );
wp_enqueue_script(
'amp-validation-detail-toggle',
amp_get_asset_url( 'js/amp-validation-detail-toggle.js' ),
[ 'wp-dom-ready', 'wp-i18n', 'amp-validation-tooltips' ],
AMP__VERSION,
true
);
}
if ( 'post' === $current_screen->base && AMP_Validated_URL_Post_Type::POST_TYPE_SLUG === $current_screen->post_type ) {
wp_enqueue_style(
'amp-validation-single-error-url',
amp_get_asset_url( 'css/amp-validation-single-error-url.css' ),
[ 'common', 'amp-icons' ],
AMP__VERSION
);
wp_styles()->add_data( 'amp-validation-single-error-url', 'rtl', 'replace' );
$asset_file = AMP__DIR__ . '/assets/js/amp-validation-single-error-url-details.asset.php';
$asset = require $asset_file;
$dependencies = $asset['dependencies'];
$version = $asset['version'];
wp_enqueue_script(
'amp-validation-single-error-url-details',
amp_get_asset_url( 'js/amp-validation-single-error-url-details.js' ),
$dependencies,
$version,
true