-
Notifications
You must be signed in to change notification settings - Fork 384
/
class-amp-theme-support.php
2578 lines (2330 loc) · 86.6 KB
/
class-amp-theme-support.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_Theme_Support
*
* @package AMP
*/
/**
* Class AMP_Theme_Support
*
* Callbacks for adding AMP-related things when theme support is added.
*/
class AMP_Theme_Support {
/**
* Theme support slug.
*
* @var string
*/
const SLUG = 'amp';
/**
* Response cache group name.
*
* @var string
*/
const RESPONSE_CACHE_GROUP = 'amp-response';
/**
* Post-processor cache effectiveness group name.
*
* @var string
*/
const POST_PROCESSOR_CACHE_EFFECTIVENESS_GROUP = 'post_processor_cache_effectiveness_group';
/**
* Post-processor cache effectiveness key name.
*
* @var string
*/
const POST_PROCESSOR_CACHE_EFFECTIVENESS_KEY = 'post_processor_cache_effectiveness';
/**
* Cache miss threshold for determining when to disable post-processor cache.
*
* @var int
*/
const CACHE_MISS_THRESHOLD = 20;
/**
* Cache miss URL option name.
*
* @var string
*/
const CACHE_MISS_URL_OPTION = 'amp_cache_miss_url';
/**
* Slug identifying standard website mode.
*
* @since 1.2
* @var string
*/
const STANDARD_MODE_SLUG = 'standard';
/**
* Slug identifying transitional website mode.
*
* @since 1.2
* @var string
*/
const TRANSITIONAL_MODE_SLUG = 'transitional';
/**
* Slug identifying reader website mode.
*
* @since 1.2
* @var string
*/
const READER_MODE_SLUG = 'reader';
/**
* Flag used in args passed to add_theme_support('amp') to indicate transitional mode supported.
*
* @since 1.2
* @var string
*/
const PAIRED_FLAG = 'paired';
/**
* The directory name in a theme where Reader Mode templates can be.
*
* For example, this could be at your-theme-name/amp.
*
* @var string
*/
const READER_MODE_TEMPLATE_DIRECTORY = 'amp';
/**
* Sanitizer classes.
*
* @var array
*/
protected static $sanitizer_classes = [];
/**
* Embed handlers.
*
* @var AMP_Base_Embed_Handler[]
*/
protected static $embed_handlers = [];
/**
* Template types.
*
* @var array
*/
protected static $template_types = [
'paged', // Deprecated.
'index',
'404',
'archive',
'author',
'category',
'tag',
'taxonomy',
'date',
'home',
'front_page',
'page',
'search',
'single',
'embed',
'singular',
'attachment',
];
/**
* Start time when init was called.
*
* @since 1.0
* @var float
*/
public static $init_start_time;
/**
* Whether output buffering has started.
*
* @since 0.7
* @var bool
*/
protected static $is_output_buffering = false;
/**
* Theme support mode that was added via option.
*
* This should be either null (reader), 'standard', or 'transitional'.
*
* @since 1.0
* @var null|string
*/
protected static $support_added_via_option;
/**
* Theme support mode which was added via the theme.
*
* This should be either null (reader), 'standard', or 'transitional'.
*
* @var null|string
*/
protected static $support_added_via_theme;
/**
* Initialize.
*
* @since 0.7
*/
public static function init() {
self::read_theme_support();
self::$init_start_time = microtime( true );
if ( AMP_Options_Manager::is_website_experience_enabled() && current_theme_supports( self::SLUG ) ) {
// Ensure extra theme support for core themes is in place.
AMP_Core_Theme_Sanitizer::extend_theme_support();
require_once AMP__DIR__ . '/includes/amp-post-template-functions.php';
add_action( 'widgets_init', [ __CLASS__, 'register_widgets' ] );
/*
* Note that wp action is use instead of template_redirect because some themes/plugins output
* the response at this action and then short-circuit with exit. So this is why the the preceding
* action to template_redirect--the wp action--is used instead.
*/
add_action( 'wp', [ __CLASS__, 'finish_init' ], PHP_INT_MAX );
} elseif ( AMP_Options_Manager::is_stories_experience_enabled() ) {
add_action(
'wp',
static function () {
if ( is_singular( AMP_Story_Post_Type::POST_TYPE_SLUG ) ) {
self::finish_init();
}
},
PHP_INT_MAX
);
}
}
/**
* Determine whether theme support was added via admin option.
*
* @since 1.0
* @see AMP_Theme_Support::read_theme_support()
* @see AMP_Theme_Support::get_support_mode()
* @deprecated Use AMP_Theme_Support::get_support_mode_added_via_option().
*
* @return bool Support added via option.
*/
public static function is_support_added_via_option() {
_deprecated_function( __METHOD__, '1.2', 'AMP_Theme_Support::get_support_mode_added_via_option' );
return null !== self::$support_added_via_option;
}
/**
* Get the theme support mode added via admin option.
*
* @return null|string Support added via option, with null meaning Reader, and otherwise being 'standard' or 'transitional'.
* @see AMP_Theme_Support::read_theme_support()
* @see AMP_Theme_Support::TRANSITIONAL_MODE_SLUG
* @see AMP_Theme_Support::STANDARD_MODE_SLUG
*
* @since 1.2
*/
public static function get_support_mode_added_via_option() {
return self::$support_added_via_option;
}
/**
* Get the theme support mode added via admin option.
*
* @return null|string Support added via option, with null meaning Reader, and otherwise being 'standard' or 'transitional'.
* @see AMP_Theme_Support::read_theme_support()
* @see AMP_Theme_Support::TRANSITIONAL_MODE_SLUG
* @see AMP_Theme_Support::STANDARD_MODE_SLUG
*
* @since 1.2
*/
public static function get_support_mode_added_via_theme() {
return self::$support_added_via_theme;
}
/**
* Get theme support mode.
*
* @return string Theme support mode.
* @see AMP_Theme_Support::read_theme_support()
* @see AMP_Theme_Support::TRANSITIONAL_MODE_SLUG
* @see AMP_Theme_Support::STANDARD_MODE_SLUG
*
* @since 1.2
*/
public static function get_support_mode() {
$theme_support = self::get_support_mode_added_via_option();
if ( ! $theme_support ) {
$theme_support = self::get_support_mode_added_via_theme();
}
if ( ! $theme_support ) {
$theme_support = self::READER_MODE_SLUG;
}
return $theme_support;
}
/**
* Check theme support args or add theme support if option is set in the admin.
*
* The DB option is only considered if the theme does not already explicitly support AMP.
*
* @see AMP_Theme_Support::get_support_mode_added_via_theme()
* @see AMP_Theme_Support::get_support_mode_added_via_option()
* @see AMP_Post_Type_Support::add_post_type_support() For where post type support is added, since it is irrespective of theme support.
*/
public static function read_theme_support() {
self::$support_added_via_theme = null;
self::$support_added_via_option = null;
$theme_support_option = AMP_Options_Manager::get_option( 'theme_support' );
if ( current_theme_supports( self::SLUG ) ) {
$args = self::get_theme_support_args();
// Validate theme support usage.
$keys = [ 'template_dir', 'comments_live_list', self::PAIRED_FLAG, 'templates_supported', 'available_callback', 'service_worker', 'nav_menu_toggle', 'nav_menu_dropdown' ];
if ( count( array_diff( array_keys( $args ), $keys ) ) !== 0 ) {
_doing_it_wrong(
'add_theme_support',
esc_html(
sprintf( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
/* translators: 1: comma-separated list of expected keys, 2: comma-separated list of actual keys */
__( 'Expected AMP theme support to keys (%1$s) but saw (%2$s)', 'amp' ),
implode( ', ', $keys ),
implode( ', ', array_keys( $args ) )
)
),
'1.0'
);
}
if ( isset( $args['available_callback'] ) ) {
_doing_it_wrong(
'add_theme_support',
sprintf(
/* translators: 1: available_callback. 2: supported_templates */
esc_html__( 'The %1$s is deprecated when adding amp theme support in favor of declaratively setting the %2$s.', 'amp' ),
'available_callback',
'supported_templates'
),
'1.0'
);
}
// See amp_is_canonical().
$is_paired = isset( $args[ self::PAIRED_FLAG ] ) ? $args[ self::PAIRED_FLAG ] : ! empty( $args['template_dir'] );
self::$support_added_via_theme = $is_paired ? self::TRANSITIONAL_MODE_SLUG : self::STANDARD_MODE_SLUG;
self::$support_added_via_option = $theme_support_option;
// Make sure the user option can override what the theme has specified.
if ( $is_paired && self::STANDARD_MODE_SLUG === $theme_support_option ) {
$args[ self::PAIRED_FLAG ] = false;
add_theme_support( self::SLUG, $args );
} elseif ( ! $is_paired && self::TRANSITIONAL_MODE_SLUG === $theme_support_option ) {
$args[ self::PAIRED_FLAG ] = true;
add_theme_support( self::SLUG, $args );
} elseif ( self::READER_MODE_SLUG === $theme_support_option ) {
remove_theme_support( self::SLUG );
}
} elseif ( self::READER_MODE_SLUG !== $theme_support_option ) {
$is_paired = ( self::TRANSITIONAL_MODE_SLUG === $theme_support_option );
add_theme_support(
self::SLUG,
[
self::PAIRED_FLAG => $is_paired,
]
);
self::$support_added_via_option = $is_paired ? self::TRANSITIONAL_MODE_SLUG : self::STANDARD_MODE_SLUG;
} elseif ( AMP_Validation_Manager::is_theme_support_forced() ) {
self::$support_added_via_option = self::STANDARD_MODE_SLUG;
add_theme_support( self::SLUG );
}
}
/**
* Get the theme support args.
*
* This avoids having to repeatedly call `get_theme_support()`, check the args, shift an item off the array, and so on.
*
* @since 1.0
*
* @return array|false Theme support args, or false if theme support is not present.
*/
public static function get_theme_support_args() {
if ( ! current_theme_supports( self::SLUG ) ) {
return false;
}
$support = get_theme_support( self::SLUG );
if ( true === $support ) {
return [
self::PAIRED_FLAG => false,
];
}
if ( ! isset( $support[0] ) || ! is_array( $support[0] ) ) {
return [];
}
return $support[0];
}
/**
* Gets whether the parent or child theme supports Reader Mode.
*
* True if the theme does not call add_theme_support( 'amp' ) at all,
* and it has an amp/ directory for templates.
*
* @return bool Whether the theme supports Reader Mode.
*/
public static function supports_reader_mode() {
return (
! self::get_support_mode_added_via_theme()
&&
(
is_dir( trailingslashit( get_template_directory() ) . self::READER_MODE_TEMPLATE_DIRECTORY )
||
is_dir( trailingslashit( get_stylesheet_directory() ) . self::READER_MODE_TEMPLATE_DIRECTORY )
)
);
}
/**
* Finish initialization once query vars are set.
*
* @since 0.7
*/
public static function finish_init() {
if ( ! is_amp_endpoint() ) {
/*
* Redirect to AMP-less variable if AMP is not available for this URL and yet the query var is present.
* Temporary redirect is used for admin users because implied transitional mode and template support can be
* enabled by user ay any time, so they will be able to make AMP available for this URL and see the change
* without wrestling with the redirect cache.
*/
if ( isset( $_GET[ amp_get_slug() ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
self::redirect_non_amp_url( current_user_can( 'manage_options' ) ? 302 : 301, true );
}
amp_add_frontend_actions();
return;
}
self::ensure_proper_amp_location();
$theme_support = self::get_theme_support_args();
if ( ! empty( $theme_support['template_dir'] ) ) {
self::add_amp_template_filters();
}
self::add_hooks();
self::$sanitizer_classes = amp_get_content_sanitizers();
self::$sanitizer_classes = AMP_Validation_Manager::filter_sanitizer_args( self::$sanitizer_classes );
self::$embed_handlers = self::register_content_embed_handlers();
self::$sanitizer_classes['AMP_Embed_Sanitizer']['embed_handlers'] = self::$embed_handlers;
foreach ( self::$sanitizer_classes as $sanitizer_class => $args ) {
if ( method_exists( $sanitizer_class, 'add_buffering_hooks' ) ) {
call_user_func( [ $sanitizer_class, 'add_buffering_hooks' ], $args );
}
}
}
/**
* Ensure that the current AMP location is correct.
*
* @since 1.0
*
* @param bool $exit Whether to exit after redirecting.
* @return bool Whether redirection was done. Naturally this is irrelevant if $exit is true.
*/
public static function ensure_proper_amp_location( $exit = true ) {
$has_query_var = false !== get_query_var( amp_get_slug(), false ); // May come from URL param or endpoint slug.
$has_url_param = isset( $_GET[ amp_get_slug() ] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( amp_is_canonical() || is_singular( AMP_Story_Post_Type::POST_TYPE_SLUG ) ) {
/*
* When AMP-first/canonical, then when there is an /amp/ endpoint or ?amp URL param,
* then a redirect needs to be done to the URL without any AMP indicator in the URL.
* Permanent redirect is used for unauthenticated users since switching between modes
* should happen infrequently. For admin users, this is kept temporary to allow them
* to not be hampered by browser remembering permanent redirects and preventing test.
*/
if ( $has_query_var || $has_url_param ) {
return self::redirect_non_amp_url( current_user_can( 'manage_options' ) ? 302 : 301, $exit );
}
} else {
/*
* When in AMP transitional mode *with* theme support, then the proper AMP URL has the 'amp' URL param
* and not the /amp/ endpoint. The URL param is now the exclusive way to mark AMP in transitional mode
* when amp theme support present. This is important for plugins to be able to reliably call
* is_amp_endpoint() before the parse_query action.
*/
if ( $has_query_var && ! $has_url_param ) {
$old_url = amp_get_current_url();
$new_url = add_query_arg( amp_get_slug(), '', amp_remove_endpoint( $old_url ) );
if ( $old_url !== $new_url ) {
// A temporary redirect is used for admin users to allow them to see changes between reader mode and transitional modes.
wp_safe_redirect( $new_url, current_user_can( 'manage_options' ) ? 302 : 301 );
// @codeCoverageIgnoreStart
if ( $exit ) {
exit;
}
return true;
// @codeCoverageIgnoreEnd
}
}
}
return false;
}
/**
* Redirect to non-AMP version of the current URL, such as because AMP is canonical or there are unaccepted validation errors.
*
* If the current URL is already AMP-less then do nothing.
*
* @since 0.7
* @since 1.0 Added $exit param.
* @since 1.0 Renamed from redirect_canonical_amp().
*
* @param int $status Status code (301 or 302).
* @param bool $exit Whether to exit after redirecting.
* @return bool Whether redirection was done. Naturally this is irrelevant if $exit is true.
*/
public static function redirect_non_amp_url( $status = 302, $exit = true ) {
$current_url = amp_get_current_url();
$non_amp_url = amp_remove_endpoint( $current_url );
if ( $non_amp_url === $current_url ) {
return false;
}
wp_safe_redirect( $non_amp_url, $status );
// @codeCoverageIgnoreStart
if ( $exit ) {
exit;
}
return true;
// @codeCoverageIgnoreEnd
}
/**
* Determines whether transitional mode is available.
*
* When 'amp' theme support has not been added or canonical mode is enabled, then this returns false.
*
* @since 0.7
*
* @see amp_is_canonical()
* @return bool Whether available.
*/
public static function is_paired_available() {
if ( ! current_theme_supports( self::SLUG ) ) {
return false;
}
if ( amp_is_canonical() ) {
return false;
}
$availability = self::get_template_availability();
return $availability['supported'];
}
/**
* Determine whether the user is in the Customizer preview iframe.
*
* @since 0.7
*
* @return bool Whether in Customizer preview iframe.
*/
public static function is_customize_preview_iframe() {
global $wp_customize;
return is_customize_preview() && $wp_customize->get_messenger_channel();
}
/**
* Register filters for loading AMP-specific templates.
*/
public static function add_amp_template_filters() {
foreach ( self::$template_types as $template_type ) {
// See get_query_template().
$template_type = preg_replace( '|[^a-z0-9-]+|', '', $template_type );
add_filter( "{$template_type}_template_hierarchy", [ __CLASS__, 'filter_amp_template_hierarchy' ] );
}
}
/**
* Determine template availability of AMP for the given query.
*
* This is not intended to return whether AMP is available for a _specific_ post. For that, use `post_supports_amp()`.
*
* @since 1.0
* @global WP_Query $wp_query
* @see post_supports_amp()
*
* @param WP_Query|WP_Post|null $query Query or queried post. If null then the global query will be used.
* @return array {
* Template availability.
*
* @type bool $supported Whether the template is supported in AMP.
* @type bool|null $immutable Whether the supported status is known to be unchangeable.
* @type string|null $template The ID of the matched template (conditional), such as 'is_singular', or null if nothing was matched.
* @type string[] $errors List of the errors or reasons for why the template is not available.
* }
*/
public static function get_template_availability( $query = null ) {
global $wp_query;
if ( ! $query ) {
$query = $wp_query;
} elseif ( $query instanceof WP_Post ) {
$post = $query;
$query = new WP_Query();
if ( 'page' === $post->post_type ) {
$query->set( 'page_id', $post->ID );
} else {
$query->set( 'p', $post->ID );
}
$query->queried_object = $post;
$query->queried_object_id = $post->ID;
$query->parse_query_vars();
}
$default_response = [
'errors' => [],
'supported' => false,
'immutable' => null,
'template' => null,
];
if ( ! ( $query instanceof WP_Query ) ) {
_doing_it_wrong( __METHOD__, esc_html__( 'No WP_Query available.', 'amp' ), '1.0' );
return array_merge(
$default_response,
[ 'errors' => [ 'no_query_available' ] ]
);
}
$theme_support_args = self::get_theme_support_args();
if ( false === $theme_support_args ) {
return array_merge(
$default_response,
[ 'errors' => [ 'no_theme_support' ] ]
);
}
// Support available_callback from 0.7, though it is deprecated.
if ( isset( $theme_support_args['available_callback'] ) && is_callable( $theme_support_args['available_callback'] ) ) {
/**
* Queried object.
*
* @var WP_Post $queried_object
*/
$queried_object = $query->get_queried_object();
if ( ( is_singular() || $query->is_posts_page ) && ! post_supports_amp( $queried_object ) ) {
return array_merge(
$default_response,
[
'errors' => [ 'no-post-support' ],
'supported' => false,
'immutable' => true,
]
);
}
$response = array_merge(
$default_response,
[
'supported' => call_user_func( $theme_support_args['available_callback'] ),
'immutable' => true,
]
);
if ( ! $response['supported'] ) {
$response['errors'][] = 'available_callback';
}
return $response;
}
$all_templates_supported_by_theme_support = false;
if ( isset( $theme_support_args['templates_supported'] ) ) {
$all_templates_supported_by_theme_support = 'all' === $theme_support_args['templates_supported'];
}
$all_templates_supported = (
$all_templates_supported_by_theme_support || AMP_Options_Manager::get_option( 'all_templates_supported' )
);
// Make sure global $wp_query is set in case of conditionals that unfortunately look at global scope.
$prev_query = $wp_query;
$wp_query = $query; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
$matching_templates = [];
$supportable_templates = self::get_supportable_templates();
foreach ( $supportable_templates as $id => $supportable_template ) {
if ( empty( $supportable_template['callback'] ) ) {
$callback = $id;
} else {
$callback = $supportable_template['callback'];
}
// If the callback is a method on the query, then call the method on the query itself.
if ( is_string( $callback ) && 'is_' === substr( $callback, 0, 3 ) && method_exists( $query, $callback ) ) {
$is_match = call_user_func( [ $query, $callback ] );
} elseif ( is_callable( $callback ) ) {
$is_match = $callback( $query );
} else {
/* translators: %s: the supportable template ID. */
_doing_it_wrong( __FUNCTION__, esc_html( sprintf( __( 'Supportable template "%s" does not have a callable callback.', 'amp' ), $id ) ), '1.0' );
$is_match = false;
}
if ( $is_match ) {
$matching_templates[ $id ] = [
'template' => $id,
'supported' => ! empty( $supportable_template['supported'] ),
'immutable' => ! empty( $supportable_template['immutable'] ),
];
}
}
// Restore previous $wp_query (if any).
$wp_query = $prev_query; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
// Make sure children override their parents.
$matching_template_ids = array_keys( $matching_templates );
foreach ( array_diff( array_keys( $supportable_templates ), $matching_template_ids ) as $template_id ) {
unset( $supportable_templates[ $template_id ] );
}
foreach ( $matching_template_ids as $id ) {
$has_children = false;
foreach ( $supportable_templates as $other_id => $supportable_template ) {
if ( $other_id === $id ) {
continue;
}
if ( isset( $supportable_template['parent'] ) && $id === $supportable_template['parent'] ) {
$has_children = true;
break;
}
}
// Delete all matching parent templates since the child will override them.
if ( ! $has_children ) {
$supportable_template = $supportable_templates[ $id ];
while ( ! empty( $supportable_template['parent'] ) ) {
$parent = $supportable_template['parent'];
/*
* If the parent is not amongst the supportable templates, then something is off in terms of hierarchy.
* Either the matching is off-track, or the template is badly configured.
*/
if ( ! array_key_exists( $parent, $supportable_templates ) ) {
_doing_it_wrong(
__METHOD__,
esc_html(
sprintf(
/* translators: %s: amp_supportable_templates */
__( 'An expected parent was not found. Did you filter %s to not honor the template hierarchy?', 'amp' ),
'amp_supportable_templates'
)
),
'1.4'
);
break;
}
$supportable_template = $supportable_templates[ $parent ];
// Let the child supported status override the parent's supported status.
unset( $matching_templates[ $parent ] );
}
}
}
// If there is more than 1 matching template, the is_home() condition is the default so discard it if there are other matching templates.
if ( count( $matching_templates ) > 1 && isset( $matching_templates['is_home'] ) ) {
unset( $matching_templates['is_home'] );
}
/*
* When there is still more than one matching template, account for ambiguous cases, informed by the order in template-loader.php.
* See <https://github.com/WordPress/wordpress-develop/blob/5.1.0/src/wp-includes/template-loader.php#L49-L68>.
*/
if ( count( $matching_templates ) > 1 ) {
$template_conditional_priority_order = [
'is_embed',
'is_404',
'is_search',
'is_front_page',
'is_home',
'is_post_type_archive',
'is_tax',
'is_attachment',
'is_single',
'is_page',
'is_singular',
'is_category',
'is_tag',
'is_author',
'is_date',
'is_archive',
];
// Obtain the template conditionals for each matching template ID (e.g. 'is_post_type_archive[product]' => 'is_post_type_archive').
$template_conditional_id_mapping = [];
foreach ( array_keys( $matching_templates ) as $template_id ) {
$template_conditional_id_mapping[ strtok( $template_id, '[' ) ] = $template_id;
}
// If there are any custom supportable templates, only consider them since they would override the conditional logic in core.
$custom_template_conditions = array_diff(
array_keys( $template_conditional_id_mapping ),
$template_conditional_priority_order
);
if ( ! empty( $custom_template_conditions ) ) {
$matching_templates = wp_array_slice_assoc(
$matching_templates,
array_values( wp_array_slice_assoc( $template_conditional_id_mapping, $custom_template_conditions ) )
);
} else {
/*
* Otherwise, iterate over the template conditionals in the order they occur in the if/elseif/else conditional chain.
* to then populate $matching_templates with just this one entry.
*/
foreach ( $template_conditional_priority_order as $template_conditional ) {
if ( isset( $template_conditional_id_mapping[ $template_conditional ] ) ) {
$template_id = $template_conditional_id_mapping[ $template_conditional ];
$matching_templates = [
$template_id => $matching_templates[ $template_id ],
];
break;
}
}
}
}
/*
* If there are more than one matching templates, then something is probably not right.
* Template conditions need to be set up properly to prevent this from happening.
*/
if ( count( $matching_templates ) > 1 ) {
_doing_it_wrong(
__METHOD__,
esc_html(
sprintf(
/* translators: %s: amp_supportable_templates */
__( 'Did not expect there to be more than one matching template. Did you filter %s to not honor the template hierarchy?', 'amp' ),
'amp_supportable_templates'
)
),
'1.0'
);
}
$matching_template = array_shift( $matching_templates );
// If there aren't any matching templates left that are supported, then we consider it to not be available.
if ( ! $matching_template ) {
if ( $all_templates_supported ) {
return array_merge(
$default_response,
[
'supported' => true,
]
);
}
return array_merge(
$default_response,
[ 'errors' => [ 'no_matching_template' ] ]
);
}
$matching_template = array_merge( $default_response, $matching_template );
// If there aren't any matching templates left that are supported, then we consider it to not be available.
if ( empty( $matching_template['supported'] ) ) {
$matching_template['errors'][] = 'template_unsupported';
}
// For singular queries, post_supports_amp() is given the final say.
if ( $query->is_singular() || $query->is_posts_page ) {
/**
* Queried object.
*
* @var WP_Post $queried_object
*/
$queried_object = $query->get_queried_object();
if ( $queried_object instanceof WP_Post ) {
$support_errors = AMP_Post_Type_Support::get_support_errors( $queried_object );
if ( ! empty( $support_errors ) ) {
$matching_template['errors'] = array_merge( $matching_template['errors'], $support_errors );
$matching_template['supported'] = false;
}
}
}
return $matching_template;
}
/**
* Get the templates which can be supported.
*
* @return array Supportable templates.
*/
public static function get_supportable_templates() {
$templates = [
'is_singular' => [
'label' => __( 'Singular', 'amp' ),
'description' => __( 'Required for the above content types.', 'amp' ),
],
];
if ( 'page' === get_option( 'show_on_front' ) ) {
$templates['is_front_page'] = [
'label' => __( 'Homepage', 'amp' ),
'parent' => 'is_singular',
];
if ( AMP_Post_Meta_Box::DISABLED_STATUS === get_post_meta( get_option( 'page_on_front' ), AMP_Post_Meta_Box::STATUS_POST_META_KEY, true ) ) {
/* translators: %s: the URL to the edit post screen. */
$templates['is_front_page']['description'] = sprintf( __( 'Currently disabled at the <a href="%s">page level</a>.', 'amp' ), esc_url( get_edit_post_link( get_option( 'page_on_front' ) ) ) );
}
// In other words, same as is_posts_page, *but* it not is_singular.
$templates['is_home'] = [
'label' => __( 'Blog', 'amp' ),
];
if ( AMP_Post_Meta_Box::DISABLED_STATUS === get_post_meta( get_option( 'page_for_posts' ), AMP_Post_Meta_Box::STATUS_POST_META_KEY, true ) ) {
/* translators: %s: the URL to the edit post screen. */
$templates['is_home']['description'] = sprintf( __( 'Currently disabled at the <a href="%s">page level</a>.', 'amp' ), esc_url( get_edit_post_link( get_option( 'page_for_posts' ) ) ) );
}
} else {
$templates['is_home'] = [
'label' => __( 'Homepage', 'amp' ),
];
}
$templates = array_merge(
$templates,
[
'is_archive' => [
'label' => __( 'Archives', 'amp' ),
],
'is_author' => [
'label' => __( 'Author', 'amp' ),
'parent' => 'is_archive',
],
'is_date' => [
'label' => __( 'Date', 'amp' ),
'parent' => 'is_archive',
],
'is_search' => [
'label' => __( 'Search', 'amp' ),
],
'is_404' => [
'label' => __( 'Not Found (404)', 'amp' ),
],
]
);
if ( taxonomy_exists( 'category' ) ) {
$templates['is_category'] = [
'label' => get_taxonomy( 'category' )->labels->name,
'parent' => 'is_archive',
];
}
if ( taxonomy_exists( 'post_tag' ) ) {
$templates['is_tag'] = [
'label' => get_taxonomy( 'post_tag' )->labels->name,
'parent' => 'is_archive',
];
}
$taxonomy_args = [
'_builtin' => false,
'public' => true,
];
foreach ( get_taxonomies( $taxonomy_args, 'objects' ) as $taxonomy ) {
$templates[ sprintf( 'is_tax[%s]', $taxonomy->name ) ] = [
'label' => $taxonomy->labels->name,
'parent' => 'is_archive',
'callback' => static function ( WP_Query $query ) use ( $taxonomy ) {
return $query->is_tax( $taxonomy->name );
},
];
}
$post_type_args = [
'has_archive' => true,
'public' => true,
];
foreach ( get_post_types( $post_type_args, 'objects' ) as $post_type ) {
$templates[ sprintf( 'is_post_type_archive[%s]', $post_type->name ) ] = [
'label' => $post_type->labels->archives,
'parent' => 'is_archive',
'callback' => static function ( WP_Query $query ) use ( $post_type ) {
return $query->is_post_type_archive( $post_type->name );
},
];
}
/**
* Filters list of supportable templates.
*
* A theme or plugin can force a given template to be supported or not by preemptively
* setting the 'supported' flag for a given template. Otherwise, if the flag is undefined
* then the user will be able to toggle it themselves in the admin. Each array item should
* have a key that corresponds to a template conditional function. If the key is such a
* function, then the key is used to evaluate whether the given template entry is a match.
* Otherwise, a supportable template item can include a callback value which is used instead.
* Each item needs a 'label' value. Additionally, if the supportable template is a subset of
* another condition (e.g. is_singular > is_single) then this relationship needs to be
* indicated via the 'parent' value.
*
* @since 1.0
*
* @param array $templates Supportable templates.
*/
$templates = apply_filters( 'amp_supportable_templates', $templates );
$theme_support_args = self::get_theme_support_args();
$theme_supported_templates = [];
if ( isset( $theme_support_args['templates_supported'] ) ) {
$theme_supported_templates = $theme_support_args['templates_supported'];
}
$supported_templates = AMP_Options_Manager::get_option( 'supported_templates' );
foreach ( $templates as $id => &$template ) {
// Capture user-elected support from options. This allows us to preserve the original user selection through programmatic overrides.