-
Notifications
You must be signed in to change notification settings - Fork 383
/
class-amp-options-manager.php
745 lines (659 loc) · 25.4 KB
/
class-amp-options-manager.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
<?php
/**
* Class AMP_Options_Manager.
*
* @package AMP
*/
use AmpProject\AmpWP\Option;
/**
* Class AMP_Options_Manager
*/
class AMP_Options_Manager {
/**
* Option name.
*
* @var string
*/
const OPTION_NAME = 'amp-options';
/**
* Default option values.
*
* @var array
*/
protected static $defaults = [
Option::THEME_SUPPORT => AMP_Theme_Support::READER_MODE_SLUG,
Option::SUPPORTED_POST_TYPES => [ 'post' ],
Option::ANALYTICS => [],
Option::ALL_TEMPLATES_SUPPORTED => true,
Option::SUPPORTED_TEMPLATES => [ 'is_singular' ],
Option::VERSION => AMP__VERSION,
Option::READER_THEME => AMP_Reader_Themes::DEFAULT_READER_THEME,
Option::WIZARD_COMPLETED => false,
];
/**
* Sets up hooks.
*/
public static function init() {
add_action( 'admin_notices', [ __CLASS__, 'render_welcome_notice' ] );
add_action( 'admin_notices', [ __CLASS__, 'render_php_css_parser_conflict_notice' ] );
add_action( 'admin_notices', [ __CLASS__, 'insecure_connection_notice' ] );
}
/**
* Register settings.
*/
public static function register_settings() {
register_setting(
self::OPTION_NAME,
self::OPTION_NAME,
[
'type' => 'array',
'sanitize_callback' => [ __CLASS__, 'validate_options' ],
]
);
add_action( 'update_option_' . self::OPTION_NAME, [ __CLASS__, 'maybe_flush_rewrite_rules' ], 10, 2 );
}
/**
* Flush rewrite rules if the supported_post_types have changed.
*
* @since 0.6.2
*
* @param array $old_options Old options.
* @param array $new_options New options.
*/
public static function maybe_flush_rewrite_rules( $old_options, $new_options ) {
$old_post_types = isset( $old_options[ Option::SUPPORTED_POST_TYPES ] ) ? $old_options[ Option::SUPPORTED_POST_TYPES ] : [];
$new_post_types = isset( $new_options[ Option::SUPPORTED_POST_TYPES ] ) ? $new_options[ Option::SUPPORTED_POST_TYPES ] : [];
sort( $old_post_types );
sort( $new_post_types );
if ( $old_post_types !== $new_post_types ) {
// Flush rewrite rules.
add_rewrite_endpoint( amp_get_slug(), EP_PERMALINK );
flush_rewrite_rules( false );
}
}
/**
* Get plugin options.
*
* @return array Options.
*/
public static function get_options() {
$options = get_option( self::OPTION_NAME, [] );
if ( empty( $options ) ) {
$options = []; // Ensure empty string becomes array.
}
$defaults = self::$defaults;
if ( current_theme_supports( 'amp' ) ) {
$defaults[ Option::THEME_SUPPORT ] = amp_is_canonical() ? AMP_Theme_Support::STANDARD_MODE_SLUG : AMP_Theme_Support::TRANSITIONAL_MODE_SLUG;
}
/**
* Filters default options.
*
* @internal
* @param array $defaults Default options.
*/
$defaults = apply_filters( 'amp_default_options', $defaults );
$options = array_merge( $defaults, $options );
// Migrate theme support slugs.
if ( 'native' === $options[ Option::THEME_SUPPORT ] ) {
$options[ Option::THEME_SUPPORT ] = AMP_Theme_Support::STANDARD_MODE_SLUG;
} elseif ( 'paired' === $options[ Option::THEME_SUPPORT ] ) {
$options[ Option::THEME_SUPPORT ] = AMP_Theme_Support::TRANSITIONAL_MODE_SLUG;
} elseif ( 'disabled' === $options[ Option::THEME_SUPPORT ] ) {
/*
* Prior to 1.2, the theme support slug for Reader mode was 'disabled'. This would be saved in options for
* themes that had 'amp' theme support defined. Also prior to 1.2, the user could not switch between modes
* when the theme had 'amp' theme support. The result is that a site running 1.1 could be AMP-first and then
* upon upgrading to 1.2, be switched to Reader mode. So when migrating the old 'disabled' slug to the new
* value, we need to make sure we use the default theme support slug as it has been determined above. If the
* site has non-paired 'amp' theme support and the theme support slug is 'disabled' then it should here be
* set to 'standard' as opposed to 'reader', and the same goes for paired 'amp' theme support, as it should
* become 'transitional'. Otherwise, if the theme lacks 'amp' theme support, then this will become the
* default 'reader' mode.
*/
$options[ Option::THEME_SUPPORT ] = $defaults[ Option::THEME_SUPPORT ];
}
unset(
/**
* Remove 'auto_accept_sanitization' option.
*
* @since 1.4.0
*/
$options[ Option::AUTO_ACCEPT_SANITIZATION ],
/**
* Remove Story related options.
*
* Option::ENABLE_AMP_STORIES was added in 1.2-beta and later migrated into the `experiences` option.
*
* @since 1.5.0
*/
$options[ Option::STORY_TEMPLATES_VERSION ],
$options[ Option::STORY_EXPORT_BASE_URL ],
$options[ Option::STORY_SETTINGS ],
$options[ Option::ENABLE_AMP_STORIES ],
/**
* Remove 'experiences' option.
*
* @since 1.5.0
*/
$options[ Option::EXPERIENCES ],
/**
* Remove 'enable_response_caching' option.
*
* @since 1.5.0
*/
$options[ Option::ENABLE_RESPONSE_CACHING ]
);
return $options;
}
/**
* Get plugin option.
*
* @param string $option Plugin option name.
* @param bool $default Default value.
*
* @return mixed Option value.
*/
public static function get_option( $option, $default = false ) {
$amp_options = self::get_options();
if ( ! isset( $amp_options[ $option ] ) ) {
return $default;
}
return $amp_options[ $option ];
}
/**
* Validate options.
*
* @param array $new_options Plugin options.
* @return array Options.
*/
public static function validate_options( $new_options ) {
$options = self::get_options();
if ( ! current_user_can( 'manage_options' ) ) {
return $options;
}
// Theme support.
$recognized_theme_supports = [
AMP_Theme_Support::READER_MODE_SLUG,
AMP_Theme_Support::TRANSITIONAL_MODE_SLUG,
AMP_Theme_Support::STANDARD_MODE_SLUG,
];
if ( isset( $new_options[ Option::THEME_SUPPORT ] ) && in_array( $new_options[ Option::THEME_SUPPORT ], $recognized_theme_supports, true ) ) {
$options[ Option::THEME_SUPPORT ] = $new_options[ Option::THEME_SUPPORT ];
// If this option was changed, display a notice with the new template mode.
if ( self::get_option( Option::THEME_SUPPORT ) !== $new_options[ Option::THEME_SUPPORT ] ) {
add_action( 'update_option_' . self::OPTION_NAME, [ __CLASS__, 'handle_updated_theme_support_option' ] );
}
}
// Validate post type support.
if ( isset( $new_options[ Option::SUPPORTED_POST_TYPES ] ) ) {
$options[ Option::SUPPORTED_POST_TYPES ] = [];
foreach ( $new_options[ Option::SUPPORTED_POST_TYPES ] as $post_type ) {
if ( ! post_type_exists( $post_type ) ) {
self::add_settings_error( self::OPTION_NAME, 'unknown_post_type', __( 'Unrecognized post type.', 'amp' ) );
} else {
$options[ Option::SUPPORTED_POST_TYPES ][] = $post_type;
}
}
}
$theme_support_args = AMP_Theme_Support::get_theme_support_args();
$is_template_support_required = ( isset( $theme_support_args['templates_supported'] ) && 'all' === $theme_support_args['templates_supported'] );
if ( ! $is_template_support_required && ! isset( $theme_support_args['available_callback'] ) ) {
$options[ Option::ALL_TEMPLATES_SUPPORTED ] = ! empty( $new_options[ Option::ALL_TEMPLATES_SUPPORTED ] );
// Validate supported templates.
$options[ Option::SUPPORTED_TEMPLATES ] = [];
if ( isset( $new_options[ Option::SUPPORTED_TEMPLATES ] ) ) {
$options[ Option::SUPPORTED_TEMPLATES ] = array_intersect(
$new_options[ Option::SUPPORTED_TEMPLATES ],
array_keys( AMP_Theme_Support::get_supportable_templates() )
);
}
}
// Validate wizard completion.
if ( isset( $new_options[ Option::WIZARD_COMPLETED ] ) ) {
$options[ Option::WIZARD_COMPLETED ] = (bool) $new_options[ OPTION::WIZARD_COMPLETED ];
}
// Validate analytics.
if ( isset( $new_options[ Option::ANALYTICS ] ) && $new_options[ Option::ANALYTICS ] !== $options[ Option::ANALYTICS ] ) {
foreach ( $new_options[ Option::ANALYTICS ] as $data ) {
// Check save/delete pre-conditions and proceed if correct.
if ( empty( $data['type'] ) || empty( $data['config'] ) ) {
self::add_settings_error( self::OPTION_NAME, 'missing_analytics_vendor_or_config', __( 'Missing vendor type or config.', 'amp' ) );
continue;
}
// Validate JSON configuration.
$is_valid_json = AMP_HTML_Utils::is_valid_json( $data['config'] );
if ( ! $is_valid_json ) {
self::add_settings_error( self::OPTION_NAME, 'invalid_analytics_config_json', __( 'Invalid analytics config JSON.', 'amp' ) );
continue;
}
$entry_vendor_type = preg_replace( '/[^a-zA-Z0-9_\-]/', '', $data['type'] );
$entry_config = trim( $data['config'] );
if ( ! empty( $data['id'] ) && '__new__' !== $data['id'] ) {
$entry_id = sanitize_key( $data['id'] );
} else {
// Generate a hash string to uniquely identify this entry.
$entry_id = substr( md5( $entry_vendor_type . $entry_config ), 0, 12 );
// Avoid duplicates.
if ( isset( $options[ Option::ANALYTICS ][ $entry_id ] ) ) {
self::add_settings_error( self::OPTION_NAME, 'duplicate_analytics_entry', __( 'Duplicate analytics entry found.', 'amp' ) );
continue;
}
}
if ( isset( $data['delete'] ) ) {
unset( $options[ Option::ANALYTICS ][ $entry_id ] );
} else {
$options[ Option::ANALYTICS ][ $entry_id ] = [
'type' => $entry_vendor_type,
'config' => $entry_config,
];
}
}
}
if ( isset( $new_options[ Option::READER_THEME ] ) ) {
$reader_theme_slugs = wp_list_pluck( ( new AMP_Reader_Themes() )->get_themes(), 'slug' );
if ( in_array( $new_options[ Option::READER_THEME ], $reader_theme_slugs, true ) ) {
$options[ Option::READER_THEME ] = $new_options[ Option::READER_THEME ];
}
}
if ( array_key_exists( Option::DISABLE_CSS_TRANSIENT_CACHING, $new_options ) && true === $new_options[ Option::DISABLE_CSS_TRANSIENT_CACHING ] ) {
$options[ Option::DISABLE_CSS_TRANSIENT_CACHING ] = true;
} else {
unset( $options[ Option::DISABLE_CSS_TRANSIENT_CACHING ] );
}
/**
* Filter the options being updated, so services can handle the sanitization and validation of
* their respective options.
*
* @internal
*
* @param array $options Existing options with already-sanitized values for updating.
* @param array $new_options Unsanitized options being submitted for updating.
*/
$options = apply_filters( 'amp_options_updating', $options, $new_options );
// Store the current version with the options so we know the format.
$options[ Option::VERSION ] = AMP__VERSION;
return $options;
}
/**
* Check for errors with updating the supported post types.
*
* @since 0.6
* @see add_settings_error()
*/
public static function check_supported_post_type_update_errors() {
// If all templates are supported then skip check since all post types are also supported. This option only applies with standard/transitional theme support.
if ( self::get_option( Option::ALL_TEMPLATES_SUPPORTED, false ) && AMP_Theme_Support::READER_MODE_SLUG !== self::get_option( Option::THEME_SUPPORT ) ) {
return;
}
$supported_types = self::get_option( Option::SUPPORTED_POST_TYPES, [] );
foreach ( AMP_Post_Type_Support::get_eligible_post_types() as $name ) {
$post_type = get_post_type_object( $name );
if ( empty( $post_type ) ) {
continue;
}
$post_type_supported = post_type_supports( $post_type->name, AMP_Post_Type_Support::SLUG );
$is_support_elected = in_array( $post_type->name, $supported_types, true );
$error = null;
$code = null;
if ( $is_support_elected && ! $post_type_supported ) {
/* translators: %s: Post type name. */
$error = __( '"%s" could not be activated because support is removed by a plugin or theme', 'amp' );
$code = sprintf( '%s_activation_error', $post_type->name );
} elseif ( ! $is_support_elected && $post_type_supported ) {
/* translators: %s: Post type name. */
$error = __( '"%s" could not be deactivated because support is added by a plugin or theme', 'amp' );
$code = sprintf( '%s_deactivation_error', $post_type->name );
}
if ( isset( $error, $code ) ) {
self::add_settings_error(
self::OPTION_NAME,
$code,
esc_html(
sprintf(
$error,
isset( $post_type->label ) ? $post_type->label : $post_type->name
)
)
);
}
}
}
/**
* Update plugin option.
*
* @param string $option Plugin option name.
* @param mixed $value Plugin option value.
*
* @return bool Whether update succeeded.
*/
public static function update_option( $option, $value ) {
$amp_options = self::get_options();
$amp_options[ $option ] = $value;
return update_option( self::OPTION_NAME, $amp_options, false );
}
/**
* Update plugin options.
*
* @param array $options Plugin option name.
* @return bool Whether update succeeded.
*/
public static function update_options( $options ) {
$amp_options = array_merge(
self::get_options(),
$options
);
return update_option( self::OPTION_NAME, $amp_options, false );
}
/**
* Handle analytics submission.
*/
public static function handle_analytics_submit() {
// Request must come from user with right capabilities.
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'Sorry, you do not have the necessary permissions to perform this action', 'amp' ) );
}
// Ensure request is coming from analytics option form.
check_admin_referer( 'analytics-options', 'analytics-options' );
if ( isset( $_POST[ self::OPTION_NAME ][ Option::ANALYTICS ] ) ) {
self::update_option( Option::ANALYTICS, wp_unslash( $_POST[ self::OPTION_NAME ][ Option::ANALYTICS ] ) );
$errors = get_settings_errors( self::OPTION_NAME );
if ( empty( $errors ) ) {
self::add_settings_error( self::OPTION_NAME, 'settings_updated', __( 'The analytics entry was successfully saved!', 'amp' ), 'updated' );
$errors = get_settings_errors( self::OPTION_NAME );
}
set_transient( 'settings_errors', $errors );
}
/*
* Redirect to keep the user in the analytics options page.
* Wrap in is_admin() to enable phpunit tests to exercise this code.
*/
wp_safe_redirect( admin_url( 'admin.php?page=amp-analytics-options&settings-updated=1' ) );
exit;
}
/**
* Update analytics options.
*
* @codeCoverageIgnore
* @deprecated
* @param array $data Unsanitized unslashed data.
* @return bool Whether options were updated.
*/
public static function update_analytics_options( $data ) {
_deprecated_function( __METHOD__, '0.6', __CLASS__ . '::update_option' );
return self::update_option( Option::ANALYTICS, wp_unslash( $data ) );
}
/**
* Renders the welcome notice on the 'AMP Settings' page.
*
* Uses the user meta values for the dismissed WP pointers.
* So once the user dismisses this notice, it will never appear again.
*/
public static function render_welcome_notice() {
if ( 'toplevel_page_' . self::OPTION_NAME !== get_current_screen()->id ) {
return;
}
$notice_id = 'amp-welcome-notice-1';
$dismissed = get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true );
if ( in_array( $notice_id, explode( ',', (string) $dismissed ), true ) ) {
return;
}
?>
<div class="amp-welcome-notice notice notice-info is-dismissible" id="<?php echo esc_attr( $notice_id ); ?>">
<div class="notice-dismiss"></div>
<div class="amp-welcome-icon-holder">
<img width="200" height="200" class="amp-welcome-icon" src="<?php echo esc_url( amp_get_asset_url( 'images/amp-welcome-icon.svg' ) ); ?>" alt="<?php esc_attr_e( 'Illustration of WordPress running AMP plugin.', 'amp' ); ?>" />
</div>
<h2><?php esc_html_e( 'Welcome to AMP for WordPress', 'amp' ); ?></h2>
<h3><?php esc_html_e( 'Bring the speed and features of the open source AMP project to your site, complete with the tools to support content authoring and website development.', 'amp' ); ?></h3>
<h3><?php esc_html_e( 'From granular controls that help you create AMP content, to Core Gutenberg support, to a sanitizer that only shows visitors error-free pages, to a full error workflow for developers, this release enables rich, performant experiences for your WordPress site.', 'amp' ); ?></h3>
<a href="https://amp-wp.org/getting-started/" target="_blank" class="button button-primary"><?php esc_html_e( 'Learn More', 'amp' ); ?></a>
</div>
<script>
jQuery( function( $ ) {
// On dismissing the notice, make a POST request to store this notice with the dismissed WP pointers so it doesn't display again.
$( <?php echo wp_json_encode( "#$notice_id" ); ?> ).on( 'click', '.notice-dismiss', function() {
$.post( ajaxurl, {
pointer: <?php echo wp_json_encode( $notice_id ); ?>,
action: 'dismiss-wp-pointer'
} );
} );
} );
</script>
<style type="text/css">
.amp-welcome-notice {
padding: 38px;
min-height: 200px;
}
.amp-welcome-notice + .notice {
clear: both;
}
.amp-welcome-icon-holder {
width: 200px;
height: 200px;
float: left;
margin: 0 38px 38px 0;
}
.amp-welcome-icon {
width: 100%;
height: 100%;
display: block;
}
.amp-welcome-notice h1 {
font-weight: bold;
}
.amp-welcome-notice h3 {
font-size: 16px;
font-weight: 500;
}
</style>
<?php
}
/**
* Render PHP-CSS-Parser conflict notice.
*
* @return void
*/
public static function render_php_css_parser_conflict_notice() {
if ( 'toplevel_page_' . self::OPTION_NAME !== get_current_screen()->id ) {
return;
}
if ( AMP_Style_Sanitizer::has_required_php_css_parser() ) {
return;
}
try {
$reflection = new ReflectionClass( 'Sabberworm\CSS\CSSList\CSSList' );
$source_dir = str_replace(
trailingslashit( WP_CONTENT_DIR ),
'',
preg_replace( '#/vendor/sabberworm/.+#', '', $reflection->getFileName() )
);
printf(
'<div class="notice notice-warning"><p>%s</p></div>',
wp_kses(
sprintf(
/* translators: %s: path to the conflicting library */
__( 'A conflicting version of PHP-CSS-Parser appears to be installed by another plugin or theme (located in %s). Because of this, CSS processing will be limited, and tree shaking will not be available.', 'amp' ),
'<code>' . esc_html( $source_dir ) . '</code>'
),
[ 'code' => [] ]
)
);
} catch ( ReflectionException $e ) {
printf(
'<div class="notice notice-warning"><p>%s</p></div>',
esc_html__( 'PHP-CSS-Parser is not available so CSS processing will not be available.', 'amp' )
);
}
}
/**
* Outputs an admin notice if the site is not served over HTTPS.
*
* @since 1.3
*
* @return void
*/
public static function insecure_connection_notice() {
// is_ssl() only tells us whether the admin backend uses HTTPS here, so we add a few more sanity checks.
$uses_ssl = (
is_ssl()
&&
( strpos( get_bloginfo( 'wpurl' ), 'https' ) === 0 )
&&
( strpos( get_bloginfo( 'url' ), 'https' ) === 0 )
);
if ( ! $uses_ssl && 'toplevel_page_' . self::OPTION_NAME === get_current_screen()->id ) {
printf(
'<div class="notice notice-warning"><p>%s</p></div>',
wp_kses(
sprintf(
/* translators: %s: "Why should I use HTTPS" support URL */
__( 'Your site is not being fully served over a secure connection (using HTTPS).<br>As some AMP functionality requires a secure connection, you might experience degraded performance or broken components.<br><a href="%s">More details</a>', 'amp' ),
esc_url( __( 'https://wordpress.org/support/article/why-should-i-use-https/', 'amp' ) )
),
[
'br' => [],
'a' => [ 'href' => true ],
]
)
);
}
}
/**
* Adds a message for an update of the theme support setting.
*/
public static function handle_updated_theme_support_option() {
$template_mode = self::get_option( Option::THEME_SUPPORT );
// Make sure post type support has been added for sake of amp_admin_get_preview_permalink().
foreach ( AMP_Post_Type_Support::get_eligible_post_types() as $post_type ) {
remove_post_type_support( $post_type, AMP_Post_Type_Support::SLUG );
}
AMP_Post_Type_Support::add_post_type_support();
// Ensure theme support flags are set properly according to the new mode so that proper AMP URL can be generated.
if ( AMP_Theme_Support::STANDARD_MODE_SLUG === $template_mode || AMP_Theme_Support::TRANSITIONAL_MODE_SLUG === $template_mode ) {
$theme_support = current_theme_supports( AMP_Theme_Support::SLUG );
if ( ! is_array( $theme_support ) ) {
$theme_support = [];
}
$theme_support['paired'] = AMP_Theme_Support::TRANSITIONAL_MODE_SLUG === $template_mode;
add_theme_support( AMP_Theme_Support::SLUG, $theme_support );
} else {
remove_theme_support( AMP_Theme_Support::SLUG ); // So that the amp_get_permalink() will work for reader mode URL.
}
$url = amp_admin_get_preview_permalink();
$notice_type = 'updated';
$review_messages = [];
if ( $url ) {
$validation = AMP_Validation_Manager::validate_url_and_store( $url );
if ( is_wp_error( $validation ) ) {
$review_messages[] = esc_html__( 'However, there was an error when checking the AMP validity for your site.', 'amp' );
$review_messages[] = AMP_Validation_Manager::get_validate_url_error_message( $validation->get_error_code(), $validation->get_error_message() );
$notice_type = 'error';
} elseif ( is_array( $validation ) ) {
$new_errors = 0;
$rejected_errors = 0;
$errors = wp_list_pluck( $validation['results'], 'error' );
foreach ( $errors as $error ) {
$sanitization = AMP_Validation_Error_Taxonomy::get_validation_error_sanitization( $error );
$is_new_rejected = AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_REJECTED_STATUS === $sanitization['status'];
if ( $is_new_rejected || AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_ACCEPTED_STATUS === $sanitization['status'] ) {
$new_errors++;
}
if ( $is_new_rejected || AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_REJECTED_STATUS === $sanitization['status'] ) {
$rejected_errors++;
}
}
$invalid_url_post_id = $validation['post_id'];
$invalid_url_screen_url = ! is_wp_error( $invalid_url_post_id ) ? get_edit_post_link( $invalid_url_post_id, 'raw' ) : null;
if ( $rejected_errors > 0 ) {
$notice_type = 'error';
$message = esc_html(
sprintf(
/* translators: %s is count of rejected errors */
_n(
'However, AMP is not yet available due to %s validation error (for one URL at least).',
'However, AMP is not yet available due to %s validation errors (for one URL at least).',
number_format_i18n( $rejected_errors ),
'amp'
),
$rejected_errors,
esc_url( $invalid_url_screen_url )
)
);
if ( $invalid_url_screen_url ) {
$message .= ' ' . sprintf(
/* translators: %s is URL to review issues */
_n(
'<a href="%s">Review Issue</a>.',
'<a href="%s">Review Issues</a>.',
$rejected_errors,
'amp'
),
esc_url( $invalid_url_screen_url )
);
}
$review_messages[] = $message;
} else {
$message = sprintf(
/* translators: %s is an AMP URL */
__( 'View an <a href="%s">AMP version of your site</a>.', 'amp' ),
esc_url( $url )
);
if ( $new_errors > 0 && $invalid_url_screen_url ) {
$message .= ' ' . sprintf(
/* translators: 1: URL to review issues. 2: count of new errors. */
_n(
'Please also <a href="%1$s">review %2$s issue</a> which may need to be fixed (for one URL at least).',
'Please also <a href="%1$s">review %2$s issues</a> which may need to be fixed (for one URL at least).',
$new_errors,
'amp'
),
esc_url( $invalid_url_screen_url ),
number_format_i18n( $new_errors )
);
}
$review_messages[] = $message;
}
}
}
switch ( $template_mode ) {
case AMP_Theme_Support::STANDARD_MODE_SLUG:
$message = esc_html__( 'Standard mode activated!', 'amp' );
if ( $review_messages ) {
$message .= ' ' . implode( ' ', $review_messages );
}
break;
case AMP_Theme_Support::TRANSITIONAL_MODE_SLUG:
$message = esc_html__( 'Transitional mode activated!', 'amp' );
if ( $review_messages ) {
$message .= ' ' . implode( ' ', $review_messages );
}
break;
case AMP_Theme_Support::READER_MODE_SLUG:
$message = sprintf(
/* translators: %s is an AMP URL */
__( 'Reader mode activated! View the <a href="%s">AMP version of a recent post</a>. It is recommended that you upgrade to Standard or Transitional mode.', 'amp' ),
esc_url( $url )
);
break;
}
if ( isset( $message ) ) {
self::add_settings_error( self::OPTION_NAME, 'template_mode_updated', wp_kses_post( $message ), $notice_type );
}
}
/**
* Register a settings error to be displayed to the user.
*
* @see add_settings_error()
*
* @param string $setting Slug title of the setting to which this error applies.
* @param string $code Slug-name to identify the error. Used as part of 'id' attribute in HTML output.
* @param string $message The formatted message text to display to the user (will be shown inside styled
* `<div>` and `<p>` tags).
* @param string $type Optional. Message type, controls HTML class. Possible values include 'error',
* 'success', 'warning', 'info'. Default 'error'.
*/
private static function add_settings_error( $setting, $code, $message, $type = 'error' ) {
require_once ABSPATH . 'wp-admin/includes/template.php';
add_settings_error( $setting, $code, $message, $type );
}
}