-
Notifications
You must be signed in to change notification settings - Fork 383
/
amp-helper-functions.php
1985 lines (1789 loc) · 62.9 KB
/
amp-helper-functions.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
/**
* AMP Helper Functions
*
* @package AMP
*/
use AmpProject\AmpWP\Admin\ReaderThemes;
use AmpProject\AmpWP\AmpWpPluginFactory;
use AmpProject\AmpWP\Icon;
use AmpProject\AmpWP\Option;
use AmpProject\AmpWP\QueryVar;
use AmpProject\AmpWP\Services;
/**
* Handle activation of plugin.
*
* @since 0.2
* @internal
*
* @param bool $network_wide Whether the activation was done network-wide.
*/
function amp_activate( $network_wide = false ) {
AmpWpPluginFactory::create()->activate( $network_wide );
amp_after_setup_theme();
if ( ! did_action( 'amp_init' ) ) {
amp_init();
}
flush_rewrite_rules();
}
/**
* Handle deactivation of plugin.
*
* @since 0.2
* @internal
*
* @param bool $network_wide Whether the activation was done network-wide.
*/
function amp_deactivate( $network_wide = false ) {
AmpWpPluginFactory::create()->deactivate( $network_wide );
// We need to manually remove the amp endpoint.
global $wp_rewrite;
foreach ( $wp_rewrite->endpoints as $index => $endpoint ) {
if ( amp_get_slug() === $endpoint[1] ) {
unset( $wp_rewrite->endpoints[ $index ] );
break;
}
}
flush_rewrite_rules( false );
}
/**
* Bootstrap plugin.
*
* @since 1.5
* @internal
*/
function amp_bootstrap_plugin() {
/**
* Filters whether AMP is enabled on the current site.
*
* Useful if the plugin is network activated and you want to turn it off on select sites.
*
* @since 0.2
* @since 2.0 Filter now runs earlier at plugins_loaded (with earliest priority) rather than at the after_setup_theme action.
*/
if ( false === apply_filters( 'amp_is_enabled', true ) ) {
return;
}
AmpWpPluginFactory::create()->register();
// The amp_bootstrap_plugin() function is called at the plugins_loaded action with the earliest priority. This is
// the earliest we can run this since that is when pluggable.php has been required and wp_hash() is available.
AMP_Validation_Manager::init_validate_request();
/*
* Register AMP scripts regardless of whether AMP is enabled or it is the AMP endpoint
* for the sake of being able to use AMP components on non-AMP documents ("dirty AMP").
*/
add_action( 'wp_default_scripts', 'amp_register_default_scripts' );
add_action( 'wp_default_styles', 'amp_register_default_styles' );
// Ensure async and custom-element/custom-template attributes are present on script tags.
add_filter( 'script_loader_tag', 'amp_filter_script_loader_tag', PHP_INT_MAX, 2 );
// Ensure crossorigin=anonymous is added to font links.
add_filter( 'style_loader_tag', 'amp_filter_font_style_loader_tag_with_crossorigin_anonymous', 10, 4 );
add_action( 'after_setup_theme', 'amp_after_setup_theme', 5 );
add_action( 'plugins_loaded', '_amp_bootstrap_customizer', 9 ); // Should be hooked before priority 10 on 'plugins_loaded' to properly unhook core panels.
}
/**
* Init AMP.
*
* @since 0.1
* @internal
*/
function amp_init() {
/**
* Triggers on init when AMP plugin is active.
*
* @since 0.3
*/
do_action( 'amp_init' );
add_filter( 'allowed_redirect_hosts', [ 'AMP_HTTP', 'filter_allowed_redirect_hosts' ] );
AMP_HTTP::purge_amp_query_vars();
AMP_HTTP::send_cors_headers();
AMP_HTTP::handle_xhr_request();
AMP_Theme_Support::init();
AMP_Validation_Manager::init();
AMP_Service_Worker::init();
add_action( 'admin_init', 'AMP_Options_Manager::init' );
add_action( 'admin_init', 'AMP_Options_Manager::register_settings' );
add_action( 'rest_api_init', 'AMP_Options_Manager::register_settings' );
add_action( 'wp_loaded', 'amp_bootstrap_admin' );
add_rewrite_endpoint( amp_get_slug(), EP_PERMALINK );
add_action( 'parse_query', 'amp_correct_query_when_is_front_page' );
add_action( 'admin_bar_menu', 'amp_add_admin_bar_view_link', 100 );
add_action(
'admin_bar_init',
function () {
$handle = 'amp-icons';
if ( ! is_admin() && wp_style_is( $handle, 'registered' ) ) {
wp_styles()->registered[ $handle ]->deps[] = 'admin-bar'; // Ensure included in dev mode.
wp_enqueue_style( $handle );
}
}
);
add_action( 'wp_loaded', 'amp_editor_core_blocks' );
add_filter( 'request', 'amp_force_query_var_value' );
// Redirect the old url of amp page to the updated url.
add_filter( 'old_slug_redirect_url', 'amp_redirect_old_slug_to_new_url' );
if ( defined( 'WP_CLI' ) && WP_CLI ) {
if ( class_exists( 'WP_CLI\Dispatcher\CommandNamespace' ) ) {
WP_CLI::add_command( 'amp', 'AMP_CLI_Namespace' );
}
WP_CLI::add_command( 'amp validation', 'AMP_CLI_Validation_Command' );
}
/*
* Broadcast plugin updates.
* Note that AMP_Options_Manager::get_option( Option::VERSION, '0.0' ) cannot be used because
* version was new option added, and in that case default would never be used for a site
* upgrading from a version prior to 1.0. So this is why get_option() is currently used.
*/
$options = get_option( AMP_Options_Manager::OPTION_NAME, [] );
$old_version = isset( $options[ Option::VERSION ] ) ? $options[ Option::VERSION ] : '0.0';
if ( AMP__VERSION !== $old_version && is_admin() && current_user_can( 'manage_options' ) ) {
// This waits to happen until the very end of init to ensure that amp theme support and amp post type support have all been added.
add_action(
'init',
static function () use ( $old_version ) {
/**
* Triggers when after amp_init when the plugin version has updated.
*
* @param string $old_version Old version.
*/
do_action( 'amp_plugin_update', $old_version );
AMP_Options_Manager::update_option( Option::VERSION, AMP__VERSION );
},
PHP_INT_MAX
);
}
add_action(
'rest_api_init',
static function() {
$reader_themes = new ReaderThemes();
$reader_theme_controller = new AMP_Reader_Theme_REST_Controller( $reader_themes );
$reader_theme_controller->register_routes();
}
);
/*
* Hide admin bar if the window is inside the setup wizard iframe.
*
* Detects whether the current window is in an iframe with the specified `name` attribute. The iframe is created
* by Preview component located in <assets/src/setup/pages/save/index.js>.
*/
add_action(
'wp_print_scripts',
function() {
if ( ! amp_is_dev_mode() || ! is_admin_bar_showing() ) {
return;
}
?>
<script data-ampdevmode>
( () => {
if ( 'amp-wizard-completion-preview' !== window.name ) {
return;
}
/** @type {HTMLStyleElement} */
const style = document.createElement( 'style' );
style.setAttribute( 'type', 'text/css' );
style.appendChild( document.createTextNode( 'html { margin-top: 0 !important; } #wpadminbar { display: none !important; }' ) );
document.head.appendChild( style );
document.addEventListener( 'DOMContentLoaded', function() {
const adminBar = document.getElementById( 'wpadminbar' );
if ( adminBar ) {
document.body.classList.remove( 'admin-bar' );
adminBar.remove();
}
});
} )();
</script>
<?php
}
);
}
/**
* Set up AMP.
*
* This function must be invoked through the 'after_setup_theme' action to allow
* the AMP setting to declare the post types support earlier than plugins/theme.
*
* @since 0.6
* @internal
*/
function amp_after_setup_theme() {
// Ensure AMP_QUERY_VAR is set since some plugins still try reading it instead of using amp_get_slug().
if ( ! defined( 'AMP_QUERY_VAR' ) ) {
define( 'AMP_QUERY_VAR', amp_get_slug() );
}
/** This filter is documented in includes/amp-helper-functions.php */
if ( false === apply_filters( 'amp_is_enabled', true ) ) {
_doing_it_wrong(
'add_filter',
esc_html(
sprintf(
/* translators: 1: amp_is_enabled filter name, 2: plugins_loaded action */
__( 'Filter for "%1$s" added too late. To disable AMP, this filter must be added before the "%2$s" action.', 'amp' ),
'amp_is_enabled',
'plugins_loaded'
)
),
'2.0'
);
}
add_action( 'init', 'amp_init', 0 ); // Must be 0 because widgets_init happens at init priority 1.
}
/**
* Make sure the `amp` query var has an explicit value.
*
* This avoids issues when filtering the deprecated `query_string` hook.
*
* @since 0.3.3
* @internal
*
* @param array $query_vars Query vars.
* @return array Query vars.
*/
function amp_force_query_var_value( $query_vars ) {
if ( isset( $query_vars[ amp_get_slug() ] ) && '' === $query_vars[ amp_get_slug() ] ) {
$query_vars[ amp_get_slug() ] = 1;
}
return $query_vars;
}
/**
* Fix up WP_Query for front page when amp query var is present.
*
* Normally the front page would not get served if a query var is present other than preview, page, paged, and cpage.
*
* @since 0.6
* @internal
* @see WP_Query::parse_query()
* @link https://github.com/WordPress/wordpress-develop/blob/0baa8ae85c670d338e78e408f8d6e301c6410c86/src/wp-includes/class-wp-query.php#L951-L971
*
* @param WP_Query $query Query.
*/
function amp_correct_query_when_is_front_page( WP_Query $query ) {
$is_front_page_query = (
$query->is_main_query()
&&
$query->is_home()
&&
// Is AMP endpoint.
false !== $query->get( amp_get_slug(), false )
&&
// Is query not yet fixed uo up to be front page.
! $query->is_front_page()
&&
// Is showing pages on front.
'page' === get_option( 'show_on_front' )
&&
// Has page on front set.
get_option( 'page_on_front' )
&&
// See line in WP_Query::parse_query() at <https://github.com/WordPress/wordpress-develop/blob/0baa8ae/src/wp-includes/class-wp-query.php#L961>.
0 === count( array_diff( array_keys( wp_parse_args( $query->query ) ), [ amp_get_slug(), 'preview', 'page', 'paged', 'cpage' ] ) )
);
if ( $is_front_page_query ) {
$query->is_home = false;
$query->is_page = true;
$query->is_singular = true;
$query->set( 'page_id', get_option( 'page_on_front' ) );
}
}
/**
* Whether this is in 'canonical mode'.
*
* Themes can register support for this with `add_theme_support( AMP_Theme_Support::SLUG )`:
*
* add_theme_support( AMP_Theme_Support::SLUG );
*
* This will serve templates in AMP-first, allowing you to use AMP components in your theme templates.
* If you want to make available in transitional mode, where templates are served in AMP or non-AMP documents, do:
*
* add_theme_support( AMP_Theme_Support::SLUG, array(
* 'paired' => true,
* ) );
*
* Transitional mode is also implied if you define a template_dir:
*
* add_theme_support( AMP_Theme_Support::SLUG, array(
* 'template_dir' => 'amp',
* ) );
*
* If you want to have AMP-specific templates in addition to serving AMP-first, do:
*
* add_theme_support( AMP_Theme_Support::SLUG, array(
* 'paired' => false,
* 'template_dir' => 'amp',
* ) );
*
* If you want to force AMP to always be served on a given template, you can use the templates_supported arg,
* for example to always serve the Category template in AMP:
*
* add_theme_support( AMP_Theme_Support::SLUG, array(
* 'templates_supported' => array(
* 'is_category' => true,
* ),
* ) );
*
* Or if you want to force AMP to be used on all templates:
*
* add_theme_support( AMP_Theme_Support::SLUG, array(
* 'templates_supported' => 'all',
* ) );
*
* @see AMP_Theme_Support::read_theme_support()
* @return boolean Whether this is in AMP 'canonical' mode, that is whether it is AMP-first and there is not a separate (paired) AMP URL.
*/
function amp_is_canonical() {
return AMP_Theme_Support::STANDARD_MODE_SLUG === AMP_Options_Manager::get_option( Option::THEME_SUPPORT );
}
/**
* Determines whether the legacy AMP post templates are being used.
*
* @since 2.0
* @return bool
*/
function amp_is_legacy() {
if ( AMP_Theme_Support::READER_MODE_SLUG !== AMP_Options_Manager::get_option( Option::THEME_SUPPORT ) ) {
return false;
}
$reader_theme = AMP_Options_Manager::get_option( Option::READER_THEME );
if ( ReaderThemes::DEFAULT_READER_THEME === $reader_theme ) {
return true;
}
return ! wp_get_theme( $reader_theme )->exists();
}
/**
* Add frontend actions.
*
* @since 0.2
* @internal
*/
function amp_add_frontend_actions() {
add_action( 'wp_head', 'amp_add_amphtml_link' );
}
/**
* Determine whether AMP is available for the current URL.
*
* @since 2.0
*
* @return bool Whether there is an AMP version for the provided URL.
* @global string $pagenow
* @global WP_Query $wp_query
*/
function amp_is_available() {
global $pagenow, $wp_query;
// Short-circuit for admin requests or requests to non-frontend pages.
if ( is_admin() || in_array( $pagenow, [ 'wp-login.php', 'wp-signup.php', 'wp-activate.php', 'repair.php' ], true ) ) {
return false;
}
$warn = static function () {
static $already_warned_sources = [];
$likely_culprit_detector = Services::get( 'dev_tools.likely_culprit_detector' );
$closest_source = $likely_culprit_detector->analyze_backtrace();
$closest_source_identifier = $closest_source['type'] . ':' . $closest_source['name'];
if ( in_array( $closest_source_identifier, $already_warned_sources, true ) ) {
return;
}
$message = sprintf(
/* translators: 1: amp_is_available() function, 2: amp_is_request() function, 3: is_amp_endpoint() function */
__( '%1$s (or %2$s, formerly %3$s) was called too early and so it will not work properly.', 'amp' ),
'`amp_is_available()`',
'`amp_is_request()`',
'`is_amp_endpoint()`'
);
$message .= ' ' . sprintf(
/* translators: 1: the current hook, 2: the wp action, 4: the WP_Query class, 4: the amp_skip_post() function */
__( 'WordPress is currently doing the %1$s hook. Calling this function before the %2$s action means it will not have access to %3$s and the queried object to determine if it is an AMP response, thus neither the %4$s filter nor the AMP enabled toggle will be considered.', 'amp' ),
'`' . current_action() . '`',
'`wp`',
'`WP_Query`',
'`amp_skip_post()`'
);
if ( ! empty( $closest_source['type'] ) && ! empty( $closest_source['name'] ) ) {
$translated_string = false;
switch ( $closest_source['type'] ) {
case 'plugin':
/* translators: placeholder is the slug of the plugin */
$translated_string = __( 'It appears the plugin with slug %s is responsible; please contact the author.', 'amp' );
break;
case 'mu-plugin':
/* translators: placeholder is the slug of the must-use plugin */
$translated_string = __( 'It appears the must-use plugin with slug %s is responsible; please contact the author.', 'amp' );
break;
case 'theme':
/* translators: placeholder is the slug of the theme */
$translated_string = __( 'It appears the theme with slug %s is responsible; please contact the author.', 'amp' );
break;
}
if ( $translated_string ) {
$message .= ' ' . sprintf( $translated_string, '`' . $closest_source['name'] . '`' );
}
}
_doing_it_wrong( 'amp_is_available', esc_html( $message ), '2.0.0' );
$already_warned_sources[] = $closest_source_identifier;
};
// Make sure the parse_request action has triggered before trying to read from the REST_REQUEST constant, which is set during rest_api_loaded().
if ( ! did_action( 'parse_request' ) ) {
$warn();
} elseif ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
return false;
}
// Make sure that the parse_query action has triggered, as this is required to initially populate the global WP_Query.
if ( ! ( $wp_query instanceof WP_Query || did_action( 'parse_query' ) ) ) {
$warn();
}
// Always return false when requesting the service worker.
// Note this is no longer strictly required because AMP_Theme_Support::prepare_response() will abort for non-HTML responses.
// But it is still good to do so because it avoids needlessly output-buffering the response.
if ( class_exists( 'WP_Service_Workers' ) && $wp_query instanceof WP_Query && defined( 'WP_Service_Workers::QUERY_VAR' ) && $wp_query->get( WP_Service_Workers::QUERY_VAR ) ) {
return false;
}
// Short-circuit queries that can never have AMP responses (e.g. post embeds and feeds).
// Note that these conditionals only require the parse_query action to have been run. They don't depend on the wp action having been fired.
if (
$wp_query instanceof WP_Query
&&
(
$wp_query->is_embed()
||
$wp_query->is_feed()
||
$wp_query->is_comment_feed()
||
$wp_query->is_trackback()
||
$wp_query->is_robots()
||
( method_exists( $wp_query, 'is_favicon' ) && $wp_query->is_favicon() )
)
) {
return false;
}
// Ensure that all templates can be accessed in AMP when a Reader theme is selected.
$has_reader_theme = (
AMP_Theme_Support::READER_MODE_SLUG === AMP_Options_Manager::get_option( Option::THEME_SUPPORT )
&&
ReaderThemes::DEFAULT_READER_THEME !== AMP_Options_Manager::get_option( Option::READER_THEME )
);
if ( $has_reader_theme && is_customize_preview() ) {
return true;
}
$is_legacy = amp_is_legacy();
// If the query has not been initialized, we can only assume AMP is available if theme support is present and all templates are supported.
if ( ! $wp_query instanceof WP_Query || ! did_action( 'wp' ) ) {
$warn();
return ! $is_legacy && AMP_Options_Manager::get_option( Option::ALL_TEMPLATES_SUPPORTED );
}
// If redirected to this page because AMP is not available due to validation errors, prevent AMP from being available (if not AMP-first).
if (
( ! amp_is_canonical() || AMP_Validation_Manager::has_cap() )
&&
( isset( $_GET[ QueryVar::NOAMP ] ) && QueryVar::NOAMP_AVAILABLE === $_GET[ QueryVar::NOAMP ] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
) {
return false;
}
/*
* If this is a URL for validation, and validation is forced for all URLs, return true.
* Normally, this would be false if the user has deselected a template,
* like by unchecking 'Categories' in 'AMP Settings' > 'Supported Templates'.
* But there's a flag for the WP-CLI command that sets this query var to validate all URLs.
*/
if ( AMP_Validation_Manager::is_theme_support_forced() ) {
return true;
}
$queried_object = get_queried_object();
if ( ! $is_legacy ) {
// Abort if in Transitional mode and AMP is not available for the URL.
$availability = AMP_Theme_Support::get_template_availability( $wp_query );
if ( ! $availability['supported'] ) {
return false;
}
// If not in an AMP-first mode, check if there are any validation errors with kept invalid markup for this URL.
// And if so, and if the user cannot do validation (since they can always get fresh validation results), then
// AMP is not available.
if ( ! amp_is_canonical() && ! AMP_Validation_Manager::has_cap() ) {
$validation_errors = AMP_Validated_URL_Post_Type::get_invalid_url_validation_errors(
amp_get_current_url(),
[ 'ignore_accepted' => true ]
);
if ( count( $validation_errors ) > 0 ) {
return false;
}
}
} elseif ( ! (
$queried_object instanceof WP_Post &&
$wp_query instanceof WP_Query &&
( $wp_query->is_singular() || $wp_query->is_posts_page ) &&
amp_is_post_supported( $queried_object ) )
) {
// Abort if in legacy Reader mode and the post doesn't support AMP.
return false;
}
return true;
}
/**
* Bootstraps the AMP customizer.
*
* Uses the priority of 12 for the 'after_setup_theme' action.
* Many themes run `add_theme_support()` on the 'after_setup_theme' hook, at the default priority of 10.
* And that function's documentation suggests adding it to that action.
* So this enables themes to `add_theme_support( AMP_Theme_Support::SLUG )`.
* And `amp_init_customizer()` will be able to recognize theme support by calling `amp_is_canonical()`.
*
* @since 0.4
* @internal
*/
function _amp_bootstrap_customizer() {
add_action( 'after_setup_theme', 'amp_init_customizer', 12 );
}
/**
* Redirects the old AMP URL to the new AMP URL.
*
* If post slug is updated the amp page with old post slug will be redirected to the updated url.
*
* @since 0.5
* @internal
*
* @param string $link New URL of the post.
* @return string URL to be redirected.
*/
function amp_redirect_old_slug_to_new_url( $link ) {
if ( amp_is_request() && ! amp_is_canonical() ) {
if ( ! amp_is_legacy() ) {
$link = add_query_arg( amp_get_slug(), '', $link );
} else {
$link = trailingslashit( trailingslashit( $link ) . amp_get_slug() );
}
}
return $link;
}
/**
* Get the slug used in AMP for the query var, endpoint, and post type support.
*
* The return value can be overridden by previously defining a AMP_QUERY_VAR
* constant or by adding a 'amp_query_var' filter, but *warning* this ability
* may be deprecated in the future. Normally the slug should be just 'amp'.
*
* @since 0.7
*
* @return string Slug used for query var, endpoint, and post type support.
*/
function amp_get_slug() {
/**
* Filter the AMP query variable.
*
* Warning: This filter may become deprecated.
*
* @since 0.3.2
*
* @param string $query_var The AMP query variable.
*/
return apply_filters( 'amp_query_var', defined( 'AMP_QUERY_VAR' ) ? AMP_QUERY_VAR : QueryVar::AMP );
}
/**
* Get the URL for the current request.
*
* This is essentially the REQUEST_URI prefixed by the scheme and host for the home URL.
* This is needed in particular due to subdirectory installs.
*
* @since 1.0
* @internal
*
* @return string Current URL.
*/
function amp_get_current_url() {
$parsed_url = wp_parse_url( home_url() );
if ( ! is_array( $parsed_url ) ) {
$parsed_url = [];
}
if ( empty( $parsed_url['scheme'] ) ) {
$parsed_url['scheme'] = is_ssl() ? 'https' : 'http';
}
if ( ! isset( $parsed_url['host'] ) ) {
$parsed_url['host'] = isset( $_SERVER['HTTP_HOST'] ) ? wp_unslash( $_SERVER['HTTP_HOST'] ) : 'localhost';
}
$current_url = $parsed_url['scheme'] . '://';
if ( isset( $parsed_url['user'] ) ) {
$current_url .= $parsed_url['user'];
if ( isset( $parsed_url['pass'] ) ) {
$current_url .= ':' . $parsed_url['pass'];
}
$current_url .= '@';
}
$current_url .= $parsed_url['host'];
if ( isset( $parsed_url['port'] ) ) {
$current_url .= ':' . $parsed_url['port'];
}
$current_url .= '/';
if ( isset( $_SERVER['REQUEST_URI'] ) ) {
$current_url .= ltrim( wp_unslash( $_SERVER['REQUEST_URI'] ), '/' );
}
return esc_url_raw( $current_url );
}
/**
* Retrieves the full AMP-specific permalink for the given post ID.
*
* @since 0.1
*
* @param int $post_id Post ID.
* @return string AMP permalink.
*/
function amp_get_permalink( $post_id ) {
// When theme support is present (i.e. not using legacy Reader post templates), the plain query var should always be used.
if ( ! amp_is_legacy() ) {
$permalink = get_permalink( $post_id );
if ( ! amp_is_canonical() ) {
$permalink = add_query_arg( amp_get_slug(), '', $permalink );
}
return $permalink;
}
/**
* Filters the AMP permalink to short-circuit normal generation.
*
* Returning a non-false value in this filter will cause the `get_permalink()` to get called and the `amp_get_permalink` filter to not apply.
*
* @since 0.4
* @since 1.0 This filter does not apply when 'amp' theme support is present.
*
* @param false $url Short-circuited URL.
* @param int $post_id Post ID.
*/
$pre_url = apply_filters( 'amp_pre_get_permalink', false, $post_id );
if ( false !== $pre_url ) {
return $pre_url;
}
$permalink = get_permalink( $post_id );
if ( amp_is_canonical() ) {
$amp_url = $permalink;
} else {
$parsed_url = wp_parse_url( get_permalink( $post_id ) );
$structure = get_option( 'permalink_structure' );
$use_query_var = (
// If pretty permalinks aren't available, then query var must be used.
empty( $structure )
||
// If there are existing query vars, then always use the amp query var as well.
! empty( $parsed_url['query'] )
||
// If the post type is hierarchical then the /amp/ endpoint isn't available.
is_post_type_hierarchical( get_post_type( $post_id ) )
||
// Attachment pages don't accept the /amp/ endpoint.
'attachment' === get_post_type( $post_id )
);
if ( $use_query_var ) {
$amp_url = add_query_arg( amp_get_slug(), '', $permalink );
} else {
$amp_url = preg_replace( '/#.*/', '', $permalink );
$amp_url = trailingslashit( $amp_url ) . user_trailingslashit( amp_get_slug(), 'single_amp' );
if ( ! empty( $parsed_url['fragment'] ) ) {
$amp_url .= '#' . $parsed_url['fragment'];
}
}
}
/**
* Filters AMP permalink.
*
* @since 0.2
* @since 1.0 This filter does not apply when 'amp' theme support is present.
*
* @param false $amp_url AMP URL.
* @param int $post_id Post ID.
*/
return apply_filters( 'amp_get_permalink', $amp_url, $post_id );
}
/**
* Remove the AMP endpoint (and query var) from a given URL.
*
* @since 0.7
*
* @param string $url URL.
* @return string URL with AMP stripped.
*/
function amp_remove_endpoint( $url ) {
// Strip endpoint.
$url = preg_replace( ':/' . preg_quote( amp_get_slug(), ':' ) . '(?=/?(\?|#|$)):', '', $url );
// Strip query var.
$url = remove_query_arg( amp_get_slug(), $url );
return $url;
}
/**
* Add amphtml link.
*
* If there are known validation errors for the current URL then do not output anything.
*
* @since 1.0
*/
function amp_add_amphtml_link() {
if (
amp_is_canonical()
||
/**
* Filters whether to show the amphtml link on the frontend.
*
* This is deprecated since the name was wrong and the use case is not clear. To remove this from being printed,
* instead of using the filter you can rather do:
*
* add_action( 'template_redirect', static function () {
* remove_action( 'wp_head', 'amp_add_amphtml_link' );
* } );
*
* @since 0.2
* @deprecated Remove amp_add_amphtml_link() call on wp_head action instead.
*/
false === apply_filters_deprecated(
'amp_frontend_show_canonical',
[ true ],
'2.0',
'',
sprintf(
/* translators: 1: amphtml, 2: amp_add_amphtml_link(), 3: wp_head, 4: template_redirect */
esc_html__( 'Removal of %1$s link should be done by removing %2$s from the %3$s action at %4$s.', 'amp' ),
'amphtml',
__FUNCTION__ . '()',
'wp_head',
'template_redirect'
)
)
) {
return;
}
if ( ! amp_is_available() ) {
printf( '<!-- %s -->', esc_html__( 'There is no amphtml version available for this URL.', 'amp' ) );
return;
}
if ( AMP_Theme_Support::is_paired_available() ) {
$amp_url = add_query_arg( amp_get_slug(), '', amp_get_current_url() );
} else {
$amp_url = amp_get_permalink( get_queried_object_id() );
}
if ( $amp_url ) {
$amp_url = remove_query_arg( QueryVar::NOAMP, $amp_url );
printf( '<link rel="amphtml" href="%s">', esc_url( $amp_url ) );
}
}
/**
* Determine whether a given post supports AMP.
*
* @since 2.0 Formerly known as post_supports_amp().
* @see AMP_Post_Type_Support::get_support_errors()
*
* @param WP_Post $post Post.
* @return bool Whether the post supports AMP.
*/
function amp_is_post_supported( $post ) {
return 0 === count( AMP_Post_Type_Support::get_support_errors( $post ) );
}
/**
* Determine whether a given post supports AMP.
*
* @since 0.1
* @since 0.6 Returns false when post has meta to disable AMP.
* @since 2.0 Renamed to AMP-prefixed version, amp_is_post_supported().
* @deprecated Use amp_is_post_supported() instead.
*
* @param WP_Post $post Post.
* @return bool Whether the post supports AMP.
*/
function post_supports_amp( $post ) {
return amp_is_post_supported( $post );
}
/**
* Determine whether the current request is for an AMP page.
*
* This function cannot be called before the parse_query action because it needs to be able
* to determine the queried object is able to be served as AMP. If 'amp' theme support is not
* present, this function returns true just if the query var is present. If theme support is
* present, then it returns true in transitional mode if an AMP template is available and the query
* var is present, or else in standard mode if just the template is available.
*
* @since 2.0 Formerly known as is_amp_endpoint().
*
* @return bool Whether it is the AMP endpoint.
* @global WP_Query $wp_query
*/
function amp_is_request() {
global $wp_query;
if ( AMP_Validation_Manager::$is_validate_request ) {
return true;
}
$is_amp_url = (
amp_is_canonical()
||
isset( $_GET[ amp_get_slug() ] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
||
(
$wp_query instanceof WP_Query
&&
false !== $wp_query->get( amp_get_slug(), false )
)
);
// If AMP is not available, then it's definitely not an AMP endpoint.
if ( ! amp_is_available() ) {
// But, if WP_Query was not available yet, then we will just assume the query is supported since at this point we do
// know either that the site is in Standard mode or the URL was requested with the AMP query var. This can still
// produce an undesired result when a Standard mode site has a post that opts out of AMP, but this issue will
// have been flagged via _doing_it_wrong() in amp_is_available() above.
if ( ! did_action( 'wp' ) || ! $wp_query instanceof WP_Query ) {
return $is_amp_url && AMP_Options_Manager::get_option( Option::ALL_TEMPLATES_SUPPORTED );
}
return false;
}
return $is_amp_url;
}
/**
* Determine whether the current response being served as AMP.
*
* This function cannot be called before the parse_query action because it needs to be able
* to determine the queried object is able to be served as AMP. If 'amp' theme support is not
* present, this function returns true just if the query var is present. If theme support is
* present, then it returns true in transitional mode if an AMP template is available and the query
* var is present, or else in standard mode if just the template is available.
*
* @since 0.1
* @since 2.0 Renamed to AMP-prefixed version, amp_is_request().
* @deprecated Use amp_is_request() instead.
*
* @return bool Whether it is the AMP endpoint.
*/
function is_amp_endpoint() {
return amp_is_request();
}
/**
* Get AMP asset URL.
*
* @since 0.1
* @internal
*
* @param string $file Relative path to file in assets directory.
* @return string URL.
*/
function amp_get_asset_url( $file ) {
return plugins_url( sprintf( 'assets/%s', $file ), AMP__FILE__ );
}
/**
* Get AMP boilerplate code.
*
* @since 0.7
* @internal
* @link https://www.ampproject.org/docs/reference/spec#boilerplate
*
* @return string Boilerplate code.
*/
function amp_get_boilerplate_code() {
$stylesheets = amp_get_boilerplate_stylesheets();
return sprintf( '<style amp-boilerplate>%s</style><noscript><style amp-boilerplate>%s</style></noscript>', $stylesheets[0], $stylesheets[1] );
}
/**
* Get AMP boilerplate stylesheets.
*
* @since 1.3
* @internal
* @link https://www.ampproject.org/docs/reference/spec#boilerplate
*
* @return string[] Stylesheets, where first is contained in style[amp-boilerplate] and the second in noscript>style[amp-boilerplate].
*/
function amp_get_boilerplate_stylesheets() {
return [
'body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}',
'body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}',
];
}
/**
* Add generator metadata.
*
* @since 0.6
* @since 1.0 Add template mode.
* @since 2.0 Add reader theme.
* @internal
*/
function amp_add_generator_metadata() {
$content = sprintf( 'AMP Plugin v%s', AMP__VERSION );
$mode = AMP_Options_Manager::get_option( Option::THEME_SUPPORT );