Completed
Push — add/changelog-910 ( c277c8...7fd9c0 )
by Jeremy
19:06 queued 09:10
created

class.photon.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2
/**
3
 * Class for photon functionality.
4
 *
5
 * @package Jetpack.
6
 */
7
8
use Automattic\Jetpack\Assets;
9
10
/**
11
 * Class Jetpack_Photon
12
 */
13
class Jetpack_Photon {
14
	/**
15
	 * Singleton.
16
	 *
17
	 * @var null
18
	 */
19
	private static $instance = null;
20
21
	/**
22
	 * Allowed extensions.
23
	 *
24
	 * @var string[] Allowed extensions must match https://code.trac.wordpress.org/browser/photon/index.php#L31
25
	 */
26
	protected static $extensions = array(
27
		'gif',
28
		'jpg',
29
		'jpeg',
30
		'png',
31
	);
32
33
	/**
34
	 * Image sizes.
35
	 *
36
	 * Don't access this directly. Instead, use self::image_sizes() so it's actually populated with something.
37
	 *
38
	 * @var array Image sizes.
39
	 */
40
	protected static $image_sizes = null;
41
42
	/**
43
	 * Singleton implementation
44
	 *
45
	 * @return object
46
	 */
47
	public static function instance() {
48
		if ( ! is_a( self::$instance, 'Jetpack_Photon' ) ) {
49
			self::$instance = new Jetpack_Photon();
50
			self::$instance->setup();
51
		}
52
53
		return self::$instance;
54
	}
55
56
	/**
57
	 * Silence is golden.
58
	 */
59
	private function __construct() {}
60
61
	/**
62
	 * Register actions and filters, but only if basic Photon functions are available.
63
	 * The basic functions are found in ./functions.photon.php.
64
	 *
65
	 * @uses add_action, add_filter
66
	 * @return null
67
	 */
68
	private function setup() {
69
		if ( ! function_exists( 'jetpack_photon_url' ) ) {
70
			return;
71
		}
72
73
		// Images in post content and galleries.
74
		add_filter( 'the_content', array( __CLASS__, 'filter_the_content' ), 999999 );
75
		add_filter( 'get_post_galleries', array( __CLASS__, 'filter_the_galleries' ), 999999 );
76
		add_filter( 'widget_media_image_instance', array( __CLASS__, 'filter_the_image_widget' ), 999999 );
77
78
		// Core image retrieval.
79
		add_filter( 'image_downsize', array( $this, 'filter_image_downsize' ), 10, 3 );
80
		add_filter( 'rest_request_before_callbacks', array( $this, 'should_rest_photon_image_downsize' ), 10, 3 );
81
		add_action( 'rest_after_insert_attachment', array( $this, 'should_rest_photon_image_downsize_insert_attachment' ), 10, 2 );
82
		add_filter( 'rest_request_after_callbacks', array( $this, 'cleanup_rest_photon_image_downsize' ) );
83
84
		// Responsive image srcset substitution.
85
		add_filter( 'wp_calculate_image_srcset', array( $this, 'filter_srcset_array' ), 10, 5 );
86
		add_filter( 'wp_calculate_image_sizes', array( $this, 'filter_sizes' ), 1, 2 ); // Early so themes can still easily filter.
87
88
		// Helpers for maniuplated images.
89
		add_action( 'wp_enqueue_scripts', array( $this, 'action_wp_enqueue_scripts' ), 9 );
90
91
		/**
92
		 * Allow Photon to disable uploaded images resizing and use its own resize capabilities instead.
93
		 *
94
		 * @module photon
95
		 *
96
		 * @since 7.1.0
97
		 *
98
		 * @param bool false Should Photon enable noresize mode. Default to false.
99
		 */
100
		if ( apply_filters( 'jetpack_photon_noresize_mode', false ) ) {
101
			$this->enable_noresize_mode();
102
		}
103
	}
104
105
	/**
106
	 * Enables the noresize mode for Photon, allowing to avoid intermediate size files generation.
107
	 */
108
	private function enable_noresize_mode() {
109
		jetpack_require_lib( 'class.jetpack-photon-image-sizes' );
110
111
		// The main objective of noresize mode is to disable additional resized image versions creation.
112
		// This filter handles removal of additional sizes.
113
		add_filter( 'intermediate_image_sizes_advanced', array( __CLASS__, 'filter_photon_noresize_intermediate_sizes' ) );
114
115
		// Load the noresize srcset solution on priority of 20, allowing other plugins to set sizes earlier.
116
		add_filter( 'wp_get_attachment_metadata', array( __CLASS__, 'filter_photon_norezise_maybe_inject_sizes' ), 20, 2 );
117
118
		// Photonize thumbnail URLs in the API response.
119
		add_filter( 'rest_api_thumbnail_size_urls', array( __CLASS__, 'filter_photon_noresize_thumbnail_urls' ) );
120
121
		// This allows to assign the Photon domain to images that normally use the home URL as base.
122
		add_filter( 'jetpack_photon_domain', array( __CLASS__, 'filter_photon_norezise_domain' ), 10, 2 );
123
124
		add_filter( 'the_content', array( __CLASS__, 'filter_content_add' ), 0 );
125
126
		// Jetpack hooks in at six nines (999999) so this filter does at seven.
127
		add_filter( 'the_content', array( __CLASS__, 'filter_content_remove' ), 9999999 );
128
129
		// Regular Photon operation mode filter doesn't run when is_admin(), so we need an additional filter.
130
		// This is temporary until Jetpack allows more easily running these filters for is_admin().
131
		if ( is_admin() ) {
132
			add_filter( 'image_downsize', array( $this, 'filter_image_downsize' ), 5, 3 );
133
134
			// Allows any image that gets passed to Photon to be resized via Photon.
135
			add_filter( 'jetpack_photon_admin_allow_image_downsize', '__return_true' );
136
		}
137
	}
138
139
	/**
140
	 * This is our catch-all to strip dimensions from intermediate images in content.
141
	 * Since this primarily only impacts post_content we do a little dance to add the filter early
142
	 * to `the_content` and then remove it later on in the same hook.
143
	 *
144
	 * @param String $content the post content.
145
	 * @return String the post content unchanged.
146
	 */
147
	public static function filter_content_add( $content ) {
148
		add_filter( 'jetpack_photon_pre_image_url', array( __CLASS__, 'strip_image_dimensions_maybe' ) );
149
		return $content;
150
	}
151
152
	/**
153
	 * Removing the content filter that was set previously.
154
	 *
155
	 * @param String $content the post content.
156
	 * @return String the post content unchanged.
157
	 */
158
	public static function filter_content_remove( $content ) {
159
		remove_filter( 'jetpack_photon_pre_image_url', array( __CLASS__, 'strip_image_dimensions_maybe' ) );
160
		return $content;
161
	}
162
163
	/**
164
	 * Short circuits the Photon filter to enable Photon processing for any URL.
165
	 *
166
	 * @param String $photon_url a proposed Photon URL for the media file.
167
	 *
168
	 * @return String an URL to be used for the media file.
169
	 */
170
	public static function filter_photon_norezise_domain( $photon_url ) {
171
		return $photon_url;
172
	}
173
174
	/**
175
	 * Disables intermediate sizes to disallow resizing.
176
	 *
177
	 * @return array Empty array.
178
	 */
179
	public static function filter_photon_noresize_intermediate_sizes() {
180
		return array();
181
	}
182
183
	/**
184
	 * Filter thumbnail URLS to not generate.
185
	 *
186
	 * @param array $sizes Image sizes.
187
	 *
188
	 * @return mixed
189
	 */
190
	public static function filter_photon_noresize_thumbnail_urls( $sizes ) {
191
		foreach ( $sizes as $size => $url ) {
192
			$parts     = explode( '?', $url );
193
			$arguments = isset( $parts[1] ) ? $parts[1] : array();
194
195
			$sizes[ $size ] = jetpack_photon_url( $url, wp_parse_args( $arguments ) );
196
		}
197
198
		return $sizes;
199
	}
200
201
	/**
202
	 * Inject image sizes to attachment metadata.
203
	 *
204
	 * @param array $data          Attachment metadata.
205
	 * @param int   $attachment_id Attachment's post ID.
206
	 *
207
	 * @return array Attachment metadata.
208
	 */
209
	public static function filter_photon_norezise_maybe_inject_sizes( $data, $attachment_id ) {
210
		// Can't do much if data is empty.
211
		if ( empty( $data ) ) {
212
			return $data;
213
		}
214
		$sizes_already_exist = (
215
			true === is_array( $data )
216
			&& true === array_key_exists( 'sizes', $data )
217
			&& true === is_array( $data['sizes'] )
218
			&& false === empty( $data['sizes'] )
219
		);
220
		if ( $sizes_already_exist ) {
221
			return $data;
222
		}
223
		// Missing some critical data we need to determine sizes, not processing.
224
		if ( ! isset( $data['file'] )
225
			|| ! isset( $data['width'] )
226
			|| ! isset( $data['height'] )
227
		) {
228
			return $data;
229
		}
230
231
		$mime_type           = get_post_mime_type( $attachment_id );
232
		$attachment_is_image = preg_match( '!^image/!', $mime_type );
233
234
		if ( 1 === $attachment_is_image ) {
235
			$image_sizes   = new Jetpack_Photon_ImageSizes( $attachment_id, $data );
236
			$data['sizes'] = $image_sizes->generate_sizes_meta();
237
		}
238
		return $data;
239
	}
240
241
	/**
242
	 * Inject image sizes to Jetpack REST API responses. This wraps the filter_photon_norezise_maybe_inject_sizes function.
243
	 *
244
	 * @param array $sizes Attachment sizes data.
245
	 * @param int   $attachment_id Attachment's post ID.
246
	 *
247
	 * @return array Attachment sizes array.
248
	 */
249
	public static function filter_photon_norezise_maybe_inject_sizes_api( $sizes, $attachment_id ) {
250
		return self::filter_photon_norezise_maybe_inject_sizes( wp_get_attachment_metadata( $attachment_id ), $attachment_id );
251
	}
252
253
	/**
254
	 * * IN-CONTENT IMAGE MANIPULATION FUNCTIONS
255
	 **/
256
257
	/**
258
	 * Match all images and any relevant <a> tags in a block of HTML.
259
	 *
260
	 * @param string $content Some HTML.
261
	 * @return array An array of $images matches, where $images[0] is
262
	 *         an array of full matches, and the link_url, img_tag,
263
	 *         and img_url keys are arrays of those matches.
264
	 */
265
	public static function parse_images_from_html( $content ) {
266
		$images = array();
267
268
		if ( preg_match_all( '#(?:<a[^>]+?href=["|\'](?P<link_url>[^\s]+?)["|\'][^>]*?>\s*)?(?P<img_tag><(?:img|amp-img|amp-anim)[^>]*?\s+?src=["|\'](?P<img_url>[^\s]+?)["|\'].*?>){1}(?:\s*</a>)?#is', $content, $images ) ) {
269
			foreach ( $images as $key => $unused ) {
270
				// Simplify the output as much as possible, mostly for confirming test results.
271
				if ( is_numeric( $key ) && $key > 0 ) {
272
					unset( $images[ $key ] );
273
				}
274
			}
275
276
			return $images;
277
		}
278
279
		return array();
280
	}
281
282
	/**
283
	 * Try to determine height and width from strings WP appends to resized image filenames.
284
	 *
285
	 * @param string $src The image URL.
286
	 * @return array An array consisting of width and height.
287
	 */
288
	public static function parse_dimensions_from_filename( $src ) {
289
		$width_height_string = array();
290
291
		if ( preg_match( '#-(\d+)x(\d+)\.(?:' . implode( '|', self::$extensions ) . '){1}$#i', $src, $width_height_string ) ) {
292
			$width  = (int) $width_height_string[1];
293
			$height = (int) $width_height_string[2];
294
295
			if ( $width && $height ) {
296
				return array( $width, $height );
297
			}
298
		}
299
300
		return array( false, false );
301
	}
302
303
	/**
304
	 * Identify images in post content, and if images are local (uploaded to the current site), pass through Photon.
305
	 *
306
	 * @param string $content The content.
307
	 *
308
	 * @uses self::validate_image_url, apply_filters, jetpack_photon_url, esc_url
309
	 * @filter the_content
310
	 *
311
	 * @return string
312
	 */
313
	public static function filter_the_content( $content ) {
314
		$images = self::parse_images_from_html( $content );
315
316
		if ( ! empty( $images ) ) {
317
			$content_width = Jetpack::get_content_width();
318
319
			$image_sizes = self::image_sizes();
320
321
			$upload_dir = wp_get_upload_dir();
322
323
			foreach ( $images[0] as $index => $tag ) {
324
				// Default to resize, though fit may be used in certain cases where a dimension cannot be ascertained.
325
				$transform = 'resize';
326
327
				// Start with a clean attachment ID each time.
328
				$attachment_id = false;
329
330
				// Flag if we need to munge a fullsize URL.
331
				$fullsize_url = false;
332
333
				// Identify image source.
334
				$src_orig = $images['img_url'][ $index ];
335
				$src      = $src_orig;
336
337
				/**
338
				 * Allow specific images to be skipped by Photon.
339
				 *
340
				 * @module photon
341
				 *
342
				 * @since 2.0.3
343
				 *
344
				 * @param bool false Should Photon ignore this image. Default to false.
345
				 * @param string $src Image URL.
346
				 * @param string $tag Image Tag (Image HTML output).
347
				 */
348
				if ( apply_filters( 'jetpack_photon_skip_image', false, $src, $tag ) ) {
349
					continue;
350
				}
351
352
				// Support Automattic's Lazy Load plugin.
353
				// Can't modify $tag yet as we need unadulterated version later.
354
				if ( preg_match( '#data-lazy-src=["|\'](.+?)["|\']#i', $images['img_tag'][ $index ], $lazy_load_src ) ) {
355
					$placeholder_src_orig = $src;
356
					$placeholder_src      = $placeholder_src_orig;
357
					$src_orig             = $lazy_load_src[1];
358
					$src                  = $src_orig;
359
				} elseif ( preg_match( '#data-lazy-original=["|\'](.+?)["|\']#i', $images['img_tag'][ $index ], $lazy_load_src ) ) {
360
					$placeholder_src_orig = $src;
361
					$placeholder_src      = $placeholder_src_orig;
362
					$src_orig             = $lazy_load_src[1];
363
					$src                  = $src_orig;
364
				}
365
366
				// Check if image URL should be used with Photon.
367
				if ( self::validate_image_url( $src ) ) {
368
					// Find the width and height attributes.
369
					$width  = false;
370
					$height = false;
371
372
					// First, check the image tag. Note we only check for pixel sizes now; HTML4 percentages have never been correctly
373
					// supported, so we stopped pretending to support them in JP 9.1.0.
374 View Code Duplication
					if ( preg_match( '#[\s|"|\']width=["|\']?([\d%]+)["|\']?#i', $images['img_tag'][ $index ], $width_string ) ) {
375
						$width = false === strpos( $width_string[1], '%' ) ? $width_string[1] : false;
376
					}
377
378 View Code Duplication
					if ( preg_match( '#[\s|"|\']height=["|\']?([\d%]+)["|\']?#i', $images['img_tag'][ $index ], $height_string ) ) {
379
						$height = false === strpos( $height_string[1], '%' ) ? $height_string[1] : false;
380
					}
381
382
					// Detect WP registered image size from HTML class.
383
					if ( preg_match( '#class=["|\']?[^"\']*size-([^"\'\s]+)[^"\']*["|\']?#i', $images['img_tag'][ $index ], $size ) ) {
384
						$size = array_pop( $size );
385
386
						if ( false === $width && false === $height && 'full' !== $size && array_key_exists( $size, $image_sizes ) ) {
387
							$width     = (int) $image_sizes[ $size ]['width'];
388
							$height    = (int) $image_sizes[ $size ]['height'];
389
							$transform = $image_sizes[ $size ]['crop'] ? 'resize' : 'fit';
390
						}
391
					} else {
392
						unset( $size );
393
					}
394
395
					// WP Attachment ID, if uploaded to this site.
396
					if (
397
						preg_match( '#class=["|\']?[^"\']*wp-image-([\d]+)[^"\']*["|\']?#i', $images['img_tag'][ $index ], $attachment_id ) &&
398
						0 === strpos( $src, $upload_dir['baseurl'] ) &&
399
						/**
400
						 * Filter whether an image using an attachment ID in its class has to be uploaded to the local site to go through Photon.
401
						 *
402
						 * @module photon
403
						 *
404
						 * @since 2.0.3
405
						 *
406
						 * @param bool false Was the image uploaded to the local site. Default to false.
407
						 * @param array $args {
408
						 *   Array of image details.
409
						 *
410
						 *   @type $src Image URL.
411
						 *   @type tag Image tag (Image HTML output).
412
						 *   @type $images Array of information about the image.
413
						 *   @type $index Image index.
414
						 * }
415
						 */
416
						apply_filters( 'jetpack_photon_image_is_local', false, compact( 'src', 'tag', 'images', 'index' ) )
417
					) {
418
						$attachment_id = (int) array_pop( $attachment_id );
419
420
						if ( $attachment_id ) {
421
							$attachment = get_post( $attachment_id );
422
423
							// Basic check on returned post object.
424
							if ( is_object( $attachment ) && ! is_wp_error( $attachment ) && 'attachment' === $attachment->post_type ) {
425
								$src_per_wp = wp_get_attachment_image_src( $attachment_id, isset( $size ) ? $size : 'full' );
426
427
								if ( self::validate_image_url( $src_per_wp[0] ) ) {
428
									$src          = $src_per_wp[0];
429
									$fullsize_url = true;
430
431
									// Prevent image distortion if a detected dimension exceeds the image's natural dimensions.
432
									if ( ( false !== $width && $width > $src_per_wp[1] ) || ( false !== $height && $height > $src_per_wp[2] ) ) {
433
										$width  = false === $width ? false : min( $width, $src_per_wp[1] );
434
										$height = false === $height ? false : min( $height, $src_per_wp[2] );
435
									}
436
437
									// If no width and height are found, max out at source image's natural dimensions.
438
									// Otherwise, respect registered image sizes' cropping setting.
439
									if ( false === $width && false === $height ) {
440
										$width     = $src_per_wp[1];
441
										$height    = $src_per_wp[2];
442
										$transform = 'fit';
443
									} elseif ( isset( $size ) && array_key_exists( $size, $image_sizes ) && isset( $image_sizes[ $size ]['crop'] ) ) {
444
										$transform = (bool) $image_sizes[ $size ]['crop'] ? 'resize' : 'fit';
445
									}
446
								}
447
							} else {
448
								unset( $attachment_id );
449
								unset( $attachment );
450
							}
451
						}
452
					}
453
454
					// If image tag lacks width and height arguments, try to determine from strings WP appends to resized image filenames.
455
					if ( false === $width && false === $height ) {
456
						list( $width, $height ) = self::parse_dimensions_from_filename( $src );
457
					}
458
459
					$width_orig     = $width;
460
					$height_orig    = $height;
461
					$transform_orig = $transform;
462
463
					// If width is available, constrain to $content_width.
464
					if ( false !== $width && is_numeric( $content_width ) && $width > $content_width ) {
465
						if ( false !== $height ) {
466
							$height = round( ( $content_width * $height ) / $width );
467
						}
468
						$width = $content_width;
469
					}
470
471
					// Set a width if none is found and $content_width is available.
472
					// If width is set in this manner and height is available, use `fit` instead of `resize` to prevent skewing.
473
					if ( false === $width && is_numeric( $content_width ) ) {
474
						$width = (int) $content_width;
475
476
						if ( false !== $height ) {
477
							$transform = 'fit';
478
						}
479
					}
480
481
					// Detect if image source is for a custom-cropped thumbnail and prevent further URL manipulation.
482
					if ( ! $fullsize_url && preg_match_all( '#-e[a-z0-9]+(-\d+x\d+)?\.(' . implode( '|', self::$extensions ) . '){1}$#i', basename( $src ), $filename ) ) {
483
						$fullsize_url = true;
484
					}
485
486
					// Build URL, first maybe removing WP's resized string so we pass the original image to Photon.
487
					if ( ! $fullsize_url && 0 === strpos( $src, $upload_dir['baseurl'] ) ) {
488
						$src = self::strip_image_dimensions_maybe( $src );
489
					}
490
491
					// Build array of Photon args and expose to filter before passing to Photon URL function.
492
					$args = array();
493
494 View Code Duplication
					if ( false !== $width && false !== $height ) {
495
						$args[ $transform ] = $width . ',' . $height;
496
					} elseif ( false !== $width ) {
497
						$args['w'] = $width;
498
					} elseif ( false !== $height ) {
499
						$args['h'] = $height;
500
					}
501
502
					/**
503
					 * Filter the array of Photon arguments added to an image when it goes through Photon.
504
					 * By default, only includes width and height values.
505
					 *
506
					 * @see https://developer.wordpress.com/docs/photon/api/
507
					 *
508
					 * @module photon
509
					 *
510
					 * @since 2.0.0
511
					 *
512
					 * @param array $args Array of Photon Arguments.
513
					 * @param array $details {
514
					 *     Array of image details.
515
					 *
516
					 *     @type string    $tag            Image tag (Image HTML output).
517
					 *     @type string    $src            Image URL.
518
					 *     @type string    $src_orig       Original Image URL.
519
					 *     @type int|false $width          Image width.
520
					 *     @type int|false $height         Image height.
521
					 *     @type int|false $width_orig     Original image width before constrained by content_width.
522
					 *     @type int|false $height_orig    Original Image height before constrained by content_width.
523
					 *     @type string    $transform      Transform.
524
					 *     @type string    $transform_orig Original transform before constrained by content_width.
525
					 * }
526
					 */
527
					$args = apply_filters( 'jetpack_photon_post_image_args', $args, compact( 'tag', 'src', 'src_orig', 'width', 'height', 'width_orig', 'height_orig', 'transform', 'transform_orig' ) );
528
529
					$photon_url = jetpack_photon_url( $src, $args );
530
531
					// Modify image tag if Photon function provides a URL
532
					// Ensure changes are only applied to the current image by copying and modifying the matched tag, then replacing the entire tag with our modified version.
533
					if ( $src !== $photon_url ) {
534
						$new_tag = $tag;
535
536
						// If present, replace the link href with a Photoned URL for the full-size image.
537
						if ( ! empty( $images['link_url'][ $index ] ) && self::validate_image_url( $images['link_url'][ $index ] ) ) {
538
							$new_tag = preg_replace( '#(href=["|\'])' . preg_quote( $images['link_url'][ $index ], '#' ) . '(["|\'])#i', '\1' . jetpack_photon_url( $images['link_url'][ $index ] ) . '\2', $new_tag, 1 );
539
						}
540
541
						// Supplant the original source value with our Photon URL.
542
						$photon_url = esc_url( $photon_url );
543
						$new_tag    = str_replace( $src_orig, $photon_url, $new_tag );
544
545
						// If Lazy Load is in use, pass placeholder image through Photon.
546
						if ( isset( $placeholder_src ) && self::validate_image_url( $placeholder_src ) ) {
547
							$placeholder_src = jetpack_photon_url( $placeholder_src );
548
549
							if ( $placeholder_src !== $placeholder_src_orig ) {
550
								$new_tag = str_replace( $placeholder_src_orig, esc_url( $placeholder_src ), $new_tag );
551
							}
552
553
							unset( $placeholder_src );
554
						}
555
556
						// If we are not transforming the image with resize, fit, or letterbox (lb), then we should remove
557
						// the width and height arguments (including HTML4 percentages) from the image to prevent distortion.
558
						// Even if $args['w'] and $args['h'] are present, Photon does not crop to those dimensions. Instead,
559
						// it appears to favor height.
560
						//
561
						// If we are transforming the image via one of those methods, let's update the width and height attributes.
562
						if ( empty( $args['resize'] ) && empty( $args['fit'] ) && empty( $args['lb'] ) ) {
563
							$new_tag = preg_replace( '#(?<=\s)(width|height)=["|\']?[\d%]+["|\']?\s?#i', '', $new_tag );
564
						} else {
565
							$resize_args = isset( $args['resize'] ) ? $args['resize'] : false;
566 View Code Duplication
							if ( false === $resize_args ) {
567
								$resize_args = ( ! $resize_args && isset( $args['fit'] ) )
568
									? $args['fit']
569
									: false;
570
							}
571 View Code Duplication
							if ( false === $resize_args ) {
572
								$resize_args = ( ! $resize_args && isset( $args['lb'] ) )
573
									? $args['lb']
574
									: false;
575
							}
576
577
							$resize_args = array_map( 'trim', explode( ',', $resize_args ) );
578
579
							// (?<=\s)         - Ensure width or height attribute is preceded by a space
580
							// (width=["|\']?) - Matches, and captures, width=, width=", or width='
581
							// [\d%]+          - Matches 1 or more digits or percent signs
582
							// (["|\']?)       - Matches, and captures, ", ', or empty string
583
							// \s              - Ensures there's a space after the attribute
584
							$new_tag = preg_replace( '#(?<=\s)(width=["|\']?)[\d%]+(["|\']?)\s?#i', sprintf( '${1}%d${2} ', $resize_args[0] ), $new_tag );
585
							$new_tag = preg_replace( '#(?<=\s)(height=["|\']?)[\d%]+(["|\']?)\s?#i', sprintf( '${1}%d${2} ', $resize_args[1] ), $new_tag );
586
						}
587
588
						// Tag an image for dimension checking.
589
						if ( ! self::is_amp_endpoint() ) {
590
							$new_tag = preg_replace( '#(\s?/)?>(\s*</a>)?$#i', ' data-recalc-dims="1"\1>\2', $new_tag );
591
						}
592
593
						// Replace original tag with modified version.
594
						$content = str_replace( $tag, $new_tag, $content );
595
					}
596
				} elseif ( preg_match( '#^http(s)?://i[\d]{1}.wp.com#', $src ) && ! empty( $images['link_url'][ $index ] ) && self::validate_image_url( $images['link_url'][ $index ] ) ) {
597
					$new_tag = preg_replace( '#(href=["|\'])' . preg_quote( $images['link_url'][ $index ], '#' ) . '(["|\'])#i', '\1' . jetpack_photon_url( $images['link_url'][ $index ] ) . '\2', $tag, 1 );
598
599
					$content = str_replace( $tag, $new_tag, $content );
600
				}
601
			}
602
		}
603
604
		return $content;
605
	}
606
607
	/**
608
	 * Filter Core galleries
609
	 *
610
	 * @param array $galleries Gallery array.
611
	 *
612
	 * @return array
613
	 */
614
	public static function filter_the_galleries( $galleries ) {
615
		if ( empty( $galleries ) || ! is_array( $galleries ) ) {
616
			return $galleries;
617
		}
618
619
		// Pass by reference, so we can modify them in place.
620
		foreach ( $galleries as &$this_gallery ) {
621
			if ( is_string( $this_gallery ) ) {
622
				$this_gallery = self::filter_the_content( $this_gallery );
623
			}
624
		}
625
		unset( $this_gallery ); // break the reference.
626
627
		return $galleries;
628
	}
629
630
631
	/**
632
	 * Runs the image widget through photon.
633
	 *
634
	 * @param array $instance Image widget instance data.
635
	 * @return array
636
	 */
637
	public static function filter_the_image_widget( $instance ) {
638
		if ( Jetpack::is_module_active( 'photon' ) && ! $instance['attachment_id'] && $instance['url'] ) {
639
			jetpack_photon_url(
640
				$instance['url'],
641
				array(
642
					'w' => $instance['width'],
643
					'h' => $instance['height'],
644
				)
645
			);
646
		}
647
648
		return $instance;
649
	}
650
651
	/**
652
	 * * CORE IMAGE RETRIEVAL
653
	 **/
654
655
	/**
656
	 * Filter post thumbnail image retrieval, passing images through Photon
657
	 *
658
	 * @param string|bool  $image Image URL.
659
	 * @param int          $attachment_id Attachment ID.
660
	 * @param string|array $size Declared size or a size array.
661
	 * @uses is_admin, apply_filters, wp_get_attachment_url, self::validate_image_url, this::image_sizes, jetpack_photon_url
662
	 * @filter image_downsize
663
	 * @return string|bool
664
	 */
665
	public function filter_image_downsize( $image, $attachment_id, $size ) {
666
		// Don't foul up the admin side of things, unless a plugin wants to.
667
		if ( is_admin() &&
668
			/**
669
			 * Provide plugins a way of running Photon for images in the WordPress Dashboard (wp-admin).
670
			 *
671
			 * Note: enabling this will result in Photon URLs added to your post content, which could make migrations across domains (and off Photon) a bit more challenging.
672
			 *
673
			 * @module photon
674
			 *
675
			 * @since 4.8.0
676
			 *
677
			 * @param bool false Stop Photon from being run on the Dashboard. Default to false.
678
			 * @param array $args {
679
			 *   Array of image details.
680
			 *
681
			 *   @type $image Image URL.
682
			 *   @type $attachment_id Attachment ID of the image.
683
			 *   @type $size Image size. Can be a string (name of the image size, e.g. full) or an array of width and height.
684
			 * }
685
			 */
686
			false === apply_filters( 'jetpack_photon_admin_allow_image_downsize', false, compact( 'image', 'attachment_id', 'size' ) )
687
		) {
688
			return $image;
689
		}
690
691
		/**
692
		 * Provide plugins a way of preventing Photon from being applied to images retrieved from WordPress Core.
693
		 *
694
		 * @module photon
695
		 *
696
		 * @since 2.0.0
697
		 *
698
		 * @param bool false Stop Photon from being applied to the image. Default to false.
699
		 * @param array $args {
700
		 *   Array of image details.
701
		 *
702
		 *   @type $image Image URL.
703
		 *   @type $attachment_id Attachment ID of the image.
704
		 *   @type $size Image size. Can be a string (name of the image size, e.g. full) or an array of width and height.
705
		 * }
706
		 */
707
		if ( apply_filters( 'jetpack_photon_override_image_downsize', false, compact( 'image', 'attachment_id', 'size' ) ) ) {
708
			return $image;
709
		}
710
711
		// Get the image URL and proceed with Photon-ification if successful.
712
		$image_url = wp_get_attachment_url( $attachment_id );
713
714
		// Set this to true later when we know we have size meta.
715
		$has_size_meta = false;
716
717
		if ( $image_url ) {
718
			// Check if image URL should be used with Photon.
719
			if ( ! self::validate_image_url( $image_url ) ) {
720
				return $image;
721
			}
722
723
			$intermediate = true; // For the fourth array item returned by the image_downsize filter.
724
725
			// If an image is requested with a size known to WordPress, use that size's settings with Photon.
726
			// WP states that `add_image_size()` should use a string for the name, but doesn't enforce that.
727
			// Due to differences in how Core and Photon check for the registered image size, we check both types.
728
			if ( ( is_string( $size ) || is_int( $size ) ) && array_key_exists( $size, self::image_sizes() ) ) {
729
				$image_args = self::image_sizes();
730
				$image_args = $image_args[ $size ];
731
732
				$photon_args = array();
733
734
				$image_meta = image_get_intermediate_size( $attachment_id, $size );
735
736
				// 'full' is a special case: We need consistent data regardless of the requested size.
737
				if ( 'full' === $size ) {
738
					$image_meta   = wp_get_attachment_metadata( $attachment_id );
739
					$intermediate = false;
740
				} elseif ( ! $image_meta ) {
741
					// If we still don't have any image meta at this point, it's probably from a custom thumbnail size
742
					// for an image that was uploaded before the custom image was added to the theme.  Try to determine the size manually.
743
					$image_meta = wp_get_attachment_metadata( $attachment_id );
744
745
					if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
746
						$image_resized = image_resize_dimensions( $image_meta['width'], $image_meta['height'], $image_args['width'], $image_args['height'], $image_args['crop'] );
747
						if ( $image_resized ) { // This could be false when the requested image size is larger than the full-size image.
748
							$image_meta['width']  = $image_resized[6];
749
							$image_meta['height'] = $image_resized[7];
750
						}
751
					}
752
				}
753
754
				if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
755
					$image_args['width']  = $image_meta['width'];
756
					$image_args['height'] = $image_meta['height'];
757
758
					list( $image_args['width'], $image_args['height'] ) = image_constrain_size_for_editor( $image_args['width'], $image_args['height'], $size, 'display' );
759
					$has_size_meta                                      = true;
760
				}
761
762
				// Expose determined arguments to a filter before passing to Photon.
763
				$transform = $image_args['crop'] ? 'resize' : 'fit';
764
765
				// Check specified image dimensions and account for possible zero values; photon fails to resize if a dimension is zero.
766
				if ( 0 === $image_args['width'] || 0 === $image_args['height'] ) {
767
					if ( 0 === $image_args['width'] && 0 < $image_args['height'] ) {
768
						$photon_args['h'] = $image_args['height'];
769
					} elseif ( 0 === $image_args['height'] && 0 < $image_args['width'] ) {
770
						$photon_args['w'] = $image_args['width'];
771
					}
772
				} else {
773
					$image_meta = wp_get_attachment_metadata( $attachment_id );
774
					if ( ( 'resize' === $transform ) && $image_meta ) {
775
						if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
776
							// Lets make sure that we don't upscale images since wp never upscales them as well.
777
							$smaller_width  = ( ( $image_meta['width'] < $image_args['width'] ) ? $image_meta['width'] : $image_args['width'] );
778
							$smaller_height = ( ( $image_meta['height'] < $image_args['height'] ) ? $image_meta['height'] : $image_args['height'] );
779
780
							$photon_args[ $transform ] = $smaller_width . ',' . $smaller_height;
781
						}
782
					} else {
783
						$photon_args[ $transform ] = $image_args['width'] . ',' . $image_args['height'];
784
					}
785
				}
786
787
				/**
788
				 * Filter the Photon Arguments added to an image when going through Photon, when that image size is a string.
789
				 * Image size will be a string (e.g. "full", "medium") when it is known to WordPress.
790
				 *
791
				 * @module photon
792
				 *
793
				 * @since 2.0.0
794
				 *
795
				 * @param array $photon_args Array of Photon arguments.
796
				 * @param array $args {
797
				 *   Array of image details.
798
				 *
799
				 *   @type array $image_args Array of Image arguments (width, height, crop).
800
				 *   @type string $image_url Image URL.
801
				 *   @type int $attachment_id Attachment ID of the image.
802
				 *   @type string|int $size Image size. Can be a string (name of the image size, e.g. full) or an integer.
803
				 *   @type string $transform Value can be resize or fit.
804
				 *                    @see https://developer.wordpress.com/docs/photon/api
805
				 * }
806
				 */
807
				$photon_args = apply_filters( 'jetpack_photon_image_downsize_string', $photon_args, compact( 'image_args', 'image_url', 'attachment_id', 'size', 'transform' ) );
808
809
				// Generate Photon URL.
810
				$image = array(
811
					jetpack_photon_url( $image_url, $photon_args ),
812
					$has_size_meta ? $image_args['width'] : false,
813
					$has_size_meta ? $image_args['height'] : false,
814
					$intermediate,
815
				);
816
			} elseif ( is_array( $size ) ) {
817
				// Pull width and height values from the provided array, if possible.
818
				$width  = isset( $size[0] ) ? (int) $size[0] : false;
819
				$height = isset( $size[1] ) ? (int) $size[1] : false;
820
821
				// Don't bother if necessary parameters aren't passed.
822
				if ( ! $width || ! $height ) {
823
					return $image;
824
				}
825
826
				$image_meta = wp_get_attachment_metadata( $attachment_id );
827
				if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
828
					$image_resized = image_resize_dimensions( $image_meta['width'], $image_meta['height'], $width, $height );
829
830
					if ( $image_resized ) { // This could be false when the requested image size is larger than the full-size image.
831
						$width  = $image_resized[6];
832
						$height = $image_resized[7];
833
					} else {
834
						$width  = $image_meta['width'];
835
						$height = $image_meta['height'];
836
					}
837
838
					$has_size_meta = true;
839
				}
840
841
				list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
842
843
				// Expose arguments to a filter before passing to Photon.
844
				$photon_args = array(
845
					'fit' => $width . ',' . $height,
846
				);
847
848
				/**
849
				 * Filter the Photon Arguments added to an image when going through Photon,
850
				 * when the image size is an array of height and width values.
851
				 *
852
				 * @module photon
853
				 *
854
				 * @since 2.0.0
855
				 *
856
				 * @param array $photon_args Array of Photon arguments.
857
				 * @param array $args {
858
				 *   Array of image details.
859
				 *
860
				 *   @type $width Image width.
861
				 *   @type height Image height.
862
				 *   @type $image_url Image URL.
863
				 *   @type $attachment_id Attachment ID of the image.
864
				 * }
865
				 */
866
				$photon_args = apply_filters( 'jetpack_photon_image_downsize_array', $photon_args, compact( 'width', 'height', 'image_url', 'attachment_id' ) );
867
868
				// Generate Photon URL.
869
				$image = array(
870
					jetpack_photon_url( $image_url, $photon_args ),
871
					$has_size_meta ? $width : false,
872
					$has_size_meta ? $height : false,
873
					$intermediate,
874
				);
875
			}
876
		}
877
878
		return $image;
879
	}
880
881
	/**
882
	 * Filters an array of image `srcset` values, replacing each URL with its Photon equivalent.
883
	 *
884
	 * @since 3.8.0
885
	 * @since 4.0.4 Added automatically additional sizes beyond declared image sizes.
886
	 *
887
	 * @param array $sources An array of image urls and widths.
888
	 * @param array $size_array The size array for srcset.
889
	 * @param array $image_src The image srcs.
890
	 * @param array $image_meta The image meta.
891
	 * @param int   $attachment_id Attachment ID.
892
	 *
893
	 * @uses self::validate_image_url, jetpack_photon_url, Jetpack_Photon::parse_from_filename
894
	 * @uses Jetpack_Photon::strip_image_dimensions_maybe, Jetpack::get_content_width
895
	 *
896
	 * @return array An array of Photon image urls and widths.
897
	 */
898
	public function filter_srcset_array( $sources = array(), $size_array = array(), $image_src = array(), $image_meta = array(), $attachment_id = 0 ) {
899
		if ( ! is_array( $sources ) ) {
900
			return $sources;
901
		}
902
		$upload_dir = wp_get_upload_dir();
903
904
		foreach ( $sources as $i => $source ) {
905
			if ( ! self::validate_image_url( $source['url'] ) ) {
906
				continue;
907
			}
908
909
			/** This filter is already documented in class.photon.php */
910
			if ( apply_filters( 'jetpack_photon_skip_image', false, $source['url'], $source ) ) {
911
				continue;
912
			}
913
914
			$url                    = $source['url'];
915
			list( $width, $height ) = self::parse_dimensions_from_filename( $url );
916
917
			// It's quicker to get the full size with the data we have already, if available.
918
			if ( ! empty( $attachment_id ) ) {
919
				$url = wp_get_attachment_url( $attachment_id );
920
			} else {
921
				$url = self::strip_image_dimensions_maybe( $url );
922
			}
923
924
			$args = array();
925
			if ( 'w' === $source['descriptor'] ) {
926
				if ( $height && ( $source['value'] === $width ) ) {
927
					$args['resize'] = $width . ',' . $height;
928
				} else {
929
					$args['w'] = $source['value'];
930
				}
931
			}
932
933
			$sources[ $i ]['url'] = jetpack_photon_url( $url, $args );
934
		}
935
936
		/**
937
		 * At this point, $sources is the original srcset with Photonized URLs.
938
		 * Now, we're going to construct additional sizes based on multiples of the content_width.
939
		 * This will reduce the gap between the largest defined size and the original image.
940
		 */
941
942
		/**
943
		 * Filter the multiplier Photon uses to create new srcset items.
944
		 * Return false to short-circuit and bypass auto-generation.
945
		 *
946
		 * @module photon
947
		 *
948
		 * @since 4.0.4
949
		 *
950
		 * @param array|bool $multipliers Array of multipliers to use or false to bypass.
951
		 */
952
		$multipliers = apply_filters( 'jetpack_photon_srcset_multipliers', array( 2, 3 ) );
953
		$url         = trailingslashit( $upload_dir['baseurl'] ) . $image_meta['file'];
954
955
		if (
956
			/** Short-circuit via jetpack_photon_srcset_multipliers filter. */
957
			is_array( $multipliers )
958
			/** This filter is already documented in class.photon.php */
959
			&& ! apply_filters( 'jetpack_photon_skip_image', false, $url, null )
960
			/** Verify basic meta is intact. */
961
			&& isset( $image_meta['width'] ) && isset( $image_meta['height'] ) && isset( $image_meta['file'] )
962
			/** Verify we have the requested width/height. */
963
			&& isset( $size_array[0] ) && isset( $size_array[1] )
964
			) {
965
966
			$fullwidth  = $image_meta['width'];
967
			$fullheight = $image_meta['height'];
968
			$reqwidth   = $size_array[0];
969
			$reqheight  = $size_array[1];
970
971
			$constrained_size = wp_constrain_dimensions( $fullwidth, $fullheight, $reqwidth );
972
			$expected_size    = array( $reqwidth, $reqheight );
973
974
			if ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 ) {
975
				$crop = 'soft';
976
				$base = Jetpack::get_content_width() ? Jetpack::get_content_width() : 1000; // Provide a default width if none set by the theme.
977
			} else {
978
				$crop = 'hard';
979
				$base = $reqwidth;
980
			}
981
982
			$currentwidths = array_keys( $sources );
983
			$newsources    = null;
984
985
			foreach ( $multipliers as $multiplier ) {
986
987
				$newwidth = $base * $multiplier;
988
				foreach ( $currentwidths as $currentwidth ) {
989
					// If a new width would be within 100 pixes of an existing one or larger than the full size image, skip.
990
					if ( abs( $currentwidth - $newwidth ) < 50 || ( $newwidth > $fullwidth ) ) {
991
						continue 2; // Bump out back to the $multipliers as $multiplier.
992
					}
993
				} //end foreach ( $currentwidths as $currentwidth ){
994
995
				if ( 'soft' === $crop ) {
996
					$args = array(
997
						'w' => $newwidth,
998
					);
999
				} else { // hard crop, e.g. add_image_size( 'example', 200, 200, true ).
1000
					$args = array(
1001
						'zoom'   => $multiplier,
1002
						'resize' => $reqwidth . ',' . $reqheight,
1003
					);
1004
				}
1005
1006
				$newsources[ $newwidth ] = array(
1007
					'url'        => jetpack_photon_url( $url, $args ),
1008
					'descriptor' => 'w',
1009
					'value'      => $newwidth,
1010
				);
1011
			} //end foreach ( $multipliers as $multiplier )
1012
			if ( is_array( $newsources ) ) {
1013
				$sources = array_replace( $sources, $newsources );
1014
			}
1015
		} //end if isset( $image_meta['width'] ) && isset( $image_meta['file'] ) )
1016
1017
		return $sources;
1018
	}
1019
1020
	/**
1021
	 * Filters an array of image `sizes` values, using $content_width instead of image's full size.
1022
	 *
1023
	 * @since 4.0.4
1024
	 * @since 4.1.0 Returns early for images not within the_content.
1025
	 * @param array $sizes An array of media query breakpoints.
1026
	 * @param array $size  Width and height of the image.
1027
	 * @uses Jetpack::get_content_width
1028
	 * @return array An array of media query breakpoints.
1029
	 */
1030
	public function filter_sizes( $sizes, $size ) {
1031
		if ( ! doing_filter( 'the_content' ) ) {
1032
			return $sizes;
1033
		}
1034
		$content_width = Jetpack::get_content_width();
1035
		if ( ! $content_width ) {
1036
			$content_width = 1000;
1037
		}
1038
1039
		if ( ( is_array( $size ) && $size[0] < $content_width ) ) {
1040
			return $sizes;
1041
		}
1042
1043
		return sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $content_width );
1044
	}
1045
1046
	/**
1047
	 * * GENERAL FUNCTIONS
1048
	 **/
1049
1050
	/**
1051
	 * Ensure image URL is valid for Photon.
1052
	 * Though Photon functions address some of the URL issues, we should avoid unnecessary processing if we know early on that the image isn't supported.
1053
	 *
1054
	 * @param string $url Image URL.
1055
	 * @uses wp_parse_args
1056
	 * @return bool
1057
	 */
1058
	protected static function validate_image_url( $url ) {
1059
		$parsed_url = wp_parse_url( $url );
1060
1061
		if ( ! $parsed_url ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parsed_url of type string|false is loosely compared to false; 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...
1062
			return false;
1063
		}
1064
1065
		// Parse URL and ensure needed keys exist, since the array returned by `wp_parse_url` only includes the URL components it finds.
1066
		$url_info = wp_parse_args(
1067
			$parsed_url,
1068
			array(
1069
				'scheme' => null,
1070
				'host'   => null,
1071
				'port'   => null,
1072
				'path'   => null,
1073
			)
1074
		);
1075
1076
		// Bail if scheme isn't http or port is set that isn't port 80.
1077
		if (
1078
			( 'http' !== $url_info['scheme'] || ! in_array( $url_info['port'], array( 80, null ), true ) ) &&
1079
			/**
1080
			 * Allow Photon to fetch images that are served via HTTPS.
1081
			 *
1082
			 * @module photon
1083
			 *
1084
			 * @since 2.4.0
1085
			 * @since 3.9.0 Default to false.
1086
			 *
1087
			 * @param bool $reject_https Should Photon ignore images using the HTTPS scheme. Default to false.
1088
			 */
1089
			apply_filters( 'jetpack_photon_reject_https', false )
1090
		) {
1091
			return false;
1092
		}
1093
1094
		// Bail if no host is found.
1095
		if ( is_null( $url_info['host'] ) ) {
1096
			return false;
1097
		}
1098
1099
		// Bail if the image already went through Photon.
1100
		if ( preg_match( '#^i[\d]{1}.wp.com$#i', $url_info['host'] ) ) {
1101
			return false;
1102
		}
1103
1104
		// Bail if no path is found.
1105
		if ( is_null( $url_info['path'] ) ) {
1106
			return false;
1107
		}
1108
1109
		// Ensure image extension is acceptable.
1110
		if ( ! in_array( strtolower( pathinfo( $url_info['path'], PATHINFO_EXTENSION ) ), self::$extensions, true ) ) {
1111
			return false;
1112
		}
1113
1114
		// If we got this far, we should have an acceptable image URL
1115
		// But let folks filter to decline if they prefer.
1116
		/**
1117
		 * Overwrite the results of the validation steps an image goes through before to be considered valid to be used by Photon.
1118
		 *
1119
		 * @module photon
1120
		 *
1121
		 * @since 3.0.0
1122
		 *
1123
		 * @param bool true Is the image URL valid and can it be used by Photon. Default to true.
1124
		 * @param string $url Image URL.
1125
		 * @param array $parsed_url Array of information about the image.
1126
		 */
1127
		return apply_filters( 'photon_validate_image_url', true, $url, $parsed_url );
1128
	}
1129
1130
	/**
1131
	 * Checks if the file exists before it passes the file to photon.
1132
	 *
1133
	 * @param string $src The image URL.
1134
	 * @return string
1135
	 **/
1136
	public static function strip_image_dimensions_maybe( $src ) {
1137
		$stripped_src = $src;
1138
1139
		// Build URL, first removing WP's resized string so we pass the original image to Photon.
1140
		if ( preg_match( '#(-\d+x\d+)\.(' . implode( '|', self::$extensions ) . '){1}$#i', $src, $src_parts ) ) {
1141
			$stripped_src = str_replace( $src_parts[1], '', $src );
1142
			$upload_dir   = wp_get_upload_dir();
1143
1144
			// Extracts the file path to the image minus the base url.
1145
			$file_path = substr( $stripped_src, strlen( $upload_dir['baseurl'] ) );
1146
1147
			if ( file_exists( $upload_dir['basedir'] . $file_path ) ) {
1148
				$src = $stripped_src;
1149
			}
1150
		}
1151
1152
		return $src;
1153
	}
1154
1155
	/**
1156
	 * Provide an array of available image sizes and corresponding dimensions.
1157
	 * Similar to get_intermediate_image_sizes() except that it includes image sizes' dimensions, not just their names.
1158
	 *
1159
	 * @global $wp_additional_image_sizes
1160
	 * @uses get_option
1161
	 * @return array
1162
	 */
1163
	protected static function image_sizes() {
1164
		if ( null === self::$image_sizes ) {
1165
			global $_wp_additional_image_sizes;
1166
1167
			// Populate an array matching the data structure of $_wp_additional_image_sizes so we have a consistent structure for image sizes.
1168
			$images = array(
1169
				'thumb'        => array(
1170
					'width'  => (int) get_option( 'thumbnail_size_w' ),
1171
					'height' => (int) get_option( 'thumbnail_size_h' ),
1172
					'crop'   => (bool) get_option( 'thumbnail_crop' ),
1173
				),
1174
				'medium'       => array(
1175
					'width'  => (int) get_option( 'medium_size_w' ),
1176
					'height' => (int) get_option( 'medium_size_h' ),
1177
					'crop'   => false,
1178
				),
1179
				'medium_large' => array(
1180
					'width'  => (int) get_option( 'medium_large_size_w' ),
1181
					'height' => (int) get_option( 'medium_large_size_h' ),
1182
					'crop'   => false,
1183
				),
1184
				'large'        => array(
1185
					'width'  => (int) get_option( 'large_size_w' ),
1186
					'height' => (int) get_option( 'large_size_h' ),
1187
					'crop'   => false,
1188
				),
1189
				'full'         => array(
1190
					'width'  => null,
1191
					'height' => null,
1192
					'crop'   => false,
1193
				),
1194
			);
1195
1196
			// Compatibility mapping as found in wp-includes/media.php.
1197
			$images['thumbnail'] = $images['thumb'];
1198
1199
			// Update class variable, merging in $_wp_additional_image_sizes if any are set.
1200
			if ( is_array( $_wp_additional_image_sizes ) && ! empty( $_wp_additional_image_sizes ) ) {
1201
				self::$image_sizes = array_merge( $images, $_wp_additional_image_sizes );
1202
			} else {
1203
				self::$image_sizes = $images;
1204
			}
1205
		}
1206
1207
		return is_array( self::$image_sizes ) ? self::$image_sizes : array();
1208
	}
1209
1210
	/**
1211
	 * Pass og:image URLs through Photon
1212
	 *
1213
	 * @param array $tags Open graph tags.
1214
	 * @param array $parameters Image parameters.
1215
	 * @uses jetpack_photon_url
1216
	 * @return array Open graph tags.
1217
	 */
1218
	public function filter_open_graph_tags( $tags, $parameters ) {
1219
		if ( empty( $tags['og:image'] ) ) {
1220
			return $tags;
1221
		}
1222
1223
		$photon_args = array(
1224
			'fit' => sprintf( '%d,%d', 2 * $parameters['image_width'], 2 * $parameters['image_height'] ),
1225
		);
1226
1227
		if ( is_array( $tags['og:image'] ) ) {
1228
			$images = array();
1229
			foreach ( $tags['og:image'] as $image ) {
1230
				$images[] = jetpack_photon_url( $image, $photon_args );
1231
			}
1232
			$tags['og:image'] = $images;
1233
		} else {
1234
			$tags['og:image'] = jetpack_photon_url( $tags['og:image'], $photon_args );
1235
		}
1236
1237
		return $tags;
1238
	}
1239
1240
	/**
1241
	 * Returns empty array.
1242
	 *
1243
	 * @deprecated 8.8.0 Use filter_photon_noresize_intermediate_sizes.
1244
	 *
1245
	 * @return array Empty array.
1246
	 */
1247
	public function noresize_intermediate_sizes() {
1248
		_deprecated_function( __METHOD__, 'jetpack-8.8.0', '::filter_photon_noresize_intermediate_sizes' );
1249
		return __return_empty_array();
1250
	}
1251
1252
	/**
1253
	 * Enqueue Photon helper script
1254
	 *
1255
	 * @uses wp_enqueue_script, plugins_url
1256
	 * @action wp_enqueue_script
1257
	 * @return null
1258
	 */
1259
	public function action_wp_enqueue_scripts() {
1260
		if ( self::is_amp_endpoint() ) {
1261
			return;
1262
		}
1263
		wp_enqueue_script(
1264
			'jetpack-photon',
1265
			Assets::get_file_url_for_environment(
1266
				'_inc/build/photon/photon.min.js',
1267
				'modules/photon/photon.js'
1268
			),
1269
			array(),
1270
			20191001,
1271
			true
1272
		);
1273
	}
1274
1275
	/**
1276
	 * Determine if image_downsize should utilize Photon via REST API.
1277
	 *
1278
	 * The WordPress Block Editor (Gutenberg) and other REST API consumers using the wp/v2/media endpoint, especially in the "edit"
1279
	 * context is more akin to the is_admin usage of Photon (see filter_image_downsize). Since consumers are trying to edit content in posts,
1280
	 * Photon should not fire as it will fire later on display. By aborting an attempt to Photonize an image here, we
1281
	 * prevents issues like https://github.com/Automattic/jetpack/issues/10580 .
1282
	 *
1283
	 * To determine if we're using the wp/v2/media endpoint, we hook onto the `rest_request_before_callbacks` filter and
1284
	 * if determined we are using it in the edit context, we'll false out the `jetpack_photon_override_image_downsize` filter.
1285
	 *
1286
	 * @see Jetpack_Photon::filter_image_downsize()
1287
	 *
1288
	 * @param null|WP_Error   $response REST API response.
1289
	 * @param array           $endpoint_data Endpoint data. Not used, but part of the filter.
1290
	 * @param WP_REST_Request $request  Request used to generate the response.
1291
	 *
1292
	 * @return null|WP_Error The original response object without modification.
1293
	 */
1294
	public function should_rest_photon_image_downsize( $response, $endpoint_data, $request ) {
1295
		if ( ! is_a( $request, 'WP_REST_Request' ) ) {
1296
			return $response; // Something odd is happening. Do nothing and return the response.
1297
		}
1298
1299
		if ( is_wp_error( $response ) ) {
1300
			// If we're going to return an error, we don't need to do anything with Photon.
1301
			return $response;
1302
		}
1303
1304
		$this->should_rest_photon_image_downsize_override( $request );
1305
1306
		return $response;
1307
1308
	}
1309
1310
	/**
1311
	 * Helper function to check if a WP_REST_Request is the media endpoint in the edit context.
1312
	 *
1313
	 * @param WP_REST_Request $request The current REST request.
1314
	 */
1315
	private function should_rest_photon_image_downsize_override( WP_REST_Request $request ) {
1316
		$route = $request->get_route();
1317
1318
		if (
1319
			(
1320
				false !== strpos( $route, 'wp/v2/media' )
1321
				&& 'edit' === $request->get_param( 'context' )
1322
			)
1323
			|| false !== strpos( $route, 'wpcom/v2/external-media/copy' )
1324
		) {
1325
			// Don't use `__return_true()`: Use something unique. See ::_override_image_downsize_in_rest_edit_context()
1326
			// Late execution to avoid conflict with other plugins as we really don't want to run in this situation.
1327
			add_filter(
1328
				'jetpack_photon_override_image_downsize',
1329
				array(
1330
					$this,
1331
					'override_image_downsize_in_rest_edit_context',
1332
				),
1333
				999999
1334
			);
1335
		}
1336
	}
1337
1338
	/**
1339
	 * Brings in should_rest_photon_image_downsize for the rest_after_insert_attachment hook.
1340
	 *
1341
	 * @since 8.7.0
1342
	 *
1343
	 * @param WP_Post         $attachment Inserted or updated attachment object.
1344
	 * @param WP_REST_Request $request    Request object.
1345
	 */
1346
	public function should_rest_photon_image_downsize_insert_attachment( WP_Post $attachment, WP_REST_Request $request ) {
1347
		if ( ! is_a( $request, 'WP_REST_Request' ) ) {
1348
			// Something odd is happening.
1349
			return;
1350
		}
1351
1352
		$this->should_rest_photon_image_downsize_override( $request );
1353
1354
	}
1355
1356
	/**
1357
	 * Remove the override we may have added in ::should_rest_photon_image_downsize()
1358
	 * Since ::_override_image_downsize_in_rest_edit_context() is only
1359
	 * every used here, we can always remove it without ever worrying
1360
	 * about breaking any other configuration.
1361
	 *
1362
	 * @param mixed $response REST API Response.
1363
	 * @return mixed Unchanged $response
1364
	 */
1365
	public function cleanup_rest_photon_image_downsize( $response ) {
1366
		remove_filter(
1367
			'jetpack_photon_override_image_downsize',
1368
			array(
1369
				$this,
1370
				'override_image_downsize_in_rest_edit_context',
1371
			),
1372
			999999
1373
		);
1374
		return $response;
1375
	}
1376
1377
	/**
1378
	 * Used internally by ::should_rest_photon_image_downsize() to not photonize
1379
	 * image URLs in ?context=edit REST requests.
1380
	 * MUST NOT be used anywhere else.
1381
	 * We use a unique function instead of __return_true so that we can clean up
1382
	 * after ourselves without breaking anyone else's filters.
1383
	 *
1384
	 * @internal
1385
	 * @return true
1386
	 */
1387
	public function override_image_downsize_in_rest_edit_context() {
1388
		return true;
1389
	}
1390
1391
	/**
1392
	 * Return whether the current page is AMP.
1393
	 *
1394
	 * This is only present for the sake of WordPress.com where the Jetpack_AMP_Support
1395
	 * class does not yet exist. This mehod may only be called at the wp action or later.
1396
	 *
1397
	 * @return bool Whether AMP page.
1398
	 */
1399
	private static function is_amp_endpoint() {
1400
		return class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request();
1401
	}
1402
}
1403