Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
45.34% covered (danger)
45.34%
253 / 558
15.79% covered (danger)
15.79%
3 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
Images
45.34% covered (danger)
45.34%
253 / 558
15.79% covered (danger)
15.79%
3 / 19
7763.73
0.00% covered (danger)
0.00%
0 / 1
 from_slideshow
0.00% covered (danger)
0.00%
0 / 46
0.00% covered (danger)
0.00%
0 / 1
182
 filter_gallery_urls
73.33% covered (warning)
73.33%
11 / 15
0.00% covered (danger)
0.00%
0 / 1
7.93
 from_gallery
65.57% covered (warning)
65.57%
40 / 61
0.00% covered (danger)
0.00%
0 / 1
31.22
 from_attachment
0.00% covered (danger)
0.00%
0 / 39
0.00% covered (danger)
0.00%
0 / 1
240
 from_thumbnail
0.00% covered (danger)
0.00%
0 / 65
0.00% covered (danger)
0.00%
0 / 1
992
 from_blocks
92.86% covered (success)
92.86%
26 / 28
0.00% covered (danger)
0.00%
0 / 1
7.02
 get_images_from_block_attributes
94.44% covered (success)
94.44%
34 / 36
0.00% covered (danger)
0.00%
0 / 1
23.09
 from_html
87.88% covered (warning)
87.88%
58 / 66
0.00% covered (danger)
0.00%
0 / 1
25.03
 from_blavatar
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
42
 from_gravatar
88.46% covered (warning)
88.46%
23 / 26
0.00% covered (danger)
0.00%
0 / 1
5.04
 get_image
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
42
 get_images
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
342
 generate_cropped_srcset
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
90
 fit_image_url
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
72
 get_post_html
92.31% covered (success)
92.31%
12 / 13
0.00% covered (danger)
0.00%
0 / 1
4.01
 get_attachment_data
90.62% covered (success)
90.62%
29 / 32
0.00% covered (danger)
0.00%
0 / 1
12.12
 get_alt_text
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 determine_thumbnail_size_for_photon
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
7
 get_max_thumbnail_dimension
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Useful for finding an image to display alongside/in representation of a specific post.
4 *
5 * @package automattic/jetpack-post-media
6 */
7
8namespace Automattic\Jetpack\Post_Media;
9
10use Automattic\Block_Scanner;
11use Automattic\Jetpack\Image_CDN\Image_CDN_Core;
12
13/**
14 * Useful for finding an image to display alongside/in representation of a specific post.
15 *
16 * Includes a few different methods, all of which return a similar-format array containing
17 * details of any images found. Everything can (should) be called statically, it's just a
18 * function-bucket. You can also call Images::get_image() to cycle through all of the methods until
19 * one of them finds something useful.
20 */
21class Images {
22    /**
23     * If a slideshow is embedded within a post, then parse out the images involved and return them
24     *
25     * @param int $post_id Post ID.
26     * @param int $width Image width.
27     * @param int $height Image height.
28     * @return array Images.
29     */
30    public static function from_slideshow( $post_id, $width = 200, $height = 200 ) {
31        $images = array();
32
33        $post = get_post( $post_id );
34        if ( ! $post instanceof \WP_Post ) {
35            return $images;
36        }
37
38        if ( ! empty( $post->post_password ) ) {
39            return $images;
40        }
41
42        if ( false === has_shortcode( $post->post_content, 'slideshow' ) ) {
43            return $images; // no slideshow - bail.
44        }
45
46        $permalink = get_permalink( $post->ID );
47
48        // Mechanic: Somebody set us up the bomb.
49        $old_post                  = $GLOBALS['post'] ?? null;
50        $GLOBALS['post']           = $post; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
51        $old_shortcodes            = $GLOBALS['shortcode_tags'];
52        $GLOBALS['shortcode_tags'] = array( 'slideshow' => $old_shortcodes['slideshow'] ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
53
54        // Find all the slideshows.
55        preg_match_all( '/' . get_shortcode_regex() . '/sx', $post->post_content, $slideshow_matches, PREG_SET_ORDER );
56
57        ob_start(); // The slideshow shortcode handler calls wp_print_scripts and wp_print_styles... not too happy about that.
58
59        foreach ( $slideshow_matches as $slideshow_match ) {
60            $slideshow = do_shortcode_tag( $slideshow_match );
61            $pos       = stripos( $slideshow, 'jetpack-slideshow' );
62            if ( false === $pos ) { // must be something wrong - or we changed the output format in which case none of the following will work.
63                continue;
64            }
65            $start       = strpos( $slideshow, '[', $pos );
66            $end         = strpos( $slideshow, ']', $start );
67            $post_images = json_decode( wp_specialchars_decode( str_replace( "'", '"', substr( $slideshow, $start, $end - $start + 1 ) ), ENT_QUOTES ) ); // parse via JSON
68            // If the JSON didn't decode don't try and act on it.
69            if ( is_array( $post_images ) ) {
70                foreach ( $post_images as $post_image ) {
71                    $post_image_id = absint( $post_image->id );
72                    if ( ! $post_image_id ) {
73                        continue;
74                    }
75
76                    $meta = wp_get_attachment_metadata( $post_image_id );
77
78                    // Must be larger than 200x200 (or user-specified).
79                    if ( ! isset( $meta['width'] ) || $meta['width'] < $width ) {
80                        continue;
81                    }
82                    if ( ! isset( $meta['height'] ) || $meta['height'] < $height ) {
83                        continue;
84                    }
85
86                    $url = wp_get_attachment_url( $post_image_id );
87
88                    $images[] = array(
89                        'type'       => 'image',
90                        'from'       => 'slideshow',
91                        'src'        => $url,
92                        'src_width'  => $meta['width'],
93                        'src_height' => $meta['height'],
94                        'href'       => $permalink,
95                    );
96                }
97            }
98        }
99        ob_end_clean();
100
101        // Operator: Main screen turn on.
102        $GLOBALS['shortcode_tags'] = $old_shortcodes; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
103        $GLOBALS['post']           = $old_post; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
104
105        return $images;
106    }
107
108    /**
109     * Filtering out images with broken URL from galleries.
110     *
111     * @param array $galleries Galleries.
112     * @return array $filtered_galleries
113     */
114    public static function filter_gallery_urls( $galleries ) {
115        $filtered_galleries = array();
116        foreach ( $galleries as $this_gallery ) {
117            if ( ! isset( $this_gallery['src'] ) ) {
118                continue;
119            }
120            $ids = isset( $this_gallery['ids'] ) ? explode( ',', $this_gallery['ids'] ) : array();
121            // Make sure 'src' array isn't associative and has no holes.
122            $this_gallery['src'] = array_values( $this_gallery['src'] );
123            foreach ( $this_gallery['src'] as $idx => $src_url ) {
124                if ( filter_var( $src_url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED ) === false ) {
125                    unset( $this_gallery['src'][ $idx ] );
126                    unset( $ids[ $idx ] );
127                }
128            }
129            if ( isset( $this_gallery['ids'] ) ) {
130                $this_gallery['ids'] = implode( ',', $ids );
131            }
132            // Remove any holes we introduced.
133            $this_gallery['src']  = array_values( $this_gallery['src'] );
134            $filtered_galleries[] = $this_gallery;
135        }
136
137        return $filtered_galleries;
138    }
139
140    /**
141     * If a gallery is detected, then get all the images from it.
142     *
143     * @param int $post_id Post ID.
144     * @param int $width Minimum image width to consider.
145     * @param int $height Minimum image height to consider.
146     * @return array Images.
147     */
148    public static function from_gallery( $post_id, $width = 200, $height = 200 ) {
149        $images = array();
150
151        $post = get_post( $post_id );
152        if ( ! $post instanceof \WP_Post ) {
153            return $images;
154        }
155
156        if ( ! empty( $post->post_password ) ) {
157            return $images;
158        }
159        add_filter( 'get_post_galleries', array( __CLASS__, 'filter_gallery_urls' ), 999999 );
160
161        $permalink = get_permalink( $post->ID );
162
163        /**
164         *  Juggle global post object because the gallery shortcode uses the
165         *  global object.
166         *
167         *  See core ticket:
168         *  https://core.trac.wordpress.org/ticket/39304
169         */
170        // phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
171        if ( isset( $GLOBALS['post'] ) ) {
172            $juggle_post     = $GLOBALS['post'];
173            $GLOBALS['post'] = $post;
174            $galleries       = get_post_galleries( $post->ID, false );
175            $GLOBALS['post'] = $juggle_post;
176        } else {
177            $GLOBALS['post'] = $post;
178            $galleries       = get_post_galleries( $post->ID, false );
179            unset( $GLOBALS['post'] );
180        }
181        // phpcs:enable WordPress.WP.GlobalVariablesOverride.Prohibited
182
183        // WooCommerce stores product gallery image IDs in the `_product_image_gallery`
184        // postmeta rather than in post_content, so get_post_galleries() does not see them.
185        // Append them as a synthetic gallery in the same `ids` shape the loop below expects.
186        if ( 'product' === $post->post_type ) {
187            $wc_gallery_ids = get_post_meta( $post->ID, '_product_image_gallery', true );
188            if ( ! empty( $wc_gallery_ids ) ) {
189                $galleries[] = array(
190                    'ids'  => $wc_gallery_ids,
191                    'size' => 'full',
192                );
193            }
194        }
195
196        foreach ( $galleries as $gallery ) {
197            if ( ! empty( $gallery['ids'] ) ) {
198                $image_ids  = explode( ',', $gallery['ids'] );
199                $image_size = $gallery['size'] ?? 'thumbnail';
200                foreach ( $image_ids as $image_id ) {
201                    $image_id = (int) $image_id;
202                    $image    = wp_get_attachment_image_src( $image_id, $image_size );
203                    $meta     = wp_get_attachment_metadata( $image_id );
204
205                    if ( isset( $gallery['type'] ) && 'slideshow' === $gallery['type'] ) {
206                        // Must be larger than 200x200 (or user-specified).
207                        if ( ! isset( $meta['width'] ) || $meta['width'] < $width ) {
208                            continue;
209                        }
210                        if ( ! isset( $meta['height'] ) || $meta['height'] < $height ) {
211                            continue;
212                        }
213                    }
214
215                    if ( ! empty( $image[0] ) ) {
216                        list( $raw_src ) = explode( '?', $image[0] ); // pull off any Query string (?w=250).
217                        $raw_src         = wp_specialchars_decode( $raw_src ); // rawify it.
218                        $raw_src         = esc_url_raw( $raw_src ); // clean it.
219                        $images[]        = array(
220                            'type'       => 'image',
221                            'from'       => 'gallery',
222                            'src'        => $raw_src,
223                            'src_width'  => $meta['width'] ?? 0,
224                            'src_height' => $meta['height'] ?? 0,
225                            'href'       => $permalink,
226                            'alt_text'   => self::get_alt_text( $image_id ),
227                        );
228                    }
229                }
230            } elseif ( ! empty( $gallery['src'] ) ) {
231                foreach ( $gallery['src'] as $src ) {
232                    list( $raw_src ) = explode( '?', $src ); // pull off any Query string (?w=250).
233                    $raw_src         = wp_specialchars_decode( $raw_src ); // rawify it.
234                    $raw_src         = esc_url_raw( $raw_src ); // clean it.
235                    $images[]        = array(
236                        'type' => 'image',
237                        'from' => 'gallery',
238                        'src'  => $raw_src,
239                        'href' => $permalink,
240                    );
241                }
242            }
243        }
244
245        return $images;
246    }
247
248    /**
249     * Get attachment images for a specified post and return them. Also make sure
250     * their dimensions are at or above a required minimum.
251     *
252     * @param  int $post_id The post ID to check.
253     * @param  int $width Image width.
254     * @param  int $height Image height.
255     * @return array Containing details of the image, or empty array if none.
256     */
257    public static function from_attachment( $post_id, $width = 200, $height = 200 ) {
258        $images = array();
259
260        $post = get_post( $post_id );
261        if ( ! $post instanceof \WP_Post ) {
262            return $images;
263        }
264
265        if ( ! empty( $post->post_password ) ) {
266            return $images;
267        }
268
269        $post_images = get_posts(
270            array(
271                'post_parent'      => $post_id,   // Must be children of post.
272                'numberposts'      => 5,          // No more than 5.
273                'post_type'        => 'attachment', // Must be attachments.
274                'post_mime_type'   => 'image', // Must be images.
275                'suppress_filters' => false,
276            )
277        );
278
279        if ( ! $post_images ) {
280            return $images;
281        }
282
283        $permalink = get_permalink( $post_id );
284
285        foreach ( $post_images as $post_image ) {
286            if ( ! $post_image instanceof \WP_Post ) {
287                continue;
288            }
289            $current_image = self::get_attachment_data( $post_image->ID, $permalink, $width, $height );
290            if ( false !== $current_image ) {
291                $images[] = $current_image;
292            }
293        }
294
295        /*
296        * We only want to pass back attached images that were actually inserted.
297        * We can load up all the images found in the HTML source and then
298        * compare URLs to see if an image is attached AND inserted.
299        */
300        $html_images     = self::from_html( $post_id );
301        $inserted_images = array();
302
303        foreach ( $html_images as $html_image ) {
304            $src = wp_parse_url( $html_image['src'] );
305            if ( ! $src || empty( $src['path'] ) ) {
306                continue;
307            }
308
309            // strip off any query strings from src.
310            if ( ! empty( $src['scheme'] ) && ! empty( $src['host'] ) ) {
311                $inserted_images[] = $src['scheme'] . '://' . $src['host'] . $src['path'];
312            } elseif ( ! empty( $src['host'] ) ) {
313                $inserted_images[] = set_url_scheme( 'http://' . $src['host'] . $src['path'] );
314            } else {
315                $inserted_images[] = site_url( '/' ) . $src['path'];
316            }
317        }
318        foreach ( $images as $i => $image ) {
319            if ( ! in_array( $image['src'], $inserted_images, true ) ) {
320                unset( $images[ $i ] );
321            }
322        }
323
324        return $images;
325    }
326
327    /**
328     * Check if a Featured Image is set for this post, and return it in a similar
329     * format to the other images?_from_*() methods.
330     *
331     * @param  int $post_id The post ID to check.
332     * @param  int $width Image width.
333     * @param  int $height Image height.
334     * @return array containing details of the Featured Image, or empty array if none.
335     */
336    public static function from_thumbnail( $post_id, $width = 200, $height = 200 ) {
337        $images = array();
338
339        $post = get_post( $post_id );
340        if ( ! $post instanceof \WP_Post ) {
341            return $images;
342        }
343
344        if ( ! empty( $post->post_password ) ) {
345            return $images;
346        }
347
348        if ( 'attachment' === get_post_type( $post ) && wp_attachment_is_image( $post ) ) {
349            $thumb = $post_id;
350        } else {
351            $thumb = get_post_thumbnail_id( $post );
352        }
353
354        if ( $thumb ) {
355            $meta = wp_get_attachment_metadata( $thumb );
356            // Must be larger than requested minimums.
357            if ( ! isset( $meta['width'] ) || $meta['width'] < $width ) {
358                return $images;
359            }
360            if ( ! isset( $meta['height'] ) || $meta['height'] < $height ) {
361                return $images;
362            }
363            $max_dimension = self::get_max_thumbnail_dimension();
364            $too_big       = ( ( ! empty( $meta['width'] ) && $meta['width'] > $max_dimension ) || ( ! empty( $meta['height'] ) && $meta['height'] > $max_dimension ) );
365
366            if (
367                $too_big &&
368                (
369                    // @phan-suppress-next-line PhanUndeclaredClassMethod, PhanUndeclaredClassReference -- Checked with method_exists().
370                    ( method_exists( 'Jetpack', 'is_module_active' ) && \Jetpack::is_module_active( 'photon' ) ) ||
371                    ( defined( 'IS_WPCOM' ) && IS_WPCOM )
372                )
373            ) {
374                $size        = self::determine_thumbnail_size_for_photon( $meta['width'], $meta['height'] );
375                $photon_args = array(
376                    'fit' => $size['width'] . ',' . $size['height'],
377                );
378                $img_src     = array( Image_CDN_Core::cdn_url( wp_get_attachment_url( $thumb ), $photon_args ), $size['width'], $size['height'], true ); // Match the signature of wp_get_attachment_image_src
379            } else {
380                $img_src = wp_get_attachment_image_src( $thumb, 'full' );
381            }
382            if ( ! is_array( $img_src ) ) {
383                // If wp_get_attachment_image_src returns false but we know that there should be an image that could be used.
384                // we try a bit harder and user the data that we have.
385                $thumb_post_data = get_post( $thumb );
386                $img_src         = array( $thumb_post_data->guid ?? null, $meta['width'], $meta['height'] );
387            }
388
389            // Let's try to use the postmeta if we can, since it seems to be
390            // more reliable
391            if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
392                $featured_image = get_post_meta( $post->ID, '_jetpack_featured_image', false );
393                if ( $featured_image ) {
394                    $url = $featured_image[0];
395                } else {
396                    $url = $img_src[0];
397                }
398            } else {
399                $url = $img_src[0];
400            }
401            $images = array(
402                array( // Other methods below all return an array of arrays.
403                    'type'       => 'image',
404                    'from'       => 'thumbnail',
405                    'src'        => $url,
406                    'src_width'  => $img_src[1],
407                    'src_height' => $img_src[2],
408                    'href'       => get_permalink( $thumb ),
409                    'alt_text'   => self::get_alt_text( $thumb ),
410                ),
411            );
412
413        }
414
415        if ( empty( $images ) && ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) {
416            $meta_thumbnail = get_post_meta( $post_id, '_jetpack_post_thumbnail', true );
417            if ( ! empty( $meta_thumbnail ) ) {
418                if ( ! isset( $meta_thumbnail['width'] ) || $meta_thumbnail['width'] < $width ) {
419                    return $images;
420                }
421
422                if ( ! isset( $meta_thumbnail['height'] ) || $meta_thumbnail['height'] < $height ) {
423                    return $images;
424                }
425
426                $images = array(
427                    array( // Other methods below all return an array of arrays.
428                        'type'       => 'image',
429                        'from'       => 'thumbnail',
430                        'src'        => $meta_thumbnail['URL'],
431                        'src_width'  => $meta_thumbnail['width'],
432                        'src_height' => $meta_thumbnail['height'],
433                        'href'       => $meta_thumbnail['URL'],
434                        'alt_text'   => $thumb ? self::get_alt_text( $thumb ) : '',
435                    ),
436                );
437            }
438        }
439
440        return $images;
441    }
442
443    /**
444     * Get images from Gutenberg Image blocks.
445     *
446     * @since jetpack-6.9.0
447     * @since jetpack-14.8 Updated to use Block_Delimiter for improved performance.
448     * @since jetpack-14.9 Updated to use Block_Scanner for improved performance.
449     *
450     * @param mixed $html_or_id The HTML string to parse for images, or a post id.
451     * @param int   $width      Minimum Image width.
452     * @param int   $height     Minimum Image height.
453     */
454    public static function from_blocks( $html_or_id, $width = 200, $height = 200 ) {
455        $images = array();
456
457        $html_info = self::get_post_html( $html_or_id );
458
459        if ( empty( $html_info['html'] ) ) {
460            return $images;
461        }
462
463        $scanner = Block_Scanner::create( $html_info['html'] );
464        if ( ! $scanner ) {
465            return $images;
466        }
467
468        /*
469         * Use Block_Scanner to parse our post content HTML,
470         * and find all the block delimiters for supported blocks,
471         * whether they're parent or nested blocks.
472         */
473        $supported_blocks = array(
474            'core/image',
475            'core/media-text',
476            'core/gallery',
477            'jetpack/tiled-gallery',
478            'jetpack/slideshow',
479            'jetpack/story',
480        );
481
482        while ( $scanner->next_delimiter() ) {
483            $type = $scanner->get_delimiter_type();
484            // Only process opening delimiters for supported block types.
485            if ( Block_Scanner::OPENER !== $type ) {
486                continue;
487            }
488
489            $block_type         = $scanner->get_block_type();
490            $is_supported_block = in_array( $block_type, $supported_blocks, true );
491            if ( ! $is_supported_block ) {
492                continue;
493            }
494
495            $attributes   = $scanner->allocate_and_return_parsed_attributes() ?? array();
496            $block_images = self::get_images_from_block_attributes( $block_type, $attributes, $html_info, $width, $height );
497
498            if ( ! empty( $block_images ) ) {
499                $images = array_merge( $images, $block_images );
500            }
501        }
502
503        /**
504         * Returning a filtered array because get_attachment_data returns false
505         * for unsuccessful attempts.
506         */
507        return array_filter( $images );
508    }
509
510    /**
511     * Extract images from block attributes based on block type.
512     *
513     * @since jetpack-14.8
514     *
515     * @param string $block_type Block type name.
516     * @param array  $attributes Block attributes.
517     * @param array  $html_info  Info about the post where the block is found.
518     * @param int    $width      Desired image width.
519     * @param int    $height     Desired image height.
520     *
521     * @return array Array of images found.
522     */
523    private static function get_images_from_block_attributes( $block_type, $attributes, $html_info, $width, $height ) {
524        $images = array();
525
526        // Skip blocks marked with the jetpack-ignore-thumbnail CSS class
527        // (set via the block editor's "Advanced > Additional CSS class" panel).
528        $class_name = $attributes['className'] ?? '';
529        if ( str_contains( $class_name, 'jetpack-ignore-thumbnail' ) ) {
530            return $images;
531        }
532
533        switch ( $block_type ) {
534            case 'core/image':
535            case 'core/media-text':
536                $id_key = 'core/image' === $block_type ? 'id' : 'mediaId';
537                if ( ! empty( $attributes[ $id_key ] ) ) {
538                    $image = self::get_attachment_data( $attributes[ $id_key ], $html_info['post_url'], $width, $height );
539                    if ( false !== $image ) {
540                        /** This filter is documented in class-images.php */
541                        if ( apply_filters( 'jetpack_postimages_exclude_image', false, $image ) ) {
542                            break;
543                        }
544                        $images[] = $image;
545                    }
546                }
547                break;
548
549            case 'core/gallery':
550            case 'jetpack/tiled-gallery':
551            case 'jetpack/slideshow':
552                if ( ! empty( $attributes['ids'] ) && is_array( $attributes['ids'] ) ) {
553                    foreach ( $attributes['ids'] as $img_id ) {
554                        $image = self::get_attachment_data( $img_id, $html_info['post_url'], $width, $height );
555                        if ( false !== $image ) {
556                            /** This filter is documented in class-images.php */
557                            if ( apply_filters( 'jetpack_postimages_exclude_image', false, $image ) ) {
558                                continue;
559                            }
560                            $images[] = $image;
561                        }
562                    }
563                }
564                break;
565
566            case 'jetpack/story':
567                if ( ! empty( $attributes['mediaFiles'] ) && is_array( $attributes['mediaFiles'] ) ) {
568                    foreach ( $attributes['mediaFiles'] as $media_file ) {
569                        if ( ! empty( $media_file['id'] ) ) {
570                            $image = self::get_attachment_data( $media_file['id'], $html_info['post_url'], $width, $height );
571                            if ( false !== $image ) {
572                                /** This filter is documented in class-images.php */
573                                if ( apply_filters( 'jetpack_postimages_exclude_image', false, $image ) ) {
574                                    continue;
575                                }
576                                $images[] = $image;
577                            }
578                        }
579                    }
580                }
581                break;
582        }
583
584        return $images;
585    }
586
587    /**
588     * Very raw -- just parse the HTML and pull out any/all img tags and return their src
589     *
590     * @param mixed $html_or_id The HTML string to parse for images, or a post id.
591     * @param int   $width      Minimum Image width.
592     * @param int   $height     Minimum Image height.
593     *
594     * @uses DOMDocument
595     *
596     * @return array containing images
597     */
598    public static function from_html( $html_or_id, $width = 200, $height = 200 ) {
599        $images = array();
600
601        $html_info = self::get_post_html( $html_or_id );
602
603        if ( empty( $html_info['html'] ) ) {
604            return $images;
605        }
606
607        // Do not go any further if DOMDocument is disabled on the server.
608        if ( ! class_exists( 'DOMDocument' ) ) {
609            return $images;
610        }
611
612        // Let's grab all image tags from the HTML.
613        $dom_doc = new \DOMDocument();
614
615        // DOMDocument defaults to ISO-8859 because we're loading only the post content, without head tag.
616        // Fix: Enforce encoding with meta tag.
617        $charset = get_option( 'blog_charset' );
618        if ( empty( $charset ) || ! preg_match( '/^[a-zA-Z0-9_-]+$/', $charset ) ) {
619            $charset = 'UTF-8';
620        }
621        $html_prefix = sprintf( '<meta http-equiv="Content-Type" content="text/html; charset=%s">', esc_attr( $charset ) );
622
623        // The @ is not enough to suppress errors when dealing with libxml,
624        // we have to tell it directly how we want to handle errors.
625        libxml_use_internal_errors( true );
626        @$dom_doc->loadHTML( $html_prefix . $html_info['html'] ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
627        libxml_use_internal_errors( false );
628
629        $image_tags = $dom_doc->getElementsByTagName( 'img' );
630
631        // For each image Tag, make sure it can be added to the $images array, and add it.
632        foreach ( $image_tags as $image_tag ) {
633            $img_src = $image_tag->getAttribute( 'src' );
634
635            if ( empty( $img_src ) ) {
636                continue;
637            }
638
639            // Do not grab smiley images that were automatically created by WP when entering text smilies.
640            if ( stripos( $img_src, '/smilies/' ) ) {
641                continue;
642            }
643
644            // Do not grab Gravatar images.
645            if ( stripos( $img_src, 'gravatar.com' ) ) {
646                continue;
647            }
648
649            // Allow users to exclude images by adding a CSS class to the img tag.
650            if ( str_contains( $image_tag->getAttribute( 'class' ) ?? '', 'jetpack-ignore-thumbnail' ) ) {
651                continue;
652            }
653
654            // First try to get the width and height from the img attributes, but if they are not set, check to see if they are specified in the url. WordPress automatically names files like foo-1024x768.jpg during the upload process
655            $width  = (int) $image_tag->getAttribute( 'width' );
656            $height = (int) $image_tag->getAttribute( 'height' );
657            if ( 0 === $width && 0 === $height ) {
658                preg_match( '/-([0-9]{1,5})x([0-9]{1,5})\.(?:jpg|jpeg|png|gif|webp)$/i', $img_src, $matches );
659                if ( ! empty( $matches[1] ) ) {
660                    $width = (int) $matches[1];
661                }
662                if ( ! empty( $matches[2] ) ) {
663                    $height = (int) $matches[2];
664                }
665            }
666            // If width and height are still 0, try to get the id of the image from the class, e.g. wp-image-1234
667            if ( 0 === $width && 0 === $height ) {
668
669                preg_match( '/wp-image-([0-9]+)/', $image_tag->getAttribute( 'class' ), $matches );
670                if ( ! empty( $matches[1] ) ) {
671                    $attachment_id = (int) $matches[1];
672                    $meta          = wp_get_attachment_metadata( $attachment_id );
673                    $height        = $meta['height'] ?? 0;
674                    $width         = $meta['width'] ?? 0;
675                }
676            }
677
678            $meta = array(
679                'width'    => $width,
680                'height'   => $height,
681                'alt_text' => $image_tag->getAttribute( 'alt' ),
682            );
683
684            /**
685             * Filters the switch to ignore minimum image size requirements. Can be used
686             * to add custom logic to image dimensions, like only enforcing one of the dimensions,
687             * or disabling it entirely.
688             *
689             * @since jetpack-6.4.0
690             *
691             * @param bool $ignore Should the image dimensions be ignored?
692             * @param array $meta Array containing image dimensions parsed from the markup.
693             */
694            $ignore_dimensions = apply_filters( 'jetpack_postimages_ignore_minimum_dimensions', false, $meta );
695
696            // Must be larger than 200x200 (or user-specified).
697            if (
698                ! $ignore_dimensions
699                && (
700                    empty( $meta['width'] )
701                    || empty( $meta['height'] )
702                    || $meta['width'] < $width
703                    || $meta['height'] < $height
704                )
705            ) {
706                continue;
707            }
708
709            $image = array(
710                'type'       => 'image',
711                'from'       => 'html',
712                'src'        => $img_src,
713                'src_width'  => $meta['width'],
714                'src_height' => $meta['height'],
715                'href'       => $html_info['post_url'],
716            );
717            if ( ! empty( $meta['alt_text'] ) ) {
718                $image['alt_text'] = $meta['alt_text'];
719            }
720
721            /**
722             * Filters whether to exclude a specific image from post image discovery.
723             *
724             * This filter runs inside the Images class, which powers image selection
725             * for Related Posts, Open Graph tags, and other features. Returning a truthy
726             * value causes the image to be skipped.
727             *
728             * @since 0.1.0
729             *
730             * @param bool  $exclude Whether to exclude the image. Default false.
731             * @param array $image   {
732             *     Image data.
733             *
734             *     @type string $type       The type of the image (always 'image').
735             *     @type string $from       The source method ('html', 'attachment', 'thumbnail', etc.).
736             *     @type string $src        The image URL.
737             *     @type int    $src_width  The image width in pixels.
738             *     @type int    $src_height The image height in pixels.
739             *     @type string $href       The permalink of the post containing the image.
740             *     @type string $alt_text   The image alt text, if available.
741             * }
742             */
743            if ( apply_filters( 'jetpack_postimages_exclude_image', false, $image ) ) {
744                continue;
745            }
746
747            $images[] = $image;
748        }
749        return $images;
750    }
751
752    /**
753     * Data from blavatar.
754     *
755     * @param    int $post_id The post ID to check.
756     * @param    int $size Size.
757     * @return array containing details of the image, or empty array if none.
758     */
759    public static function from_blavatar( $post_id, $size = 96 ) {
760
761        $permalink = get_permalink( $post_id );
762
763        if ( function_exists( 'blavatar_domain' ) && function_exists( 'blavatar_exists' ) && function_exists( 'blavatar_url' ) ) {
764            $domain = blavatar_domain( $permalink ); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists().
765
766            if ( ! blavatar_exists( $domain ) ) { // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists().
767                return array();
768            }
769
770            $url = blavatar_url( $domain, 'img', $size ); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists().
771        } else {
772            $url = get_site_icon_url( $size );
773            if ( ! $url ) {
774                return array();
775            }
776        }
777
778        return array(
779            array(
780                'type'       => 'image',
781                'from'       => 'blavatar',
782                'src'        => $url,
783                'src_width'  => $size,
784                'src_height' => $size,
785                'href'       => $permalink,
786                'alt_text'   => '',
787            ),
788        );
789    }
790
791    /**
792     * Gets a post image from the author avatar.
793     *
794     * @param int          $post_id The post ID to check.
795     * @param int          $size The size of the avatar to get.
796     * @param string|false $default The default image to use.
797     * @return array containing details of the image, or empty array if none.
798     */
799    public static function from_gravatar( $post_id, $size = 96, $default = false ) {
800        $post = get_post( $post_id );
801        if ( ! $post instanceof \WP_Post ) {
802            return array();
803        }
804
805        $permalink = get_permalink( $post_id );
806
807        if ( function_exists( 'wpcom_get_avatar_url' ) ) {
808            $url = wpcom_get_avatar_url( $post->post_author, $size, $default, true ); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists().
809            if ( $url && is_array( $url ) ) {
810                $url = $url[0];
811            }
812        } else {
813            $url = get_avatar_url(
814                $post->post_author,
815                array(
816                    'size'    => $size,
817                    'default' => $default,
818                )
819            );
820        }
821
822        return array(
823            array(
824                'type'       => 'image',
825                'from'       => 'gravatar',
826                'src'        => $url,
827                'src_width'  => $size,
828                'src_height' => $size,
829                'href'       => $permalink,
830                'alt_text'   => '',
831            ),
832        );
833    }
834
835    /**
836     * Run through the different methods that we have available to try to find a single good
837     * display image for this post.
838     *
839     * @param int   $post_id Post ID.
840     * @param array $args Other arguments (currently width and height required for images where possible to determine).
841     * @return array|null containing details of the best image to be used, or null if no image is found.
842     */
843    public static function get_image( $post_id, $args = array() ) {
844        $image = null;
845
846        /**
847         * Fires before we find a single good image for a specific post.
848         *
849         * @since jetpack-2.2.0
850         *
851         * @param int $post_id Post ID.
852         */
853        do_action( 'jetpack_postimages_pre_get_image', $post_id );
854        $media = self::get_images( $post_id, $args );
855
856        if ( is_array( $media ) ) {
857            foreach ( $media as $item ) {
858                if ( is_array( $item ) && isset( $item['type'] ) && 'image' === $item['type'] ) {
859                    $image = $item;
860                    break;
861                }
862            }
863        }
864
865        /**
866         * Fires after we find a single good image for a specific post.
867         *
868         * @since jetpack-2.2.0
869         *
870         * @param int $post_id Post ID.
871         */
872        do_action( 'jetpack_postimages_post_get_image', $post_id );
873
874        return $image;
875    }
876
877    /**
878     * Get an array containing a collection of possible images for this post, stopping once we hit a method
879     * that returns something useful.
880     *
881     * @param  int   $post_id Post ID.
882     * @param  array $args Optional args, see defaults list for details.
883     * @return array containing images that would be good for representing this post
884     */
885    public static function get_images( $post_id, $args = array() ) {
886        // Figure out which image to attach to this post.
887        $media = array();
888
889        /**
890         * Filters the array of images that would be good for a specific post.
891         * This filter is applied before options ($args) filter the original array.
892         *
893         * @since jetpack-2.0.0
894         *
895         * @param array $media Array of images that would be good for a specific post.
896         * @param int $post_id Post ID.
897         * @param array $args Array of options to get images.
898         */
899        $media = apply_filters( 'jetpack_images_pre_get_images', $media, $post_id, $args );
900        if ( $media ) {
901            return $media;
902        }
903
904        $defaults = array(
905            'width'               => 200, // Required minimum width (if possible to determine).
906            'height'              => 200, // Required minimum height (if possible to determine).
907
908            'fallback_to_avatars' => false, // Optionally include Blavatar and Gravatar (in that order) in the image stack.
909            'avatar_size'         => 96, // Used for both Grav and Blav.
910            'gravatar_default'    => false, // Default image to use if we end up with no Gravatar.
911
912            'from_thumbnail'      => true, // Use these flags to specify which methods to use to find an image.
913            'from_slideshow'      => true,
914            'from_gallery'        => true,
915            'from_attachment'     => true,
916            'from_blocks'         => true,
917            'from_html'           => true,
918
919            'html_content'        => '', // HTML string to pass to from_html().
920        );
921        $args     = wp_parse_args( $args, $defaults );
922
923        $media = array();
924        if ( $args['from_thumbnail'] ) {
925            $media = self::from_thumbnail( $post_id, $args['width'], $args['height'] );
926        }
927        if ( ! $media && $args['from_slideshow'] ) {
928            $media = self::from_slideshow( $post_id, $args['width'], $args['height'] );
929        }
930        if ( ! $media && $args['from_gallery'] ) {
931            $media = self::from_gallery( $post_id );
932        }
933        if ( ! $media && $args['from_attachment'] ) {
934            $media = self::from_attachment( $post_id, $args['width'], $args['height'] );
935        }
936        if ( ! $media && $args['from_blocks'] ) {
937            if ( empty( $args['html_content'] ) ) {
938                $media = self::from_blocks( $post_id, $args['width'], $args['height'] ); // Use the post_id, which will load the content.
939            } else {
940                $media = self::from_blocks( $args['html_content'], $args['width'], $args['height'] ); // If html_content is provided, use that.
941            }
942        }
943        if ( ! $media && $args['from_html'] ) {
944            if ( empty( $args['html_content'] ) ) {
945                $media = self::from_html( $post_id, $args['width'], $args['height'] ); // Use the post_id, which will load the content.
946            } else {
947                $media = self::from_html( $args['html_content'], $args['width'], $args['height'] ); // If html_content is provided, use that.
948            }
949        }
950
951        if ( ! $media && $args['fallback_to_avatars'] ) {
952            $media = self::from_blavatar( $post_id, $args['avatar_size'] );
953            if ( ! $media ) {
954                $media = self::from_gravatar( $post_id, $args['avatar_size'], $args['gravatar_default'] );
955            }
956        }
957
958        /**
959         * Filters the array of images that would be good for a specific post.
960         * This filter is applied after options ($args) filter the original array.
961         *
962         * @since jetpack-2.0.0
963         *
964         * @param array $media Array of images that would be good for a specific post.
965         * @param int $post_id Post ID.
966         * @param array $args Array of options to get images.
967         */
968        return apply_filters( 'jetpack_images_get_images', $media, $post_id, $args );
969    }
970
971    /**
972     * Takes an image and base pixel dimensions and returns a srcset for the
973     * resized and cropped images, based on a fixed set of multipliers.
974     *
975     * @param  array $image Array containing details of the image.
976     * @param  int   $base_width Base image width (i.e., the width at 1x).
977     * @param  int   $base_height Base image height (i.e., the height at 1x).
978     * @param  bool  $use_widths Whether to generate the srcset with widths instead of multipliers.
979     * @return string The srcset for the image.
980     */
981    public static function generate_cropped_srcset( $image, $base_width, $base_height, $use_widths = false ) {
982        $srcset = '';
983
984        if ( ! is_array( $image ) || empty( $image['src'] ) || empty( $image['src_width'] ) ) {
985            return $srcset;
986        }
987
988        $multipliers   = array( 1, 1.5, 2, 3, 4 );
989        $srcset_values = array();
990        foreach ( $multipliers as $multiplier ) {
991            $srcset_width  = (int) ( $base_width * $multiplier );
992            $srcset_height = (int) ( $base_height * $multiplier );
993            if ( $srcset_width < 1 || $srcset_width > $image['src_width'] ) {
994                break;
995            }
996
997            $srcset_url = self::fit_image_url(
998                $image['src'],
999                $srcset_width,
1000                $srcset_height
1001            );
1002
1003            if ( $use_widths ) {
1004                $srcset_values[] = "{$srcset_url} {$srcset_width}w";
1005            } else {
1006                $srcset_values[] = "{$srcset_url} {$multiplier}x";
1007            }
1008        }
1009
1010        if ( count( $srcset_values ) > 1 ) {
1011            $srcset = implode( ', ', $srcset_values );
1012        }
1013
1014        return $srcset;
1015    }
1016
1017    /**
1018     * Takes an image URL and pixel dimensions then returns a URL for the
1019     * resized and cropped image.
1020     *
1021     * @param  string $src Image URL.
1022     * @param  int    $width Image width.
1023     * @param  int    $height Image height.
1024     * @return string Transformed image URL
1025     */
1026    public static function fit_image_url( $src, $width, $height ) {
1027        $width  = (int) $width;
1028        $height = (int) $height;
1029
1030        if ( $width < 1 || $height < 1 ) {
1031            return $src;
1032        }
1033
1034        // See if we should bypass WordPress.com SaaS resizing.
1035        if ( has_filter( 'jetpack_images_fit_image_url_override' ) ) {
1036            /**
1037             * Filters the image URL used after dimensions are set by Photon.
1038             *
1039             * @since jetpack-3.3.0
1040             *
1041             * @param string $src Image URL.
1042             * @param int $width Image width.
1043             * @param int $width Image height.
1044             */
1045            return apply_filters( 'jetpack_images_fit_image_url_override', $src, $width, $height );
1046        }
1047
1048        // If WPCOM hosted image use native transformations.
1049        $img_host = wp_parse_url( $src, PHP_URL_HOST );
1050        if ( $img_host && str_ends_with( $img_host, '.files.wordpress.com' ) ) {
1051            return add_query_arg(
1052                array(
1053                    'w'    => $width,
1054                    'h'    => $height,
1055                    'crop' => 1,
1056                ),
1057                set_url_scheme( $src )
1058            );
1059        }
1060
1061        // Use image cdn magic.
1062        if ( class_exists( Image_CDN_Core::class ) && method_exists( Image_CDN_Core::class, 'cdn_url' ) ) {
1063            return Image_CDN_Core::cdn_url( $src, array( 'resize' => "$width,$height" ) );
1064        }
1065
1066        // Arg... no way to resize image using WordPress.com infrastructure!
1067        return $src;
1068    }
1069
1070    /**
1071     * Get HTML from given post content.
1072     *
1073     * @since jetpack-6.9.0
1074     *
1075     * @param mixed $html_or_id The HTML string to parse for images, or a post id.
1076     *
1077     * @return array $html_info {
1078     * @type string $html     Post content.
1079     * @type string $post_url Post URL.
1080     * }
1081     */
1082    public static function get_post_html( $html_or_id ) {
1083        if ( is_numeric( $html_or_id ) ) {
1084            $post = get_post( $html_or_id );
1085            if ( ! $post instanceof \WP_Post || ! empty( $post->post_password ) ) {
1086                return array();
1087            }
1088
1089            $html_info = array(
1090                'html'     => $post->post_content, // DO NOT apply the_content filters here, it will cause loops.
1091                'post_url' => get_permalink( $post->ID ),
1092            );
1093        } else {
1094            $html_info = array(
1095                'html'     => $html_or_id,
1096                'post_url' => '',
1097            );
1098        }
1099        return $html_info;
1100    }
1101
1102    /**
1103     * Get info about a WordPress attachment.
1104     *
1105     * @since jetpack-6.9.0
1106     *
1107     * @param int    $attachment_id Attachment ID.
1108     * @param string $post_url      URL of the post, if we have one.
1109     * @param int    $width         Minimum Image width.
1110     * @param int    $height        Minimum Image height.
1111     * @return array|bool           Image data or false if unavailable.
1112     */
1113    public static function get_attachment_data( $attachment_id, $post_url, $width, $height ) {
1114        if ( empty( $attachment_id ) ) {
1115            return false;
1116        }
1117
1118        $meta = wp_get_attachment_metadata( $attachment_id );
1119
1120        if ( empty( $meta ) ) {
1121            return false;
1122        }
1123
1124        if ( isset( $meta['videopress']['poster'] ) && isset( $meta['videopress']['width'] ) && isset( $meta['videopress']['height'] ) ) {
1125            // Use poster image for VideoPress videos.
1126            $url         = $meta['videopress']['poster'];
1127            $meta_width  = $meta['videopress']['width'];
1128            $meta_height = $meta['videopress']['height'];
1129        } elseif ( ! empty( $meta['thumb'] ) ) {
1130            // On WordPress.com, VideoPress videos have a 'thumb' property with the
1131            // poster image filename instead.
1132            $media_url   = wp_get_attachment_url( $attachment_id );
1133            $url         = str_replace( wp_basename( $media_url ), $meta['thumb'], $media_url );
1134            $meta_width  = $meta['width'];
1135            $meta_height = $meta['height'];
1136        } elseif ( wp_attachment_is( 'video', $attachment_id ) ) {
1137            // We don't have thumbnail images for non-VideoPress videos - skip them.
1138            return false;
1139        } else {
1140            if ( ! isset( $meta['width'] ) || ! isset( $meta['height'] ) ) {
1141                return false;
1142            }
1143            $url         = wp_get_attachment_url( $attachment_id );
1144            $meta_width  = $meta['width'];
1145            $meta_height = $meta['height'];
1146        }
1147
1148        if ( $meta_width < $width || $meta_height < $height ) {
1149            return false;
1150        }
1151
1152        return array(
1153            'type'       => 'image',
1154            'from'       => 'attachment',
1155            'src'        => $url,
1156            'src_width'  => $meta_width,
1157            'src_height' => $meta_height,
1158            'href'       => $post_url,
1159            'alt_text'   => self::get_alt_text( $attachment_id ),
1160        );
1161    }
1162
1163    /**
1164     * Get the alt text for an image or other media from the Media Library.
1165     *
1166     * @since jetpack-7.1
1167     *
1168     * @param int $attachment_id The Post ID of the media.
1169     * @return string The alt text value or an empty string.
1170     */
1171    public static function get_alt_text( $attachment_id ) {
1172        return (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
1173    }
1174
1175    /**
1176     * Determine the size to use with Photon for a thumbnail image.
1177     * Images larger than the maximum thumbnail dimension in either dimension are resized to maintain aspect ratio.
1178     *
1179     * @since jetpack-14.6
1180     * @see https://github.com/Automattic/jetpack/issues/40349
1181     *
1182     * @param int $width Original image width.
1183     * @param int $height Original image height.
1184     * @return array Array containing the width and height to use with Photon (null means auto).
1185     */
1186    public static function determine_thumbnail_size_for_photon( $width, $height ) {
1187        $max_dimension = self::get_max_thumbnail_dimension();
1188
1189        // If neither dimension exceeds max size, return original dimensions.
1190        if ( $width <= $max_dimension && $height <= $max_dimension ) {
1191            return array(
1192                'width'  => $width,
1193                'height' => $height,
1194            );
1195        }
1196
1197        if ( $width >= $height ) {
1198            // For landscape or square images.
1199            $dims = image_resize_dimensions( $width, $height, $max_dimension, 0 ); // Height will be calculated automatically.
1200        } else {
1201            // For portrait images.
1202            $dims = image_resize_dimensions( $width, $height, 0, $max_dimension ); // Width will be calculated automatically.
1203        }
1204
1205        // $dims can be false if the image is virtually the same size as the max dimension, e.g. wp_fuzzy_number_match.
1206        if ( $dims && isset( $dims[4] ) && isset( $dims[5] ) ) {
1207            return array(
1208                'width'  => $dims[4],
1209                'height' => $dims[5],
1210            );
1211        }
1212
1213        return array(
1214            'width'  => $width,
1215            'height' => $height,
1216        );
1217    }
1218
1219    /**
1220     * Function to provide the maximum dimension for a thumbnail image.
1221     * Filterable via the `jetpack_post_images_max_dimension` filter.
1222     *
1223     * @since jetpack-14.6
1224     * @see https://github.com/Automattic/jetpack/issues/40349
1225     *
1226     * @return int The maximum dimension for a thumbnail image.
1227     */
1228    public static function get_max_thumbnail_dimension() {
1229        /**
1230         * Filter the maximum dimension allowed for a thumbnail image.
1231         * The default value is 1200 pixels.
1232         *
1233         * @since jetpack-14.6
1234         *
1235         * @param int $max_dimension Maximum dimension in pixels.
1236         */
1237        return (int) apply_filters( 'jetpack_post_images_max_thumbnail_dimension', 1200 );
1238    }
1239}