PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 3.1.5
Jetpack – WP Security, Backup, Speed, & Growth v3.1.5
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 in Jetpack – WP Security, Backup, Speed, & Growth 3.1.5, at class.photon.php

595 lines 21.1 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 // Display warning if site is private
49 add_action( 'jetpack_activate_module_photon', array( $this, 'action_jetpack_activate_module_photon' ) );
50
51 if ( ! function_exists( 'jetpack_photon_url' ) )
52 return;
53
54 // Images in post content and galleries
55 add_filter( 'the_content', array( __CLASS__, 'filter_the_content' ), 999999 );
56 add_filter( 'get_post_gallery', array( __CLASS__, 'filter_the_content' ), 999999 );
57
58 // Core image retrieval
59 add_filter( 'image_downsize', array( $this, 'filter_image_downsize' ), 10, 3 );
60
61 // Helpers for maniuplated images
62 add_action( 'wp_enqueue_scripts', array( $this, 'action_wp_enqueue_scripts' ), 9 );
63 }
64
65 /**
66 * Check if site is private and warn user if it is
67 *
68 * @uses Jetpack::check_privacy
69 * @action jetpack_activate_module_photon
70 * @return null
71 */
72 public function action_jetpack_activate_module_photon() {
73 Jetpack::check_privacy( __FILE__ );
74 }
75
76 /**
77 ** IN-CONTENT IMAGE MANIPULATION FUNCTIONS
78 **/
79
80 /**
81 * Match all images and any relevant <a> tags in a block of HTML.
82 *
83 * @param string $content Some HTML.
84 * @return array An array of $images matches, where $images[0] is
85 * an array of full matches, and the link_url, img_tag,
86 * and img_url keys are arrays of those matches.
87 */
88 public static function parse_images_from_html( $content ) {
89 $images = array();
90
91 if ( preg_match_all( '#(?:<a[^>]+?href=["|\'](?P<link_url>[^\s]+?)["|\'][^>]*?>\s*)?(?P<img_tag><img[^>]+?src=["|\'](?P<img_url>[^\s]+?)["|\'].*?>){1}(?:\s*</a>)?#is', $content, $images ) ) {
92 foreach ( $images as $key => $unused ) {
93 // Simplify the output as much as possible, mostly for confirming test results.
94 if ( is_numeric( $key ) && $key > 0 )
95 unset( $images[$key] );
96 }
97
98 return $images;
99 }
100
101 return array();
102 }
103
104 /**
105 * Try to determine height and width from strings WP appends to resized image filenames.
106 *
107 * @param string $src The image URL.
108 * @return array An array consisting of width and height.
109 */
110 public static function parse_dimensions_from_filename( $src ) {
111 $width_height_string = array();
112
113 if ( preg_match( '#-(\d+)x(\d+)\.(?:' . implode('|', self::$extensions ) . '){1}$#i', $src, $width_height_string ) ) {
114 $width = (int) $width_height_string[1];
115 $height = (int) $width_height_string[2];
116
117 if ( $width && $height )
118 return array( $width, $height );
119 }
120
121 return array( false, false );
122 }
123
124 /**
125 * Identify images in post content, and if images are local (uploaded to the current site), pass through Photon.
126 *
127 * @param string $content
128 * @uses self::validate_image_url, apply_filters, jetpack_photon_url, esc_url
129 * @filter the_content
130 * @return string
131 */
132 public static function filter_the_content( $content ) {
133 $images = Jetpack_Photon::parse_images_from_html( $content );
134
135 if ( ! empty( $images ) ) {
136 $content_width = Jetpack::get_content_width();
137
138 $image_sizes = self::image_sizes();
139 $upload_dir = wp_upload_dir();
140
141 foreach ( $images[0] as $index => $tag ) {
142 // Default to resize, though fit may be used in certain cases where a dimension cannot be ascertained
143 $transform = 'resize';
144
145 // Start with a clean attachment ID each time
146 $attachment_id = false;
147
148 // Flag if we need to munge a fullsize URL
149 $fullsize_url = false;
150
151 // Identify image source
152 $src = $src_orig = $images['img_url'][ $index ];
153
154 // Allow specific images to be skipped
155 if ( apply_filters( 'jetpack_photon_skip_image', false, $src, $tag ) )
156 continue;
157
158 // Support Automattic's Lazy Load plugin
159 // Can't modify $tag yet as we need unadulterated version later
160 if ( preg_match( '#data-lazy-src=["|\'](.+?)["|\']#i', $images['img_tag'][ $index ], $lazy_load_src ) ) {
161 $placeholder_src = $placeholder_src_orig = $src;
162 $src = $src_orig = $lazy_load_src[1];
163 }
164
165 // Check if image URL should be used with Photon
166 if ( self::validate_image_url( $src ) ) {
167 // Find the width and height attributes
168 $width = $height = false;
169
170 // First, check the image tag
171 if ( preg_match( '#width=["|\']?([\d%]+)["|\']?#i', $images['img_tag'][ $index ], $width_string ) )
172 $width = $width_string[1];
173
174 if ( preg_match( '#height=["|\']?([\d%]+)["|\']?#i', $images['img_tag'][ $index ], $height_string ) )
175 $height = $height_string[1];
176
177 // Can't pass both a relative width and height, so unset the height in favor of not breaking the horizontal layout.
178 if ( false !== strpos( $width, '%' ) && false !== strpos( $height, '%' ) )
179 $width = $height = false;
180
181 // Detect WP registered image size from HTML class
182 if ( preg_match( '#class=["|\']?[^"\']*size-([^"\'\s]+)[^"\']*["|\']?#i', $images['img_tag'][ $index ], $size ) ) {
183 $size = array_pop( $size );
184
185 if ( false === $width && false === $height && 'full' != $size && array_key_exists( $size, $image_sizes ) ) {
186 $width = (int) $image_sizes[ $size ]['width'];
187 $height = (int) $image_sizes[ $size ]['height'];
188 $transform = $image_sizes[ $size ]['crop'] ? 'resize' : 'fit';
189 }
190 } else {
191 unset( $size );
192 }
193
194 // WP Attachment ID, if uploaded to this site
195 if ( preg_match( '#class=["|\']?[^"\']*wp-image-([\d]+)[^"\']*["|\']?#i', $images['img_tag'][ $index ], $attachment_id ) && ( 0 === strpos( $src, $upload_dir['baseurl'] ) || apply_filters( 'jetpack_photon_image_is_local', false, compact( 'src', 'tag', 'images', 'index' ) ) ) ) {
196 $attachment_id = intval( array_pop( $attachment_id ) );
197
198 if ( $attachment_id ) {
199 $attachment = get_post( $attachment_id );
200
201 // Basic check on returned post object
202 if ( is_object( $attachment ) && ! is_wp_error( $attachment ) && 'attachment' == $attachment->post_type ) {
203 $src_per_wp = wp_get_attachment_image_src( $attachment_id, isset( $size ) ? $size : 'full' );
204
205 if ( self::validate_image_url( $src_per_wp[0] ) ) {
206 $src = $src_per_wp[0];
207 $fullsize_url = true;
208
209 // Prevent image distortion if a detected dimension exceeds the image's natural dimensions
210 if ( ( false !== $width && $width > $src_per_wp[1] ) || ( false !== $height && $height > $src_per_wp[2] ) ) {
211 $width = false == $width ? false : min( $width, $src_per_wp[1] );
212 $height = false == $height ? false : min( $height, $src_per_wp[2] );
213 }
214
215 // If no width and height are found, max out at source image's natural dimensions
216 // Otherwise, respect registered image sizes' cropping setting
217 if ( false == $width && false == $height ) {
218 $width = $src_per_wp[1];
219 $height = $src_per_wp[2];
220 $transform = 'fit';
221 } elseif ( isset( $size ) && array_key_exists( $size, $image_sizes ) && isset( $image_sizes[ $size ]['crop'] ) ) {
222 $transform = (bool) $image_sizes[ $size ]['crop'] ? 'resize' : 'fit';
223 }
224 }
225 } else {
226 unset( $attachment_id );
227 unset( $attachment );
228 }
229 }
230 }
231
232 // If image tag lacks width and height arguments, try to determine from strings WP appends to resized image filenames.
233 if ( false === $width && false === $height ) {
234 list( $width, $height ) = Jetpack_Photon::parse_dimensions_from_filename( $src );
235 }
236
237 // If width is available, constrain to $content_width
238 if ( false !== $width && false === strpos( $width, '%' ) && is_numeric( $content_width ) ) {
239 if ( $width > $content_width && false !== $height && false === strpos( $height, '%' ) ) {
240 $height = round( ( $content_width * $height ) / $width );
241 $width = $content_width;
242 } elseif ( $width > $content_width ) {
243 $width = $content_width;
244 }
245 }
246
247 // Set a width if none is found and $content_width is available
248 // If width is set in this manner and height is available, use `fit` instead of `resize` to prevent skewing
249 if ( false === $width && is_numeric( $content_width ) ) {
250 $width = (int) $content_width;
251
252 if ( false !== $height )
253 $transform = 'fit';
254 }
255
256 // Detect if image source is for a custom-cropped thumbnail and prevent further URL manipulation.
257 if ( ! $fullsize_url && preg_match_all( '#-e[a-z0-9]+(-\d+x\d+)?\.(' . implode('|', self::$extensions ) . '){1}$#i', basename( $src ), $filename ) )
258 $fullsize_url = true;
259
260 // Build URL, first maybe removing WP's resized string so we pass the original image to Photon
261 if ( ! $fullsize_url ) {
262 $src = self::strip_image_dimensions_maybe( $src );
263 }
264
265 // Build array of Photon args and expose to filter before passing to Photon URL function
266 $args = array();
267
268 if ( false !== $width && false !== $height && false === strpos( $width, '%' ) && false === strpos( $height, '%' ) )
269 $args[ $transform ] = $width . ',' . $height;
270 elseif ( false !== $width )
271 $args['w'] = $width;
272 elseif ( false !== $height )
273 $args['h'] = $height;
274
275 $args = apply_filters( 'jetpack_photon_post_image_args', $args, compact( 'tag', 'src', 'src_orig', 'width', 'height' ) );
276
277 $photon_url = jetpack_photon_url( $src, $args );
278
279 // Modify image tag if Photon function provides a URL
280 // 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.
281 if ( $src != $photon_url ) {
282 $new_tag = $tag;
283
284 // If present, replace the link href with a Photoned URL for the full-size image.
285 if ( ! empty( $images['link_url'][ $index ] ) && self::validate_image_url( $images['link_url'][ $index ] ) )
286 $new_tag = preg_replace( '#(href=["|\'])' . $images['link_url'][ $index ] . '(["|\'])#i', '\1' . jetpack_photon_url( $images['link_url'][ $index ] ) . '\2', $new_tag, 1 );
287
288 // Supplant the original source value with our Photon URL
289 $photon_url = esc_url( $photon_url );
290 $new_tag = str_replace( $src_orig, $photon_url, $new_tag );
291
292 // If Lazy Load is in use, pass placeholder image through Photon
293 if ( isset( $placeholder_src ) && self::validate_image_url( $placeholder_src ) ) {
294 $placeholder_src = jetpack_photon_url( $placeholder_src );
295
296 if ( $placeholder_src != $placeholder_src_orig )
297 $new_tag = str_replace( $placeholder_src_orig, esc_url( $placeholder_src ), $new_tag );
298
299 unset( $placeholder_src );
300 }
301
302 // Remove the width and height arguments from the tag to prevent distortion
303 $new_tag = preg_replace( '#(?<=\s)(width|height)=["|\']?[\d%]+["|\']?\s?#i', '', $new_tag );
304
305 // Tag an image for dimension checking
306 $new_tag = preg_replace( '#(\s?/)?>(</a>)?$#i', ' data-recalc-dims="1"\1>\2', $new_tag );
307
308 // Replace original tag with modified version
309 $content = str_replace( $tag, $new_tag, $content );
310 }
311 } elseif ( preg_match( '#^http(s)?://i[\d]{1}.wp.com#', $src ) && ! empty( $images['link_url'][ $index ] ) && self::validate_image_url( $images['link_url'][ $index ] ) ) {
312 $new_tag = preg_replace( '#(href=["|\'])' . $images['link_url'][ $index ] . '(["|\'])#i', '\1' . jetpack_photon_url( $images['link_url'][ $index ] ) . '\2', $tag, 1 );
313
314 $content = str_replace( $tag, $new_tag, $content );
315 }
316 }
317 }
318
319 return $content;
320 }
321
322 /**
323 ** CORE IMAGE RETRIEVAL
324 **/
325
326 /**
327 * Filter post thumbnail image retrieval, passing images through Photon
328 *
329 * @param string|bool $image
330 * @param int $attachment_id
331 * @param string|array $size
332 * @uses is_admin, apply_filters, wp_get_attachment_url, self::validate_image_url, this::image_sizes, jetpack_photon_url
333 * @filter image_downsize
334 * @return string|bool
335 */
336 public function filter_image_downsize( $image, $attachment_id, $size ) {
337 // Don't foul up the admin side of things, and provide plugins a way of preventing Photon from being applied to images.
338 if ( is_admin() || apply_filters( 'jetpack_photon_override_image_downsize', false, compact( 'image', 'attachment_id', 'size' ) ) )
339 return $image;
340
341 // Get the image URL and proceed with Photon-ification if successful
342 $image_url = wp_get_attachment_url( $attachment_id );
343
344 if ( $image_url ) {
345 // Check if image URL should be used with Photon
346 if ( ! self::validate_image_url( $image_url ) )
347 return $image;
348
349 // If an image is requested with a size known to WordPress, use that size's settings with Photon
350 if ( ( is_string( $size ) || is_int( $size ) ) && array_key_exists( $size, self::image_sizes() ) ) {
351 $image_args = self::image_sizes();
352 $image_args = $image_args[ $size ];
353
354 $photon_args = array();
355
356 // `full` is a special case in WP
357 // To ensure filter receives consistent data regardless of requested size, `$image_args` is overridden with dimensions of original image.
358 if ( 'full' == $size ) {
359 $image_meta = wp_get_attachment_metadata( $attachment_id );
360 if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
361 // 'crop' is true so Photon's `resize` method is used
362 $image_args = array(
363 'width' => $image_meta['width'],
364 'height' => $image_meta['height'],
365 'crop' => true
366 );
367 }
368 }
369
370 // Expose determined arguments to a filter before passing to Photon
371 $transform = $image_args['crop'] ? 'resize' : 'fit';
372
373 // Check specified image dimensions and account for possible zero values; photon fails to resize if a dimension is zero.
374 if ( 0 == $image_args['width'] || 0 == $image_args['height'] ) {
375 if ( 0 == $image_args['width'] && 0 < $image_args['height'] )
376 $photon_args['h'] = $image_args['height'];
377 elseif ( 0 == $image_args['height'] && 0 < $image_args['width'] )
378 $photon_args['w'] = $image_args['width'];
379 } else {
380 if( 'resize' == $transform ) {
381 // Lets make sure that we don't upscale images since wp never upscales them as well
382 $image_meta = wp_get_attachment_metadata( $attachment_id );
383
384 $smaller_width = ( ( $image_meta['width'] < $image_args['width'] ) ? $image_meta['width'] : $image_args['width'] );
385 $smaller_height = ( ( $image_meta['height'] < $image_args['height'] ) ? $image_meta['height'] : $image_args['height'] );
386
387 $photon_args[ $transform ] = $smaller_width . ',' . $smaller_height;
388 } else {
389 $photon_args[ $transform ] = $image_args['width'] . ',' . $image_args['height'];
390 }
391
392 }
393
394 $photon_args = apply_filters( 'jetpack_photon_image_downsize_string', $photon_args, compact( 'image_args', 'image_url', 'attachment_id', 'size', 'transform' ) );
395
396 // Generate Photon URL
397 $image = array(
398 jetpack_photon_url( $image_url, $photon_args ),
399 false,
400 false
401 );
402 } elseif ( is_array( $size ) ) {
403 // Pull width and height values from the provided array, if possible
404 $width = isset( $size[0] ) ? (int) $size[0] : false;
405 $height = isset( $size[1] ) ? (int) $size[1] : false;
406
407 // Don't bother if necessary parameters aren't passed.
408 if ( ! $width || ! $height )
409 return $image;
410
411 // Expose arguments to a filter before passing to Photon
412 $photon_args = array(
413 'fit' => $width . ',' . $height
414 );
415
416 $photon_args = apply_filters( 'jetpack_photon_image_downsize_array', $photon_args, compact( 'width', 'height', 'image_url', 'attachment_id' ) );
417
418 // Generate Photon URL
419 $image = array(
420 jetpack_photon_url( $image_url, $photon_args ),
421 false,
422 false
423 );
424 }
425 }
426
427 return $image;
428 }
429
430 /**
431 ** GENERAL FUNCTIONS
432 **/
433
434 /**
435 * Ensure image URL is valid for Photon.
436 * 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.
437 *
438 * @param string $url
439 * @uses wp_parse_args
440 * @return bool
441 */
442 protected static function validate_image_url( $url ) {
443 $parsed_url = @parse_url( $url );
444
445 if ( ! $parsed_url )
446 return false;
447
448 // Parse URL and ensure needed keys exist, since the array returned by `parse_url` only includes the URL components it finds.
449 $url_info = wp_parse_args( $parsed_url, array(
450 'scheme' => null,
451 'host' => null,
452 'port' => null,
453 'path' => null
454 ) );
455
456 // Bail if scheme isn't http or port is set that isn't port 80
457 if ( ( 'http' != $url_info['scheme'] || ! in_array( $url_info['port'], array( 80, null ) ) ) && apply_filters( 'jetpack_photon_reject_https', true ) )
458 return false;
459
460 // Bail if no host is found
461 if ( is_null( $url_info['host'] ) )
462 return false;
463
464 // Bail if the image alredy went through Photon
465 if ( preg_match( '#^i[\d]{1}.wp.com$#i', $url_info['host'] ) )
466 return false;
467
468 // Bail if no path is found
469 if ( is_null( $url_info['path'] ) )
470 return false;
471
472 // Ensure image extension is acceptable
473 if ( ! in_array( strtolower( pathinfo( $url_info['path'], PATHINFO_EXTENSION ) ), self::$extensions ) )
474 return false;
475
476 // If we got this far, we should have an acceptable image URL
477 // But let folks filter to decline if they prefer.
478 return apply_filters( 'photon_validate_image_url', true, $url, $parsed_url );
479 }
480
481 /**
482 * Checks if the file exists before it passes the file to photon
483 *
484 * @param string $src The image URL
485 * @return string
486 **/
487 protected static function strip_image_dimensions_maybe( $src ){
488 $stripped_src = $src;
489
490 // Build URL, first removing WP's resized string so we pass the original image to Photon
491 if ( preg_match( '#(-\d+x\d+)\.(' . implode('|', self::$extensions ) . '){1}$#i', $src, $src_parts ) ) {
492 $stripped_src = str_replace( $src_parts[1], '', $src );
493 $upload_dir = wp_upload_dir();
494
495 // Extracts the file path to the image minus the base url
496 $file_path = substr( $stripped_src, strlen ( $upload_dir['baseurl'] ) );
497
498 if( file_exists( $upload_dir["basedir"] . $file_path ) )
499 $src = $stripped_src;
500 }
501
502 return $src;
503 }
504
505 /**
506 * Provide an array of available image sizes and corresponding dimensions.
507 * Similar to get_intermediate_image_sizes() except that it includes image sizes' dimensions, not just their names.
508 *
509 * @global $wp_additional_image_sizes
510 * @uses get_option
511 * @return array
512 */
513 protected static function image_sizes() {
514 if ( null == self::$image_sizes ) {
515 global $_wp_additional_image_sizes;
516
517 // Populate an array matching the data structure of $_wp_additional_image_sizes so we have a consistent structure for image sizes
518 $images = array(
519 'thumb' => array(
520 'width' => intval( get_option( 'thumbnail_size_w' ) ),
521 'height' => intval( get_option( 'thumbnail_size_h' ) ),
522 'crop' => (bool) get_option( 'thumbnail_crop' )
523 ),
524 'medium' => array(
525 'width' => intval( get_option( 'medium_size_w' ) ),
526 'height' => intval( get_option( 'medium_size_h' ) ),
527 'crop' => false
528 ),
529 'large' => array(
530 'width' => intval( get_option( 'large_size_w' ) ),
531 'height' => intval( get_option( 'large_size_h' ) ),
532 'crop' => false
533 ),
534 'full' => array(
535 'width' => null,
536 'height' => null,
537 'crop' => false
538 )
539 );
540
541 // Compatibility mapping as found in wp-includes/media.php
542 $images['thumbnail'] = $images['thumb'];
543
544 // Update class variable, merging in $_wp_additional_image_sizes if any are set
545 if ( is_array( $_wp_additional_image_sizes ) && ! empty( $_wp_additional_image_sizes ) )
546 self::$image_sizes = array_merge( $images, $_wp_additional_image_sizes );
547 else
548 self::$image_sizes = $images;
549 }
550
551 return is_array( self::$image_sizes ) ? self::$image_sizes : array();
552 }
553
554 /**
555 * Pass og:image URLs through Photon
556 *
557 * @param array $tags
558 * @param array $parameters
559 * @uses jetpack_photon_url
560 * @return array
561 */
562 function filter_open_graph_tags( $tags, $parameters ) {
563 if ( empty( $tags['og:image'] ) ) {
564 return $tags;
565 }
566
567 $photon_args = array(
568 'fit' => sprintf( '%d,%d', 2 * $parameters['image_width'], 2 * $parameters['image_height'] ),
569 );
570
571 if ( is_array( $tags['og:image'] ) ) {
572 $images = array();
573 foreach ( $tags['og:image'] as $image ) {
574 $images[] = jetpack_photon_url( $image, $photon_args );
575 }
576 $tags['og:image'] = $images;
577 } else {
578 $tags['og:image'] = jetpack_photon_url( $tags['og:image'], $photon_args );
579 }
580
581 return $tags;
582 }
583
584 /**
585 * Enqueue Photon helper script
586 *
587 * @uses wp_enqueue_script, plugins_url
588 * @action wp_enqueue_script
589 * @return null
590 */
591 public function action_wp_enqueue_scripts() {
592 wp_enqueue_script( 'jetpack-photon', plugins_url( 'modules/photon/photon.js', __FILE__ ), array( 'jquery' ), 20130122, true );
593 }
594 }
595