Completed
Push — fix/og-image-width-height-big-... ( f9e4ad )
by Jeremy
17:02
created

class.jetpack-post-images.php (4 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
/**
4
 * Useful for finding an image to display alongside/in representation of a specific post.
5
 *
6
 * Includes a few different methods, all of which return a similar-format array containing
7
 * details of any images found. Everything can (should) be called statically, it's just a
8
 * function-bucket. You can also call Jetpack_PostImages::get_image() to cycle through all of the methods until
9
 * one of them finds something useful.
10
 *
11
 * This file is included verbatim in Jetpack
12
 */
13
class Jetpack_PostImages {
14
	/**
15
	 * If a slideshow is embedded within a post, then parse out the images involved and return them
16
	 */
17
	static function from_slideshow( $post_id, $width = 200, $height = 200 ) {
18
		$images = array();
19
20
		$post = get_post( $post_id );
21
		if ( !empty( $post->post_password ) )
22
			return $images;
23
24
		if ( false === has_shortcode( $post->post_content, 'slideshow' ) ) {
25
			return false; // no slideshow - bail
26
		}
27
28
		$permalink = get_permalink( $post->ID );
29
30
		// Mechanic: Somebody set us up the bomb
31
		$old_post = $GLOBALS['post'];
32
		$GLOBALS['post'] = $post;
33
		$old_shortcodes = $GLOBALS['shortcode_tags'];
34
		$GLOBALS['shortcode_tags'] = array( 'slideshow' => $old_shortcodes['slideshow'] );
35
36
		// Find all the slideshows
37
		preg_match_all( '/' . get_shortcode_regex() . '/sx', $post->post_content, $slideshow_matches, PREG_SET_ORDER );
38
39
		ob_start(); // The slideshow shortcode handler calls wp_print_scripts and wp_print_styles... not too happy about that
40
41
		foreach ( $slideshow_matches as $slideshow_match ) {
0 ignored issues
show
The expression $slideshow_matches of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
42
			$slideshow = do_shortcode_tag( $slideshow_match );
43
			if ( false === $pos = stripos( $slideshow, 'slideShow.images' ) ) // must be something wrong - or we changed the output format in which case none of the following will work
44
				continue;
45
			$start = strpos( $slideshow, '[', $pos );
46
			$end = strpos( $slideshow, ']', $start );
47
			$post_images = json_decode( str_replace( "'", '"', substr( $slideshow, $start, $end - $start + 1 ) ) ); // parse via JSON
48
			foreach ( $post_images as $post_image ) {
49
				if ( !$post_image_id = absint( $post_image->id ) )
50
					continue;
51
52
				$meta = wp_get_attachment_metadata( $post_image_id );
53
54
				// Must be larger than 200x200 (or user-specified)
55
				if ( !isset( $meta['width'] ) || $meta['width'] < $width )
56
					continue;
57
				if ( !isset( $meta['height'] ) || $meta['height'] < $height )
58
					continue;
59
60
				$url = wp_get_attachment_url( $post_image_id );
61
62
				$images[] = array(
63
					'type'       => 'image',
64
					'from'       => 'slideshow',
65
					'src'        => $url,
66
					'src_width'  => $meta['width'],
67
					'src_height' => $meta['height'],
68
					'href'       => $permalink,
69
				);
70
			}
71
		}
72
		ob_end_clean();
73
74
		// Operator: Main screen turn on
75
		$GLOBALS['shortcode_tags'] = $old_shortcodes;
76
		$GLOBALS['post'] = $old_post;
77
78
		return $images;
79
	}
80
81
	/**
82
	 * If a gallery is detected, then get all the images from it.
83
	 */
84
	static function from_gallery( $post_id ) {
85
		$images = array();
86
87
		$post = get_post( $post_id );
88
		if ( ! empty( $post->post_password ) ) {
89
			return $images;
90
		}
91
92
		$permalink = get_permalink( $post->ID );
93
94
		$gallery_images = get_post_galleries_images( $post->ID, false );
95
96
		foreach ( $gallery_images as $galleries ) {
97
			foreach ( $galleries as $src ) {
98
				list( $raw_src ) = explode( '?', $src ); // pull off any Query string (?w=250)
99
				$raw_src = wp_specialchars_decode( $raw_src ); // rawify it
100
				$raw_src = esc_url_raw( $raw_src ); // clean it
101
				$images[] = array(
102
					'type'  => 'image',
103
					'from'  => 'gallery',
104
					'src'   => $raw_src,
105
					'href'  => $permalink,
106
				);
107
			}
108
		}
109
110
		return $images;
111
	}
112
113
	/**
114
	 * Get attachment images for a specified post and return them. Also make sure
115
	 * their dimensions are at or above a required minimum.
116
	 */
117
	static function from_attachment( $post_id, $width = 200, $height = 200 ) {
118
		$images = array();
119
120
		$post = get_post( $post_id );
121
		if ( !empty( $post->post_password ) )
122
			return $images;
123
124
		$post_images = get_posts( array(
125
			'post_parent' => $post_id,   // Must be children of post
126
			'numberposts' => 5,          // No more than 5
127
			'post_type' => 'attachment', // Must be attachments
128
			'post_mime_type' => 'image', // Must be images
129
		) );
130
131
		if ( !$post_images )
132
			return false;
133
134
		$permalink = get_permalink( $post_id );
135
136
		foreach ( $post_images as $post_image ) {
137
			$meta = wp_get_attachment_metadata( $post_image->ID );
138
			// Must be larger than 200x200
139
			if ( !isset( $meta['width'] ) || $meta['width'] < $width )
140
				continue;
141
			if ( !isset( $meta['height'] ) || $meta['height'] < $height )
142
				continue;
143
144
			$url = wp_get_attachment_url( $post_image->ID );
145
146
			$images[] = array(
147
				'type'       => 'image',
148
				'from'       => 'attachment',
149
				'src'        => $url,
150
				'src_width'  => $meta['width'],
151
				'src_height' => $meta['height'],
152
				'href'       => $permalink,
153
			);
154
		}
155
156
		/*
157
		* We only want to pass back attached images that were actually inserted.
158
		* We can load up all the images found in the HTML source and then
159
		* compare URLs to see if an image is attached AND inserted.
160
		*/
161
		$html_images = self::from_html( $post_id );
162
		$inserted_images = array();
163
164
		foreach( $html_images as $html_image ) {
165
			$src = parse_url( $html_image['src'] );
166
			// strip off any query strings from src
167
			if( ! empty( $src['scheme'] ) && ! empty( $src['host'] ) ) {
168
				$inserted_images[] = $src['scheme'] . '://' . $src['host'] . $src['path'];
169
			} elseif( ! empty( $src['host'] ) ) {
170
				$inserted_images[] = set_url_scheme( 'http://' . $src['host'] . $src['path'] );
171
			} else {
172
				$inserted_images[] = site_url( '/' ) . $src['path'];
173
			}
174
		}
175
		foreach( $images as $i => $image ) {
176
			if ( !in_array( $image['src'], $inserted_images ) )
177
				unset( $images[$i] );
178
		}
179
180
		return $images;
181
	}
182
183
	/**
184
	 * Check if a Featured Image is set for this post, and return it in a similar
185
	 * format to the other images?_from_*() methods.
186
	 * @param  int $post_id The post ID to check
187
	 * @return Array containing details of the Featured Image, or empty array if none.
188
	 */
189
	static function from_thumbnail( $post_id, $width = 200, $height = 200 ) {
190
		$images = array();
191
192
		$post = get_post( $post_id );
193
		if ( !empty( $post->post_password ) )
194
			return $images;
195
196
		if ( !function_exists( 'get_post_thumbnail_id' ) )
197
			return $images;
198
199
		$thumb = get_post_thumbnail_id( $post_id );
200
201
		if ( $thumb ) {
202
			$meta = wp_get_attachment_metadata( $thumb );
203
204
			// Must be larger than requested minimums
205
			if ( !isset( $meta['width'] ) || $meta['width'] < $width )
206
				return $images;
207
			if ( !isset( $meta['height'] ) || $meta['height'] < $height )
208
				return $images;
209
210
			$too_big = ( ( ! empty( $meta['width'] ) && $meta['width'] > 1200 ) || ( ! empty( $meta['height'] ) && $meta['height'] > 1200 ) );
211
212
			if (
213
				$too_big &&
214
				( Jetpack::is_module_active( 'photon' ) || ( defined( 'WPCOM' ) && IS_WPCOM ) )
215
			) {
216
				$img_src = wp_get_attachment_image_src( $thumb, array( 1200, 1200 ) );
217
			} else {
218
				$img_src = wp_get_attachment_image_src( $thumb, 'full' );
219
			}
220
221
			$url = $img_src[0];
222
223
			$images = array( array( // Other methods below all return an array of arrays
224
				'type'       => 'image',
225
				'from'       => 'thumbnail',
226
				'src'        => $url,
227
				'src_width'  => $img_src[1],
228
				'src_height' => $img_src[2],
229
				'href'       => get_permalink( $thumb ),
230
			) );
231
		}
232
		return $images;
233
	}
234
235
	/**
236
	 * Very raw -- just parse the HTML and pull out any/all img tags and return their src
237
	 * @param  mixed $html_or_id The HTML string to parse for images, or a post id
238
	 * @return Array containing images
239
	 */
240
	static function from_html( $html_or_id ) {
241
		$images = array();
242
243
		if ( is_numeric( $html_or_id ) ) {
244
			$post = get_post( $html_or_id );
245
			if ( empty( $post ) || !empty( $post->post_password ) )
246
				return $images;
247
248
			$html = $post->post_content; // DO NOT apply the_content filters here, it will cause loops
249
		} else {
250
			$html = $html_or_id;
251
		}
252
253
		if ( !$html )
254
			return $images;
255
256
		preg_match_all( '!<img.*src=[\'"]([^"]+)[\'"].*/?>!iUs', $html, $matches );
257
		if ( !empty( $matches[1] ) ) {
258
			foreach ( $matches[1] as $match ) {
259
				if ( stristr( $match, '/smilies/' ) )
260
					continue;
261
262
				$images[] = array(
263
					'type'  => 'image',
264
					'from'  => 'html',
265
					'src'   => html_entity_decode( $match ),
266
					'href'  => '', // No link to apply to these. Might potentially parse for that as well, but not for now
267
				);
268
			}
269
		}
270
271
		return $images;
272
	}
273
274
	/**
275
	 * @param    int $post_id The post ID to check
276
	 * @param    int $size
277
	 * @return Array containing details of the image, or empty array if none.
278
	 */
279
	static function from_blavatar( $post_id, $size = 96 ) {
280
281
		$permalink = get_permalink( $post_id );
282
283
		if ( function_exists( 'blavatar_domain' ) && function_exists( 'blavatar_exists' ) && function_exists( 'blavatar_url' ) ) {
284
			$domain = blavatar_domain( $permalink );
285
286
			if ( ! blavatar_exists( $domain ) ) {
287
				return array();
288
			}
289
290
			$url = blavatar_url( $domain, 'img', $size );
291
		} elseif ( function_exists( 'jetpack_has_site_icon' ) && jetpack_has_site_icon() ) {
292
			$url = jetpack_site_icon_url( null, $size, $default = false );
293
		} else {
294
			return array();
295
		}
296
297
		return array( array(
298
			'type'       => 'image',
299
			'from'       => 'blavatar',
300
			'src'        => $url,
301
			'src_width'  => $size,
302
			'src_height' => $size,
303
			'href'       => $permalink,
304
		) );
305
	}
306
307
	/**
308
	 * @param    int $post_id The post ID to check
309
	 * @param    int $size
310
	 * @param string $default The default image to use.
0 ignored issues
show
Should the type for parameter $default not be false|string?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
311
	 * @return Array containing details of the image, or empty array if none.
312
	 */
313
	static function from_gravatar( $post_id, $size = 96, $default = false ) {
314
		$post = get_post( $post_id );
315
		$permalink = get_permalink( $post_id );
316
317
		if ( function_exists( 'wpcom_get_avatar_url' ) ) {
318
			$url = wpcom_get_avatar_url( $post->post_author, $size, $default, true );
319
			if ( $url && is_array( $url ) ) {
320
				$url = $url[0];
321
			}
322
		} else {
323
			$has_filter = has_filter( 'pre_option_show_avatars', '__return_true' );
324
			if ( !$has_filter ) {
325
				add_filter( 'pre_option_show_avatars', '__return_true' );
326
			}
327
			$avatar = get_avatar( $post->post_author, $size, $default );
328
			if ( !$has_filter ) {
329
				remove_filter( 'pre_option_show_avatars', '__return_true' );
330
			}
331
332
			if ( !$avatar ) {
333
				return array();
334
			}
335
336
			if ( !preg_match( '/src=["\']([^"\']+)["\']/', $avatar, $matches ) ) {
337
				return array();
338
			}
339
340
			$url = wp_specialchars_decode( $matches[1], ENT_QUOTES );
341
		}
342
343
		return array( array(
344
			'type'       => 'image',
345
			'from'       => 'gravatar',
346
			'src'        => $url,
347
			'src_width'  => $size,
348
			'src_height' => $size,
349
			'href'       => $permalink,
350
		) );
351
	}
352
353
	/**
354
	 * Run through the different methods that we have available to try to find a single good
355
	 * display image for this post.
356
	 * @param  int $post_id
357
	 * @param array $args Other arguments (currently width and height required for images where possible to determine)
358
	 * @return Array containing details of the best image to be used
359
	 */
360
	static function get_image( $post_id, $args = array() ) {
361
		$image = '';
362
363
		/**
364
		 * Fires before we find a single good image for a specific post.
365
		 *
366
		 * @since 2.2.0
367
		 *
368
		 * @param int $post_id Post ID.
369
		 */
370
		do_action( 'jetpack_postimages_pre_get_image', $post_id );
371
		$media = self::get_images( $post_id, $args );
372
373
374
		if ( is_array( $media ) ) {
375
			foreach ( $media as $item ) {
376
				if ( 'image' == $item['type'] ) {
377
					$image = $item;
378
					break;
379
				}
380
			}
381
		}
382
383
		/**
384
		 * Fires after we find a single good image for a specific post.
385
		 *
386
		 * @since 2.2.0
387
		 *
388
		 * @param int $post_id Post ID.
389
		 */
390
		do_action( 'jetpack_postimages_post_get_image', $post_id );
391
392
		return $image;
393
	}
394
395
	/**
396
	 * Get an array containing a collection of possible images for this post, stopping once we hit a method
397
	 * that returns something useful.
398
	 * @param  int $post_id
399
	 * @param  array  $args Optional args, see defaults list for details
400
	 * @return Array containing images that would be good for representing this post
401
	 */
402
	static function get_images( $post_id, $args = array() ) {
403
		// Figure out which image to attach to this post.
404
		$media = false;
405
406
		/**
407
		 * Filters the array of images that would be good for a specific post.
408
		 * This filter is applied before options ($args) filter the original array.
409
		 *
410
		 * @since 2.0.0
411
		 *
412
		 * @param array $media Array of images that would be good for a specific post.
413
		 * @param int $post_id Post ID.
414
		 * @param array $args Array of options to get images.
415
		 */
416
		$media = apply_filters( 'jetpack_images_pre_get_images', $media, $post_id, $args );
417
		if ( $media )
418
			return $media;
419
420
		$defaults = array(
421
			'width'               => 200, // Required minimum width (if possible to determine)
422
			'height'              => 200, // Required minimum height (if possible to determine)
423
424
			'fallback_to_avatars' => false, // Optionally include Blavatar and Gravatar (in that order) in the image stack
425
			'avatar_size'         => 96, // Used for both Grav and Blav
426
			'gravatar_default'    => false, // Default image to use if we end up with no Gravatar
427
428
			'from_thumbnail'      => true, // Use these flags to specify which methods to use to find an image
429
			'from_slideshow'      => true,
430
			'from_gallery'        => true,
431
			'from_attachment'     => true,
432
			'from_html'           => true,
433
434
			'html_content'        => '' // HTML string to pass to from_html()
435
		);
436
		$args = wp_parse_args( $args, $defaults );
437
438
		$media = false;
439
		if ( $args['from_thumbnail'] )
440
			$media = self::from_thumbnail( $post_id, $args['width'], $args['height'] );
441 View Code Duplication
		if ( !$media && $args['from_slideshow'] )
442
			$media = self::from_slideshow( $post_id, $args['width'], $args['height'] );
443
		if ( !$media && $args['from_gallery'] )
444
			$media = self::from_gallery( $post_id );
445 View Code Duplication
		if ( !$media && $args['from_attachment'] )
446
			$media = self::from_attachment( $post_id, $args['width'], $args['height'] );
447
		if ( !$media && $args['from_html'] ) {
448
			if ( empty( $args['html_content'] ) )
449
				$media = self::from_html( $post_id ); // Use the post_id, which will load the content
450
			else
451
				$media = self::from_html( $args['html_content'] ); // If html_content is provided, use that
452
		}
453
454
		if ( !$media && $args['fallback_to_avatars'] ) {
455
			$media = self::from_blavatar( $post_id, $args['avatar_size'] );
456
			if ( !$media )
0 ignored issues
show
Bug Best Practice introduced by
The expression $media of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
457
				$media = self::from_gravatar( $post_id, $args['avatar_size'], $args['gravatar_default'] );
458
		}
459
460
		/**
461
		 * Filters the array of images that would be good for a specific post.
462
		 * This filter is applied after options ($args) filter the original array.
463
		 *
464
		 * @since 2.0.0
465
		 *
466
		 * @param array $media Array of images that would be good for a specific post.
467
		 * @param int $post_id Post ID.
468
		 * @param array $args Array of options to get images.
469
		 */
470
		return apply_filters( 'jetpack_images_get_images', $media, $post_id, $args );
471
	}
472
473
	/**
474
	 * Takes an image URL and pixel dimensions then returns a URL for the
475
	 * resized and croped image.
476
	 *
477
	 * @param  string $src
478
	 * @param  int    $dimension
0 ignored issues
show
There is no parameter named $dimension. 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...
479
	 * @return string            Transformed image URL
480
	 */
481
	static function fit_image_url( $src, $width, $height ) {
482
		$width = (int) $width;
483
		$height = (int) $height;
484
485
		// Umm...
486
		if ( $width < 1 || $height < 1 ) {
487
			return $src;
488
		}
489
490
		// See if we should bypass WordPress.com SaaS resizing
491
		if ( has_filter( 'jetpack_images_fit_image_url_override' ) ) {
492
			/**
493
			 * Filters the image URL used after dimensions are set by Photon.
494
			 *
495
			 * @since 3.3.0
496
			 *
497
			 * @param string $src Image URL.
498
			 * @param int $width Image width.
499
			 * @param int $width Image height.
500
			 */
501
			return apply_filters( 'jetpack_images_fit_image_url_override', $src, $width, $height );
502
		}
503
504
		// If WPCOM hosted image use native transformations
505
		$img_host = parse_url( $src, PHP_URL_HOST );
506
		if ( '.files.wordpress.com' == substr( $img_host, -20 ) ) {
507
			return add_query_arg( array( 'w' => $width, 'h' => $height, 'crop' => 1 ), $src );
508
		}
509
510
		// Use Photon magic
511
		if( function_exists( 'jetpack_photon_url' ) ) {
512
			return jetpack_photon_url( $src, array( 'resize' => "$width,$height" ) );
513
		}
514
515
		// Arg... no way to resize image using WordPress.com infrastructure!
516
		return $src;
517
	}
518
}
519