Completed
Push — fusion-sync/jeherve/r203534-wp... ( f0c187 )
by
unknown
06:31
created

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