Completed
Push — master ( a9f7c3...bf825c )
by Marin
06:41
created

class.jetpack-post-images.php (5 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/**
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
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
			}
52
			$start       = strpos( $slideshow, '[', $pos );
53
			$end         = strpos( $slideshow, ']', $start );
54
			$post_images = json_decode( wp_specialchars_decode( str_replace( "'", '"', substr( $slideshow, $start, $end - $start + 1 ) ), ENT_QUOTES ) ); // parse via JSON
55
			// If the JSON didn't decode don't try and act on it.
56
			if ( is_array( $post_images ) ) {
57
				foreach ( $post_images as $post_image ) {
58
					if ( ! $post_image_id = absint( $post_image->id ) ) {
59
						continue;
60
					}
61
62
					$meta = wp_get_attachment_metadata( $post_image_id );
63
64
					// Must be larger than 200x200 (or user-specified)
65
					if ( ! isset( $meta['width'] ) || $meta['width'] < $width ) {
66
						continue;
67
					}
68
					if ( ! isset( $meta['height'] ) || $meta['height'] < $height ) {
69
						continue;
70
					}
71
72
					$url = wp_get_attachment_url( $post_image_id );
73
74
					$images[] = array(
75
						'type'       => 'image',
76
						'from'       => 'slideshow',
77
						'src'        => $url,
78
						'src_width'  => $meta['width'],
79
						'src_height' => $meta['height'],
80
						'href'       => $permalink,
81
					);
82
				}
83
			}
84
		}
85
		ob_end_clean();
86
87
		// Operator: Main screen turn on
88
		$GLOBALS['shortcode_tags'] = $old_shortcodes;
89
		$GLOBALS['post']           = $old_post;
90
91
		return $images;
92
	}
93
94
	/**
95
	 * If a gallery is detected, then get all the images from it.
96
	 */
97
	static function from_gallery( $post_id ) {
98
		$images = array();
99
100
		$post = get_post( $post_id );
101
102
		if ( ! $post ) {
103
			return $images;
104
		}
105
106
		if ( ! empty( $post->post_password ) ) {
107
			return $images;
108
		}
109
110
		$permalink = get_permalink( $post->ID );
111
112
		/**
113
		 *  Juggle global post object because the gallery shortcode uses the
114
		 *  global object.
115
		 *
116
		 *  See core ticket:
117
		 *  https://core.trac.wordpress.org/ticket/39304
118
		 */
119
		if ( isset( $GLOBALS['post'] ) ) {
120
			$juggle_post     = $GLOBALS['post'];
121
			$GLOBALS['post'] = $post;
122
			$galleries       = get_post_galleries( $post->ID, false );
123
			$GLOBALS['post'] = $juggle_post;
124
		} else {
125
			$GLOBALS['post'] = $post;
126
			$galleries       = get_post_galleries( $post->ID, false );
127
			unset( $GLOBALS['post'] );
128
		}
129
130
		foreach ( $galleries as $gallery ) {
131
			if ( isset( $gallery['type'] ) && 'slideshow' === $gallery['type'] && ! empty( $gallery['ids'] ) ) {
132
				$image_ids  = explode( ',', $gallery['ids'] );
133
				$image_size = isset( $gallery['size'] ) ? $gallery['size'] : 'thumbnail';
134
				foreach ( $image_ids as $image_id ) {
135
					$image = wp_get_attachment_image_src( $image_id, $image_size );
136 View Code Duplication
					if ( ! empty( $image[0] ) ) {
137
						list( $raw_src ) = explode( '?', $image[0] ); // pull off any Query string (?w=250)
138
						$raw_src         = wp_specialchars_decode( $raw_src ); // rawify it
139
						$raw_src         = esc_url_raw( $raw_src ); // clean it
140
						$images[]        = array(
141
							'type' => 'image',
142
							'from' => 'gallery',
143
							'src'  => $raw_src,
144
							'href' => $permalink,
145
						);
146
					}
147
				}
148 View Code Duplication
			} elseif ( ! empty( $gallery['src'] ) ) {
149
				foreach ( $gallery['src'] as $src ) {
150
					list( $raw_src ) = explode( '?', $src ); // pull off any Query string (?w=250)
151
					$raw_src         = wp_specialchars_decode( $raw_src ); // rawify it
152
					$raw_src         = esc_url_raw( $raw_src ); // clean it
153
					$images[]        = array(
154
						'type' => 'image',
155
						'from' => 'gallery',
156
						'src'  => $raw_src,
157
						'href' => $permalink,
158
					);
159
				}
160
			}
161
		}
162
163
		return $images;
164
	}
165
166
	/**
167
	 * Get attachment images for a specified post and return them. Also make sure
168
	 * their dimensions are at or above a required minimum.
169
	 */
170
	static function from_attachment( $post_id, $width = 200, $height = 200 ) {
171
		$images = array();
172
173
		$post = get_post( $post_id );
174
175
		if ( ! empty( $post->post_password ) ) {
176
			return $images;
177
		}
178
179
		$post_images = get_posts(
180
			array(
181
				'post_parent'      => $post_id,   // Must be children of post
182
				'numberposts'      => 5,          // No more than 5
183
				'post_type'        => 'attachment', // Must be attachments
184
				'post_mime_type'   => 'image', // Must be images
185
				'suppress_filters' => false,
186
			)
187
		);
188
189
		if ( ! $post_images ) {
190
			return $images;
191
		}
192
193
		$permalink = get_permalink( $post_id );
194
195
		foreach ( $post_images as $post_image ) {
196
			$current_image = self::get_attachment_data( $post_image->ID, $permalink, $width, $height );
197
			if ( false !== $current_image ) {
198
				$images[] = $current_image;
199
			}
200
		}
201
202
		/*
203
		* We only want to pass back attached images that were actually inserted.
204
		* We can load up all the images found in the HTML source and then
205
		* compare URLs to see if an image is attached AND inserted.
206
		*/
207
		$html_images     = self::from_html( $post_id );
208
		$inserted_images = array();
209
210
		foreach ( $html_images as $html_image ) {
211
			$src = parse_url( $html_image['src'] );
212
			// strip off any query strings from src
213
			if ( ! empty( $src['scheme'] ) && ! empty( $src['host'] ) ) {
214
				$inserted_images[] = $src['scheme'] . '://' . $src['host'] . $src['path'];
215
			} elseif ( ! empty( $src['host'] ) ) {
216
				$inserted_images[] = set_url_scheme( 'http://' . $src['host'] . $src['path'] );
217
			} else {
218
				$inserted_images[] = site_url( '/' ) . $src['path'];
219
			}
220
		}
221
		foreach ( $images as $i => $image ) {
222
			if ( ! in_array( $image['src'], $inserted_images ) ) {
223
				unset( $images[ $i ] );
224
			}
225
		}
226
227
		return $images;
228
	}
229
230
	/**
231
	 * Check if a Featured Image is set for this post, and return it in a similar
232
	 * format to the other images?_from_*() methods.
233
	 *
234
	 * @param  int $post_id The post ID to check
235
	 * @return Array containing details of the Featured Image, or empty array if none.
236
	 */
237
	static function from_thumbnail( $post_id, $width = 200, $height = 200 ) {
238
		$images = array();
239
240
		$post = get_post( $post_id );
241
242
		if ( ! empty( $post->post_password ) ) {
243
			return $images;
244
		}
245
246
		if ( 'attachment' === get_post_type( $post ) && wp_attachment_is_image( $post ) ) {
247
			$thumb = $post_id;
248
		} else {
249
			$thumb = get_post_thumbnail_id( $post );
250
		}
251
252
		if ( $thumb ) {
253
			$meta = wp_get_attachment_metadata( $thumb );
254
			// Must be larger than requested minimums
255
			if ( ! isset( $meta['width'] ) || $meta['width'] < $width ) {
256
				return $images;
257
			}
258
			if ( ! isset( $meta['height'] ) || $meta['height'] < $height ) {
259
				return $images;
260
			}
261
262
			$too_big = ( ( ! empty( $meta['width'] ) && $meta['width'] > 1200 ) || ( ! empty( $meta['height'] ) && $meta['height'] > 1200 ) );
263
264
			if (
265
				$too_big &&
266
				(
267
					( method_exists( 'Jetpack', 'is_module_active' ) && Jetpack::is_module_active( 'photon' ) ) ||
268
					( defined( 'IS_WPCOM' ) && IS_WPCOM )
269
				)
270
			) {
271
				$img_src = wp_get_attachment_image_src( $thumb, array( 1200, 1200 ) );
272
			} else {
273
				$img_src = wp_get_attachment_image_src( $thumb, 'full' );
274
			}
275
			if ( ! is_array( $img_src ) ) {
276
				// If wp_get_attachment_image_src returns false but we know that there should be an image that could be used.
277
				// we try a bit harder and user the data that we have.
278
				$thumb_post_data = get_post( $thumb );
279
				$img_src         = array( $thumb_post_data->guid, $meta['width'], $meta['height'] );
280
			}
281
282
			$url    = $img_src[0];
283
			$images = array(
284
				array( // Other methods below all return an array of arrays
285
					'type'       => 'image',
286
					'from'       => 'thumbnail',
287
					'src'        => $url,
288
					'src_width'  => $img_src[1],
289
					'src_height' => $img_src[2],
290
					'href'       => get_permalink( $thumb ),
291
					'alt_text'   => self::get_alt_text( $thumb ),
292
				),
293
			);
294
295
		}
296
297
		if ( empty( $images ) && ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) {
298
			$meta_thumbnail = get_post_meta( $post_id, '_jetpack_post_thumbnail', true );
299
			if ( ! empty( $meta_thumbnail ) ) {
300
				if ( ! isset( $meta_thumbnail['width'] ) || $meta_thumbnail['width'] < $width ) {
301
					return $images;
302
				}
303
304
				if ( ! isset( $meta_thumbnail['height'] ) || $meta_thumbnail['height'] < $height ) {
305
					return $images;
306
				}
307
308
				$images = array(
309
					array( // Other methods below all return an array of arrays
310
						'type'       => 'image',
311
						'from'       => 'thumbnail',
312
						'src'        => $meta_thumbnail['URL'],
313
						'src_width'  => $meta_thumbnail['width'],
314
						'src_height' => $meta_thumbnail['height'],
315
						'href'       => $meta_thumbnail['URL'],
316
						'alt_text'   => self::get_alt_text( $thumb ),
317
					),
318
				);
319
			}
320
		}
321
322
		return $images;
323
	}
324
325
	/**
326
	 * Get images from Gutenberg Image blocks.
327
	 *
328
	 * @since 6.9.0
329
	 *
330
	 * @param mixed $html_or_id The HTML string to parse for images, or a post id.
331
	 * @param int   $width      Minimum Image width.
332
	 * @param int   $height     Minimum Image height.
333
	 */
334
	public static function from_blocks( $html_or_id, $width = 200, $height = 200 ) {
335
		$images = array();
336
337
		$html_info = self::get_post_html( $html_or_id );
338
339
		if ( empty( $html_info['html'] ) ) {
340
			return $images;
341
		}
342
343
		// Look for block information in the HTML.
344
		$blocks = parse_blocks( $html_info['html'] );
345
		if ( empty( $blocks ) ) {
346
			return $images;
347
		}
348
349
		foreach ( $blocks as $block ) {
350
			/**
351
			 * Parse content from Core Image blocks.
352
			 * If it is an image block for an image hosted on our site, it will have an ID.
353
			 * If it does not have an ID, let `from_html` parse that content later,
354
			 * and extract an image if it has size parameters.
355
			 */
356
			if (
357
				'core/image' === $block['blockName']
358
				&& ! empty( $block['attrs']['id'] )
359
			) {
360
				$images[] = self::get_attachment_data( $block['attrs']['id'], $html_info['post_url'], $width, $height );
361
			}
362
363
			/**
364
			 * Parse content from Core Gallery blocks as well from Jetpack's Tiled Gallery and Slideshow blocks.
365
			 * Gallery blocks include the ID of each one of the images in the gallery.
366
			 */
367
			if ( in_array( $block['blockName'], array( 'core/gallery', 'jetpack/tiled-gallery', 'jetpack/slideshow' ) )
368
				&& ! empty( $block['attrs']['ids'] )
369
			) {
370
				foreach ( $block['attrs']['ids'] as $img_id ) {
371
					$images[] = self::get_attachment_data( $img_id, $html_info['post_url'], $width, $height );
372
				}
373
			}
374
		}
375
376
		/**
377
		 * Returning a filtered array because get_attachment_data returns false
378
		 * for unsuccessful attempts.
379
		 */
380
		return array_filter( $images );
381
	}
382
383
	/**
384
	 * Very raw -- just parse the HTML and pull out any/all img tags and return their src
385
	 *
386
	 * @param mixed $html_or_id The HTML string to parse for images, or a post id.
387
	 * @param int   $width      Minimum Image width.
388
	 * @param int   $height     Minimum Image height.
389
	 *
390
	 * @uses DOMDocument
391
	 *
392
	 * @return Array containing images
393
	 */
394
	static function from_html( $html_or_id, $width = 200, $height = 200 ) {
395
		$images = array();
396
397
		$html_info = self::get_post_html( $html_or_id );
398
399
		if ( empty( $html_info['html'] ) ) {
400
			return $images;
401
		}
402
403
		// Do not go any further if DOMDocument is disabled on the server.
404
		if ( ! class_exists( 'DOMDocument' ) ) {
405
			return $images;
406
		}
407
408
		// Let's grab all image tags from the HTML.
409
		$dom_doc = new DOMDocument();
410
411
		// The @ is not enough to suppress errors when dealing with libxml,
412
		// we have to tell it directly how we want to handle errors.
413
		libxml_use_internal_errors( true );
414
		@$dom_doc->loadHTML( $html_info['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...
415
		libxml_use_internal_errors( false );
416
417
		$image_tags = $dom_doc->getElementsByTagName( 'img' );
418
419
		// For each image Tag, make sure it can be added to the $images array, and add it.
420
		foreach ( $image_tags as $image_tag ) {
421
			$img_src = $image_tag->getAttribute( 'src' );
422
423
			if ( empty( $img_src ) ) {
424
				continue;
425
			}
426
427
			// Do not grab smiley images that were automatically created by WP when entering text smilies.
428
			if ( stripos( $img_src, '/smilies/' ) ) {
429
				continue;
430
			}
431
432
			$meta = array(
433
				'width'    => (int) $image_tag->getAttribute( 'width' ),
434
				'height'   => (int) $image_tag->getAttribute( 'height' ),
435
				'alt_text' => $image_tag->getAttribute( 'alt' ),
436
			);
437
438
			/**
439
			 * Filters the switch to ignore minimum image size requirements. Can be used
440
			 * to add custom logic to image dimensions, like only enforcing one of the dimensions,
441
			 * or disabling it entirely.
442
			 *
443
			 * @since 6.4.0
444
			 *
445
			 * @param bool $ignore Should the image dimensions be ignored?
446
			 * @param array $meta Array containing image dimensions parsed from the markup.
447
			 */
448
			$ignore_dimensions = apply_filters( 'jetpack_postimages_ignore_minimum_dimensions', false, $meta );
449
450
			// Must be larger than 200x200 (or user-specified).
451
			if (
452
				! $ignore_dimensions
453
				&& (
454
					empty( $meta['width'] )
455
					|| empty( $meta['height'] )
456
					|| $meta['width'] < $width
457
					|| $meta['height'] < $height
458
				)
459
			) {
460
				continue;
461
			}
462
463
			$images[] = array(
464
				'type'       => 'image',
465
				'from'       => 'html',
466
				'src'        => $img_src,
467
				'src_width'  => $meta['width'],
468
				'src_height' => $meta['height'],
469
				'href'       => $html_info['post_url'],
470
				'alt_text'   => $meta['alt_text'],
471
			);
472
		}
473
		return $images;
474
	}
475
476
	/**
477
	 * @param    int $post_id The post ID to check
478
	 * @param    int $size
479
	 * @return Array containing details of the image, or empty array if none.
480
	 */
481
	static function from_blavatar( $post_id, $size = 96 ) {
482
483
		$permalink = get_permalink( $post_id );
484
485
		if ( function_exists( 'blavatar_domain' ) && function_exists( 'blavatar_exists' ) && function_exists( 'blavatar_url' ) ) {
486
			$domain = blavatar_domain( $permalink );
487
488
			if ( ! blavatar_exists( $domain ) ) {
489
				return array();
490
			}
491
492
			$url = blavatar_url( $domain, 'img', $size );
493
		} else {
494
			$url = get_site_icon_url( $size );
495
			if ( ! $url ) {
496
				return array();
497
			}
498
		}
499
500
		return array(
501
			array(
502
				'type'       => 'image',
503
				'from'       => 'blavatar',
504
				'src'        => $url,
505
				'src_width'  => $size,
506
				'src_height' => $size,
507
				'href'       => $permalink,
508
				'alt_text'   => '',
509
			),
510
		);
511
	}
512
513
	/**
514
	 * Gets a post image from the author avatar.
515
	 *
516
	 * @param int    $post_id The post ID to check.
517
	 * @param int    $size The size of the avatar to get.
518
	 * @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...
519
	 * @return Array containing details of the image, or empty array if none.
520
	 */
521
	static function from_gravatar( $post_id, $size = 96, $default = false ) {
522
		$post      = get_post( $post_id );
523
		$permalink = get_permalink( $post_id );
524
525
		if ( function_exists( 'wpcom_get_avatar_url' ) ) {
526
			$url = wpcom_get_avatar_url( $post->post_author, $size, $default, true );
527
			if ( $url && is_array( $url ) ) {
528
				$url = $url[0];
529
			}
530
		} else {
531
			$url = get_avatar_url(
532
				$post->post_author,
533
				array(
534
					'size'    => $size,
535
					'default' => $default,
536
				)
537
			);
538
		}
539
540
		return array(
541
			array(
542
				'type'       => 'image',
543
				'from'       => 'gravatar',
544
				'src'        => $url,
545
				'src_width'  => $size,
546
				'src_height' => $size,
547
				'href'       => $permalink,
548
				'alt_text'   => '',
549
			),
550
		);
551
	}
552
553
	/**
554
	 * Run through the different methods that we have available to try to find a single good
555
	 * display image for this post.
556
	 *
557
	 * @param  int   $post_id
558
	 * @param array $args Other arguments (currently width and height required for images where possible to determine)
559
	 * @return Array containing details of the best image to be used
560
	 */
561
	static function get_image( $post_id, $args = array() ) {
562
		$image = '';
563
564
		/**
565
		 * Fires before we find a single good image for a specific post.
566
		 *
567
		 * @since 2.2.0
568
		 *
569
		 * @param int $post_id Post ID.
570
		 */
571
		do_action( 'jetpack_postimages_pre_get_image', $post_id );
572
		$media = self::get_images( $post_id, $args );
573
574
		if ( is_array( $media ) ) {
575
			foreach ( $media as $item ) {
576
				if ( 'image' == $item['type'] ) {
577
					$image = $item;
578
					break;
579
				}
580
			}
581
		}
582
583
		/**
584
		 * Fires after we find a single good image for a specific post.
585
		 *
586
		 * @since 2.2.0
587
		 *
588
		 * @param int $post_id Post ID.
589
		 */
590
		do_action( 'jetpack_postimages_post_get_image', $post_id );
591
592
		return $image;
593
	}
594
595
	/**
596
	 * Get an array containing a collection of possible images for this post, stopping once we hit a method
597
	 * that returns something useful.
598
	 *
599
	 * @param  int   $post_id
600
	 * @param  array $args Optional args, see defaults list for details
601
	 * @return Array containing images that would be good for representing this post
602
	 */
603
	static function get_images( $post_id, $args = array() ) {
604
		// Figure out which image to attach to this post.
605
		$media = false;
606
607
		/**
608
		 * Filters the array of images that would be good for a specific post.
609
		 * This filter is applied before options ($args) filter the original array.
610
		 *
611
		 * @since 2.0.0
612
		 *
613
		 * @param array $media Array of images that would be good for a specific post.
614
		 * @param int $post_id Post ID.
615
		 * @param array $args Array of options to get images.
616
		 */
617
		$media = apply_filters( 'jetpack_images_pre_get_images', $media, $post_id, $args );
618
		if ( $media ) {
619
			return $media;
620
		}
621
622
		$defaults = array(
623
			'width'               => 200, // Required minimum width (if possible to determine)
624
			'height'              => 200, // Required minimum height (if possible to determine)
625
626
			'fallback_to_avatars' => false, // Optionally include Blavatar and Gravatar (in that order) in the image stack
627
			'avatar_size'         => 96, // Used for both Grav and Blav
628
			'gravatar_default'    => false, // Default image to use if we end up with no Gravatar
629
630
			'from_thumbnail'      => true, // Use these flags to specify which methods to use to find an image
631
			'from_slideshow'      => true,
632
			'from_gallery'        => true,
633
			'from_attachment'     => true,
634
			'from_blocks'         => true,
635
			'from_html'           => true,
636
637
			'html_content'        => '', // HTML string to pass to from_html()
638
		);
639
		$args     = wp_parse_args( $args, $defaults );
640
641
		$media = false;
642
		if ( $args['from_thumbnail'] ) {
643
			$media = self::from_thumbnail( $post_id, $args['width'], $args['height'] );
644
		}
645 View Code Duplication
		if ( ! $media && $args['from_slideshow'] ) {
646
			$media = self::from_slideshow( $post_id, $args['width'], $args['height'] );
647
		}
648
		if ( ! $media && $args['from_gallery'] ) {
649
			$media = self::from_gallery( $post_id );
650
		}
651 View Code Duplication
		if ( ! $media && $args['from_attachment'] ) {
652
			$media = self::from_attachment( $post_id, $args['width'], $args['height'] );
653
		}
654 View Code Duplication
		if ( ! $media && $args['from_blocks'] ) {
655
			if ( empty( $args['html_content'] ) ) {
656
				$media = self::from_blocks( $post_id, $args['width'], $args['height'] ); // Use the post_id, which will load the content
657
			} else {
658
				$media = self::from_blocks( $args['html_content'], $args['width'], $args['height'] ); // If html_content is provided, use that
659
			}
660
		}
661 View Code Duplication
		if ( ! $media && $args['from_html'] ) {
662
			if ( empty( $args['html_content'] ) ) {
663
				$media = self::from_html( $post_id, $args['width'], $args['height'] ); // Use the post_id, which will load the content
664
			} else {
665
				$media = self::from_html( $args['html_content'], $args['width'], $args['height'] ); // If html_content is provided, use that
666
			}
667
		}
668
669
		if ( ! $media && $args['fallback_to_avatars'] ) {
670
			$media = self::from_blavatar( $post_id, $args['avatar_size'] );
671
			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...
672
				$media = self::from_gravatar( $post_id, $args['avatar_size'], $args['gravatar_default'] );
673
			}
674
		}
675
676
		/**
677
		 * Filters the array of images that would be good for a specific post.
678
		 * This filter is applied after options ($args) filter the original array.
679
		 *
680
		 * @since 2.0.0
681
		 *
682
		 * @param array $media Array of images that would be good for a specific post.
683
		 * @param int $post_id Post ID.
684
		 * @param array $args Array of options to get images.
685
		 */
686
		return apply_filters( 'jetpack_images_get_images', $media, $post_id, $args );
687
	}
688
689
	/**
690
	 * Takes an image URL and pixel dimensions then returns a URL for the
691
	 * resized and cropped image.
692
	 *
693
	 * @param  string $src
694
	 * @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...
695
	 * @return string            Transformed image URL
696
	 */
697
	static function fit_image_url( $src, $width, $height ) {
698
		$width  = (int) $width;
699
		$height = (int) $height;
700
701
		if ( $width < 1 || $height < 1 ) {
702
			return $src;
703
		}
704
705
		// See if we should bypass WordPress.com SaaS resizing
706
		if ( has_filter( 'jetpack_images_fit_image_url_override' ) ) {
707
			/**
708
			 * Filters the image URL used after dimensions are set by Photon.
709
			 *
710
			 * @since 3.3.0
711
			 *
712
			 * @param string $src Image URL.
713
			 * @param int $width Image width.
714
			 * @param int $width Image height.
715
			 */
716
			return apply_filters( 'jetpack_images_fit_image_url_override', $src, $width, $height );
717
		}
718
719
		// If WPCOM hosted image use native transformations
720
		$img_host = parse_url( $src, PHP_URL_HOST );
721
		if ( '.files.wordpress.com' == substr( $img_host, -20 ) ) {
722
			return add_query_arg(
723
				array(
724
					'w'    => $width,
725
					'h'    => $height,
726
					'crop' => 1,
727
				),
728
				set_url_scheme( $src )
729
			);
730
		}
731
732
		// Use Photon magic
733
		if ( function_exists( 'jetpack_photon_url' ) ) {
734
			return jetpack_photon_url( $src, array( 'resize' => "$width,$height" ) );
735
		}
736
737
		// Arg... no way to resize image using WordPress.com infrastructure!
738
		return $src;
739
	}
740
741
	/**
742
	 * Get HTML from given post content.
743
	 *
744
	 * @since 6.9.0
745
	 *
746
	 * @param mixed $html_or_id The HTML string to parse for images, or a post id.
747
	 *
748
	 * @return array $html_info {
749
	 * @type string $html     Post content.
750
	 * @type string $post_url Post URL.
751
	 * }
752
	 */
753
	static function get_post_html( $html_or_id ) {
754
		if ( is_numeric( $html_or_id ) ) {
755
			$post = get_post( $html_or_id );
756
757
			if ( empty( $post ) || ! empty( $post->post_password ) ) {
758
				return '';
759
			}
760
761
			$html_info = array(
762
				'html'     => $post->post_content, // DO NOT apply the_content filters here, it will cause loops.
763
				'post_url' => get_permalink( $post->ID ),
764
			);
765
		} else {
766
			$html_info = array(
767
				'html'     => $html_or_id,
768
				'post_url' => '',
769
			);
770
		}
771
		return $html_info;
772
	}
773
774
	/**
775
	 * Get info about a WordPress attachment.
776
	 *
777
	 * @since 6.9.0
778
	 *
779
	 * @param int    $attachment_id Attachment ID.
780
	 * @param string $post_url      URL of the post, if we have one.
781
	 * @param int    $width         Minimum Image width.
782
	 * @param int    $height        Minimum Image height.
783
	 * @return array|bool           Image data or false if unavailable.
784
	 */
785
	public static function get_attachment_data( $attachment_id, $post_url = '', $width, $height ) {
786
		if ( empty( $attachment_id ) ) {
787
			return false;
788
		}
789
790
		$meta = wp_get_attachment_metadata( $attachment_id );
791
792
		// The image must be larger than 200x200.
793
		if ( ! isset( $meta['width'] ) || $meta['width'] < $width ) {
794
			return false;
795
		}
796
		if ( ! isset( $meta['height'] ) || $meta['height'] < $height ) {
797
			return false;
798
		}
799
800
		$url = wp_get_attachment_url( $attachment_id );
801
802
		return array(
803
			'type'       => 'image',
804
			'from'       => 'attachment',
805
			'src'        => $url,
806
			'src_width'  => $meta['width'],
807
			'src_height' => $meta['height'],
808
			'href'       => $post_url,
809
			'alt_text'   => self::get_alt_text( $attachment_id ),
810
		);
811
	}
812
813
	/**
814
	 * Get the alt text for an image or other media from the Media Library.
815
	 *
816
	 * @since 7.1
817
	 *
818
	 * @param int $attachment_id The Post ID of the media.
819
	 * @return string The alt text value or an emptry string.
820
	 */
821
	public static function get_alt_text( $attachment_id ) {
822
		return get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
823
	}
824
}
825