Completed
Push — fix/tiled-gallery-amp-mosaic-c... ( b708e7...398dc2 )
by Yaroslav
08:06
created

Jetpack_AMP_Support::staticize_subdomain()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php //phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2
3
use Automattic\Jetpack\Sync\Functions;
4
5
/**
6
 * Manages compatibility with the amp-wp plugin
7
 *
8
 * @see https://github.com/Automattic/amp-wp
9
 */
10
class Jetpack_AMP_Support {
11
12
	/**
13
	 * Apply custom AMP changes on the front-end.
14
	 */
15
	public static function init() {
16
17
		// Add Stats tracking pixel on Jetpack sites when the Stats module is active.
18
		if (
19
			Jetpack::is_module_active( 'stats' )
20
			&& ! ( defined( 'IS_WPCOM' ) && IS_WPCOM )
21
		) {
22
			add_action( 'amp_post_template_footer', array( 'Jetpack_AMP_Support', 'add_stats_pixel' ) );
23
		}
24
25
		/**
26
		 * Remove this during the init hook in case users have enabled it during
27
		 * the after_setup_theme hook, which triggers before init.
28
		 */
29
		remove_theme_support( 'jetpack-devicepx' );
30
31
		// Sharing.
32
		add_filter( 'jetpack_sharing_display_markup', array( 'Jetpack_AMP_Support', 'render_sharing_html' ), 10, 2 );
33
		add_filter( 'sharing_enqueue_scripts', array( 'Jetpack_AMP_Support', 'amp_disable_sharedaddy_css' ) );
34
		add_action( 'wp_enqueue_scripts', array( 'Jetpack_AMP_Support', 'amp_enqueue_sharing_css' ) );
35
36
		// Sharing for Reader mode.
37
		if ( function_exists( 'jetpack_social_menu_include_svg_icons' ) ) {
38
			add_action( 'amp_post_template_footer', 'jetpack_social_menu_include_svg_icons' );
39
		}
40
		add_action( 'amp_post_template_css', array( 'Jetpack_AMP_Support', 'amp_reader_sharing_css' ), 10, 0 );
41
42
		// enforce freedom mode for videopress.
43
		add_filter( 'videopress_shortcode_options', array( 'Jetpack_AMP_Support', 'videopress_enable_freedom_mode' ) );
44
45
		// include Jetpack og tags when rendering native AMP head.
46
		add_action( 'amp_post_template_head', array( 'Jetpack_AMP_Support', 'amp_post_jetpack_og_tags' ) );
47
48
		// Post rendering changes for legacy AMP.
49
		add_action( 'pre_amp_render_post', array( 'Jetpack_AMP_Support', 'amp_disable_the_content_filters' ) );
50
51
		// Disable Comment Likes.
52
		add_filter( 'jetpack_comment_likes_enabled', array( 'Jetpack_AMP_Support', 'comment_likes_enabled' ) );
53
54
		// Transitional mode AMP should not have comment likes.
55
		add_filter( 'the_content', array( 'Jetpack_AMP_Support', 'disable_comment_likes_before_the_content' ) );
56
57
		// Remove the Likes button from the admin bar.
58
		add_filter( 'jetpack_admin_bar_likes_enabled', array( 'Jetpack_AMP_Support', 'disable_likes_admin_bar' ) );
59
60
		// Add post template metadata for legacy AMP.
61
		add_filter( 'amp_post_template_metadata', array( 'Jetpack_AMP_Support', 'amp_post_template_metadata' ), 10, 2 );
62
63
		// Filter photon image args for AMP Stories.
64
		add_filter( 'jetpack_photon_post_image_args', array( 'Jetpack_AMP_Support', 'filter_photon_post_image_args_for_stories' ), 10, 2 );
65
66
		// Sync the amp-options.
67
		add_filter( 'jetpack_options_whitelist', array( 'Jetpack_AMP_Support', 'filter_jetpack_options_safelist' ) );
68
	}
69
70
	/**
71
	 * Disable the Comment Likes feature on AMP views.
72
	 *
73
	 * @param bool $enabled Should comment likes be enabled.
74
	 */
75
	public static function comment_likes_enabled( $enabled ) {
76
		return $enabled && ! self::is_amp_request();
77
	}
78
79
	/**
80
	 * Apply custom AMP changes in wp-admin.
81
	 */
82
	public static function admin_init() {
83
		// disable Likes metabox for post editor if AMP canonical disabled.
84
		add_filter( 'post_flair_disable', array( 'Jetpack_AMP_Support', 'is_amp_canonical' ), 99 );
85
	}
86
87
	/**
88
	 * Is the page in AMP 'canonical mode'.
89
	 * Used when themes register support for AMP with `add_theme_support( 'amp' )`.
90
	 *
91
	 * @return bool is_amp_canonical
92
	 */
93
	public static function is_amp_canonical() {
94
		return function_exists( 'amp_is_canonical' ) && amp_is_canonical();
95
	}
96
97
	/**
98
	 * Does the page return AMP content.
99
	 *
100
	 * @return bool $is_amp_request Are we on am AMP view.
101
	 */
102
	public static function is_amp_request() {
103
		$is_amp_request = ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() );
104
105
		/**
106
		 * Returns true if the current request should return valid AMP content.
107
		 *
108
		 * @since 6.2.0
109
		 *
110
		 * @param boolean $is_amp_request Is this request supposed to return valid AMP content?
111
		 */
112
		return apply_filters( 'jetpack_is_amp_request', $is_amp_request );
113
	}
114
115
	/**
116
	 * Remove content filters added by Jetpack.
117
	 */
118
	public static function amp_disable_the_content_filters() {
119
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
120
			add_filter( 'videopress_show_2015_player', '__return_true' );
121
			add_filter( 'protected_embeds_use_form_post', '__return_false' );
122
			remove_filter( 'the_title', 'widont' );
123
		}
124
125
		remove_filter( 'pre_kses', array( 'Filter_Embedded_HTML_Objects', 'filter' ), 11 );
126
		remove_filter( 'pre_kses', array( 'Filter_Embedded_HTML_Objects', 'maybe_create_links' ), 100 );
127
	}
128
129
	/**
130
	 * Do not add comment likes on AMP requests.
131
	 *
132
	 * @param string $content Post content.
133
	 */
134
	public static function disable_comment_likes_before_the_content( $content ) {
135
		if ( self::is_amp_request() ) {
136
			remove_filter( 'comment_text', 'comment_like_button', 12, 2 );
137
		}
138
		return $content;
139
	}
140
141
	/**
142
	 * Do not display the Likes' Admin bar on AMP requests.
143
	 *
144
	 * @param bool $is_admin_bar_button_visible Should the Like button be visible in the Admin bar. Default to true.
145
	 */
146
	public static function disable_likes_admin_bar( $is_admin_bar_button_visible ) {
147
		if ( self::is_amp_request() ) {
148
			return false;
149
		}
150
		return $is_admin_bar_button_visible;
151
	}
152
153
	/**
154
	 * Add Jetpack stats pixel.
155
	 *
156
	 * @since 6.2.1
157
	 */
158
	public static function add_stats_pixel() {
159
		if ( ! has_action( 'wp_footer', 'stats_footer' ) ) {
160
			return;
161
		}
162
		stats_render_amp_footer( stats_build_view_data() );
163
	}
164
165
	/**
166
	 * Add publisher and image metadata to legacy AMP post.
167
	 *
168
	 * @since 6.2.0
169
	 *
170
	 * @param array   $metadata Metadata array.
171
	 * @param WP_Post $post     Post.
172
	 * @return array Modified metadata array.
173
	 */
174
	public static function amp_post_template_metadata( $metadata, $post ) {
175
		if ( isset( $metadata['publisher'] ) && ! isset( $metadata['publisher']['logo'] ) ) {
176
			$metadata = self::add_site_icon_to_metadata( $metadata );
177
		}
178
179
		if ( ! isset( $metadata['image'] ) ) {
180
			$metadata = self::add_image_to_metadata( $metadata, $post );
181
		}
182
183
		return $metadata;
184
	}
185
186
	/**
187
	 * Add blavatar to legacy AMP post metadata.
188
	 *
189
	 * @since 6.2.0
190
	 *
191
	 * @param array $metadata Metadata.
192
	 *
193
	 * @return array Metadata.
194
	 */
195
	private static function add_site_icon_to_metadata( $metadata ) {
196
		$size          = 60;
197
		$site_icon_url = class_exists( 'Automattic\\Jetpack\\Sync\\Functions' ) ? Functions::site_icon_url( $size ) : '';
198
199
		if ( function_exists( 'blavatar_domain' ) ) {
200
			$metadata['publisher']['logo'] = array(
201
				'@type'  => 'ImageObject',
202
				'url'    => blavatar_url( blavatar_domain( site_url() ), 'img', $size, self::staticize_subdomain( 'https://wordpress.com/i/favicons/apple-touch-icon-60x60.png' ) ),
203
				'width'  => $size,
204
				'height' => $size,
205
			);
206
		} elseif ( $site_icon_url ) {
207
			$metadata['publisher']['logo'] = array(
208
				'@type'  => 'ImageObject',
209
				'url'    => $site_icon_url,
210
				'width'  => $size,
211
				'height' => $size,
212
			);
213
		}
214
215
		return $metadata;
216
	}
217
218
	/**
219
	 * Add image to legacy AMP post metadata.
220
	 *
221
	 * @since 6.2.0
222
	 *
223
	 * @param array   $metadata Metadata.
224
	 * @param WP_Post $post     Post.
225
	 * @return array Metadata.
226
	 */
227
	private static function add_image_to_metadata( $metadata, $post ) {
228
		$image = Jetpack_PostImages::get_image(
229
			$post->ID,
230
			array(
231
				'fallback_to_avatars' => true,
232
				'avatar_size'         => 200,
233
				// AMP already attempts these.
234
				'from_thumbnail'      => false,
235
				'from_attachment'     => false,
236
			)
237
		);
238
239
		if ( empty( $image ) ) {
240
			return self::add_fallback_image_to_metadata( $metadata );
241
		}
242
243
		if ( ! isset( $image['src_width'] ) ) {
244
			$dimensions = self::extract_image_dimensions_from_getimagesize(
245
				array(
246
					$image['src'] => false,
247
				)
248
			);
249
250 View Code Duplication
			if ( false !== $dimensions[ $image['src'] ] ) {
251
				$image['src_width']  = $dimensions['width'];
252
				$image['src_height'] = $dimensions['height'];
253
			}
254
		}
255
256
		$metadata['image'] = array(
257
			'@type' => 'ImageObject',
258
			'url'   => $image['src'],
259
		);
260
		if ( isset( $image['src_width'] ) ) {
261
			$metadata['image']['width'] = $image['src_width'];
262
		}
263
		if ( isset( $image['src_width'] ) ) {
264
			$metadata['image']['height'] = $image['src_height'];
265
		}
266
267
		return $metadata;
268
	}
269
270
	/**
271
	 * Add fallback image to legacy AMP post metadata.
272
	 *
273
	 * @since 6.2.0
274
	 *
275
	 * @param array $metadata Metadata.
276
	 * @return array Metadata.
277
	 */
278
	private static function add_fallback_image_to_metadata( $metadata ) {
279
		/** This filter is documented in functions.opengraph.php */
280
		$default_image = apply_filters( 'jetpack_open_graph_image_default', 'https://wordpress.com/i/blank.jpg' );
281
282
		$metadata['image'] = array(
283
			'@type'  => 'ImageObject',
284
			'url'    => self::staticize_subdomain( $default_image ),
285
			'width'  => 200,
286
			'height' => 200,
287
		);
288
289
		return $metadata;
290
	}
291
292
	/**
293
	 * Return static WordPress.com domain to use to load resources from WordPress.com.
294
	 *
295
	 * @param string $domain Asset URL.
296
	 */
297
	private static function staticize_subdomain( $domain ) {
298
		// deal with WPCOM vs Jetpack.
299
		if ( function_exists( 'staticize_subdomain' ) ) {
300
			return staticize_subdomain( $domain );
301
		} else {
302
			return Jetpack::staticize_subdomain( $domain );
303
		}
304
	}
305
306
	/**
307
	 * Extract image dimensions via wpcom/imagesize, only on WPCOM
308
	 *
309
	 * @since 6.2.0
310
	 *
311
	 * @param array $dimensions Dimensions.
312
	 * @return array Dimensions.
313
	 */
314
	private static function extract_image_dimensions_from_getimagesize( $dimensions ) {
315
		if ( ! ( defined( 'IS_WPCOM' ) && IS_WPCOM && function_exists( 'jetpack_require_lib' ) ) ) {
316
			return $dimensions;
317
		}
318
		jetpack_require_lib( 'wpcom/imagesize' );
319
320
		foreach ( $dimensions as $url => $value ) {
321
			if ( is_array( $value ) ) {
322
				continue;
323
			}
324
			$result = wpcom_getimagesize( $url );
325
			if ( is_array( $result ) ) {
326
				$dimensions[ $url ] = array(
327
					'width'  => $result[0],
328
					'height' => $result[1],
329
				);
330
			}
331
		}
332
333
		return $dimensions;
334
	}
335
336
	/**
337
	 * Display Open Graph Meta tags in AMP views.
338
	 */
339
	public static function amp_post_jetpack_og_tags() {
340
		if ( ! ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) {
341
			Jetpack::init()->check_open_graph();
342
		}
343
344
		if ( function_exists( 'jetpack_og_tags' ) ) {
345
			jetpack_og_tags();
346
		}
347
	}
348
349
	/**
350
	 * Force Freedom mode in VideoPress.
351
	 *
352
	 * @param array $options Array of VideoPress shortcode options.
353
	 */
354
	public static function videopress_enable_freedom_mode( $options ) {
355
		if ( self::is_amp_request() ) {
356
			$options['freedom'] = true;
357
		}
358
		return $options;
359
	}
360
361
	/**
362
	 * Display custom markup for the sharing buttons when in an AMP view.
363
	 *
364
	 * @param string $markup          Content markup of the Jetpack sharing links.
365
	 * @param array  $sharing_enabled Array of Sharing Services currently enabled.
366
	 */
367
	public static function render_sharing_html( $markup, $sharing_enabled ) {
368
		global $post;
369
370
		if ( empty( $post ) ) {
371
			return '';
372
		}
373
374
		if ( ! self::is_amp_request() ) {
375
			return $markup;
376
		}
377
378
		remove_action( 'wp_footer', 'sharing_add_footer' );
379
		if ( empty( $sharing_enabled ) ) {
380
			return $markup;
381
		}
382
383
		$sharing_links = array();
384
		foreach ( $sharing_enabled['visible'] as $id => $service ) {
385
			$sharing_link = $service->get_amp_display( $post );
386
			if ( ! empty( $sharing_link ) ) {
387
				$sharing_links[] = $sharing_link;
388
			}
389
		}
390
391
		// Replace the existing unordered list with AMP sharing buttons.
392
		$markup = preg_replace( '#<ul>(.+)</ul>#', implode( '', $sharing_links ), $markup );
393
394
		// Remove any lingering share-end list items.
395
		$markup = str_replace( '<li class="share-end"></li>', '', $markup );
396
397
		return $markup;
398
	}
399
400
	/**
401
	 * Tells Jetpack not to enqueue CSS for share buttons.
402
	 *
403
	 * @param  bool $enqueue Whether or not to enqueue.
404
	 * @return bool          Whether or not to enqueue.
405
	 */
406
	public static function amp_disable_sharedaddy_css( $enqueue ) {
407
		if ( self::is_amp_request() ) {
408
			$enqueue = false;
409
		}
410
411
		return $enqueue;
412
	}
413
414
	/**
415
	 * Enqueues the AMP specific sharing styles for the sharing icons.
416
	 */
417
	public static function amp_enqueue_sharing_css() {
418
		if ( self::is_amp_request() ) {
419
			wp_enqueue_style( 'sharedaddy-amp', plugin_dir_url( dirname( __FILE__ ) ) . 'modules/sharedaddy/amp-sharing.css', array( 'social-logos' ), JETPACK__VERSION );
420
		}
421
	}
422
423
	/**
424
	 * For the AMP Reader mode template, include styles that we need.
425
	 */
426
	public static function amp_reader_sharing_css() {
427
		/*
428
		 * We'll need to output the full contents of the 2 files
429
		 * in the head on AMP views. We can't rely on regular enqueues here.
430
		 *
431
		 * phpcs:disable WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
432
		 * phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped
433
		 */
434
		echo file_get_contents( JETPACK_SOCIAL_LOGOS_DIR . 'social-logos.css' );
435
		echo file_get_contents( WP_SHARING_PLUGIN_DIR . 'amp-sharing.css' );
436
437
		/*
438
		 * phpcs:enable WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
439
		 * phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
440
		 */
441
	}
442
443
	/**
444
	 * Ensure proper Photon image dimensions for AMP Stories.
445
	 *
446
	 * @param array $args Array of Photon Arguments.
447
	 * @param array $details {
448
	 *     Array of image details.
449
	 *
450
	 *     @type string    $tag            Image tag (Image HTML output).
451
	 *     @type string    $src            Image URL.
452
	 *     @type string    $src_orig       Original Image URL.
453
	 *     @type int|false $width          Image width.
454
	 *     @type int|false $height         Image height.
455
	 *     @type int|false $width_orig     Original image width before constrained by content_width.
456
	 *     @type int|false $height_orig    Original Image height before constrained by content_width.
457
	 *     @type string    $transform_orig Original transform before constrained by content_width.
458
	 * }
459
	 * @return array Args.
460
	 */
461
	public static function filter_photon_post_image_args_for_stories( $args, $details ) {
462
		if ( ! is_singular( 'amp_story' ) ) {
463
			return $args;
464
		}
465
466
		// Percentage-based dimensions are not allowed in AMP, so this shouldn't happen, but short-circuit just in case.
467
		if ( false !== strpos( $details['width_orig'], '%' ) || false !== strpos( $details['height_orig'], '%' ) ) {
468
			return $args;
469
		}
470
471
		$max_height = 1280; // See image size with the slug \AMP_Story_Post_Type::MAX_IMAGE_SIZE_SLUG.
472
		$transform  = $details['transform_orig'];
473
		$width      = $details['width_orig'];
474
		$height     = $details['height_orig'];
475
476
		// If height is available, constrain to $max_height.
477
		if ( false !== $height ) {
478
			if ( $height > $max_height && false !== $height ) {
479
				$width  = ( $max_height * $width ) / $height;
480
				$height = $max_height;
481
			} elseif ( $height > $max_height ) {
482
				$height = $max_height;
483
			}
484
		}
485
486
		/*
487
		 * Set a height if none is found.
488
		 * If height is set in this manner and height is available, use `fit` instead of `resize` to prevent skewing.
489
		 */
490
		if ( false === $height ) {
491
			$height = $max_height;
492
			if ( false !== $width ) {
493
				$transform = 'fit';
494
			}
495
		}
496
497
		// Build array of Photon args and expose to filter before passing to Photon URL function.
498
		$args = array();
499
500
		if ( false !== $width && false !== $height ) {
501
			$args[ $transform ] = $width . ',' . $height;
502
		} elseif ( false !== $width ) {
503
			$args['w'] = $width;
504
		} elseif ( false !== $height ) {
505
			$args['h'] = $height;
506
		}
507
508
		return $args;
509
	}
510
511
	/**
512
	 *  Adds amp-options to the list of options to sync, if AMP is available
513
	 *
514
	 * @param array $options_safelist Safelist of options to sync.
515
	 *
516
	 * @return array Updated options safelist
517
	 */
518
	public static function filter_jetpack_options_safelist( $options_safelist ) {
519
		if ( function_exists( 'is_amp_endpoint' ) ) {
520
			$options_safelist[] = 'amp-options';
521
		}
522
		return $options_safelist;
523
	}
524
}
525
526
add_action( 'init', array( 'Jetpack_AMP_Support', 'init' ), 1 );
527
528
add_action( 'admin_init', array( 'Jetpack_AMP_Support', 'admin_init' ), 1 );
529