Completed
Push — fix/amp-admin-bar ( f5333e )
by Jeremy
35:49 queued 28:45
created

Jetpack_AMP_Support::show_admin_bar()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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