PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 5.1.4
Jetpack – WP Security, Backup, Speed, & Growth v5.1.4
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / class.photon.php
class.photon.php
990 lines 34.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 class Jetpack_Photon {
4 /**
5 * Class variables
6 */
7 // Oh look, a singleton
8 private static $__instance = null;
9
10 // Allowed extensions must match http://code.trac.wordpress.org/browser/photon/index.php#L31
11 protected static $extensions = array(
12 'gif',
13 'jpg',
14 'jpeg',
15 'png'
16 );
17
18 // Don't access this directly. Instead, use self::image_sizes() so it's actually populated with something.
19 protected static $image_sizes = null;
20
21 /**
22 * Singleton implementation
23 *
24 * @return object
25 */
26 public static function instance() {
27 if ( ! is_a( self::$__instance, 'Jetpack_Photon' ) ) {
28 self::$__instance = new Jetpack_Photon;
29 self::$__instance->setup();
30 }
31
32 return self::$__instance;
33 }
34
35 /**
36 * Silence is golden.
37 */
38 private function __construct() {}
39
40 /**
41 * Register actions and filters, but only if basic Photon functions are available.
42 * The basic functions are found in ./functions.photon.php.
43 *
44 * @uses add_action, add_filter
45 * @return null
46 */
47 private function setup() {
48 if ( ! function_exists( 'jetpack_photon_url' ) )
49 return;
50
51 // Images in post content and galleries
52 add_filter( 'the_content', array( __CLASS__, 'filter_the_content' ), 999999 );
53 add_filter( 'get_post_galleries', array( __CLASS__, 'filter_the_galleries' ), 999999 );
54 add_filter( 'widget_media_image_instance', array( __CLASS__, 'filter_the_image_widget' ), 999999 );
55
56 // Core image retrieval
57 add_filter( 'image_downsize', array( $this, 'filter_image_downsize' ), 10, 3 );
58
59 // Responsive image srcset substitution
60 add_filter( 'wp_calculate_image_srcset', array( $this, 'filter_srcset_array' ), 10, 5 );
61 add_filter( 'wp_calculate_image_sizes', array( $this, 'filter_sizes' ), 1, 2 ); // Early so themes can still easily filter.
62
63 // Helpers for maniuplated images
64 add_action( 'wp_enqueue_scripts', array( $this, 'action_wp_enqueue_scripts' ), 9 );
65 }
66
67 /**
68 ** IN-CONTENT IMAGE MANIPULATION FUNCTIONS
69 **/
70
71 /**
72 * Match all images and any relevant <a> tags in a block of HTML.
73 *
74 * @param string $content Some HTML.
75 * @return array An array of $images matches, where $images[0] is
76 * an array of full matches, and the link_url, img_tag,
77 * and img_url keys are arrays of those matches.
78 */
79 public static function parse_images_from_html( $content ) {
80 $images = array();
81
82 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 ) ) {
83 foreach ( $images as $key => $unused ) {
84 // Simplify the output as much as possible, mostly for confirming test results.
85 if ( is_numeric( $key ) && $key > 0 )
86 unset( $images[$key] );
87 }
88
89 return $images;
90 }
91
92 return array();
93 }
94
95 /**
96 * Try to determine height and width from strings WP appends to resized image filenames.
97 *
98 * @param string $src The image URL.
99 * @return array An array consisting of width and height.
100 */
101 public static function parse_dimensions_from_filename( $src ) {
102 $width_height_string = array();
103
104 if ( preg_match( '#-(\d+)x(\d+)\.(?:' . implode('|', self::$extensions ) . '){1}$#i', $src, $width_height_string ) ) {
105 $width = (int) $width_height_string[1];
106 $height = (int) $width_height_string[2];
107
108 if ( $width && $height )
109 return array( $width, $height );
110 }
111
112 return array( false, false );
113 }
114
115 /**
116 * Identify images in post content, and if images are local (uploaded to the current site), pass through Photon.
117 *
118 * @param string $content
119 * @uses self::validate_image_url, apply_filters, jetpack_photon_url, esc_url
120 * @filter the_content
121 * @return string
122 */
123 public static function filter_the_content( $content ) {
124 $images = Jetpack_Photon::parse_images_from_html( $content );
125
126 if ( ! empty( $images ) ) {
127 $content_width = Jetpack::get_content_width();
128
129 $image_sizes = self::image_sizes();
130 $upload_dir = wp_get_upload_dir();
131
132 foreach ( $images[0] as $index => $tag ) {
133 // Default to resize, though fit may be used in certain cases where a dimension cannot be ascertained
134 $transform = 'resize';
135
136 // Start with a clean attachment ID each time
137 $attachment_id = false;
138
139 // Flag if we need to munge a fullsize URL
140 $fullsize_url = false;
141
142 // Identify image source
143 $src = $src_orig = $images['img_url'][ $index ];
144
145 /**
146 * Allow specific images to be skipped by Photon.
147 *
148 * @module photon
149 *
150 * @since 2.0.3
151 *
152 * @param bool false Should Photon ignore this image. Default to false.
153 * @param string $src Image URL.
154 * @param string $tag Image Tag (Image HTML output).
155 */
156 if ( apply_filters( 'jetpack_photon_skip_image', false, $src, $tag ) )
157 continue;
158
159 // Support Automattic's Lazy Load plugin
160 // Can't modify $tag yet as we need unadulterated version later
161 if ( preg_match( '#data-lazy-src=["|\'](.+?)["|\']#i', $images['img_tag'][ $index ], $lazy_load_src ) ) {
162 $placeholder_src = $placeholder_src_orig = $src;
163 $src = $src_orig = $lazy_load_src[1];
164 } elseif ( preg_match( '#data-lazy-original=["|\'](.+?)["|\']#i', $images['img_tag'][ $index ], $lazy_load_src ) ) {
165 $placeholder_src = $placeholder_src_orig = $src;
166 $src = $src_orig = $lazy_load_src[1];
167 }
168
169 // Check if image URL should be used with Photon
170 if ( self::validate_image_url( $src ) ) {
171 // Find the width and height attributes
172 $width = $height = false;
173
174 // First, check the image tag
175 if ( preg_match( '#width=["|\']?([\d%]+)["|\']?#i', $images['img_tag'][ $index ], $width_string ) )
176 $width = $width_string[1];
177
178 if ( preg_match( '#height=["|\']?([\d%]+)["|\']?#i', $images['img_tag'][ $index ], $height_string ) )
179 $height = $height_string[1];
180
181 // Can't pass both a relative width and height, so unset the height in favor of not breaking the horizontal layout.
182 if ( false !== strpos( $width, '%' ) && false !== strpos( $height, '%' ) )
183 $width = $height = false;
184
185 // Detect WP registered image size from HTML class
186 if ( preg_match( '#class=["|\']?[^"\']*size-([^"\'\s]+)[^"\']*["|\']?#i', $images['img_tag'][ $index ], $size ) ) {
187 $size = array_pop( $size );
188
189 if ( false === $width && false === $height && 'full' != $size && array_key_exists( $size, $image_sizes ) ) {
190 $width = (int) $image_sizes[ $size ]['width'];
191 $height = (int) $image_sizes[ $size ]['height'];
192 $transform = $image_sizes[ $size ]['crop'] ? 'resize' : 'fit';
193 }
194 } else {
195 unset( $size );
196 }
197
198 // WP Attachment ID, if uploaded to this site
199 if (
200 preg_match( '#class=["|\']?[^"\']*wp-image-([\d]+)[^"\']*["|\']?#i', $images['img_tag'][ $index ], $attachment_id ) &&
201 0 === strpos( $src, $upload_dir['baseurl'] ) &&
202 /**
203 * Filter whether an image using an attachment ID in its class has to be uploaded to the local site to go through Photon.
204 *
205 * @module photon
206 *
207 * @since 2.0.3
208 *
209 * @param bool false Was the image uploaded to the local site. Default to false.
210 * @param array $args {
211 * Array of image details.
212 *
213 * @type $src Image URL.
214 * @type tag Image tag (Image HTML output).
215 * @type $images Array of information about the image.
216 * @type $index Image index.
217 * }
218 */
219 apply_filters( 'jetpack_photon_image_is_local', false, compact( 'src', 'tag', 'images', 'index' ) )
220 ) {
221 $attachment_id = intval( array_pop( $attachment_id ) );
222
223 if ( $attachment_id ) {
224 $attachment = get_post( $attachment_id );
225
226 // Basic check on returned post object
227 if ( is_object( $attachment ) && ! is_wp_error( $attachment ) && 'attachment' == $attachment->post_type ) {
228 $src_per_wp = wp_get_attachment_image_src( $attachment_id, isset( $size ) ? $size : 'full' );
229
230 if ( self::validate_image_url( $src_per_wp[0] ) ) {
231 $src = $src_per_wp[0];
232 $fullsize_url = true;
233
234 // Prevent image distortion if a detected dimension exceeds the image's natural dimensions
235 if ( ( false !== $width && $width > $src_per_wp[1] ) || ( false !== $height && $height > $src_per_wp[2] ) ) {
236 $width = false === $width ? false : min( $width, $src_per_wp[1] );
237 $height = false === $height ? false : min( $height, $src_per_wp[2] );
238 }
239
240 // If no width and height are found, max out at source image's natural dimensions
241 // Otherwise, respect registered image sizes' cropping setting
242 if ( false === $width && false === $height ) {
243 $width = $src_per_wp[1];
244 $height = $src_per_wp[2];
245 $transform = 'fit';
246 } elseif ( isset( $size ) && array_key_exists( $size, $image_sizes ) && isset( $image_sizes[ $size ]['crop'] ) ) {
247 $transform = (bool) $image_sizes[ $size ]['crop'] ? 'resize' : 'fit';
248 }
249 }
250 } else {
251 unset( $attachment_id );
252 unset( $attachment );
253 }
254 }
255 }
256
257 // If image tag lacks width and height arguments, try to determine from strings WP appends to resized image filenames.
258 if ( false === $width && false === $height ) {
259 list( $width, $height ) = Jetpack_Photon::parse_dimensions_from_filename( $src );
260 }
261
262 // If width is available, constrain to $content_width
263 if ( false !== $width && false === strpos( $width, '%' ) && is_numeric( $content_width ) ) {
264 if ( $width > $content_width && false !== $height && false === strpos( $height, '%' ) ) {
265 $height = round( ( $content_width * $height ) / $width );
266 $width = $content_width;
267 } elseif ( $width > $content_width ) {
268 $width = $content_width;
269 }
270 }
271
272 // Set a width if none is found and $content_width is available
273 // If width is set in this manner and height is available, use `fit` instead of `resize` to prevent skewing
274 if ( false === $width && is_numeric( $content_width ) ) {
275 $width = (int) $content_width;
276
277 if ( false !== $height )
278 $transform = 'fit';
279 }
280
281 // Detect if image source is for a custom-cropped thumbnail and prevent further URL manipulation.
282 if ( ! $fullsize_url && preg_match_all( '#-e[a-z0-9]+(-\d+x\d+)?\.(' . implode('|', self::$extensions ) . '){1}$#i', basename( $src ), $filename ) )
283 $fullsize_url = true;
284
285 // Build URL, first maybe removing WP's resized string so we pass the original image to Photon
286 if ( ! $fullsize_url ) {
287 $src = self::strip_image_dimensions_maybe( $src );
288 }
289
290 // Build array of Photon args and expose to filter before passing to Photon URL function
291 $args = array();
292
293 if ( false !== $width && false !== $height && false === strpos( $width, '%' ) && false === strpos( $height, '%' ) )
294 $args[ $transform ] = $width . ',' . $height;
295 elseif ( false !== $width )
296 $args['w'] = $width;
297 elseif ( false !== $height )
298 $args['h'] = $height;
299
300 /**
301 * Filter the array of Photon arguments added to an image when it goes through Photon.
302 * By default, only includes width and height values.
303 * @see https://developer.wordpress.com/docs/photon/api/
304 *
305 * @module photon
306 *
307 * @since 2.0.0
308 *
309 * @param array $args Array of Photon Arguments.
310 * @param array $args {
311 * Array of image details.
312 *
313 * @type $tag Image tag (Image HTML output).
314 * @type $src Image URL.
315 * @type $src_orig Original Image URL.
316 * @type $width Image width.
317 * @type $height Image height.
318 * }
319 */
320 $args = apply_filters( 'jetpack_photon_post_image_args', $args, compact( 'tag', 'src', 'src_orig', 'width', 'height' ) );
321
322 $photon_url = jetpack_photon_url( $src, $args );
323
324 // Modify image tag if Photon function provides a URL
325 // 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.
326 if ( $src != $photon_url ) {
327 $new_tag = $tag;
328
329 // If present, replace the link href with a Photoned URL for the full-size image.
330 if ( ! empty( $images['link_url'][ $index ] ) && self::validate_image_url( $images['link_url'][ $index ] ) )
331 $new_tag = preg_replace( '#(href=["|\'])' . $images['link_url'][ $index ] . '(["|\'])#i', '\1' . jetpack_photon_url( $images['link_url'][ $index ] ) . '\2', $new_tag, 1 );
332
333 // Supplant the original source value with our Photon URL
334 $photon_url = esc_url( $photon_url );
335 $new_tag = str_replace( $src_orig, $photon_url, $new_tag );
336
337 // If Lazy Load is in use, pass placeholder image through Photon
338 if ( isset( $placeholder_src ) && self::validate_image_url( $placeholder_src ) ) {
339 $placeholder_src = jetpack_photon_url( $placeholder_src );
340
341 if ( $placeholder_src != $placeholder_src_orig )
342 $new_tag = str_replace( $placeholder_src_orig, esc_url( $placeholder_src ), $new_tag );
343
344 unset( $placeholder_src );
345 }
346
347 // Remove the width and height arguments from the tag to prevent distortion
348 $new_tag = preg_replace( '#(?<=\s)(width|height)=["|\']?[\d%]+["|\']?\s?#i', '', $new_tag );
349
350 // Tag an image for dimension checking
351 $new_tag = preg_replace( '#(\s?/)?>(\s*</a>)?$#i', ' data-recalc-dims="1"\1>\2', $new_tag );
352
353 // Replace original tag with modified version
354 $content = str_replace( $tag, $new_tag, $content );
355 }
356 } elseif ( preg_match( '#^http(s)?://i[\d]{1}.wp.com#', $src ) && ! empty( $images['link_url'][ $index ] ) && self::validate_image_url( $images['link_url'][ $index ] ) ) {
357 $new_tag = preg_replace( '#(href=["|\'])' . $images['link_url'][ $index ] . '(["|\'])#i', '\1' . jetpack_photon_url( $images['link_url'][ $index ] ) . '\2', $tag, 1 );
358
359 $content = str_replace( $tag, $new_tag, $content );
360 }
361 }
362 }
363
364 return $content;
365 }
366
367 public static function filter_the_galleries( $galleries ) {
368 if ( empty( $galleries ) || ! is_array( $galleries ) ) {
369 return $galleries;
370 }
371
372 // Pass by reference, so we can modify them in place.
373 foreach ( $galleries as &$this_gallery ) {
374 if ( is_string( $this_gallery ) ) {
375 $this_gallery = self::filter_the_content( $this_gallery );
376 // LEAVING COMMENTED OUT as for the moment it doesn't seem
377 // necessary and I'm not sure how it would propagate through.
378 // } elseif ( is_array( $this_gallery )
379 // && ! empty( $this_gallery['src'] )
380 // && ! empty( $this_gallery['type'] )
381 // && in_array( $this_gallery['type'], array( 'rectangle', 'square', 'circle' ) ) ) {
382 // $this_gallery['src'] = array_map( 'jetpack_photon_url', $this_gallery['src'] );
383 }
384 }
385 unset( $this_gallery ); // break the reference.
386
387 return $galleries;
388 }
389
390
391 /**
392 * Runs the image widget through photon.
393 *
394 * @param array $instance Image widget instance data.
395 * @return array
396 */
397 public static function filter_the_image_widget( $instance ) {
398 if ( Jetpack::is_module_active( 'photon' ) && ! $instance['attachment_id'] && $instance['url'] ) {
399 jetpack_photon_url( $instance['url'], array(
400 'w' => $instance['width'],
401 'h' => $instance['height'],
402 ) );
403 }
404
405 return $instance;
406 }
407
408 /**
409 ** CORE IMAGE RETRIEVAL
410 **/
411
412 /**
413 * Filter post thumbnail image retrieval, passing images through Photon
414 *
415 * @param string|bool $image
416 * @param int $attachment_id
417 * @param string|array $size
418 * @uses is_admin, apply_filters, wp_get_attachment_url, self::validate_image_url, this::image_sizes, jetpack_photon_url
419 * @filter image_downsize
420 * @return string|bool
421 */
422 public function filter_image_downsize( $image, $attachment_id, $size ) {
423 // Don't foul up the admin side of things, unless a plugin wants to.
424 if ( is_admin() &&
425 /**
426 * Provide plugins a way of running Photon for images in the WordPress Dashboard (wp-admin).
427 *
428 * 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.
429 *
430 * @module photon
431 *
432 * @since 4.8.0
433 *
434 * @param bool false Stop Photon from being run on the Dashboard. Default to false.
435 * @param array $args {
436 * Array of image details.
437 *
438 * @type $image Image URL.
439 * @type $attachment_id Attachment ID of the image.
440 * @type $size Image size. Can be a string (name of the image size, e.g. full) or an integer.
441 * }
442 */
443 false === apply_filters( 'jetpack_photon_admin_allow_image_downsize', false, compact( 'image', 'attachment_id', 'size' ) )
444 ) {
445 return $image;
446 }
447
448 /**
449 * Provide plugins a way of preventing Photon from being applied to images retrieved from WordPress Core.
450 *
451 * @module photon
452 *
453 * @since 2.0.0
454 *
455 * @param bool false Stop Photon from being applied to the image. Default to false.
456 * @param array $args {
457 * Array of image details.
458 *
459 * @type $image Image URL.
460 * @type $attachment_id Attachment ID of the image.
461 * @type $size Image size. Can be a string (name of the image size, e.g. full) or an integer.
462 * }
463 */
464 if ( apply_filters( 'jetpack_photon_override_image_downsize', false, compact( 'image', 'attachment_id', 'size' ) ) ) {
465 return $image;
466 }
467
468 // Get the image URL and proceed with Photon-ification if successful
469 $image_url = wp_get_attachment_url( $attachment_id );
470
471 // Set this to true later when we know we have size meta.
472 $has_size_meta = false;
473
474 if ( $image_url ) {
475 // Check if image URL should be used with Photon
476 if ( ! self::validate_image_url( $image_url ) )
477 return $image;
478
479 $intermediate = true; // For the fourth array item returned by the image_downsize filter.
480
481 // If an image is requested with a size known to WordPress, use that size's settings with Photon
482 if ( ( is_string( $size ) || is_int( $size ) ) && array_key_exists( $size, self::image_sizes() ) ) {
483 $image_args = self::image_sizes();
484 $image_args = $image_args[ $size ];
485
486 $photon_args = array();
487
488 $image_meta = image_get_intermediate_size( $attachment_id, $size );
489
490 // 'full' is a special case: We need consistent data regardless of the requested size.
491 if ( 'full' == $size ) {
492 $image_meta = wp_get_attachment_metadata( $attachment_id );
493 $intermediate = false;
494 } elseif ( ! $image_meta ) {
495 // If we still don't have any image meta at this point, it's probably from a custom thumbnail size
496 // for an image that was uploaded before the custom image was added to the theme. Try to determine the size manually.
497 $image_meta = wp_get_attachment_metadata( $attachment_id );
498
499 if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
500 $image_resized = image_resize_dimensions( $image_meta['width'], $image_meta['height'], $image_args['width'], $image_args['height'], $image_args['crop'] );
501 if ( $image_resized ) { // This could be false when the requested image size is larger than the full-size image.
502 $image_meta['width'] = $image_resized[6];
503 $image_meta['height'] = $image_resized[7];
504 }
505 }
506 }
507
508 if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
509 $image_args['width'] = $image_meta['width'];
510 $image_args['height'] = $image_meta['height'];
511
512 list( $image_args['width'], $image_args['height'] ) = image_constrain_size_for_editor( $image_args['width'], $image_args['height'], $size, 'display' );
513 $has_size_meta = true;
514 }
515
516 // Expose determined arguments to a filter before passing to Photon
517 $transform = $image_args['crop'] ? 'resize' : 'fit';
518
519 // Check specified image dimensions and account for possible zero values; photon fails to resize if a dimension is zero.
520 if ( 0 == $image_args['width'] || 0 == $image_args['height'] ) {
521 if ( 0 == $image_args['width'] && 0 < $image_args['height'] ) {
522 $photon_args['h'] = $image_args['height'];
523 } elseif ( 0 == $image_args['height'] && 0 < $image_args['width'] ) {
524 $photon_args['w'] = $image_args['width'];
525 }
526 } else {
527 if ( ( 'resize' === $transform ) && $image_meta = wp_get_attachment_metadata( $attachment_id ) ) {
528 if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
529 // Lets make sure that we don't upscale images since wp never upscales them as well
530 $smaller_width = ( ( $image_meta['width'] < $image_args['width'] ) ? $image_meta['width'] : $image_args['width'] );
531 $smaller_height = ( ( $image_meta['height'] < $image_args['height'] ) ? $image_meta['height'] : $image_args['height'] );
532
533 $photon_args[ $transform ] = $smaller_width . ',' . $smaller_height;
534 }
535 } else {
536 $photon_args[ $transform ] = $image_args['width'] . ',' . $image_args['height'];
537 }
538
539 }
540
541
542 /**
543 * Filter the Photon Arguments added to an image when going through Photon, when that image size is a string.
544 * Image size will be a string (e.g. "full", "medium") when it is known to WordPress.
545 *
546 * @module photon
547 *
548 * @since 2.0.0
549 *
550 * @param array $photon_args Array of Photon arguments.
551 * @param array $args {
552 * Array of image details.
553 *
554 * @type $image_args Array of Image arguments (width, height, crop).
555 * @type $image_url Image URL.
556 * @type $attachment_id Attachment ID of the image.
557 * @type $size Image size. Can be a string (name of the image size, e.g. full) or an integer.
558 * @type $transform Value can be resize or fit.
559 * @see https://developer.wordpress.com/docs/photon/api
560 * }
561 */
562 $photon_args = apply_filters( 'jetpack_photon_image_downsize_string', $photon_args, compact( 'image_args', 'image_url', 'attachment_id', 'size', 'transform' ) );
563
564 // Generate Photon URL
565 $image = array(
566 jetpack_photon_url( $image_url, $photon_args ),
567 $has_size_meta ? $image_args['width'] : false,
568 $has_size_meta ? $image_args['height'] : false,
569 $intermediate
570 );
571 } elseif ( is_array( $size ) ) {
572 // Pull width and height values from the provided array, if possible
573 $width = isset( $size[0] ) ? (int) $size[0] : false;
574 $height = isset( $size[1] ) ? (int) $size[1] : false;
575
576 // Don't bother if necessary parameters aren't passed.
577 if ( ! $width || ! $height ) {
578 return $image;
579 }
580
581 $image_meta = wp_get_attachment_metadata( $attachment_id );
582 if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
583 $image_resized = image_resize_dimensions( $image_meta['width'], $image_meta['height'], $width, $height );
584
585 if ( $image_resized ) { // This could be false when the requested image size is larger than the full-size image.
586 $width = $image_resized[6];
587 $height = $image_resized[7];
588 } else {
589 $width = $image_meta['width'];
590 $height = $image_meta['height'];
591 }
592
593 $has_size_meta = true;
594 }
595
596 list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
597
598 // Expose arguments to a filter before passing to Photon
599 $photon_args = array(
600 'fit' => $width . ',' . $height
601 );
602
603 /**
604 * Filter the Photon Arguments added to an image when going through Photon,
605 * when the image size is an array of height and width values.
606 *
607 * @module photon
608 *
609 * @since 2.0.0
610 *
611 * @param array $photon_args Array of Photon arguments.
612 * @param array $args {
613 * Array of image details.
614 *
615 * @type $width Image width.
616 * @type height Image height.
617 * @type $image_url Image URL.
618 * @type $attachment_id Attachment ID of the image.
619 * }
620 */
621 $photon_args = apply_filters( 'jetpack_photon_image_downsize_array', $photon_args, compact( 'width', 'height', 'image_url', 'attachment_id' ) );
622
623 // Generate Photon URL
624 $image = array(
625 jetpack_photon_url( $image_url, $photon_args ),
626 $has_size_meta ? $width : false,
627 $has_size_meta ? $height : false,
628 $intermediate
629 );
630 }
631 }
632
633 return $image;
634 }
635
636 /**
637 * Filters an array of image `srcset` values, replacing each URL with its Photon equivalent.
638 *
639 * @since 3.8.0
640 * @since 4.0.4 Added automatically additional sizes beyond declared image sizes.
641 * @param array $sources An array of image urls and widths.
642 * @uses self::validate_image_url, jetpack_photon_url, Jetpack_Photon::parse_from_filename
643 * @uses Jetpack_Photon::strip_image_dimensions_maybe, Jetpack::get_content_width
644 * @return array An array of Photon image urls and widths.
645 */
646 public function filter_srcset_array( $sources = array(), $size_array = array(), $image_src = array(), $image_meta = array(), $attachment_id = 0 ) {
647 if ( ! is_array( $sources ) ) {
648 return $sources;
649 }
650 $upload_dir = wp_get_upload_dir();
651
652 foreach ( $sources as $i => $source ) {
653 if ( ! self::validate_image_url( $source['url'] ) ) {
654 continue;
655 }
656
657 /** This filter is already documented in class.photon.php */
658 if ( apply_filters( 'jetpack_photon_skip_image', false, $source['url'], $source ) ) {
659 continue;
660 }
661
662 $url = $source['url'];
663 list( $width, $height ) = Jetpack_Photon::parse_dimensions_from_filename( $url );
664
665 // It's quicker to get the full size with the data we have already, if available
666 if ( ! empty( $attachment_id ) ) {
667 $url = wp_get_attachment_url( $attachment_id );
668 } else {
669 $url = Jetpack_Photon::strip_image_dimensions_maybe( $url );
670 }
671
672 $args = array();
673 if ( 'w' === $source['descriptor'] ) {
674 if ( $height && ( $source['value'] == $width ) ) {
675 $args['resize'] = $width . ',' . $height;
676 } else {
677 $args['w'] = $source['value'];
678 }
679
680 }
681
682 $sources[ $i ]['url'] = jetpack_photon_url( $url, $args );
683 }
684
685 /**
686 * At this point, $sources is the original srcset with Photonized URLs.
687 * Now, we're going to construct additional sizes based on multiples of the content_width.
688 * This will reduce the gap between the largest defined size and the original image.
689 */
690
691 /**
692 * Filter the multiplier Photon uses to create new srcset items.
693 * Return false to short-circuit and bypass auto-generation.
694 *
695 * @module photon
696 *
697 * @since 4.0.4
698 *
699 * @param array|bool $multipliers Array of multipliers to use or false to bypass.
700 */
701 $multipliers = apply_filters( 'jetpack_photon_srcset_multipliers', array( 2, 3 ) );
702 $url = trailingslashit( $upload_dir['baseurl'] ) . $image_meta['file'];
703
704 if (
705 /** Short-circuit via jetpack_photon_srcset_multipliers filter. */
706 is_array( $multipliers )
707 /** This filter is already documented in class.photon.php */
708 && ! apply_filters( 'jetpack_photon_skip_image', false, $url, null )
709 /** Verify basic meta is intact. */
710 && isset( $image_meta['width'] ) && isset( $image_meta['height'] ) && isset( $image_meta['file'] )
711 /** Verify we have the requested width/height. */
712 && isset( $size_array[0] ) && isset( $size_array[1] )
713 ) {
714
715 $fullwidth = $image_meta['width'];
716 $fullheight = $image_meta['height'];
717 $reqwidth = $size_array[0];
718 $reqheight = $size_array[1];
719
720 $constrained_size = wp_constrain_dimensions( $fullwidth, $fullheight, $reqwidth );
721 $expected_size = array( $reqwidth, $reqheight );
722
723 if ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 ) {
724 $crop = 'soft';
725 $base = Jetpack::get_content_width() ? Jetpack::get_content_width() : 1000; // Provide a default width if none set by the theme.
726 } else {
727 $crop = 'hard';
728 $base = $reqwidth;
729 }
730
731
732 $currentwidths = array_keys( $sources );
733 $newsources = null;
734
735 foreach ( $multipliers as $multiplier ) {
736
737 $newwidth = $base * $multiplier;
738 foreach ( $currentwidths as $currentwidth ){
739 // If a new width would be within 100 pixes of an existing one or larger than the full size image, skip.
740 if ( abs( $currentwidth - $newwidth ) < 50 || ( $newwidth > $fullwidth ) ) {
741 continue 2; // Back to the foreach ( $multipliers as $multiplier )
742 }
743 } // foreach ( $currentwidths as $currentwidth ){
744
745 if ( 'soft' == $crop ) {
746 $args = array(
747 'w' => $newwidth,
748 );
749 } else { // hard crop, e.g. add_image_size( 'example', 200, 200, true );
750 $args = array(
751 'zoom' => $multiplier,
752 'resize' => $reqwidth . ',' . $reqheight,
753 );
754 }
755
756 $newsources[ $newwidth ] = array(
757 'url' => jetpack_photon_url( $url, $args ),
758 'descriptor' => 'w',
759 'value' => $newwidth,
760 );
761 } // foreach ( $multipliers as $multiplier )
762 if ( is_array( $newsources ) ) {
763 if ( function_exists( 'array_replace' ) ) { // PHP 5.3+, preferred
764 $sources = array_replace( $sources, $newsources );
765 } else { // For PHP 5.2 using WP shim function
766 $sources = array_replace_recursive( $sources, $newsources );
767 }
768 }
769 } // if ( isset( $image_meta['width'] ) && isset( $image_meta['file'] ) )
770
771 return $sources;
772 }
773
774 /**
775 * Filters an array of image `sizes` values, using $content_width instead of image's full size.
776 *
777 * @since 4.0.4
778 * @since 4.1.0 Returns early for images not within the_content.
779 * @param array $sizes An array of media query breakpoints.
780 * @param array $size Width and height of the image
781 * @uses Jetpack::get_content_width
782 * @return array An array of media query breakpoints.
783 */
784 public function filter_sizes( $sizes, $size ) {
785 if ( ! doing_filter( 'the_content' ) ){
786 return $sizes;
787 }
788 $content_width = Jetpack::get_content_width();
789 if ( ! $content_width ) {
790 $content_width = 1000;
791 }
792
793 if ( ( is_array( $size ) && $size[0] < $content_width ) ) {
794 return $sizes;
795 }
796
797 return sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $content_width );
798 }
799
800 /**
801 ** GENERAL FUNCTIONS
802 **/
803
804 /**
805 * Ensure image URL is valid for Photon.
806 * 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.
807 *
808 * @param string $url
809 * @uses wp_parse_args
810 * @return bool
811 */
812 protected static function validate_image_url( $url ) {
813 $parsed_url = @parse_url( $url );
814
815 if ( ! $parsed_url )
816 return false;
817
818 // Parse URL and ensure needed keys exist, since the array returned by `parse_url` only includes the URL components it finds.
819 $url_info = wp_parse_args( $parsed_url, array(
820 'scheme' => null,
821 'host' => null,
822 'port' => null,
823 'path' => null
824 ) );
825
826 // Bail if scheme isn't http or port is set that isn't port 80
827 if (
828 ( 'http' != $url_info['scheme'] || ! in_array( $url_info['port'], array( 80, null ) ) ) &&
829 /**
830 * Allow Photon to fetch images that are served via HTTPS.
831 *
832 * @module photon
833 *
834 * @since 2.4.0
835 * @since 3.9.0 Default to false.
836 *
837 * @param bool $reject_https Should Photon ignore images using the HTTPS scheme. Default to false.
838 */
839 apply_filters( 'jetpack_photon_reject_https', false )
840 ) {
841 return false;
842 }
843
844 // Bail if no host is found
845 if ( is_null( $url_info['host'] ) )
846 return false;
847
848 // Bail if the image alredy went through Photon
849 if ( preg_match( '#^i[\d]{1}.wp.com$#i', $url_info['host'] ) )
850 return false;
851
852 // Bail if no path is found
853 if ( is_null( $url_info['path'] ) )
854 return false;
855
856 // Ensure image extension is acceptable
857 if ( ! in_array( strtolower( pathinfo( $url_info['path'], PATHINFO_EXTENSION ) ), self::$extensions ) )
858 return false;
859
860 // If we got this far, we should have an acceptable image URL
861 // But let folks filter to decline if they prefer.
862 /**
863 * Overwrite the results of the validation steps an image goes through before to be considered valid to be used by Photon.
864 *
865 * @module photon
866 *
867 * @since 3.0.0
868 *
869 * @param bool true Is the image URL valid and can it be used by Photon. Default to true.
870 * @param string $url Image URL.
871 * @param array $parsed_url Array of information about the image.
872 */
873 return apply_filters( 'photon_validate_image_url', true, $url, $parsed_url );
874 }
875
876 /**
877 * Checks if the file exists before it passes the file to photon
878 *
879 * @param string $src The image URL
880 * @return string
881 **/
882 protected static function strip_image_dimensions_maybe( $src ){
883 $stripped_src = $src;
884
885 // Build URL, first removing WP's resized string so we pass the original image to Photon
886 if ( preg_match( '#(-\d+x\d+)\.(' . implode('|', self::$extensions ) . '){1}$#i', $src, $src_parts ) ) {
887 $stripped_src = str_replace( $src_parts[1], '', $src );
888 $upload_dir = wp_get_upload_dir();
889
890 // Extracts the file path to the image minus the base url
891 $file_path = substr( $stripped_src, strlen ( $upload_dir['baseurl'] ) );
892
893 if( file_exists( $upload_dir["basedir"] . $file_path ) )
894 $src = $stripped_src;
895 }
896
897 return $src;
898 }
899
900 /**
901 * Provide an array of available image sizes and corresponding dimensions.
902 * Similar to get_intermediate_image_sizes() except that it includes image sizes' dimensions, not just their names.
903 *
904 * @global $wp_additional_image_sizes
905 * @uses get_option
906 * @return array
907 */
908 protected static function image_sizes() {
909 if ( null == self::$image_sizes ) {
910 global $_wp_additional_image_sizes;
911
912 // Populate an array matching the data structure of $_wp_additional_image_sizes so we have a consistent structure for image sizes
913 $images = array(
914 'thumb' => array(
915 'width' => intval( get_option( 'thumbnail_size_w' ) ),
916 'height' => intval( get_option( 'thumbnail_size_h' ) ),
917 'crop' => (bool) get_option( 'thumbnail_crop' )
918 ),
919 'medium' => array(
920 'width' => intval( get_option( 'medium_size_w' ) ),
921 'height' => intval( get_option( 'medium_size_h' ) ),
922 'crop' => false
923 ),
924 'large' => array(
925 'width' => intval( get_option( 'large_size_w' ) ),
926 'height' => intval( get_option( 'large_size_h' ) ),
927 'crop' => false
928 ),
929 'full' => array(
930 'width' => null,
931 'height' => null,
932 'crop' => false
933 )
934 );
935
936 // Compatibility mapping as found in wp-includes/media.php
937 $images['thumbnail'] = $images['thumb'];
938
939 // Update class variable, merging in $_wp_additional_image_sizes if any are set
940 if ( is_array( $_wp_additional_image_sizes ) && ! empty( $_wp_additional_image_sizes ) )
941 self::$image_sizes = array_merge( $images, $_wp_additional_image_sizes );
942 else
943 self::$image_sizes = $images;
944 }
945
946 return is_array( self::$image_sizes ) ? self::$image_sizes : array();
947 }
948
949 /**
950 * Pass og:image URLs through Photon
951 *
952 * @param array $tags
953 * @param array $parameters
954 * @uses jetpack_photon_url
955 * @return array
956 */
957 function filter_open_graph_tags( $tags, $parameters ) {
958 if ( empty( $tags['og:image'] ) ) {
959 return $tags;
960 }
961
962 $photon_args = array(
963 'fit' => sprintf( '%d,%d', 2 * $parameters['image_width'], 2 * $parameters['image_height'] ),
964 );
965
966 if ( is_array( $tags['og:image'] ) ) {
967 $images = array();
968 foreach ( $tags['og:image'] as $image ) {
969 $images[] = jetpack_photon_url( $image, $photon_args );
970 }
971 $tags['og:image'] = $images;
972 } else {
973 $tags['og:image'] = jetpack_photon_url( $tags['og:image'], $photon_args );
974 }
975
976 return $tags;
977 }
978
979 /**
980 * Enqueue Photon helper script
981 *
982 * @uses wp_enqueue_script, plugins_url
983 * @action wp_enqueue_script
984 * @return null
985 */
986 public function action_wp_enqueue_scripts() {
987 wp_enqueue_script( 'jetpack-photon', plugins_url( 'modules/photon/photon.js', JETPACK__PLUGIN_FILE ), array( 'jquery' ), 20130122, true );
988 }
989 }
990