Completed
Push — add/image-block-detection ( ad6635...94163c )
by Jeremy
12:31 queued 05:41
created

Jetpack_PostImages::get_post_html()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 3
nop 1
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
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
22
		if ( ! $post ) {
23
			return $images;
24
		}
25
26
		if ( ! empty( $post->post_password ) ) {
27
			return $images;
28
		}
29
30
		if ( false === has_shortcode( $post->post_content, 'slideshow' ) ) {
31
			return $images; // no slideshow - bail
32
		}
33
34
		$permalink = get_permalink( $post->ID );
35
36
		// Mechanic: Somebody set us up the bomb
37
		$old_post = $GLOBALS['post'];
38
		$GLOBALS['post'] = $post;
39
		$old_shortcodes = $GLOBALS['shortcode_tags'];
40
		$GLOBALS['shortcode_tags'] = array( 'slideshow' => $old_shortcodes['slideshow'] );
41
42
		// Find all the slideshows
43
		preg_match_all( '/' . get_shortcode_regex() . '/sx', $post->post_content, $slideshow_matches, PREG_SET_ORDER );
44
45
		ob_start(); // The slideshow shortcode handler calls wp_print_scripts and wp_print_styles... not too happy about that
46
47
		foreach ( $slideshow_matches as $slideshow_match ) {
0 ignored issues
show
Bug introduced by
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...
48
			$slideshow = do_shortcode_tag( $slideshow_match );
49
			if ( false === $pos = stripos( $slideshow, 'jetpack-slideshow' ) ) // must be something wrong - or we changed the output format in which case none of the following will work
50
				continue;
51
			$start = strpos( $slideshow, '[', $pos );
52
			$end = strpos( $slideshow, ']', $start );
53
			$post_images = json_decode( wp_specialchars_decode( str_replace( "'", '"', substr( $slideshow, $start, $end - $start + 1 ) ), ENT_QUOTES ) ); // parse via JSON
54
			// If the JSON didn't decode don't try and act on it.
55
			if ( is_array( $post_images ) ) {
56
				foreach ( $post_images as $post_image ) {
57
					if ( !$post_image_id = absint( $post_image->id ) )
58
						continue;
59
60
					$meta = wp_get_attachment_metadata( $post_image_id );
61
62
					// Must be larger than 200x200 (or user-specified)
63
					if ( !isset( $meta['width'] ) || $meta['width'] < $width )
64
						continue;
65
					if ( !isset( $meta['height'] ) || $meta['height'] < $height )
66
						continue;
67
68
					$url = wp_get_attachment_url( $post_image_id );
69
70
					$images[] = array(
71
						'type'       => 'image',
72
						'from'       => 'slideshow',
73
						'src'        => $url,
74
						'src_width'  => $meta['width'],
75
						'src_height' => $meta['height'],
76
						'href'       => $permalink,
77
					);
78
				}
79
			}
80
		}
81
		ob_end_clean();
82
83
		// Operator: Main screen turn on
84
		$GLOBALS['shortcode_tags'] = $old_shortcodes;
85
		$GLOBALS['post'] = $old_post;
86
87
		return $images;
88
	}
89
90
	/**
91
	 * If a gallery is detected, then get all the images from it.
92
	 */
93
	static function from_gallery( $post_id ) {
94
		$images = array();
95
96
		$post = get_post( $post_id );
97
98
		if ( ! $post ) {
99
			return $images;
100
		}
101
102
		if ( ! empty( $post->post_password ) ) {
103
			return $images;
104
		}
105
106
		$permalink = get_permalink( $post->ID );
107
108
		/**
109
		 *  Juggle global post object because the gallery shortcode uses the
110
		 *  global object.
111
		 *
112
		 *  See core ticket:
113
		 *  https://core.trac.wordpress.org/ticket/39304
114
		 */
115
		if ( isset( $GLOBALS['post'] ) ) {
116
			$juggle_post = $GLOBALS['post'];
117
			$GLOBALS['post'] = $post;
118
			$galleries = get_post_galleries( $post->ID, false );
119
			$GLOBALS['post'] = $juggle_post;
120
		} else {
121
			$GLOBALS['post'] = $post;
122
			$galleries = get_post_galleries( $post->ID, false );
123
			unset( $GLOBALS['post'] );
124
		}
125
126
		foreach ( $galleries as $gallery ) {
127
			if ( isset( $gallery['type'] ) && 'slideshow' === $gallery['type'] && ! empty( $gallery['ids'] ) ) {
128
				$image_ids = explode( ',', $gallery['ids'] );
129
				$image_size = isset( $gallery['size'] ) ? $gallery['size'] : 'thumbnail';
130
				foreach ( $image_ids as $image_id ) {
131
					$image = wp_get_attachment_image_src( $image_id, $image_size );
132 View Code Duplication
					if ( ! empty( $image[0] ) ) {
133
						list( $raw_src ) = explode( '?', $image[0] ); // pull off any Query string (?w=250)
134
						$raw_src = wp_specialchars_decode( $raw_src ); // rawify it
135
						$raw_src = esc_url_raw( $raw_src ); // clean it
136
						$images[] = array(
137
							'type'  => 'image',
138
							'from'  => 'gallery',
139
							'src'   => $raw_src,
140
							'href'  => $permalink,
141
						);
142
					}
143
				}
144 View Code Duplication
			} elseif ( ! empty( $gallery['src'] ) ) {
145
				foreach ( $gallery['src'] as $src ) {
146
					list( $raw_src ) = explode( '?', $src ); // pull off any Query string (?w=250)
147
					$raw_src = wp_specialchars_decode( $raw_src ); // rawify it
148
					$raw_src = esc_url_raw( $raw_src ); // clean it
149
					$images[] = array(
150
						'type'  => 'image',
151
						'from'  => 'gallery',
152
						'src'   => $raw_src,
153
						'href'  => $permalink,
154
					);
155
				}
156
			}
157
		}
158
159
		return $images;
160
	}
161
162
	/**
163
	 * Get attachment images for a specified post and return them. Also make sure
164
	 * their dimensions are at or above a required minimum.
165
	 */
166
	static function from_attachment( $post_id, $width = 200, $height = 200 ) {
167
		$images = array();
168
169
		$post = get_post( $post_id );
170
171
		if ( ! empty( $post->post_password ) ) {
172
			return $images;
173
		}
174
175
		$post_images = get_posts( array(
176
			'post_parent' => $post_id,   // Must be children of post
177
			'numberposts' => 5,          // No more than 5
178
			'post_type' => 'attachment', // Must be attachments
179
			'post_mime_type' => 'image', // Must be images
180
			'suppress_filters' => false,
181
		) );
182
183
		if ( ! $post_images ) {
184
			return $images;
185
		}
186
187
		$permalink = get_permalink( $post_id );
188
189
		foreach ( $post_images as $post_image ) {
190
			$images[] = self::get_attachment_data( $post_image->ID, $permalink, $width, $height );
191
		}
192
193
		/*
194
		* We only want to pass back attached images that were actually inserted.
195
		* We can load up all the images found in the HTML source and then
196
		* compare URLs to see if an image is attached AND inserted.
197
		*/
198
		$html_images = self::from_html( $post_id );
199
		$inserted_images = array();
200
201
		foreach( $html_images as $html_image ) {
202
			$src = parse_url( $html_image['src'] );
203
			// strip off any query strings from src
204
			if( ! empty( $src['scheme'] ) && ! empty( $src['host'] ) ) {
205
				$inserted_images[] = $src['scheme'] . '://' . $src['host'] . $src['path'];
206
			} elseif( ! empty( $src['host'] ) ) {
207
				$inserted_images[] = set_url_scheme( 'http://' . $src['host'] . $src['path'] );
208
			} else {
209
				$inserted_images[] = site_url( '/' ) . $src['path'];
210
			}
211
		}
212
		foreach( $images as $i => $image ) {
213
			if ( !in_array( $image['src'], $inserted_images ) )
214
				unset( $images[$i] );
215
		}
216
217
		return $images;
218
	}
219
220
	/**
221
	 * Check if a Featured Image is set for this post, and return it in a similar
222
	 * format to the other images?_from_*() methods.
223
	 * @param  int $post_id The post ID to check
224
	 * @return Array containing details of the Featured Image, or empty array if none.
225
	 */
226
	static function from_thumbnail( $post_id, $width = 200, $height = 200 ) {
227
		$images = array();
228
229
		$post = get_post( $post_id );
230
231
		if ( ! empty( $post->post_password ) ) {
232
			return $images;
233
		}
234
235
		if ( ! function_exists( 'get_post_thumbnail_id' ) ) {
236
			return $images;
237
		}
238
239
		$thumb = get_post_thumbnail_id( $post_id );
240
241
		if ( $thumb ) {
242
			$meta = wp_get_attachment_metadata( $thumb );
243
			// Must be larger than requested minimums
244
			if ( !isset( $meta['width'] ) || $meta['width'] < $width )
245
				return $images;
246
			if ( !isset( $meta['height'] ) || $meta['height'] < $height )
247
				return $images;
248
249
			$too_big = ( ( ! empty( $meta['width'] ) && $meta['width'] > 1200 ) || ( ! empty( $meta['height'] ) && $meta['height'] > 1200 ) );
250
251
			if (
252
				$too_big &&
253
				(
254
					( method_exists( 'Jetpack', 'is_module_active' ) && Jetpack::is_module_active( 'photon' ) ) ||
255
					( defined( 'IS_WPCOM' ) && IS_WPCOM )
256
				)
257
			) {
258
				$img_src = wp_get_attachment_image_src( $thumb, array( 1200, 1200 ) );
259
			} else {
260
				$img_src = wp_get_attachment_image_src( $thumb, 'full' );
261
			}
262
			if ( ! is_array( $img_src ) ) {
263
				// If wp_get_attachment_image_src returns false but we know that there should be an image that could be used.
264
				// we try a bit harder and user the data that we have.
265
				$thumb_post_data = get_post( $thumb );
266
				$img_src = array( $thumb_post_data->guid, $meta['width'], $meta['height'] );
267
			}
268
269
			$url = $img_src[0];
270
			$images = array( array( // Other methods below all return an array of arrays
271
				'type'       => 'image',
272
				'from'       => 'thumbnail',
273
				'src'        => $url,
274
				'src_width'  => $img_src[1],
275
				'src_height' => $img_src[2],
276
				'href'       => get_permalink( $thumb ),
277
			) );
278
279
		}
280
281
		if ( empty( $images ) && ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) {
282
			$meta_thumbnail = get_post_meta( $post_id, '_jetpack_post_thumbnail', true );
283
			if ( ! empty( $meta_thumbnail ) ) {
284
				if ( ! isset( $meta_thumbnail['width'] ) || $meta_thumbnail['width'] < $width ) {
285
					return $images;
286
				}
287
288
				if ( ! isset( $meta_thumbnail['height'] ) || $meta_thumbnail['height'] < $height ) {
289
					return $images;
290
				}
291
292
				$images = array( array( // Other methods below all return an array of arrays
293
					'type'       => 'image',
294
					'from'       => 'thumbnail',
295
					'src'        => $meta_thumbnail['URL'],
296
					'src_width'  => $meta_thumbnail['width'],
297
					'src_height' => $meta_thumbnail['height'],
298
					'href'       => $meta_thumbnail['URL'],
299
				) );
300
			}
301
		}
302
303
		return $images;
304
	}
305
306
	/**
307
	 * Get images from Gutenberg Image blocks.
308
	 *
309
	 * @since 6.9.0
310
	 *
311
	 * @param mixed $html_or_id The HTML string to parse for images, or a post id.
312
	 * @param int   $width      Minimum Image width.
313
	 * @param int   $height     Minimum Image height.
314
	 */
315
	static function from_blocks( $html_or_id, $width = 200, $height = 200 ) {
316
		$images   = array();
317
		$post_url = '';
318
319
		// Bail early if the site does not support the block editor.
320
		if ( ! function_exists( 'parse_blocks' ) ) {
321
			return $images;
322
		}
323
324
		$html = self::get_post_html( $html_or_id );
325
326
		if ( ! $html ) {
327
			return $images;
328
		}
329
330
		// Look for block information in the HTML.
331
		$blocks = parse_blocks( $html );
332
		if ( empty( $blocks ) ) {
333
			return $images;
334
		}
335
336
		foreach ( $blocks as $block ) {
337
			/**
338
			 * Only parse content from Core Image blocks.
339
			 * If it is an image block for an image hosted on our site, it will have an ID.
340
			 * If it does not have an ID, let `from_html` parse that content later,
341
			 * and extract an image if it has size parameters.
342
			 */
343
			if (
344
				'core/image' === $block['blockName']
345
				&& ! empty( $block['attrs']['id'] )
346
			) {
347
				$images[] = self::get_attachment_data( $block['attrs']['id'], $post_url, $width, $height );
348
			}
349
		}
350
351
		return $images;
352
	}
353
354
	/**
355
	 * Very raw -- just parse the HTML and pull out any/all img tags and return their src
356
	 *
357
	 * @param mixed $html_or_id The HTML string to parse for images, or a post id.
358
	 * @param int   $width      Minimum Image width.
359
	 * @param int   $height     Minimum Image height.
360
	 *
361
	 * @uses DOMDocument
362
	 *
363
	 * @return Array containing images
364
	 */
365
	static function from_html( $html_or_id, $width = 200, $height = 200 ) {
366
		$images = array();
367
368
		$html = self::get_post_html( $html_or_id );
369
370
		if ( ! $html ) {
371
			return $images;
372
		}
373
374
		// Do not go any further if DOMDocument is disabled on the server.
375
		if ( ! class_exists( 'DOMDocument' ) ) {
376
			return $images;
377
		}
378
379
		// Let's grab all image tags from the HTML.
380
		$dom_doc = new DOMDocument;
381
382
		// The @ is not enough to suppress errors when dealing with libxml,
383
		// we have to tell it directly how we want to handle errors.
384
		libxml_use_internal_errors( true );
385
		@$dom_doc->loadHTML( $html );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
386
		libxml_use_internal_errors( false );
387
388
		$image_tags = $dom_doc->getElementsByTagName( 'img' );
389
390
		// For each image Tag, make sure it can be added to the $images array, and add it.
391
		foreach ( $image_tags as $image_tag ) {
392
			$img_src = $image_tag->getAttribute( 'src' );
393
394
			if ( empty( $img_src ) ) {
395
				continue;
396
			}
397
398
			// Do not grab smiley images that were automatically created by WP when entering text smilies.
399
			if ( stripos( $img_src, '/smilies/' ) ) {
400
				continue;
401
			}
402
403
			$meta = array(
404
				'width'  => (int) $image_tag->getAttribute( 'width' ),
405
				'height' => (int) $image_tag->getAttribute( 'height' ),
406
			);
407
408
			/**
409
			 * Filters the switch to ignore minimum image size requirements. Can be used
410
			 * to add custom logic to image dimensions, like only enforcing one of the dimensions,
411
			 * or disabling it entirely.
412
			 *
413
			 * @since 6.4.0
414
			 *
415
			 * @param bool $ignore Should the image dimensions be ignored?
416
			 * @param array $meta Array containing image dimensions parsed from the markup.
417
			 */
418
			$ignore_dimensions = apply_filters( 'jetpack_postimages_ignore_minimum_dimensions', false, $meta );
419
420
			// Must be larger than 200x200 (or user-specified).
421
			if (
422
				! $ignore_dimensions
423
				&& (
424
					empty( $meta['width'] )
425
					|| empty( $meta['height'] )
426
					|| $meta['width'] < $width
427
					|| $meta['height'] < $height
428
				)
429
			) {
430
				continue;
431
			}
432
433
			$images[] = array(
434
				'type'  => 'image',
435
				'from'  => 'html',
436
				'src'   => $img_src,
437
				'src_width'  => $meta['width'],
438
				'src_height' => $meta['height'],
439
				'href'  => '', // No link to apply to these. Might potentially parse for that as well, but not for now.
440
			);
441
		}
442
		return $images;
443
	}
444
445
	/**
446
	 * @param    int $post_id The post ID to check
447
	 * @param    int $size
448
	 * @return Array containing details of the image, or empty array if none.
449
	 */
450
	static function from_blavatar( $post_id, $size = 96 ) {
451
452
		$permalink = get_permalink( $post_id );
453
454
		if ( function_exists( 'blavatar_domain' ) && function_exists( 'blavatar_exists' ) && function_exists( 'blavatar_url' ) ) {
455
			$domain = blavatar_domain( $permalink );
456
457
			if ( ! blavatar_exists( $domain ) ) {
458
				return array();
459
			}
460
461
			$url = blavatar_url( $domain, 'img', $size );
462
		} elseif ( function_exists( 'has_site_icon' ) && has_site_icon() ) {
463
			$url = get_site_icon_url( $size );
464
		} else {
465
			return array();
466
		}
467
468
		return array( array(
469
			'type'       => 'image',
470
			'from'       => 'blavatar',
471
			'src'        => $url,
472
			'src_width'  => $size,
473
			'src_height' => $size,
474
			'href'       => $permalink,
475
		) );
476
	}
477
478
	/**
479
	 * Gets a post image from the author avatar.
480
	 *
481
	 * @param int    $post_id The post ID to check.
482
	 * @param int    $size The size of the avatar to get.
483
	 * @param string $default The default image to use.
0 ignored issues
show
Documentation introduced by
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...
484
	 * @return Array containing details of the image, or empty array if none.
485
	 */
486
	static function from_gravatar( $post_id, $size = 96, $default = false ) {
487
		$post = get_post( $post_id );
488
		$permalink = get_permalink( $post_id );
489
490
		if ( function_exists( 'wpcom_get_avatar_url' ) ) {
491
			$url = wpcom_get_avatar_url( $post->post_author, $size, $default, true );
492
			if ( $url && is_array( $url ) ) {
493
				$url = $url[0];
494
			}
495
		} else {
496
			$url = get_avatar_url( $post->post_author, array(
497
				'size' => $size,
498
				'default' => $default,
499
			) );
500
		}
501
502
		return array(
503
			array(
504
				'type'       => 'image',
505
				'from'       => 'gravatar',
506
				'src'        => $url,
507
				'src_width'  => $size,
508
				'src_height' => $size,
509
				'href'       => $permalink,
510
			),
511
		);
512
	}
513
514
	/**
515
	 * Run through the different methods that we have available to try to find a single good
516
	 * display image for this post.
517
	 * @param  int $post_id
518
	 * @param array $args Other arguments (currently width and height required for images where possible to determine)
519
	 * @return Array containing details of the best image to be used
520
	 */
521
	static function get_image( $post_id, $args = array() ) {
522
		$image = '';
523
524
		/**
525
		 * Fires before we find a single good image for a specific post.
526
		 *
527
		 * @since 2.2.0
528
		 *
529
		 * @param int $post_id Post ID.
530
		 */
531
		do_action( 'jetpack_postimages_pre_get_image', $post_id );
532
		$media = self::get_images( $post_id, $args );
533
534
535
		if ( is_array( $media ) ) {
536
			foreach ( $media as $item ) {
537
				if ( 'image' == $item['type'] ) {
538
					$image = $item;
539
					break;
540
				}
541
			}
542
		}
543
544
		/**
545
		 * Fires after we find a single good image for a specific post.
546
		 *
547
		 * @since 2.2.0
548
		 *
549
		 * @param int $post_id Post ID.
550
		 */
551
		do_action( 'jetpack_postimages_post_get_image', $post_id );
552
553
		return $image;
554
	}
555
556
	/**
557
	 * Get an array containing a collection of possible images for this post, stopping once we hit a method
558
	 * that returns something useful.
559
	 * @param  int $post_id
560
	 * @param  array  $args Optional args, see defaults list for details
561
	 * @return Array containing images that would be good for representing this post
562
	 */
563
	static function get_images( $post_id, $args = array() ) {
564
		// Figure out which image to attach to this post.
565
		$media = false;
566
567
		/**
568
		 * Filters the array of images that would be good for a specific post.
569
		 * This filter is applied before options ($args) filter the original array.
570
		 *
571
		 * @since 2.0.0
572
		 *
573
		 * @param array $media Array of images that would be good for a specific post.
574
		 * @param int $post_id Post ID.
575
		 * @param array $args Array of options to get images.
576
		 */
577
		$media = apply_filters( 'jetpack_images_pre_get_images', $media, $post_id, $args );
578
		if ( $media )
579
			return $media;
580
581
		$defaults = array(
582
			'width'               => 200, // Required minimum width (if possible to determine)
583
			'height'              => 200, // Required minimum height (if possible to determine)
584
585
			'fallback_to_avatars' => false, // Optionally include Blavatar and Gravatar (in that order) in the image stack
586
			'avatar_size'         => 96, // Used for both Grav and Blav
587
			'gravatar_default'    => false, // Default image to use if we end up with no Gravatar
588
589
			'from_thumbnail'      => true, // Use these flags to specify which methods to use to find an image
590
			'from_slideshow'      => true,
591
			'from_gallery'        => true,
592
			'from_attachment'     => true,
593
			'from_blocks'         => true,
594
			'from_html'           => true,
595
596
			'html_content'        => '' // HTML string to pass to from_html()
597
		);
598
		$args = wp_parse_args( $args, $defaults );
599
600
		$media = false;
601
		if ( $args['from_thumbnail'] )
602
			$media = self::from_thumbnail( $post_id, $args['width'], $args['height'] );
603 View Code Duplication
		if ( !$media && $args['from_slideshow'] )
604
			$media = self::from_slideshow( $post_id, $args['width'], $args['height'] );
605
		if ( !$media && $args['from_gallery'] )
606
			$media = self::from_gallery( $post_id );
607 View Code Duplication
		if ( !$media && $args['from_attachment'] )
608
			$media = self::from_attachment( $post_id, $args['width'], $args['height'] );
609 View Code Duplication
		if ( ! $media && $args['from_blocks'] ) {
610
			if ( empty( $args['html_content'] ) )
611
				$media = self::from_blocks( $post_id, $args['width'], $args['height'] ); // Use the post_id, which will load the content
612
			else
613
				$media = self::from_blocks( $args['html_content'], $args['width'], $args['height'] ); // If html_content is provided, use that
614
		}
615 View Code Duplication
		if ( !$media && $args['from_html'] ) {
616
			if ( empty( $args['html_content'] ) )
617
				$media = self::from_html( $post_id, $args['width'], $args['height'] ); // Use the post_id, which will load the content
618
			else
619
				$media = self::from_html( $args['html_content'], $args['width'], $args['height'] ); // If html_content is provided, use that
620
		}
621
622
		if ( !$media && $args['fallback_to_avatars'] ) {
623
			$media = self::from_blavatar( $post_id, $args['avatar_size'] );
624
			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...
625
				$media = self::from_gravatar( $post_id, $args['avatar_size'], $args['gravatar_default'] );
626
		}
627
628
		/**
629
		 * Filters the array of images that would be good for a specific post.
630
		 * This filter is applied after options ($args) filter the original array.
631
		 *
632
		 * @since 2.0.0
633
		 *
634
		 * @param array $media Array of images that would be good for a specific post.
635
		 * @param int $post_id Post ID.
636
		 * @param array $args Array of options to get images.
637
		 */
638
		return apply_filters( 'jetpack_images_get_images', $media, $post_id, $args );
639
	}
640
641
	/**
642
	 * Takes an image URL and pixel dimensions then returns a URL for the
643
	 * resized and cropped image.
644
	 *
645
	 * @param  string $src
646
	 * @param  int    $dimension
0 ignored issues
show
Bug introduced by
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...
647
	 * @return string            Transformed image URL
648
	 */
649
	static function fit_image_url( $src, $width, $height ) {
650
		$width = (int) $width;
651
		$height = (int) $height;
652
653
		if ( $width < 1 || $height < 1 ) {
654
			return $src;
655
		}
656
657
		// See if we should bypass WordPress.com SaaS resizing
658
		if ( has_filter( 'jetpack_images_fit_image_url_override' ) ) {
659
			/**
660
			 * Filters the image URL used after dimensions are set by Photon.
661
			 *
662
			 * @since 3.3.0
663
			 *
664
			 * @param string $src Image URL.
665
			 * @param int $width Image width.
666
			 * @param int $width Image height.
667
			 */
668
			return apply_filters( 'jetpack_images_fit_image_url_override', $src, $width, $height );
669
		}
670
671
		// If WPCOM hosted image use native transformations
672
		$img_host = parse_url( $src, PHP_URL_HOST );
673
		if ( '.files.wordpress.com' == substr( $img_host, -20 ) ) {
674
			return add_query_arg( array( 'w' => $width, 'h' => $height, 'crop' => 1 ), set_url_scheme( $src ) );
675
		}
676
677
		// Use Photon magic
678
		if( function_exists( 'jetpack_photon_url' ) ) {
679
			return jetpack_photon_url( $src, array( 'resize' => "$width,$height" ) );
680
		}
681
682
		// Arg... no way to resize image using WordPress.com infrastructure!
683
		return $src;
684
	}
685
686
	/**
687
	 * Get HTML from given post content.
688
	 *
689
	 * @since 6.9.0
690
	 *
691
	 * @param mixed $html_or_id The HTML string to parse for images, or a post id.
692
	 *
693
	 * @return string $html Post content.
694
	 */
695
	static function get_post_html( $html_or_id ) {
696
		if ( is_numeric( $html_or_id ) ) {
697
			$post = get_post( $html_or_id );
698
699
			if ( empty( $post ) || ! empty( $post->post_password ) ) {
700
				return $images;
0 ignored issues
show
Bug introduced by
The variable $images does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
701
			}
702
703
			$html     = $post->post_content; // DO NOT apply the_content filters here, it will cause loops.
704
			$post_url = $post->post_title;
0 ignored issues
show
Unused Code introduced by
$post_url 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...
705
		} else {
706
			$html = $html_or_id;
707
		}
708
709
		return $html;
710
	}
711
712
	/**
713
	 * Get info about a WordPress attachment.
714
	 *
715
	 * @since 6.9.0
716
	 *
717
	 * @param int    $attachment_id Attachment ID.
718
	 * @param string $post_url      URL of the post, if we have one.
719
	 * @param int    $width         Minimum Image width.
720
	 * @param int    $height        Minimum Image height.
721
	 */
722
	static function get_attachment_data( $attachment_id, $post_url = '', $width, $height ) {
723
		if ( empty( $attachment_id ) ) {
724
			return array();
725
		}
726
727
		$meta = wp_get_attachment_metadata( $attachment_id );
728
729
		// The image must be larger than 200x200
730
		if ( ! isset( $meta['width'] ) || $meta['width'] < $width ) {
731
			return array();
732
		}
733
		if ( ! isset( $meta['height'] ) || $meta['height'] < $height ) {
734
			return array();
735
		}
736
737
		$url = wp_get_attachment_url( $attachment_id );
738
739
		return array(
740
			'type'       => 'image',
741
			'from'       => 'attachment',
742
			'src'        => $url,
743
			'src_width'  => $meta['width'],
744
			'src_height' => $meta['height'],
745
			'href'       => $post_url,
746
		);
747
	}
748
}
749