-
Notifications
You must be signed in to change notification settings - Fork 385
/
class-amp-validation-utils.php
1794 lines (1637 loc) · 55.6 KB
/
class-amp-validation-utils.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_Utils
*
* @package AMP
*/
/**
* Class AMP_Validation_Utils
*
* @since 0.7
*/
class AMP_Validation_Utils {
/**
* Query var that triggers validation.
*
* @var string
*/
const VALIDATE_QUERY_VAR = 'amp_validate';
/**
* Query var that enables validation debug mode, to disable removal of invalid elements/attributes.
*
* @var string
*/
const DEBUG_QUERY_VAR = 'amp_debug';
/**
* Query var for cache-busting.
*
* @var string
*/
const CACHE_BUST_QUERY_VAR = 'amp_cache_bust';
/**
* The slug of the post type to store AMP errors.
*
* @var string
*/
const POST_TYPE_SLUG = 'amp_validation_error';
/**
* The key in the response for the sources that have invalid output.
*
* @var string
*/
const SOURCES_INVALID_OUTPUT = 'sources_with_invalid_output';
/**
* Validation code for an invalid element.
*
* @var string
*/
const INVALID_ELEMENT_CODE = 'invalid_element';
/**
* Validation code for an invalid attribute.
*
* @var string
*/
const INVALID_ATTRIBUTE_CODE = 'invalid_attribute';
/**
* Validation code for when script is enqueued (which is not allowed).
*
* @var string
*/
const ENQUEUED_SCRIPT_CODE = 'enqueued_script';
/**
* The meta key for the AMP URL where the error occurred.
*
* @var string
*/
const AMP_URL_META = 'amp_url';
/**
* The key for removed elements.
*
* @var string
*/
const REMOVED_ELEMENTS = 'removed_elements';
/**
* The key for removed attributes.
*
* @var string
*/
const REMOVED_ATTRIBUTES = 'removed_attributes';
/**
* The key for removed sources.
*
* @var string
*/
const REMOVED_SOURCES = 'removed_sources';
/**
* The action to recheck URLs for AMP validity.
*
* @var string
*/
const RECHECK_ACTION = 'amp_recheck';
/**
* The query arg for whether there are remaining errors after rechecking URLs.
*
* @var string
*/
const REMAINING_ERRORS = 'amp_remaining_errors';
/**
* The query arg for the number of URLs tested.
*
* @var string
*/
const URLS_TESTED = 'amp_urls_tested';
/**
* The nonce action for rechecking a URL.
*
* @var string
*/
const NONCE_ACTION = 'amp_recheck_';
/**
* HTTP response header name containing JSON-serialized validation errors.
*
* @var string
*/
const VALIDATION_ERRORS_RESPONSE_HEADER_NAME = 'X-AMP-Validation-Errors';
/**
* 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 side meta box on the CPT post.php page.
*
* @var string
*/
const STATUS_META_BOX = 'amp_validation_status';
/**
* The name of the side meta box on the CPT post.php page.
*
* @var string
*/
const VALIDATION_ERRORS_META_BOX = 'amp_validation_errors';
/**
* The errors encountered when validating.
*
* @var array[][] {
* @type string $code Error code.
* @type string $node_name Name of removed node.
* @type string $parent_name Name of parent node.
* }
*/
public static $validation_errors = array();
/**
* Sources that enqueue each script.
*
* @var array
*/
public static $enqueued_script_sources = array();
/**
* Sources that enqueue each style.
*
* @var array
*/
public static $enqueued_style_sources = array();
/**
* Post IDs for posts that have been updated which need to be re-validated.
*
* @var int[]
*/
public static $posts_pending_frontend_validation = array();
/**
* Current sources gathered for a given hook currently being run.
*
* @see AMP_Validation_Utils::wrap_hook_callbacks()
* @see AMP_Validation_Utils::decorate_filter_source()
* @var array[]
*/
protected static $current_hook_source_stack = array();
/**
* Add the actions.
*
* @return void
*/
public static function init() {
if ( current_theme_supports( 'amp' ) ) {
add_action( 'init', array( __CLASS__, 'register_post_type' ) );
add_filter( 'dashboard_glance_items', array( __CLASS__, 'filter_dashboard_glance_items' ) );
add_action( 'rightnow_end', array( __CLASS__, 'print_dashboard_glance_styles' ) );
add_action( 'save_post', array( __CLASS__, 'handle_save_post_prompting_validation' ), 10, 2 );
}
add_action( 'edit_form_top', array( __CLASS__, 'print_edit_form_validation_status' ), 10, 2 );
add_action( 'all_admin_notices', array( __CLASS__, 'plugin_notice' ) );
add_filter( 'manage_' . self::POST_TYPE_SLUG . '_posts_columns', array( __CLASS__, 'add_post_columns' ) );
add_action( 'manage_posts_custom_column', array( __CLASS__, 'output_custom_column' ), 10, 2 );
add_filter( 'post_row_actions', array( __CLASS__, 'filter_row_actions' ), 10, 2 );
add_filter( 'bulk_actions-edit-' . self::POST_TYPE_SLUG, array( __CLASS__, 'add_bulk_action' ), 10, 2 );
add_filter( 'handle_bulk_actions-edit-' . self::POST_TYPE_SLUG, array( __CLASS__, 'handle_bulk_action' ), 10, 3 );
add_action( 'admin_notices', array( __CLASS__, 'remaining_error_notice' ) );
add_action( 'post_action_' . self::RECHECK_ACTION, array( __CLASS__, 'handle_inline_recheck' ) );
add_action( 'admin_menu', array( __CLASS__, 'remove_publish_meta_box' ) );
add_action( 'admin_menu', array( __CLASS__, 'add_admin_menu_validation_status_count' ) );
add_action( 'add_meta_boxes', array( __CLASS__, 'add_meta_boxes' ) );
// Actions and filters involved in validation.
add_action( 'activate_plugin', function() {
if ( ! has_action( 'shutdown', array( __CLASS__, 'validate_after_plugin_activation' ) ) ) {
add_action( 'shutdown', array( __CLASS__, 'validate_after_plugin_activation' ) ); // Shutdown so all plugins will have been activated.
}
} );
}
/**
* Add count of how many validation error posts there are to the admin menu.
*/
public static function add_admin_menu_validation_status_count() {
global $submenu;
if ( ! isset( $submenu[ AMP_Options_Manager::OPTION_NAME ] ) ) {
return;
}
$count = wp_count_posts( self::POST_TYPE_SLUG );
if ( empty( $count->publish ) ) {
return;
}
foreach ( $submenu[ AMP_Options_Manager::OPTION_NAME ] as &$submenu_item ) {
if ( 'edit.php?post_type=' . self::POST_TYPE_SLUG === $submenu_item[2] ) {
$submenu_item[0] .= ' <span class="awaiting-mod"><span class="pending-count">' . esc_html( $count->publish ) . '</span></span>';
break;
}
}
}
/**
* Filter At a Glance items add AMP Validation Errors.
*
* @param array $items At a glance items.
* @return array Items.
*/
public static function filter_dashboard_glance_items( $items ) {
$counts = wp_count_posts( self::POST_TYPE_SLUG );
if ( ! empty( $counts->publish ) ) {
$items[] = sprintf(
'<a class="amp-validation-errors" href="%s">%s</a>',
esc_url( admin_url( 'edit.php?post_type=' . self::POST_TYPE_SLUG ) ),
esc_html( sprintf(
/* translators: %s is the validation error count */
_n( '%s AMP Validation Error', '%s AMP Validation Errors', $counts->publish, 'amp' ),
$counts->publish
) )
);
}
return $items;
}
/**
* Print styles for the At a Glance widget.
*/
public static function print_dashboard_glance_styles() {
?>
<style>
#dashboard_right_now .amp-validation-errors {
color: #a00;
}
#dashboard_right_now .amp-validation-errors:before {
content: "\f534";
}
#dashboard_right_now .amp-validation-errors:hover {
color: #dc3232;
border: none;
}
</style>
<?php
}
/**
* Add hooks for doing validation during preprocessing/sanitizing.
*/
public static function add_validation_hooks() {
self::wrap_widget_callbacks();
add_action( 'all', array( __CLASS__, 'wrap_hook_callbacks' ) );
$wrapped_filters = array( 'the_content', 'the_excerpt' );
foreach ( $wrapped_filters as $wrapped_filter ) {
add_filter( $wrapped_filter, array( __CLASS__, 'decorate_filter_source' ), PHP_INT_MAX );
}
add_filter( 'do_shortcode_tag', array( __CLASS__, 'decorate_shortcode_source' ), -1, 2 );
add_filter( 'amp_content_sanitizers', array( __CLASS__, 'add_validation_callback' ) );
}
/**
* Handle save_post action to queue re-validation of the post on the frontend.
*
* @see AMP_Validation_Utils::validate_queued_posts_on_frontend()
* @param int $post_id Post ID.
* @param WP_Post $post Post.
*/
public static function handle_save_post_prompting_validation( $post_id, $post ) {
$should_validate_post = (
is_post_type_viewable( $post->post_type )
&&
! wp_is_post_autosave( $post )
&&
! wp_is_post_revision( $post )
);
if ( $should_validate_post ) {
self::$posts_pending_frontend_validation[] = $post_id;
// The reason for shutdown is to ensure that all postmeta changes have been saved, including whether AMP is enabled.
if ( ! has_action( 'shutdown', array( __CLASS__, 'validate_queued_posts_on_frontend' ) ) ) {
add_action( 'shutdown', array( __CLASS__, 'validate_queued_posts_on_frontend' ) );
}
}
}
/**
* Validate the posts pending frontend validation.
*
* @see AMP_Validation_Utils::handle_save_post_prompting_validation()
*/
public static function validate_queued_posts_on_frontend() {
$posts = array_filter(
array_map( 'get_post', self::$posts_pending_frontend_validation ),
function( $post ) {
return $post && post_supports_amp( $post ) && 'trash' !== $post->post_status;
}
);
// @todo Only validate the first and then queue the rest in WP Cron?
foreach ( $posts as $post ) {
$url = amp_get_permalink( $post->ID );
if ( ! $url ) {
continue;
}
$validation_errors = self::validate_url( $url );
if ( is_wp_error( $validation_errors ) ) {
continue;
}
self::store_validation_errors( $validation_errors, $url );
}
}
/**
* Processes markup, to determine AMP validity.
*
* Passes $markup through the AMP sanitizers.
* Also passes a 'validation_error_callback' to keep track of stripped attributes and nodes.
*
* @param string $markup The markup to process.
* @return string Sanitized markup.
*/
public static function process_markup( $markup ) {
AMP_Theme_Support::register_content_embed_handlers();
/** This filter is documented in wp-includes/post-template.php */
$markup = apply_filters( 'the_content', $markup );
$args = array(
'content_max_width' => ! empty( $content_width ) ? $content_width : AMP_Post_Template::CONTENT_MAX_WIDTH,
'validation_error_callback' => 'AMP_Validation_Utils::add_validation_error',
);
$results = AMP_Content_Sanitizer::sanitize( $markup, amp_get_content_sanitizers(), $args );
return $results[0];
}
/**
* 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 $data {
* Data.
*
* @type string $code Error code.
* @type DOMElement|DOMNode $node The removed node.
* }
*/
public static function add_validation_error( array $data ) {
$node = null;
if ( isset( $data['node'] ) && $data['node'] instanceof DOMNode ) {
$node = $data['node'];
unset( $data['node'] );
$data['node_name'] = $node->nodeName;
$data['sources'] = self::locate_sources( $node );
if ( $node->parentNode ) {
$data['parent_name'] = $node->parentNode->nodeName;
}
}
if ( $node instanceof DOMElement ) {
if ( ! isset( $data['code'] ) ) {
$data['code'] = self::INVALID_ELEMENT_CODE;
}
$data['node_attributes'] = array();
foreach ( $node->attributes as $attribute ) {
$data['node_attributes'][ $attribute->nodeName ] = $attribute->nodeValue;
}
$is_enqueued_link = (
'link' === $node->nodeName
&&
preg_match( '/(?P<handle>.+)-css$/', (string) $node->getAttribute( 'id' ), $matches )
&&
isset( self::$enqueued_style_sources[ $matches['handle'] ] )
);
if ( $is_enqueued_link ) {
$data['sources'] = self::$enqueued_style_sources[ $matches['handle'] ];
}
} elseif ( $node instanceof DOMAttr ) {
if ( ! isset( $data['code'] ) ) {
$data['code'] = self::INVALID_ATTRIBUTE_CODE;
}
$data['element_attributes'] = array();
if ( $node->parentNode && $node->parentNode->hasAttributes() ) {
foreach ( $node->parentNode->attributes as $attribute ) {
$data['element_attributes'][ $attribute->nodeName ] = $attribute->nodeValue;
}
}
}
if ( ! isset( $data['code'] ) ) {
$data['code'] = 'unknown';
}
self::$validation_errors[] = $data;
}
/**
* 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 = array();
$removed_elements = array();
$removed_attributes = array();
$invalid_sources = array();
foreach ( $validation_errors as $validation_error ) {
$code = isset( $validation_error['code'] ) ? $validation_error['code'] : null;
if ( self::INVALID_ELEMENT_CODE === $code ) {
if ( ! isset( $removed_elements[ $validation_error['node_name'] ] ) ) {
$removed_elements[ $validation_error['node_name'] ] = 0;
}
$removed_elements[ $validation_error['node_name'] ] += 1;
} elseif ( self::INVALID_ATTRIBUTE_CODE === $code ) {
if ( ! isset( $removed_attributes[ $validation_error['node_name'] ] ) ) {
$removed_attributes[ $validation_error['node_name'] ] = 0;
}
$removed_attributes[ $validation_error['node_name'] ] += 1;
}
if ( ! empty( $validation_error['sources'] ) ) {
$source = array_pop( $validation_error['sources'] );
if ( isset( $source['type'], $source['name'] ) ) {
$invalid_sources[ $source['type'] ][] = $source['name'];
}
}
}
$results = array_merge(
array(
self::SOURCES_INVALID_OUTPUT => $invalid_sources,
),
compact(
'removed_elements',
'removed_attributes'
),
$results );
return $results;
}
/**
* 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_errors = array();
self::$enqueued_style_sources = array();
self::$enqueued_script_sources = array();
}
/**
* Checks the AMP validity of the post content.
*
* If it's not valid AMP, it displays an error message above the 'Classic' editor.
*
* @param WP_Post $post The updated post.
* @return void
*/
public static function print_edit_form_validation_status( $post ) {
if ( ! post_supports_amp( $post ) || ! self::has_cap() ) {
return;
}
$url = null;
$validation_status_post = null;
$validation_errors = array();
// Validate post content outside frontend context.
if ( post_type_supports( $post->post_type, 'editor' ) ) {
self::process_markup( $post->post_content );
$validation_errors = array_merge(
$validation_errors,
self::$validation_errors
);
self::reset_validation_results();
}
// Incorporate frontend validation status if there is a known URL for the post.
if ( is_post_type_viewable( $post->post_type ) ) {
$url = amp_get_permalink( $post->ID );
$validation_status_post = self::get_validation_status_post( $url );
if ( $validation_status_post ) {
$data = json_decode( $validation_status_post->post_content, true );
if ( is_array( $data ) ) {
$validation_errors = array_merge( $validation_errors, $data );
}
}
}
if ( empty( $validation_errors ) ) {
return;
}
echo '<div class="notice notice-warning">';
echo '<p>';
esc_html_e( 'Warning: There is content which fails AMP validation; it will be stripped when served as AMP.', 'amp' );
if ( $validation_status_post || $url ) {
if ( $validation_status_post ) {
echo sprintf(
' <a href="%s" target="_blank">%s</a>',
esc_url( get_edit_post_link( $validation_status_post ) ),
esc_html__( 'Details', 'amp' )
);
}
if ( $url ) {
if ( $validation_status_post ) {
echo ' | ';
}
echo sprintf(
' <a href="%s" aria-label="%s" target="_blank">%s</a>',
esc_url( self::get_debug_url( $url ) ),
esc_attr__( 'Validate URL on frontend but without invalid elements/attributes removed', 'amp' ),
esc_html__( 'Debug', 'amp' )
);
}
}
echo '</p>';
$results = self::summarize_validation_errors( array_unique( $validation_errors, SORT_REGULAR ) );
$removed_sets = array();
if ( ! empty( $results[ self::REMOVED_ELEMENTS ] ) && is_array( $results[ self::REMOVED_ELEMENTS ] ) ) {
$removed_sets[] = array(
'label' => __( 'Invalid elements:', 'amp' ),
'names' => array_map( 'sanitize_key', $results[ self::REMOVED_ELEMENTS ] ),
);
}
if ( ! empty( $results[ self::REMOVED_ATTRIBUTES ] ) && is_array( $results[ self::REMOVED_ATTRIBUTES ] ) ) {
$removed_sets[] = array(
'label' => __( 'Invalid attributes:', 'amp' ),
'names' => array_map( 'sanitize_key', $results[ self::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'] ) );
self::output_removed_set( $removed_set['names'] );
echo '</p>';
}
echo '</div>';
}
/**
* 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' );
}
/**
* Walk back tree to find the open sources.
*
* @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 ) {
$xpath = new DOMXPath( $node->ownerDocument );
$comments = $xpath->query( 'preceding::comment()[ starts-with( ., "amp-source-stack" ) or starts-with( ., "/amp-source-stack" ) ]', $node );
$sources = array();
foreach ( $comments as $comment ) {
$parsed_comment = self::parse_source_comment( $comment );
if ( ! $parsed_comment ) {
continue;
}
if ( $parsed_comment['closing'] ) {
array_pop( $sources );
} else {
$sources[] = $parsed_comment['source'];
}
}
return $sources;
}
/**
* Remove source comments.
*
* @param DOMDocument $dom Document.
*/
public static function remove_source_comments( $dom ) {
$xpath = new DOMXPath( $dom );
$comments = array();
foreach ( $xpath->query( '//comment()[ starts-with( ., "amp-source-stack" ) or starts-with( ., "/amp-source-stack" ) ]' ) as $comment ) {
if ( self::parse_source_comment( $comment ) ) {
$comments[] = $comment;
}
}
foreach ( $comments as $comment ) {
$comment->parentNode->removeChild( $comment );
}
}
/**
* Wrap callbacks for registered widgets to keep track of queued assets and the source for anything printed for validation.
*
* @global array $wp_filter
* @return void
*/
public static function wrap_widget_callbacks() {
global $wp_registered_widgets;
foreach ( $wp_registered_widgets as $widget_id => &$registered_widget ) {
$source = self::get_source( $registered_widget['callback'] );
if ( ! $source ) {
continue;
}
$source['widget_id'] = $widget_id;
$function = $registered_widget['callback'];
$accepted_args = 2; // For the $instance and $args arguments.
$callback = compact( 'function', 'accepted_args', 'source' );
$registered_widget['callback'] = self::wrapped_callback( $callback );
}
}
/**
* Wrap filter/action callback functions for a given hook.
*
* Wrapped callback functions are reset to their original functions after invocation.
* This runs at the 'all' action. The shutdown hook is excluded.
*
* @global WP_Hook[] $wp_filter
* @param string $hook Hook name for action or filter.
* @return void
*/
public static function wrap_hook_callbacks( $hook ) {
global $wp_filter;
if ( ! isset( $wp_filter[ $hook ] ) || 'shutdown' === $hook ) {
return;
}
self::$current_hook_source_stack[ $hook ] = array();
foreach ( $wp_filter[ $hook ]->callbacks as $priority => &$callbacks ) {
foreach ( $callbacks as &$callback ) {
$source = self::get_source( $callback['function'] );
if ( ! $source ) {
continue;
}
$reflection = $source['reflection'];
unset( $source['reflection'] ); // Omit from stored source.
// Add hook to stack for decorate_filter_source to read from.
self::$current_hook_source_stack[ $hook ][] = $source;
/*
* A current limitation with wrapping callbacks is that the wrapped function cannot have
* any parameters passed by reference. Without this the result is:
*
* > PHP Warning: Parameter 1 to wp_default_styles() expected to be a reference, value given.
*/
if ( self::has_parameters_passed_by_reference( $reflection ) ) {
continue;
}
$source['hook'] = $hook;
$original_function = $callback['function'];
$wrapped_callback = self::wrapped_callback( array_merge(
$callback,
compact( 'priority', 'source', 'hook' )
) );
$callback['function'] = function() use ( &$callback, $wrapped_callback, $original_function ) {
$callback['function'] = $original_function; // Restore original.
return call_user_func_array( $wrapped_callback, func_get_args() );
};
}
}
}
/**
* Determine whether the given reflection method/function has params passed by reference.
*
* @since 0.7
* @param ReflectionFunction|ReflectionMethod $reflection Reflection.
* @return bool Whether there are parameters passed by reference.
*/
protected static function has_parameters_passed_by_reference( $reflection ) {
foreach ( $reflection->getParameters() as $parameter ) {
if ( $parameter->isPassedByReference() ) {
return true;
}
}
return false;
}
/**
* Filters the output created by a shortcode callback.
*
* @since 0.7
*
* @param string $output Shortcode output.
* @param string $tag Shortcode name.
* @return string Output.
* @global array $shortcode_tags
*/
public static function decorate_shortcode_source( $output, $tag ) {
global $shortcode_tags;
if ( ! isset( $shortcode_tags[ $tag ] ) ) {
return $output;
}
$source = self::get_source( $shortcode_tags[ $tag ] );
if ( empty( $source ) ) {
return $output;
}
$source['shortcode'] = $tag;
$output = implode( '', array(
self::get_source_comment( $source, true ),
$output,
self::get_source_comment( $source, false ),
) );
return $output;
}
/**
* Wraps output of a filter to add source stack comments.
*
* @param string $value Value.
* @return string Value wrapped in source comments.
*/
public static function decorate_filter_source( $value ) {
// Abort if the output is not a string and it doesn't contain any HTML tags.
if ( ! is_string( $value ) || ! preg_match( '/<.+?>/s', $value ) ) {
return $value;
}
$post = get_post();
$source = array(
'hook' => current_filter(),
'filter' => true,
);
if ( $post ) {
$source['post_id'] = $post->ID;
$source['post_type'] = $post->post_type;
}
if ( isset( self::$current_hook_source_stack[ current_filter() ] ) ) {
$sources = self::$current_hook_source_stack[ current_filter() ];
array_pop( $sources ); // Remove self.
$source['sources'] = $sources;
}
return implode( '', array(
self::get_source_comment( $source, true ),
$value,
self::get_source_comment( $source, false ),
) );
}
/**
* Gets the plugin or theme of the callback, if one exists.
*
* @param string|array $callback The callback for which to get the plugin.
* @return array|null {
* The source data.
*
* @type string $type Source type (core, plugin, mu-plugin, or theme).
* @type string $name Source name.
* @type string $function Normalized function name.
* @type ReflectionMethod|ReflectionFunction $reflection
* }
*/
public static function get_source( $callback ) {
$reflection = null;
$class_name = null; // Because ReflectionMethod::getDeclaringClass() can return a parent class.
try {
if ( is_string( $callback ) && is_callable( $callback ) ) {
// The $callback is a function or static method.
$exploded_callback = explode( '::', $callback, 2 );
if ( 2 === count( $exploded_callback ) ) {
$class_name = $exploded_callback[0];
$reflection = new ReflectionMethod( $exploded_callback[0], $exploded_callback[1] );
} else {
$reflection = new ReflectionFunction( $callback );
}
} elseif ( is_array( $callback ) && isset( $callback[0], $callback[1] ) && method_exists( $callback[0], $callback[1] ) ) {
// The $callback is a method.
if ( is_string( $callback[0] ) ) {
$class_name = $callback[0];
} elseif ( is_object( $callback[0] ) ) {
$class_name = get_class( $callback[0] );
}
$reflection = new ReflectionMethod( $callback[0], $callback[1] );
} elseif ( is_object( $callback ) && ( 'Closure' === get_class( $callback ) ) ) {
$reflection = new ReflectionFunction( $callback );
}
} catch ( Exception $e ) {
return null;
}
if ( ! $reflection ) {
return null;
}
$source = compact( 'reflection' );
$file = $reflection->getFileName();
if ( $file ) {
$file = wp_normalize_path( $file );
$slug_pattern = '([^/]+)';
if ( preg_match( ':' . preg_quote( trailingslashit( wp_normalize_path( WP_PLUGIN_DIR ) ), ':' ) . $slug_pattern . ':s', $file, $matches ) ) {
$source['type'] = 'plugin';
$source['name'] = $matches[1];
} elseif ( preg_match( ':' . preg_quote( trailingslashit( wp_normalize_path( get_theme_root() ) ), ':' ) . $slug_pattern . ':s', $file, $matches ) ) {
$source['type'] = 'theme';
$source['name'] = $matches[1];
} elseif ( preg_match( ':' . preg_quote( trailingslashit( wp_normalize_path( WPMU_PLUGIN_DIR ) ), ':' ) . $slug_pattern . ':s', $file, $matches ) ) {
$source['type'] = 'mu-plugin';
$source['name'] = $matches[1];
} elseif ( preg_match( ':' . preg_quote( trailingslashit( wp_normalize_path( ABSPATH ) ), ':' ) . '(wp-admin|wp-includes)/:s', $file, $matches ) ) {
$source['type'] = 'core';
$source['name'] = $matches[1];
}
}
if ( $class_name ) {
$source['function'] = $class_name . '::' . $reflection->getName();
} else {
$source['function'] = $reflection->getName();
}
return $source;
}
/**
* Wraps a callback in comments if it outputs markup.
*
* If the sanitizer removes markup,
* this indicates which plugin it was from.
* The call_user_func_array() logic is mainly copied from WP_Hook:apply_filters().
*
* @param array $callback {
* The callback data.
*
* @type callable $function
* @type int $accepted_args
* @type array $source
* }
* @return closure $wrapped_callback The callback, wrapped in comments.
*/
public static function wrapped_callback( $callback ) {
return function() use ( $callback ) {
global $wp_styles, $wp_scripts;
$function = $callback['function'];
$accepted_args = $callback['accepted_args'];
$args = func_get_args();
$before_styles_enqueued = array();
if ( isset( $wp_styles ) && isset( $wp_styles->queue ) ) {
$before_styles_enqueued = $wp_styles->queue;
}
$before_scripts_enqueued = array();
if ( isset( $wp_scripts ) && isset( $wp_scripts->queue ) ) {
$before_scripts_enqueued = $wp_scripts->queue;
}
ob_start();
$result = call_user_func_array( $function, array_slice( $args, 0, intval( $accepted_args ) ) );
$output = ob_get_clean();
// Keep track of which source enqueued the styles.
if ( isset( $wp_styles ) && isset( $wp_styles->queue ) ) {
foreach ( array_diff( $wp_styles->queue, $before_styles_enqueued ) as $handle ) {
AMP_Validation_Utils::$enqueued_style_sources[ $handle ][] = $callback['source'];
}
}
// Keep track of which source enqueued the scripts, and immediately report validity .
if ( isset( $wp_scripts ) && isset( $wp_scripts->queue ) ) {
foreach ( array_diff( $wp_scripts->queue, $before_scripts_enqueued ) as $handle ) {
AMP_Validation_Utils::$enqueued_script_sources[ $handle ][] = $callback['source'];
// Flag all scripts not loaded from the AMP CDN as validation errors.
if ( isset( $wp_scripts->registered[ $handle ] ) && 0 !== strpos( $wp_scripts->registered[ $handle ]->src, 'https://cdn.ampproject.org/' ) ) {
self::add_validation_error( array(
'code' => self::ENQUEUED_SCRIPT_CODE,
'handle' => $handle,
'dependency' => $wp_scripts->registered[ $handle ],
'sources' => array(
$callback['source'],
),
) );
}
}
}
// Wrap output that contains HTML tags (as opposed to actions that trigger in HTML attributes).
if ( ! empty( $output ) && preg_match( '/<.+?>/s', $output ) ) {
echo AMP_Validation_Utils::get_source_comment( $callback['source'], true ); // WPCS: XSS ok.
echo $output; // WPCS: XSS ok.
echo AMP_Validation_Utils::get_source_comment( $callback['source'], false ); // WPCS: XSS ok.
}
return $result;
};
}