Completed
Push — fix/detect-amp-suffix ( d43fbe...dda40b )
by
unknown
16:28 queued 06:24
created

Jetpack_AMP_Support::is_amp_request()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 19
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 7
nc 7
nop 0
dl 0
loc 19
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Manages compatibility with the amp-wp plugin
5
 *
6
 * @see https://github.com/Automattic/amp-wp
7
 */
8
class Jetpack_AMP_Support {
9
10
	static function init() {
11
		if ( ! self::is_amp_request() ) {
12
			return;
13
		}
14
15
		// carousel
16
		add_filter( 'jp_carousel_maybe_disable', '__return_true' );
17
18
		// sharing
19
		add_filter( 'sharing_enqueue_scripts', '__return_false' );
20
		add_filter( 'jetpack_sharing_counts', '__return_false' );
21
		add_filter( 'sharing_js', '__return_false' );
22
		add_filter( 'jetpack_sharing_display_markup', array( 'Jetpack_AMP_Support', 'render_sharing_html' ), 10, 2 );
23
24
		// disable lazy images
25
		add_filter( 'lazyload_is_enabled', '__return_false' );
26
27
		// disable imploding CSS
28
		add_filter( 'jetpack_implode_frontend_css', '__return_false' );
29
30
		// enforce freedom mode for videopress
31
		add_filter( 'videopress_shortcode_options', array( 'Jetpack_AMP_Support', 'videopress_enable_freedom_mode' ) );
32
33
		// include Jetpack og tags when rendering native AMP head
34
		add_action( 'amp_post_template_head', array( 'Jetpack_AMP_Support', 'amp_post_jetpack_og_tags' ) );
35
36
		// Post rendering changes for legacy AMP
37
		add_action( 'pre_amp_render_post', array( 'Jetpack_AMP_Support', 'amp_disable_the_content_filters' ) );
38
39
		// Add post template metadata for legacy AMP
40
		add_filter( 'amp_post_template_metadata', array( 'Jetpack_AMP_Support', 'amp_post_template_metadata' ), 10, 2 );
41
	}
42
43
	static function admin_init() {
44
		// disable Likes metabox for post editor if AMP canonical disabled
45
		add_filter( 'post_flair_disable',  array( 'Jetpack_AMP_Support', 'is_amp_canonical' ), 99 );
46
	}
47
48
	static function init_filter_jetpack_widgets() {
49
		if ( ! self::is_amp_request() ) {
50
			return;
51
		}
52
53
		// widgets
54
		add_filter( 'jetpack_widgets_to_include', array( 'Jetpack_AMP_Support', 'filter_available_widgets' ) );
55
	}
56
57
	static function is_amp_canonical() {
58
		return function_exists( 'amp_is_canonical' ) && amp_is_canonical();
59
	}
60
61
	static function is_amp_request() {
62
		// can't use is_amp_endpoint() since it's not ready early enough in init.
63
		// is_amp_endpoint() implementation calls is_feed, which bails with a notice if plugins_loaded isn't finished
64
		// "Conditional query tags do not work before the query is run"
65
		$is_amp_request = ! is_admin() // this is necessary so that modules can still be enabled/disabled/configured as per normal via Jetpack admin
66
			&&
67
				function_exists( 'amp_is_canonical' ) // this is really just testing if the plugin exists
68
			&&
69
				( amp_is_canonical() || isset( $_GET[ amp_get_slug() ] ) || self::has_amp_suffix() );
70
71
		/**
72
		 * Returns true if the current request should return valid AMP content.
73
		 *
74
		 * @since 6.2.0
75
		 *
76
		 * @param boolean $is_amp_request Is this request supposed to return valid AMP content?
77
		 */
78
		return apply_filters( 'jetpack_is_amp_request', $is_amp_request );
79
	}
80
81
	static function has_amp_suffix() {
82
		$request_path = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
83
		return $request_path && substr_compare( $request_path, '/amp/', -4, 5, true );
0 ignored issues
show
Bug Best Practice introduced by
The expression $request_path of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
84
	}
85
86
	static function filter_available_widgets( $widgets ) {
87
		if ( self::is_amp_request() ) {
88
			$widgets = array_filter( $widgets, array( 'Jetpack_AMP_Support', 'is_supported_widget' ) );
89
		}
90
91
		return $widgets;
92
	}
93
94
	static function is_supported_widget( $widget_path ) {
95
		return substr( $widget_path, -14 ) !== '/milestone.php';
96
	}
97
98
	static function amp_disable_the_content_filters() {
99
		if ( defined( 'WPCOM') && WPCOM ) {
100
			add_filter( 'videopress_show_2015_player', '__return_true' );
101
			add_filter( 'protected_embeds_use_form_post', '__return_false' );
102
			remove_filter( 'the_title', 'widont' );
103
		}
104
105
		remove_filter( 'pre_kses', array( 'Filter_Embedded_HTML_Objects', 'filter' ), 11 );
106
		remove_filter( 'pre_kses', array( 'Filter_Embedded_HTML_Objects', 'maybe_create_links' ), 100 );
107
	}
108
109
	/**
110
	 * Add publisher and image metadata to legacy AMP post.
111
	 *
112
	 * @since 6.2.0
113
	 *
114
	 * @param array   $metadata Metadata array.
115
	 * @param WP_Post $post     Post.
116
	 * @return array Modified metadata array.
117
	 */
118
	static function amp_post_template_metadata( $metadata, $post ) {
119
		if ( isset( $metadata['publisher'] ) && ! isset( $metadata['publisher']['logo'] ) ) {
120
			$metadata = self::add_site_icon_to_metadata( $metadata );
121
		}
122
123
		if ( ! isset( $metadata['image'] ) ) {
124
			$metadata = self::add_image_to_metadata( $metadata, $post );
125
		}
126
127
		return $metadata;
128
	}
129
130
	/**
131
	 * Add blavatar to legacy AMP post metadata.
132
	 *
133
	 * @since 6.2.0
134
	 *
135
	 * @param array $metadata Metadata.
136
	 * @return array Metadata.
137
	 */
138
	static function add_site_icon_to_metadata( $metadata ) {
139
		$size = 60;
140
141
		if ( function_exists( 'blavatar_domain' ) ) {
142
			$metadata['publisher']['logo'] = array(
143
				'@type'  => 'ImageObject',
144
				'url'    => blavatar_url( blavatar_domain( site_url() ), 'img', $size, self::staticize_subdomain( 'https://wordpress.com/i/favicons/apple-touch-icon-60x60.png' ) ),
145
				'width'  => $size,
146
				'height' => $size,
147
			);
148
		} else if ( $site_icon_url = Jetpack_Sync_Functions::site_icon_url( $size ) ) {
149
			$metadata['publisher']['logo'] = array(
150
				'@type'  => 'ImageObject',
151
				'url'    => $site_icon_url,
152
				'width'  => $size,
153
				'height' => $size,
154
			);
155
		}
156
157
		return $metadata;
158
	}
159
160
	/**
161
	 * Add image to legacy AMP post metadata.
162
	 *
163
	 * @since 6.2.0
164
	 *
165
	 * @param array   $metadata Metadata.
166
	 * @param WP_Post $post     Post.
167
	 * @return array Metadata.
168
	 */
169
	static function add_image_to_metadata( $metadata, $post ) {
170
		$image = Jetpack_PostImages::get_image( $post->ID, array(
171
			'fallback_to_avatars' => true,
172
			'avatar_size'         => 200,
173
			// AMP already attempts these.
174
			'from_thumbnail'      => false,
175
			'from_attachment'     => false,
176
		) );
177
178
		if ( empty( $image ) ) {
179
			return self::add_fallback_image_to_metadata( $metadata );
180
		}
181
182
		if ( ! isset( $image['src_width'] ) ) {
183
			$dimensions = self::extract_image_dimensions_from_getimagesize( array(
184
				$image['src'] => false,
185
			) );
186
187 View Code Duplication
			if ( false !== $dimensions[ $image['src'] ] ) {
188
				$image['src_width']  = $dimensions['width'];
189
				$image['src_height'] = $dimensions['height'];
190
			}
191
		}
192
193
		$metadata['image'] = array(
194
			'@type'  => 'ImageObject',
195
			'url'    => $image['src'],
196
			'width'  => $image['src_width'],
197
			'height' => $image['src_height'],
198
		);
199
200
		return $metadata;
201
	}
202
203
	/**
204
	 * Add fallback image to legacy AMP post metadata.
205
	 *
206
	 * @since 6.2.0
207
	 *
208
	 * @param array $metadata Metadata.
209
	 * @return array Metadata.
210
	 */
211
	static function add_fallback_image_to_metadata( $metadata ) {
212
		/** This filter is documented in functions.opengraph.php */
213
		$default_image = apply_filters( 'jetpack_open_graph_image_default', 'https://wordpress.com/i/blank.jpg' );
214
215
		$metadata['image'] = array(
216
			'@type'  => 'ImageObject',
217
			'url'    => self::staticize_subdomain( $default_image ),
218
			'width'  => 200,
219
			'height' => 200,
220
		);
221
222
		return $metadata;
223
	}
224
225
	static function staticize_subdomain( $domain ) {
226
		// deal with WPCOM vs Jetpack
227
		if ( function_exists( 'staticize_subdomain' ) ) {
228
			return staticize_subdomain( $domain );
229
		} else {
230
			return Jetpack::staticize_subdomain( $domain );
231
		}
232
	}
233
234
	/**
235
	 * Extract image dimensions via wpcom/imagesize, only on WPCOM
236
	 *
237
	 * @since 6.2.0
238
	 *
239
	 * @param array $dimensions Dimensions.
240
	 * @return array Dimensions.
241
	 */
242
	static function extract_image_dimensions_from_getimagesize( $dimensions ) {
243
		if ( ! ( defined('WPCOM') && WPCOM && function_exists( 'require_lib' ) ) ) {
244
			return $dimensions;
245
		}
246
		require_lib( 'wpcom/imagesize' );
247
248
		foreach ( $dimensions as $url => $value ) {
249
			if ( is_array( $value ) ) {
250
				continue;
251
			}
252
			$result = wpcom_getimagesize( $url );
253
			if ( is_array( $result ) ) {
254
				$dimensions[ $url ] = array(
255
					'width'  => $result[0],
256
					'height' => $result[1],
257
				);
258
			}
259
		}
260
261
		return $dimensions;
262
	}
263
264
	static function amp_post_jetpack_og_tags() {
265
		Jetpack::init()->check_open_graph();
266
		if ( function_exists( 'jetpack_og_tags' ) ) {
267
			jetpack_og_tags();
268
		}
269
	}
270
271
	static function videopress_enable_freedom_mode( $options ) {
272
		$options['freedom'] = true;
273
		return $options;
274
	}
275
276
	static function render_sharing_html( $markup, $sharing_enabled ) {
277
		remove_action( 'wp_footer', 'sharing_add_footer' );
278
		if ( empty( $sharing_enabled ) ) {
279
			return $markup;
280
		}
281
		$supported_services = array(
282
			'facebook'      => array(
283
				/** This filter is documented in modules/sharedaddy/sharing-sources.php */
284
				'data-param-app_id' => apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' ),
285
			),
286
			'twitter'       => array(),
287
			'pinterest'     => array(),
288
			'whatsapp'      => array(),
289
			'google-plus-1' => array(
290
				'type' => 'gplus',
291
			),
292
			'tumblr'        => array(),
293
			'linkedin'      => array(),
294
		);
295
		$sharing_links = array();
296
		foreach ( $sharing_enabled['visible'] as $id => $service ) {
297
			if ( ! isset( $supported_services[ $id ] ) ) {
298
				$sharing_links[] = "<!-- not supported: $id -->";
299
				continue;
300
			}
301
			$args = array_merge(
302
				array(
303
					'type' => $id,
304
				),
305
				$supported_services[ $id ]
306
			);
307
			$sharing_link = '<amp-social-share';
308
			foreach ( $args as $key => $value ) {
309
				$sharing_link .= sprintf( ' %s="%s"', sanitize_key( $key ), esc_attr( $value ) );
310
			}
311
			$sharing_link .= '></amp-social-share>';
312
			$sharing_links[] = $sharing_link;
313
		}
314
		return preg_replace( '#(?<=<div class="sd-content">).+?(?=</div>)#s', implode( '', $sharing_links ), $markup );
315
	}
316
}
317
318
add_action( 'init', array( 'Jetpack_AMP_Support', 'init' ), 1 );
319
320
add_action( 'admin_init', array( 'Jetpack_AMP_Support', 'admin_init' ), 1 );
321
322
// this is necessary since for better or worse Jetpack modules and widget files are loaded during plugins_loaded, which means we must
323
// take the opportunity to intercept initialisation before that point, either by adding explicit detection into the module,
324
// or preventing it from loading in the first place (better for performance)
325
add_action( 'plugins_loaded', array( 'Jetpack_AMP_Support', 'init_filter_jetpack_widgets' ), 1 );
326