Completed
Push — instant-search-master ( a786a9...893b7c )
by
unknown
85:32 queued 79:17
created

Jetpack_AMP_Support   F

Complexity

Total Complexity 74

Size/Duplication

Total Lines 489
Duplicated Lines 0.82 %

Coupling/Cohesion

Components 2
Dependencies 3

Importance

Changes 0
Metric Value
wmc 74
lcom 2
cbo 3
dl 4
loc 489
rs 2.48
c 0
b 0
f 0

21 Methods

Rating   Name   Duplication   Size   Complexity  
A amp_disable_the_content_filters() 0 10 3
A init() 0 45 4
A show_admin_bar() 0 3 2
A comment_likes_enabled() 0 3 2
A admin_init() 0 4 1
A is_amp_canonical() 0 3 2
A is_amp_request() 0 12 2
A disable_comment_likes_before_the_content() 0 6 2
A add_stats_pixel() 0 6 2
A amp_post_template_metadata() 0 11 4
A add_site_icon_to_metadata() 0 22 4
B add_image_to_metadata() 4 42 6
A add_fallback_image_to_metadata() 0 13 1
A staticize_subdomain() 0 8 2
B extract_image_dimensions_from_getimagesize() 0 21 7
A amp_post_jetpack_og_tags() 0 9 4
A videopress_enable_freedom_mode() 0 6 2
B render_sharing_html() 0 48 6
A amp_disable_sharedaddy_css() 0 7 2
C filter_photon_post_image_args_for_stories() 0 49 14
A filter_jetpack_options_whitelist() 0 6 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Jetpack_AMP_Support often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Jetpack_AMP_Support, and based on these observations, apply Extract Interface, too.

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