Completed
Push — try/statically-access-asset-to... ( e50fad...74c9e7 )
by
unknown
126:59 queued 118:11
created

class.photon.php (5 issues)

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
2
3
use Automattic\Jetpack\Assets;
4
5
class Jetpack_Photon {
6
	/**
7
	 * Class variables
8
	 */
9
	// Oh look, a singleton
10
	private static $__instance = null;
11
12
	// Allowed extensions must match http://code.trac.wordpress.org/browser/photon/index.php#L31
13
	protected static $extensions = array(
14
		'gif',
15
		'jpg',
16
		'jpeg',
17
		'png'
18
	);
19
20
	// Don't access this directly. Instead, use self::image_sizes() so it's actually populated with something.
21
	protected static $image_sizes = null;
22
23
	/**
24
	 * Singleton implementation
25
	 *
26
	 * @return object
27
	 */
28
	public static function instance() {
29
		if ( ! is_a( self::$__instance, 'Jetpack_Photon' ) ) {
30
			self::$__instance = new Jetpack_Photon;
31
			self::$__instance->setup();
32
		}
33
34
		return self::$__instance;
35
	}
36
37
	/**
38
	 * Silence is golden.
39
	 */
40
	private function __construct() {}
41
42
	/**
43
	 * Register actions and filters, but only if basic Photon functions are available.
44
	 * The basic functions are found in ./functions.photon.php.
45
	 *
46
	 * @uses add_action, add_filter
47
	 * @return null
48
	 */
49
	private function setup() {
50
		if ( ! function_exists( 'jetpack_photon_url' ) ) {
51
			return;
52
		}
53
54
		// Images in post content and galleries
55
		add_filter( 'the_content', array( __CLASS__, 'filter_the_content' ), 999999 );
56
		add_filter( 'get_post_galleries', array( __CLASS__, 'filter_the_galleries' ), 999999 );
57
		add_filter( 'widget_media_image_instance', array( __CLASS__, 'filter_the_image_widget' ), 999999 );
58
59
		// Core image retrieval
60
		add_filter( 'image_downsize', array( $this, 'filter_image_downsize' ), 10, 3 );
61
		add_filter( 'rest_request_before_callbacks', array( $this, 'should_rest_photon_image_downsize' ), 10, 3 );
62
		add_filter( 'rest_request_after_callbacks', array( $this, 'cleanup_rest_photon_image_downsize' ) );
63
64
		// Responsive image srcset substitution
65
		add_filter( 'wp_calculate_image_srcset', array( $this, 'filter_srcset_array' ), 10, 5 );
66
		add_filter( 'wp_calculate_image_sizes', array( $this, 'filter_sizes' ), 1, 2 ); // Early so themes can still easily filter.
67
68
		// Helpers for maniuplated images
69
		add_action( 'wp_enqueue_scripts', array( $this, 'action_wp_enqueue_scripts' ), 9 );
70
71
		/**
72
		 * Allow Photon to disable uploaded images resizing and use its own resize capabilities instead.
73
		 *
74
		 * @module photon
75
		 *
76
		 * @since 7.1.0
77
		 *
78
		 * @param bool false Should Photon enable noresize mode. Default to false.
79
		 */
80
		if ( apply_filters( 'jetpack_photon_noresize_mode', false ) ) {
81
			$this->enable_noresize_mode();
82
		}
83
	}
84
85
	/**
86
	 * Enables the noresize mode for Photon, allowing to avoid intermediate size files generation.
87
	 */
88
	private function enable_noresize_mode() {
89
		jetpack_require_lib( 'class.jetpack-photon-image-sizes' );
90
91
		// The main objective of noresize mode is to disable additional resized image versions creation.
92
		// This filter handles removal of additional sizes.
93
		add_filter( 'intermediate_image_sizes_advanced', array( __CLASS__, 'filter_photon_noresize_intermediate_sizes' ) );
94
95
		// Load the noresize srcset solution on priority of 20, allowing other plugins to set sizes earlier.
96
		add_filter( 'wp_get_attachment_metadata', array( __CLASS__, 'filter_photon_norezise_maybe_inject_sizes' ), 20, 2 );
97
98
		// Photonize thumbnail URLs in the API response.
99
		add_filter( 'rest_api_thumbnail_size_urls', array( __CLASS__, 'filter_photon_noresize_thumbnail_urls' ) );
100
101
		// This allows to assign the Photon domain to images that normally use the home URL as base.
102
		add_filter( 'jetpack_photon_domain', array( __CLASS__, 'filter_photon_norezise_domain' ), 10, 2 );
103
104
		add_filter( 'the_content', array( __CLASS__, 'filter_content_add' ), 0 );
105
106
		// Jetpack hooks in at six nines (999999) so this filter does at seven.
107
		add_filter( 'the_content', array( __CLASS__, 'filter_content_remove' ), 9999999 );
108
109
		// Regular Photon operation mode filter doesn't run when is_admin(), so we need an additional filter.
110
		// This is temporary until Jetpack allows more easily running these filters for is_admin().
111
		if ( is_admin() ) {
112
			add_filter( 'image_downsize', array( $this, 'filter_image_downsize' ), 5, 3 );
113
114
			// Allows any image that gets passed to Photon to be resized via Photon.
115
			add_filter( 'jetpack_photon_admin_allow_image_downsize', '__return_true' );
116
		}
117
	}
118
119
	/**
120
	 * This is our catch-all to strip dimensions from intermediate images in content.
121
	 * Since this primarily only impacts post_content we do a little dance to add the filter early
122
	 * to `the_content` and then remove it later on in the same hook.
123
	 *
124
	 * @param String $content the post content.
125
	 * @return String the post content unchanged.
126
	 */
127
	public static function filter_content_add( $content ) {
128
		add_filter( 'jetpack_photon_pre_image_url', array( __CLASS__, 'strip_image_dimensions_maybe' ) );
129
		return $content;
130
	}
131
132
	/**
133
	 * Removing the content filter that was set previously.
134
	 *
135
	 * @param String $content the post content.
136
	 * @return String the post content unchanged.
137
	 */
138
	public static function filter_content_remove( $content ) {
139
		remove_filter( 'jetpack_photon_pre_image_url', array( __CLASS__, 'strip_image_dimensions_maybe' ) );
140
		return $content;
141
	}
142
143
	/**
144
	 * Short circuits the Photon filter to enable Photon processing for any URL.
145
	 *
146
	 * @param String $photon_url a proposed Photon URL for the media file.
147
	 * @param String $image_url the original media URL.
148
	 * @return String an URL to be used for the media file.
149
	 */
150
	public static function filter_photon_norezise_domain( $photon_url, $image_url ) {
151
		return $photon_url;
152
	}
153
154
	/**
155
	 * Disables intermediate sizes to disallow resizing.
156
	 *
157
	 * @param Array $sizes an array containing image sizes.
158
	 * @return Boolean
159
	 */
160
	public static function filter_photon_noresize_intermediate_sizes( $sizes ) {
161
		return array();
162
	}
163
164
	public static function filter_photon_noresize_thumbnail_urls( $sizes ) {
165
		foreach ( $sizes as $size => $url ) {
166
			$parts = explode( '?', $url );
167
			$arguments = isset( $parts[1] ) ? $parts[1] : array();
168
169
			$sizes[ $size ] = jetpack_photon_url( $url, wp_parse_args( $arguments ) );
170
		}
171
172
		return $sizes;
173
	}
174
175
	/**
176
	 * Inject image sizes to attachment metadata.
177
	 *
178
	 * @param array $data          Attachment metadata.
179
	 * @param int   $attachment_id Attachment's post ID.
180
	 *
181
	 * @return array Attachment metadata.
182
	 */
183
	public static function filter_photon_norezise_maybe_inject_sizes( $data, $attachment_id ) {
184
		// Can't do much if data is empty.
185
		if ( empty( $data ) ) {
186
			return $data;
187
		}
188
		$sizes_already_exist = (
189
			true === is_array( $data )
190
			&& true === array_key_exists( 'sizes', $data )
191
			&& true === is_array( $data['sizes'] )
192
			&& false === empty( $data['sizes'] )
193
		);
194
		if ( $sizes_already_exist ) {
195
			return $data;
196
		}
197
		// Missing some critical data we need to determine sizes, not processing.
198
		if ( ! isset( $data['file'] )
199
			|| ! isset( $data['width'] )
200
			|| ! isset( $data['height'] )
201
		) {
202
			return $data;
203
		}
204
205
		$mime_type           = get_post_mime_type( $attachment_id );
206
		$attachment_is_image = preg_match( '!^image/!', $mime_type );
207
208
		if ( 1 === $attachment_is_image ) {
209
			$image_sizes   = new Jetpack_Photon_ImageSizes( $attachment_id, $data );
210
			$data['sizes'] = $image_sizes->generate_sizes_meta();
211
		}
212
		return $data;
213
	}
214
215
	/**
216
	 * Inject image sizes to Jetpack REST API responses. This wraps the filter_photon_norezise_maybe_inject_sizes function.
217
	 *
218
	 * @param array $data          Attachment sizes data.
0 ignored issues
show
There is no parameter named $data. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
219
	 * @param int   $attachment_id Attachment's post ID.
220
	 *
221
	 * @return array Attachment sizes array.
222
	 */
223
	public static function filter_photon_norezise_maybe_inject_sizes_api( $sizes, $attachment_id ) {
224
		return self::filter_photon_norezise_maybe_inject_sizes( wp_get_attachment_metadata( $attachment_id ), $attachment_id );
225
	}
226
227
	/**
228
	 ** IN-CONTENT IMAGE MANIPULATION FUNCTIONS
229
	 **/
230
231
	/**
232
	 * Match all images and any relevant <a> tags in a block of HTML.
233
	 *
234
	 * @param string $content Some HTML.
235
	 * @return array An array of $images matches, where $images[0] is
236
	 *         an array of full matches, and the link_url, img_tag,
237
	 *         and img_url keys are arrays of those matches.
238
	 */
239
	public static function parse_images_from_html( $content ) {
240
		$images = array();
241
242
		if ( preg_match_all( '#(?:<a[^>]+?href=["|\'](?P<link_url>[^\s]+?)["|\'][^>]*?>\s*)?(?P<img_tag><img[^>]*?\s+?src=["|\'](?P<img_url>[^\s]+?)["|\'].*?>){1}(?:\s*</a>)?#is', $content, $images ) ) {
243
			foreach ( $images as $key => $unused ) {
244
				// Simplify the output as much as possible, mostly for confirming test results.
245
				if ( is_numeric( $key ) && $key > 0 )
246
					unset( $images[$key] );
247
			}
248
249
			return $images;
250
		}
251
252
		return array();
253
	}
254
255
	/**
256
	 * Try to determine height and width from strings WP appends to resized image filenames.
257
	 *
258
	 * @param string $src The image URL.
259
	 * @return array An array consisting of width and height.
260
	 */
261
	public static function parse_dimensions_from_filename( $src ) {
262
		$width_height_string = array();
263
264
		if ( preg_match( '#-(\d+)x(\d+)\.(?:' . implode('|', self::$extensions ) . '){1}$#i', $src, $width_height_string ) ) {
265
			$width = (int) $width_height_string[1];
266
			$height = (int) $width_height_string[2];
267
268
			if ( $width && $height )
269
				return array( $width, $height );
270
		}
271
272
		return array( false, false );
273
	}
274
275
	/**
276
	 * Identify images in post content, and if images are local (uploaded to the current site), pass through Photon.
277
	 *
278
	 * @param string $content
279
	 * @uses self::validate_image_url, apply_filters, jetpack_photon_url, esc_url
280
	 * @filter the_content
281
	 * @return string
282
	 */
283
	public static function filter_the_content( $content ) {
284
		$images = Jetpack_Photon::parse_images_from_html( $content );
285
286
		if ( ! empty( $images ) ) {
287
			$content_width = Jetpack::get_content_width();
288
289
			$image_sizes = self::image_sizes();
290
			$upload_dir = wp_get_upload_dir();
291
292
			foreach ( $images[0] as $index => $tag ) {
293
				// Default to resize, though fit may be used in certain cases where a dimension cannot be ascertained
294
				$transform = 'resize';
295
296
				// Start with a clean attachment ID each time
297
				$attachment_id = false;
298
299
				// Flag if we need to munge a fullsize URL
300
				$fullsize_url = false;
301
302
				// Identify image source
303
				$src = $src_orig = $images['img_url'][ $index ];
304
305
				/**
306
				 * Allow specific images to be skipped by Photon.
307
				 *
308
				 * @module photon
309
				 *
310
				 * @since 2.0.3
311
				 *
312
				 * @param bool false Should Photon ignore this image. Default to false.
313
				 * @param string $src Image URL.
314
				 * @param string $tag Image Tag (Image HTML output).
315
				 */
316
				if ( apply_filters( 'jetpack_photon_skip_image', false, $src, $tag ) )
317
					continue;
318
319
				// Support Automattic's Lazy Load plugin
320
				// Can't modify $tag yet as we need unadulterated version later
321
				if ( preg_match( '#data-lazy-src=["|\'](.+?)["|\']#i', $images['img_tag'][ $index ], $lazy_load_src ) ) {
322
					$placeholder_src = $placeholder_src_orig = $src;
323
					$src = $src_orig = $lazy_load_src[1];
324
				} elseif ( preg_match( '#data-lazy-original=["|\'](.+?)["|\']#i', $images['img_tag'][ $index ], $lazy_load_src ) ) {
325
					$placeholder_src = $placeholder_src_orig = $src;
326
					$src = $src_orig = $lazy_load_src[1];
327
				}
328
329
				// Check if image URL should be used with Photon
330
				if ( self::validate_image_url( $src ) ) {
331
					// Find the width and height attributes
332
					$width = $height = false;
333
334
					// First, check the image tag
335
					if ( preg_match( '#width=["|\']?([\d%]+)["|\']?#i', $images['img_tag'][ $index ], $width_string ) )
336
						$width = $width_string[1];
337
338
					if ( preg_match( '#height=["|\']?([\d%]+)["|\']?#i', $images['img_tag'][ $index ], $height_string ) )
339
						$height = $height_string[1];
340
341
					// Can't pass both a relative width and height, so unset the height in favor of not breaking the horizontal layout.
342
					if ( false !== strpos( $width, '%' ) && false !== strpos( $height, '%' ) )
343
						$width = $height = false;
344
345
					// Detect WP registered image size from HTML class
346
					if ( preg_match( '#class=["|\']?[^"\']*size-([^"\'\s]+)[^"\']*["|\']?#i', $images['img_tag'][ $index ], $size ) ) {
347
						$size = array_pop( $size );
348
349
						if ( false === $width && false === $height && 'full' != $size && array_key_exists( $size, $image_sizes ) ) {
350
							$width = (int) $image_sizes[ $size ]['width'];
351
							$height = (int) $image_sizes[ $size ]['height'];
352
							$transform = $image_sizes[ $size ]['crop'] ? 'resize' : 'fit';
353
						}
354
					} else {
355
						unset( $size );
356
					}
357
358
					// WP Attachment ID, if uploaded to this site
359
					if (
360
						preg_match( '#class=["|\']?[^"\']*wp-image-([\d]+)[^"\']*["|\']?#i', $images['img_tag'][ $index ], $attachment_id ) &&
361
						0 === strpos( $src, $upload_dir['baseurl'] ) &&
362
						/**
363
						 * Filter whether an image using an attachment ID in its class has to be uploaded to the local site to go through Photon.
364
						 *
365
						 * @module photon
366
						 *
367
						 * @since 2.0.3
368
						 *
369
						 * @param bool false Was the image uploaded to the local site. Default to false.
370
						 * @param array $args {
371
						 * 	 Array of image details.
372
						 *
373
						 * 	 @type $src Image URL.
374
						 * 	 @type tag Image tag (Image HTML output).
375
						 * 	 @type $images Array of information about the image.
376
						 * 	 @type $index Image index.
377
						 * }
378
						 */
379
						apply_filters( 'jetpack_photon_image_is_local', false, compact( 'src', 'tag', 'images', 'index' ) )
380
					) {
381
						$attachment_id = intval( array_pop( $attachment_id ) );
382
383
						if ( $attachment_id ) {
384
							$attachment = get_post( $attachment_id );
385
386
							// Basic check on returned post object
387
							if ( is_object( $attachment ) && ! is_wp_error( $attachment ) && 'attachment' == $attachment->post_type ) {
388
								$src_per_wp = wp_get_attachment_image_src( $attachment_id, isset( $size ) ? $size : 'full' );
389
390
								if ( self::validate_image_url( $src_per_wp[0] ) ) {
391
									$src = $src_per_wp[0];
392
									$fullsize_url = true;
393
394
									// Prevent image distortion if a detected dimension exceeds the image's natural dimensions
395
									if ( ( false !== $width && $width > $src_per_wp[1] ) || ( false !== $height && $height > $src_per_wp[2] ) ) {
396
										$width = false === $width ? false : min( $width, $src_per_wp[1] );
397
										$height = false === $height ? false : min( $height, $src_per_wp[2] );
398
									}
399
400
									// If no width and height are found, max out at source image's natural dimensions
401
									// Otherwise, respect registered image sizes' cropping setting
402
									if ( false === $width && false === $height ) {
403
										$width = $src_per_wp[1];
404
										$height = $src_per_wp[2];
405
										$transform = 'fit';
406
									} elseif ( isset( $size ) && array_key_exists( $size, $image_sizes ) && isset( $image_sizes[ $size ]['crop'] ) ) {
407
										$transform = (bool) $image_sizes[ $size ]['crop'] ? 'resize' : 'fit';
408
									}
409
								}
410
							} else {
411
								unset( $attachment_id );
412
								unset( $attachment );
413
							}
414
						}
415
					}
416
417
					// If image tag lacks width and height arguments, try to determine from strings WP appends to resized image filenames.
418
					if ( false === $width && false === $height ) {
419
						list( $width, $height ) = Jetpack_Photon::parse_dimensions_from_filename( $src );
420
					}
421
422
					// If width is available, constrain to $content_width
423
					if ( false !== $width && false === strpos( $width, '%' ) && is_numeric( $content_width ) ) {
424
						if ( $width > $content_width && false !== $height && false === strpos( $height, '%' ) ) {
425
							$height = round( ( $content_width * $height ) / $width );
426
							$width = $content_width;
427
						} elseif ( $width > $content_width ) {
428
							$width = $content_width;
429
						}
430
					}
431
432
					// Set a width if none is found and $content_width is available
433
					// If width is set in this manner and height is available, use `fit` instead of `resize` to prevent skewing
434
					if ( false === $width && is_numeric( $content_width ) ) {
435
						$width = (int) $content_width;
436
437
						if ( false !== $height )
438
							$transform = 'fit';
439
					}
440
441
					// Detect if image source is for a custom-cropped thumbnail and prevent further URL manipulation.
442
					if ( ! $fullsize_url && preg_match_all( '#-e[a-z0-9]+(-\d+x\d+)?\.(' . implode('|', self::$extensions ) . '){1}$#i', basename( $src ), $filename ) )
443
						$fullsize_url = true;
444
445
					// Build URL, first maybe removing WP's resized string so we pass the original image to Photon
446
					if ( ! $fullsize_url ) {
447
						$src = self::strip_image_dimensions_maybe( $src );
448
					}
449
450
					// Build array of Photon args and expose to filter before passing to Photon URL function
451
					$args = array();
452
453
					if ( false !== $width && false !== $height && false === strpos( $width, '%' ) && false === strpos( $height, '%' ) )
454
						$args[ $transform ] = $width . ',' . $height;
455
					elseif ( false !== $width )
456
						$args['w'] = $width;
457
					elseif ( false !== $height )
458
						$args['h'] = $height;
459
460
					/**
461
					 * Filter the array of Photon arguments added to an image when it goes through Photon.
462
					 * By default, only includes width and height values.
463
					 * @see https://developer.wordpress.com/docs/photon/api/
464
					 *
465
					 * @module photon
466
					 *
467
					 * @since 2.0.0
468
					 *
469
					 * @param array $args Array of Photon Arguments.
470
					 * @param array $args {
471
					 * 	 Array of image details.
472
					 *
473
					 * 	 @type $tag Image tag (Image HTML output).
474
					 * 	 @type $src Image URL.
475
					 * 	 @type $src_orig Original Image URL.
476
					 * 	 @type $width Image width.
477
					 * 	 @type $height Image height.
478
					 * }
479
					 */
480
					$args = apply_filters( 'jetpack_photon_post_image_args', $args, compact( 'tag', 'src', 'src_orig', 'width', 'height' ) );
481
482
					$photon_url = jetpack_photon_url( $src, $args );
483
484
					// Modify image tag if Photon function provides a URL
485
					// 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.
486
					if ( $src != $photon_url ) {
487
						$new_tag = $tag;
488
489
						// If present, replace the link href with a Photoned URL for the full-size image.
490
						if ( ! empty( $images['link_url'][ $index ] ) && self::validate_image_url( $images['link_url'][ $index ] ) )
491
							$new_tag = preg_replace( '#(href=["|\'])' . $images['link_url'][ $index ] . '(["|\'])#i', '\1' . jetpack_photon_url( $images['link_url'][ $index ] ) . '\2', $new_tag, 1 );
492
493
						// Supplant the original source value with our Photon URL
494
						$photon_url = esc_url( $photon_url );
495
						$new_tag = str_replace( $src_orig, $photon_url, $new_tag );
496
497
						// If Lazy Load is in use, pass placeholder image through Photon
498
						if ( isset( $placeholder_src ) && self::validate_image_url( $placeholder_src ) ) {
499
							$placeholder_src = jetpack_photon_url( $placeholder_src );
500
501
							if ( $placeholder_src != $placeholder_src_orig )
502
								$new_tag = str_replace( $placeholder_src_orig, esc_url( $placeholder_src ), $new_tag );
0 ignored issues
show
The variable $placeholder_src_orig does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
503
504
							unset( $placeholder_src );
505
						}
506
507
						// If we are not transforming the image with resize, fit, or letterbox (lb), then we should remove
508
						// the width and height arguments from the image to prevent distortion. Even if $args['w'] and $args['h']
509
						// are present, Photon does not crop to those dimensions. Instead, it appears to favor height.
510
						//
511
						// If we are transforming the image via one of those methods, let's update the width and height attributes.
512
						if ( empty( $args['resize'] ) && empty( $args['fit'] ) && empty( $args['lb'] ) ) {
513
							$new_tag = preg_replace( '#(?<=\s)(width|height)=["|\']?[\d%]+["|\']?\s?#i', '', $new_tag );
514
						} else {
515
							$resize_args = isset( $args['resize'] ) ? $args['resize'] : false;
516 View Code Duplication
							if ( false == $resize_args ) {
517
								$resize_args = ( ! $resize_args && isset( $args['fit'] ) )
518
									? $args['fit']
519
									: false;
520
							}
521 View Code Duplication
							if ( false == $resize_args ) {
522
								$resize_args = ( ! $resize_args && isset( $args['lb'] ) )
523
									? $args['lb']
524
									: false;
525
							}
526
527
							$resize_args = array_map( 'trim', explode( ',', $resize_args ) );
528
529
							// (?<=\s)         - Ensure width or height attribute is preceded by a space
530
							// (width=["|\']?) - Matches, and captures, width=, width=", or width='
531
							// [\d%]+          - Matches 1 or more digits
532
							// (["|\']?)       - Matches, and captures, ", ', or empty string
533
							// \s              - Ensures there's a space after the attribute
534
							$new_tag = preg_replace( '#(?<=\s)(width=["|\']?)[\d%]+(["|\']?)\s?#i', sprintf( '${1}%d${2} ', $resize_args[0] ), $new_tag );
535
							$new_tag = preg_replace( '#(?<=\s)(height=["|\']?)[\d%]+(["|\']?)\s?#i', sprintf( '${1}%d${2} ', $resize_args[1] ), $new_tag );
536
						}
537
538
						// Tag an image for dimension checking
539
						$new_tag = preg_replace( '#(\s?/)?>(\s*</a>)?$#i', ' data-recalc-dims="1"\1>\2', $new_tag );
540
541
						// Replace original tag with modified version
542
						$content = str_replace( $tag, $new_tag, $content );
543
					}
544
				} elseif ( preg_match( '#^http(s)?://i[\d]{1}.wp.com#', $src ) && ! empty( $images['link_url'][ $index ] ) && self::validate_image_url( $images['link_url'][ $index ] ) ) {
545
					$new_tag = preg_replace( '#(href=["|\'])' . $images['link_url'][ $index ] . '(["|\'])#i', '\1' . jetpack_photon_url( $images['link_url'][ $index ] ) . '\2', $tag, 1 );
546
547
					$content = str_replace( $tag, $new_tag, $content );
548
				}
549
			}
550
		}
551
552
		return $content;
553
	}
554
555
	public static function filter_the_galleries( $galleries ) {
556
		if ( empty( $galleries ) || ! is_array( $galleries ) ) {
557
			return $galleries;
558
		}
559
560
		// Pass by reference, so we can modify them in place.
561
		foreach ( $galleries as &$this_gallery ) {
562
			if ( is_string( $this_gallery ) ) {
563
				$this_gallery = self::filter_the_content( $this_gallery );
564
		// LEAVING COMMENTED OUT as for the moment it doesn't seem
565
		// necessary and I'm not sure how it would propagate through.
566
		//	} elseif ( is_array( $this_gallery )
567
		//	           && ! empty( $this_gallery['src'] )
568
		//	           && ! empty( $this_gallery['type'] )
569
		//	           && in_array( $this_gallery['type'], array( 'rectangle', 'square', 'circle' ) ) ) {
570
		//		$this_gallery['src'] = array_map( 'jetpack_photon_url', $this_gallery['src'] );
571
			}
572
		}
573
		unset( $this_gallery ); // break the reference.
574
575
		return $galleries;
576
	}
577
578
579
	/**
580
	 * Runs the image widget through photon.
581
	 *
582
	 * @param array $instance Image widget instance data.
583
	 * @return array
584
	 */
585
	public static function filter_the_image_widget( $instance ) {
586
		if ( Jetpack::is_module_active( 'photon' ) && ! $instance['attachment_id'] && $instance['url'] ) {
587
			jetpack_photon_url( $instance['url'], array(
588
				'w' => $instance['width'],
589
				'h' => $instance['height'],
590
			) );
591
		}
592
593
		return $instance;
594
	}
595
596
	/**
597
	 ** CORE IMAGE RETRIEVAL
598
	 **/
599
600
	/**
601
	 * Filter post thumbnail image retrieval, passing images through Photon
602
	 *
603
	 * @param string|bool $image
604
	 * @param int $attachment_id
605
	 * @param string|array $size
606
	 * @uses is_admin, apply_filters, wp_get_attachment_url, self::validate_image_url, this::image_sizes, jetpack_photon_url
607
	 * @filter image_downsize
608
	 * @return string|bool
609
	 */
610
	public function filter_image_downsize( $image, $attachment_id, $size ) {
611
		// Don't foul up the admin side of things, unless a plugin wants to.
612
		if ( is_admin() &&
613
			/**
614
			 * Provide plugins a way of running Photon for images in the WordPress Dashboard (wp-admin).
615
			 *
616
			 * 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.
617
			 *
618
			 * @module photon
619
			 *
620
			 * @since 4.8.0
621
			 *
622
			 * @param bool false Stop Photon from being run on the Dashboard. Default to false.
623
			 * @param array $args {
624
			 * 	 Array of image details.
625
			 *
626
			 * 	 @type $image Image URL.
627
			 * 	 @type $attachment_id Attachment ID of the image.
628
			 * 	 @type $size Image size. Can be a string (name of the image size, e.g. full) or an array of width and height.
629
			 * }
630
			 */
631
			false === apply_filters( 'jetpack_photon_admin_allow_image_downsize', false, compact( 'image', 'attachment_id', 'size' ) )
632
		) {
633
			return $image;
634
		}
635
636
		/**
637
		 * Provide plugins a way of preventing Photon from being applied to images retrieved from WordPress Core.
638
		 *
639
		 * @module photon
640
		 *
641
		 * @since 2.0.0
642
		 *
643
		 * @param bool false Stop Photon from being applied to the image. Default to false.
644
		 * @param array $args {
645
		 * 	 Array of image details.
646
		 *
647
		 * 	 @type $image Image URL.
648
		 * 	 @type $attachment_id Attachment ID of the image.
649
		 * 	 @type $size Image size. Can be a string (name of the image size, e.g. full) or an array of width and height.
650
		 * }
651
		 */
652
		if ( apply_filters( 'jetpack_photon_override_image_downsize', false, compact( 'image', 'attachment_id', 'size' ) ) ) {
653
			return $image;
654
		}
655
656
		// Get the image URL and proceed with Photon-ification if successful
657
		$image_url = wp_get_attachment_url( $attachment_id );
658
659
		// Set this to true later when we know we have size meta.
660
		$has_size_meta = false;
661
662
		if ( $image_url ) {
663
			// Check if image URL should be used with Photon
664
			if ( ! self::validate_image_url( $image_url ) ) {
665
				return $image;
666
			}
667
668
			$intermediate = true; // For the fourth array item returned by the image_downsize filter.
669
670
			// If an image is requested with a size known to WordPress, use that size's settings with Photon.
671
			// WP states that `add_image_size()` should use a string for the name, but doesn't enforce that.
672
			// Due to differences in how Core and Photon check for the registered image size, we check both types.
673
			if ( ( is_string( $size ) || is_int( $size ) ) && array_key_exists( $size, self::image_sizes() ) ) {
674
				$image_args = self::image_sizes();
675
				$image_args = $image_args[ $size ];
676
677
				$photon_args = array();
678
679
				$image_meta = image_get_intermediate_size( $attachment_id, $size );
680
681
				// 'full' is a special case: We need consistent data regardless of the requested size.
682
				if ( 'full' == $size ) {
683
					$image_meta = wp_get_attachment_metadata( $attachment_id );
684
					$intermediate = false;
685
				} elseif ( ! $image_meta ) {
686
					// If we still don't have any image meta at this point, it's probably from a custom thumbnail size
687
					// for an image that was uploaded before the custom image was added to the theme.  Try to determine the size manually.
688
					$image_meta = wp_get_attachment_metadata( $attachment_id );
689
690
					if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
691
						$image_resized = image_resize_dimensions( $image_meta['width'], $image_meta['height'], $image_args['width'], $image_args['height'], $image_args['crop'] );
692
						if ( $image_resized ) { // This could be false when the requested image size is larger than the full-size image.
693
							$image_meta['width'] = $image_resized[6];
694
							$image_meta['height'] = $image_resized[7];
695
						}
696
					}
697
				}
698
699
				if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
700
					$image_args['width']  = $image_meta['width'];
701
					$image_args['height'] = $image_meta['height'];
702
703
					list( $image_args['width'], $image_args['height'] ) = image_constrain_size_for_editor( $image_args['width'], $image_args['height'], $size, 'display' );
704
					$has_size_meta = true;
705
				}
706
707
				// Expose determined arguments to a filter before passing to Photon
708
				$transform = $image_args['crop'] ? 'resize' : 'fit';
709
710
				// Check specified image dimensions and account for possible zero values; photon fails to resize if a dimension is zero.
711
				if ( 0 == $image_args['width'] || 0 == $image_args['height'] ) {
712
					if ( 0 == $image_args['width'] && 0 < $image_args['height'] ) {
713
						$photon_args['h'] = $image_args['height'];
714
					} elseif ( 0 == $image_args['height'] && 0 < $image_args['width'] ) {
715
						$photon_args['w'] = $image_args['width'];
716
					}
717
				} else {
718
					if ( ( 'resize' === $transform ) && $image_meta = wp_get_attachment_metadata( $attachment_id ) ) {
719
						if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
720
							// Lets make sure that we don't upscale images since wp never upscales them as well
721
							$smaller_width  = ( ( $image_meta['width']  < $image_args['width']  ) ? $image_meta['width']  : $image_args['width']  );
722
							$smaller_height = ( ( $image_meta['height'] < $image_args['height'] ) ? $image_meta['height'] : $image_args['height'] );
723
724
							$photon_args[ $transform ] = $smaller_width . ',' . $smaller_height;
725
						}
726
					} else {
727
						$photon_args[ $transform ] = $image_args['width'] . ',' . $image_args['height'];
728
					}
729
730
				}
731
732
733
				/**
734
				 * Filter the Photon Arguments added to an image when going through Photon, when that image size is a string.
735
				 * Image size will be a string (e.g. "full", "medium") when it is known to WordPress.
736
				 *
737
				 * @module photon
738
				 *
739
				 * @since 2.0.0
740
				 *
741
				 * @param array $photon_args Array of Photon arguments.
742
				 * @param array $args {
743
				 * 	 Array of image details.
744
				 *
745
				 * 	 @type $image_args Array of Image arguments (width, height, crop).
746
				 * 	 @type $image_url Image URL.
747
				 * 	 @type $attachment_id Attachment ID of the image.
748
				 * 	 @type $size Image size. Can be a string (name of the image size, e.g. full) or an integer.
749
				 * 	 @type $transform Value can be resize or fit.
750
				 *                    @see https://developer.wordpress.com/docs/photon/api
751
				 * }
752
				 */
753
				$photon_args = apply_filters( 'jetpack_photon_image_downsize_string', $photon_args, compact( 'image_args', 'image_url', 'attachment_id', 'size', 'transform' ) );
754
755
				// Generate Photon URL
756
				$image = array(
757
					jetpack_photon_url( $image_url, $photon_args ),
758
					$has_size_meta ? $image_args['width'] : false,
759
					$has_size_meta ? $image_args['height'] : false,
760
					$intermediate
761
				);
762
			} elseif ( is_array( $size ) ) {
763
				// Pull width and height values from the provided array, if possible
764
				$width = isset( $size[0] ) ? (int) $size[0] : false;
765
				$height = isset( $size[1] ) ? (int) $size[1] : false;
766
767
				// Don't bother if necessary parameters aren't passed.
768
				if ( ! $width || ! $height ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $width of type integer|false is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

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

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
Bug Best Practice introduced by
The expression $height of type integer|false is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

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

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
769
					return $image;
770
				}
771
772
				$image_meta = wp_get_attachment_metadata( $attachment_id );
773
				if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
774
					$image_resized = image_resize_dimensions( $image_meta['width'], $image_meta['height'], $width, $height );
775
776
					if ( $image_resized ) { // This could be false when the requested image size is larger than the full-size image.
777
						$width = $image_resized[6];
778
						$height = $image_resized[7];
779
					} else {
780
						$width = $image_meta['width'];
781
						$height = $image_meta['height'];
782
					}
783
784
					$has_size_meta = true;
785
				}
786
787
				list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
788
789
				// Expose arguments to a filter before passing to Photon
790
				$photon_args = array(
791
					'fit' => $width . ',' . $height
792
				);
793
794
				/**
795
				 * Filter the Photon Arguments added to an image when going through Photon,
796
				 * when the image size is an array of height and width values.
797
				 *
798
				 * @module photon
799
				 *
800
				 * @since 2.0.0
801
				 *
802
				 * @param array $photon_args Array of Photon arguments.
803
				 * @param array $args {
804
				 * 	 Array of image details.
805
				 *
806
				 * 	 @type $width Image width.
807
				 * 	 @type height Image height.
808
				 * 	 @type $image_url Image URL.
809
				 * 	 @type $attachment_id Attachment ID of the image.
810
				 * }
811
				 */
812
				$photon_args = apply_filters( 'jetpack_photon_image_downsize_array', $photon_args, compact( 'width', 'height', 'image_url', 'attachment_id' ) );
813
814
				// Generate Photon URL
815
				$image = array(
816
					jetpack_photon_url( $image_url, $photon_args ),
817
					$has_size_meta ? $width : false,
818
					$has_size_meta ? $height : false,
819
					$intermediate
820
				);
821
			}
822
		}
823
824
		return $image;
825
	}
826
827
	/**
828
	 * Filters an array of image `srcset` values, replacing each URL with its Photon equivalent.
829
	 *
830
	 * @since 3.8.0
831
	 * @since 4.0.4 Added automatically additional sizes beyond declared image sizes.
832
	 * @param array $sources An array of image urls and widths.
833
	 * @uses self::validate_image_url, jetpack_photon_url, Jetpack_Photon::parse_from_filename
834
	 * @uses Jetpack_Photon::strip_image_dimensions_maybe, Jetpack::get_content_width
835
	 * @return array An array of Photon image urls and widths.
836
	 */
837
	public function filter_srcset_array( $sources = array(), $size_array = array(), $image_src = array(), $image_meta = array(), $attachment_id = 0 ) {
838
		if ( ! is_array( $sources ) ) {
839
			return $sources;
840
		}
841
		$upload_dir = wp_get_upload_dir();
842
843
		foreach ( $sources as $i => $source ) {
844
			if ( ! self::validate_image_url( $source['url'] ) ) {
845
				continue;
846
			}
847
848
			/** This filter is already documented in class.photon.php */
849
			if ( apply_filters( 'jetpack_photon_skip_image', false, $source['url'], $source ) ) {
850
				continue;
851
			}
852
853
			$url = $source['url'];
854
			list( $width, $height ) = Jetpack_Photon::parse_dimensions_from_filename( $url );
855
856
			// It's quicker to get the full size with the data we have already, if available
857
			if ( ! empty( $attachment_id ) ) {
858
				$url = wp_get_attachment_url( $attachment_id );
859
			} else {
860
				$url = Jetpack_Photon::strip_image_dimensions_maybe( $url );
861
			}
862
863
			$args = array();
864
			if ( 'w' === $source['descriptor'] ) {
865
				if ( $height && ( $source['value'] == $width ) ) {
866
					$args['resize'] = $width . ',' . $height;
867
				} else {
868
					$args['w'] = $source['value'];
869
				}
870
871
			}
872
873
			$sources[ $i ]['url'] = jetpack_photon_url( $url, $args );
874
		}
875
876
		/**
877
		 * At this point, $sources is the original srcset with Photonized URLs.
878
		 * Now, we're going to construct additional sizes based on multiples of the content_width.
879
		 * This will reduce the gap between the largest defined size and the original image.
880
		 */
881
882
		/**
883
		 * Filter the multiplier Photon uses to create new srcset items.
884
		 * Return false to short-circuit and bypass auto-generation.
885
		 *
886
		 * @module photon
887
		 *
888
		 * @since 4.0.4
889
		 *
890
		 * @param array|bool $multipliers Array of multipliers to use or false to bypass.
891
		 */
892
		$multipliers = apply_filters( 'jetpack_photon_srcset_multipliers', array( 2, 3 ) );
893
		$url         = trailingslashit( $upload_dir['baseurl'] ) . $image_meta['file'];
894
895
		if (
896
			/** Short-circuit via jetpack_photon_srcset_multipliers filter. */
897
			is_array( $multipliers )
898
			/** This filter is already documented in class.photon.php */
899
			&& ! apply_filters( 'jetpack_photon_skip_image', false, $url, null )
900
			/** Verify basic meta is intact. */
901
			&& isset( $image_meta['width'] ) && isset( $image_meta['height'] ) && isset( $image_meta['file'] )
902
			/** Verify we have the requested width/height. */
903
			&& isset( $size_array[0] ) && isset( $size_array[1] )
904
			) {
905
906
			$fullwidth  = $image_meta['width'];
907
			$fullheight = $image_meta['height'];
908
			$reqwidth   = $size_array[0];
909
			$reqheight  = $size_array[1];
910
911
			$constrained_size = wp_constrain_dimensions( $fullwidth, $fullheight, $reqwidth );
912
			$expected_size = array( $reqwidth, $reqheight );
913
914
			if ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 ) {
915
				$crop = 'soft';
916
				$base = Jetpack::get_content_width() ? Jetpack::get_content_width() : 1000; // Provide a default width if none set by the theme.
917
			} else {
918
				$crop = 'hard';
919
				$base = $reqwidth;
920
			}
921
922
923
			$currentwidths = array_keys( $sources );
924
			$newsources = null;
925
926
			foreach ( $multipliers as $multiplier ) {
927
928
				$newwidth = $base * $multiplier;
929
				foreach ( $currentwidths as $currentwidth ){
930
					// If a new width would be within 100 pixes of an existing one or larger than the full size image, skip.
931
					if ( abs( $currentwidth - $newwidth ) < 50 || ( $newwidth > $fullwidth ) ) {
932
						continue 2; // Back to the foreach ( $multipliers as $multiplier )
933
					}
934
				} // foreach ( $currentwidths as $currentwidth ){
935
936
				if ( 'soft' == $crop ) {
937
					$args = array(
938
						'w' => $newwidth,
939
					);
940
				} else { // hard crop, e.g. add_image_size( 'example', 200, 200, true );
941
					$args = array(
942
						'zoom'   => $multiplier,
943
						'resize' => $reqwidth . ',' . $reqheight,
944
					);
945
				}
946
947
				$newsources[ $newwidth ] = array(
948
					'url'         => jetpack_photon_url( $url, $args ),
949
					'descriptor'  => 'w',
950
					'value'       => $newwidth,
951
					);
952
			} // foreach ( $multipliers as $multiplier )
953
			if ( is_array( $newsources ) ) {
954
				if ( function_exists( 'array_replace' ) ) { // PHP 5.3+, preferred
955
					// phpcs:disable
956
					$sources = array_replace( $sources, $newsources );
957
					// phpcs:enable
958
				} else { // For PHP 5.2 using WP shim function
959
					$sources = array_replace_recursive( $sources, $newsources );
960
				}
961
			}
962
		} // if ( isset( $image_meta['width'] ) && isset( $image_meta['file'] ) )
963
964
		return $sources;
965
	}
966
967
	/**
968
	 * Filters an array of image `sizes` values, using $content_width instead of image's full size.
969
	 *
970
	 * @since 4.0.4
971
	 * @since 4.1.0 Returns early for images not within the_content.
972
	 * @param array $sizes An array of media query breakpoints.
973
	 * @param array $size  Width and height of the image
974
	 * @uses Jetpack::get_content_width
975
	 * @return array An array of media query breakpoints.
976
	 */
977
	public function filter_sizes( $sizes, $size ) {
978
		if ( ! doing_filter( 'the_content' ) ){
979
			return $sizes;
980
		}
981
		$content_width = Jetpack::get_content_width();
982
		if ( ! $content_width ) {
983
			$content_width = 1000;
984
		}
985
986
		if ( ( is_array( $size ) && $size[0] < $content_width ) ) {
987
			return $sizes;
988
		}
989
990
		return sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $content_width );
991
	}
992
993
	/**
994
	 ** GENERAL FUNCTIONS
995
	 **/
996
997
	/**
998
	 * Ensure image URL is valid for Photon.
999
	 * 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.
1000
	 *
1001
	 * @param string $url
1002
	 * @uses wp_parse_args
1003
	 * @return bool
1004
	 */
1005
	protected static function validate_image_url( $url ) {
1006
		$parsed_url = @parse_url( $url );
1007
1008
		if ( ! $parsed_url )
1009
			return false;
1010
1011
		// Parse URL and ensure needed keys exist, since the array returned by `parse_url` only includes the URL components it finds.
1012
		$url_info = wp_parse_args( $parsed_url, array(
1013
			'scheme' => null,
1014
			'host'   => null,
1015
			'port'   => null,
1016
			'path'   => null
1017
		) );
1018
1019
		// Bail if scheme isn't http or port is set that isn't port 80
1020
		if (
1021
			( 'http' != $url_info['scheme'] || ! in_array( $url_info['port'], array( 80, null ) ) ) &&
1022
			/**
1023
			 * Allow Photon to fetch images that are served via HTTPS.
1024
			 *
1025
			 * @module photon
1026
			 *
1027
			 * @since 2.4.0
1028
			 * @since 3.9.0 Default to false.
1029
			 *
1030
			 * @param bool $reject_https Should Photon ignore images using the HTTPS scheme. Default to false.
1031
			 */
1032
			apply_filters( 'jetpack_photon_reject_https', false )
1033
		) {
1034
			return false;
1035
		}
1036
1037
		// Bail if no host is found
1038
		if ( is_null( $url_info['host'] ) )
1039
			return false;
1040
1041
		// Bail if the image alredy went through Photon
1042
		if ( preg_match( '#^i[\d]{1}.wp.com$#i', $url_info['host'] ) )
1043
			return false;
1044
1045
		// Bail if no path is found
1046
		if ( is_null( $url_info['path'] ) )
1047
			return false;
1048
1049
		// Ensure image extension is acceptable
1050
		if ( ! in_array( strtolower( pathinfo( $url_info['path'], PATHINFO_EXTENSION ) ), self::$extensions ) )
1051
			return false;
1052
1053
		// If we got this far, we should have an acceptable image URL
1054
		// But let folks filter to decline if they prefer.
1055
		/**
1056
		 * Overwrite the results of the validation steps an image goes through before to be considered valid to be used by Photon.
1057
		 *
1058
		 * @module photon
1059
		 *
1060
		 * @since 3.0.0
1061
		 *
1062
		 * @param bool true Is the image URL valid and can it be used by Photon. Default to true.
1063
		 * @param string $url Image URL.
1064
		 * @param array $parsed_url Array of information about the image.
1065
		 */
1066
		return apply_filters( 'photon_validate_image_url', true, $url, $parsed_url );
1067
	}
1068
1069
	/**
1070
	 * Checks if the file exists before it passes the file to photon
1071
	 *
1072
	 * @param string $src The image URL
1073
	 * @return string
1074
	 **/
1075
	public static function strip_image_dimensions_maybe( $src ){
1076
		$stripped_src = $src;
0 ignored issues
show
$stripped_src is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1077
1078
		// Build URL, first removing WP's resized string so we pass the original image to Photon
1079
		if ( preg_match( '#(-\d+x\d+)\.(' . implode('|', self::$extensions ) . '){1}$#i', $src, $src_parts ) ) {
1080
			$stripped_src = str_replace( $src_parts[1], '', $src );
1081
			$upload_dir = wp_get_upload_dir();
1082
1083
			// Extracts the file path to the image minus the base url
1084
			$file_path = substr( $stripped_src, strlen ( $upload_dir['baseurl'] ) );
1085
1086
			if( file_exists( $upload_dir["basedir"] . $file_path ) )
1087
				$src = $stripped_src;
1088
		}
1089
1090
		return $src;
1091
	}
1092
1093
	/**
1094
	 * Provide an array of available image sizes and corresponding dimensions.
1095
	 * Similar to get_intermediate_image_sizes() except that it includes image sizes' dimensions, not just their names.
1096
	 *
1097
	 * @global $wp_additional_image_sizes
1098
	 * @uses get_option
1099
	 * @return array
1100
	 */
1101
	protected static function image_sizes() {
1102
		if ( null == self::$image_sizes ) {
1103
			global $_wp_additional_image_sizes;
1104
1105
			// Populate an array matching the data structure of $_wp_additional_image_sizes so we have a consistent structure for image sizes
1106
			$images = array(
1107
				'thumb'  => array(
1108
					'width'  => intval( get_option( 'thumbnail_size_w' ) ),
1109
					'height' => intval( get_option( 'thumbnail_size_h' ) ),
1110
					'crop'   => (bool) get_option( 'thumbnail_crop' )
1111
				),
1112
				'medium' => array(
1113
					'width'  => intval( get_option( 'medium_size_w' ) ),
1114
					'height' => intval( get_option( 'medium_size_h' ) ),
1115
					'crop'   => false
1116
				),
1117
				'large'  => array(
1118
					'width'  => intval( get_option( 'large_size_w' ) ),
1119
					'height' => intval( get_option( 'large_size_h' ) ),
1120
					'crop'   => false
1121
				),
1122
				'full'   => array(
1123
					'width'  => null,
1124
					'height' => null,
1125
					'crop'   => false
1126
				)
1127
			);
1128
1129
			// Compatibility mapping as found in wp-includes/media.php
1130
			$images['thumbnail'] = $images['thumb'];
1131
1132
			// Update class variable, merging in $_wp_additional_image_sizes if any are set
1133
			if ( is_array( $_wp_additional_image_sizes ) && ! empty( $_wp_additional_image_sizes ) )
1134
				self::$image_sizes = array_merge( $images, $_wp_additional_image_sizes );
1135
			else
1136
				self::$image_sizes = $images;
1137
		}
1138
1139
		return is_array( self::$image_sizes ) ? self::$image_sizes : array();
1140
	}
1141
1142
	/**
1143
	 * Pass og:image URLs through Photon
1144
	 *
1145
	 * @param array $tags
1146
	 * @param array $parameters
1147
	 * @uses jetpack_photon_url
1148
	 * @return array
1149
	 */
1150
	function filter_open_graph_tags( $tags, $parameters ) {
1151
		if ( empty( $tags['og:image'] ) ) {
1152
			return $tags;
1153
		}
1154
1155
		$photon_args = array(
1156
			'fit' => sprintf( '%d,%d', 2 * $parameters['image_width'], 2 * $parameters['image_height'] ),
1157
		);
1158
1159
		if ( is_array( $tags['og:image'] ) ) {
1160
			$images = array();
1161
			foreach ( $tags['og:image'] as $image ) {
1162
				$images[] = jetpack_photon_url( $image, $photon_args );
1163
			}
1164
			$tags['og:image'] = $images;
1165
		} else {
1166
			$tags['og:image'] = jetpack_photon_url( $tags['og:image'], $photon_args );
1167
		}
1168
1169
		return $tags;
1170
	}
1171
1172
	public function noresize_intermediate_sizes( $sizes ) {
1173
		return __return_empty_array();
1174
	}
1175
1176
	/**
1177
	 * Enqueue Photon helper script
1178
	 *
1179
	 * @uses wp_enqueue_script, plugins_url
1180
	 * @action wp_enqueue_script
1181
	 * @return null
1182
	 */
1183
	public function action_wp_enqueue_scripts() {
1184
		if ( Jetpack_AMP_Support::is_amp_request() ) {
1185
			return;
1186
		}
1187
		wp_enqueue_script(
1188
			'jetpack-photon',
1189
			Assets::get_file_url_for_environment(
1190
				'_inc/build/photon/photon.min.js',
1191
				'modules/photon/photon.js'
1192
			),
1193
			array(),
1194
			20190201,
1195
			true
1196
		);
1197
	}
1198
1199
	/**
1200
	 * Determine if image_downsize should utilize Photon via REST API.
1201
	 *
1202
	 * The WordPress Block Editor (Gutenberg) and other REST API consumers using the wp/v2/media endpoint, especially in the "edit"
1203
	 * context is more akin to the is_admin usage of Photon (see filter_image_downsize). Since consumers are trying to edit content in posts,
1204
	 * Photon should not fire as it will fire later on display. By aborting an attempt to Photonize an image here, we
1205
	 * prevents issues like https://github.com/Automattic/jetpack/issues/10580 .
1206
	 *
1207
	 * To determine if we're using the wp/v2/media endpoint, we hook onto the `rest_request_before_callbacks` filter and
1208
	 * if determined we are using it in the edit context, we'll false out the `jetpack_photon_override_image_downsize` filter.
1209
	 *
1210
	 * @see Jetpack_Photon::filter_image_downsize()
1211
	 *
1212
	 * @param null|WP_Error   $response
1213
	 * @param array           $endpoint_data
1214
	 * @param WP_REST_Request $request  Request used to generate the response.
1215
	 *
1216
	 * @return null|WP_Error The original response object without modification.
1217
	 */
1218
	public function should_rest_photon_image_downsize( $response, $endpoint_data, $request ) {
1219
		if ( ! is_a( $request , 'WP_REST_Request' ) ) {
1220
			return $response; // Something odd is happening. Do nothing and return the response.
1221
		}
1222
1223
		if ( is_wp_error( $response ) ) {
1224
			// If we're going to return an error, we don't need to do anything with Photon.
1225
			return $response;
1226
		}
1227
1228
		$route = $request->get_route();
1229
1230
		if ( false !== strpos( $route, 'wp/v2/media' ) && 'edit' === $request['context'] ) {
1231
			// Don't use `__return_true()`: Use something unique. See ::_override_image_downsize_in_rest_edit_context()
1232
			// Late execution to avoid conflict with other plugins as we really don't want to run in this situation.
1233
			add_filter( 'jetpack_photon_override_image_downsize', array( $this, '_override_image_downsize_in_rest_edit_context' ), 999999 );
1234
		}
1235
1236
		return $response;
1237
1238
	}
1239
1240
	/**
1241
	 * Remove the override we may have added in ::should_rest_photon_image_downsize()
1242
	 * Since ::_override_image_downsize_in_rest_edit_context() is only
1243
	 * every used here, we can always remove it without ever worrying
1244
	 * about breaking any other configuration.
1245
	 *
1246
	 * @param mixed $response
1247
	 * @return mixed Unchanged $response
1248
	 */
1249
	public function cleanup_rest_photon_image_downsize( $response ) {
1250
		remove_filter( 'jetpack_photon_override_image_downsize', array( $this, '_override_image_downsize_in_rest_edit_context' ), 999999 );
1251
		return $response;
1252
	}
1253
1254
	/**
1255
	 * Used internally by ::should_rest_photon_image_downsize() to not photonize
1256
	 * image URLs in ?context=edit REST requests.
1257
	 * MUST NOT be used anywhere else.
1258
	 * We use a unique function instead of __return_true so that we can clean up
1259
	 * after ourselves without breaking anyone else's filters.
1260
	 *
1261
	 * @internal
1262
	 * @return true
1263
	 */
1264
	public function _override_image_downsize_in_rest_edit_context() {
1265
		return true;
1266
	}
1267
}
1268