Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
45.50% covered (danger)
45.50%
253 / 556
15.79% covered (danger)
15.79%
3 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
Images
45.50% covered (danger)
45.50%
253 / 556
15.79% covered (danger)
15.79%
3 / 19
7347.43
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 / 37
0.00% covered (danger)
0.00%
0 / 1
210
 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
20
 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
10.08
 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            $current_image = self::get_attachment_data( $post_image->ID, $permalink, $width, $height );
287            if ( false !== $current_image ) {
288                $images[] = $current_image;
289            }
290        }
291
292        /*
293        * We only want to pass back attached images that were actually inserted.
294        * We can load up all the images found in the HTML source and then
295        * compare URLs to see if an image is attached AND inserted.
296        */
297        $html_images     = self::from_html( $post_id );
298        $inserted_images = array();
299
300        foreach ( $html_images as $html_image ) {
301            $src = wp_parse_url( $html_image['src'] );
302            if ( ! $src || empty( $src['path'] ) ) {
303                continue;
304            }
305
306            // strip off any query strings from src.
307            if ( ! empty( $src['scheme'] ) && ! empty( $src['host'] ) ) {
308                $inserted_images[] = $src['scheme'] . '://' . $src['host'] . $src['path'];
309            } elseif ( ! empty( $src['host'] ) ) {
310                $inserted_images[] = set_url_scheme( 'http://' . $src['host'] . $src['path'] );
311            } else {
312                $inserted_images[] = site_url( '/' ) . $src['path'];
313            }
314        }
315        foreach ( $images as $i => $image ) {
316            if ( ! in_array( $image['src'], $inserted_images, true ) ) {
317                unset( $images[ $i ] );
318            }
319        }
320
321        return $images;
322    }
323
324    /**
325     * Check if a Featured Image is set for this post, and return it in a similar
326     * format to the other images?_from_*() methods.
327     *
328     * @param  int $post_id The post ID to check.
329     * @param  int $width Image width.
330     * @param  int $height Image height.
331     * @return array containing details of the Featured Image, or empty array if none.
332     */
333    public static function from_thumbnail( $post_id, $width = 200, $height = 200 ) {
334        $images = array();
335
336        $post = get_post( $post_id );
337        if ( ! $post instanceof \WP_Post ) {
338            return $images;
339        }
340
341        if ( ! empty( $post->post_password ) ) {
342            return $images;
343        }
344
345        if ( 'attachment' === get_post_type( $post ) && wp_attachment_is_image( $post ) ) {
346            $thumb = $post_id;
347        } else {
348            $thumb = get_post_thumbnail_id( $post );
349        }
350
351        if ( $thumb ) {
352            $meta = wp_get_attachment_metadata( $thumb );
353            // Must be larger than requested minimums.
354            if ( ! isset( $meta['width'] ) || $meta['width'] < $width ) {
355                return $images;
356            }
357            if ( ! isset( $meta['height'] ) || $meta['height'] < $height ) {
358                return $images;
359            }
360            $max_dimension = self::get_max_thumbnail_dimension();
361            $too_big       = ( ( ! empty( $meta['width'] ) && $meta['width'] > $max_dimension ) || ( ! empty( $meta['height'] ) && $meta['height'] > $max_dimension ) );
362
363            if (
364                $too_big &&
365                (
366                    // @phan-suppress-next-line PhanUndeclaredClassMethod, PhanUndeclaredClassReference -- Checked with method_exists().
367                    ( method_exists( 'Jetpack', 'is_module_active' ) && \Jetpack::is_module_active( 'photon' ) ) ||
368                    ( defined( 'IS_WPCOM' ) && IS_WPCOM )
369                )
370            ) {
371                $size        = self::determine_thumbnail_size_for_photon( $meta['width'], $meta['height'] );
372                $photon_args = array(
373                    'fit' => $size['width'] . ',' . $size['height'],
374                );
375                $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
376            } else {
377                $img_src = wp_get_attachment_image_src( $thumb, 'full' );
378            }
379            if ( ! is_array( $img_src ) ) {
380                // If wp_get_attachment_image_src returns false but we know that there should be an image that could be used.
381                // we try a bit harder and user the data that we have.
382                $thumb_post_data = get_post( $thumb );
383                $img_src         = array( $thumb_post_data->guid ?? null, $meta['width'], $meta['height'] );
384            }
385
386            // Let's try to use the postmeta if we can, since it seems to be
387            // more reliable
388            if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
389                $featured_image = get_post_meta( $post->ID, '_jetpack_featured_image', false );
390                if ( $featured_image ) {
391                    $url = $featured_image[0];
392                } else {
393                    $url = $img_src[0];
394                }
395            } else {
396                $url = $img_src[0];
397            }
398            $images = array(
399                array( // Other methods below all return an array of arrays.
400                    'type'       => 'image',
401                    'from'       => 'thumbnail',
402                    'src'        => $url,
403                    'src_width'  => $img_src[1],
404                    'src_height' => $img_src[2],
405                    'href'       => get_permalink( $thumb ),
406                    'alt_text'   => self::get_alt_text( $thumb ),
407                ),
408            );
409
410        }
411
412        if ( empty( $images ) && ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) {
413            $meta_thumbnail = get_post_meta( $post_id, '_jetpack_post_thumbnail', true );
414            if ( ! empty( $meta_thumbnail ) ) {
415                if ( ! isset( $meta_thumbnail['width'] ) || $meta_thumbnail['width'] < $width ) {
416                    return $images;
417                }
418
419                if ( ! isset( $meta_thumbnail['height'] ) || $meta_thumbnail['height'] < $height ) {
420                    return $images;
421                }
422
423                $images = array(
424                    array( // Other methods below all return an array of arrays.
425                        'type'       => 'image',
426                        'from'       => 'thumbnail',
427                        'src'        => $meta_thumbnail['URL'],
428                        'src_width'  => $meta_thumbnail['width'],
429                        'src_height' => $meta_thumbnail['height'],
430                        'href'       => $meta_thumbnail['URL'],
431                        'alt_text'   => $thumb ? self::get_alt_text( $thumb ) : '',
432                    ),
433                );
434            }
435        }
436
437        return $images;
438    }
439
440    /**
441     * Get images from Gutenberg Image blocks.
442     *
443     * @since jetpack-6.9.0
444     * @since jetpack-14.8 Updated to use Block_Delimiter for improved performance.
445     * @since jetpack-14.9 Updated to use Block_Scanner for improved performance.
446     *
447     * @param mixed $html_or_id The HTML string to parse for images, or a post id.
448     * @param int   $width      Minimum Image width.
449     * @param int   $height     Minimum Image height.
450     */
451    public static function from_blocks( $html_or_id, $width = 200, $height = 200 ) {
452        $images = array();
453
454        $html_info = self::get_post_html( $html_or_id );
455
456        if ( empty( $html_info['html'] ) ) {
457            return $images;
458        }
459
460        $scanner = Block_Scanner::create( $html_info['html'] );
461        if ( ! $scanner ) {
462            return $images;
463        }
464
465        /*
466         * Use Block_Scanner to parse our post content HTML,
467         * and find all the block delimiters for supported blocks,
468         * whether they're parent or nested blocks.
469         */
470        $supported_blocks = array(
471            'core/image',
472            'core/media-text',
473            'core/gallery',
474            'jetpack/tiled-gallery',
475            'jetpack/slideshow',
476            'jetpack/story',
477        );
478
479        while ( $scanner->next_delimiter() ) {
480            $type = $scanner->get_delimiter_type();
481            // Only process opening delimiters for supported block types.
482            if ( Block_Scanner::OPENER !== $type ) {
483                continue;
484            }
485
486            $block_type         = $scanner->get_block_type();
487            $is_supported_block = in_array( $block_type, $supported_blocks, true );
488            if ( ! $is_supported_block ) {
489                continue;
490            }
491
492            $attributes   = $scanner->allocate_and_return_parsed_attributes() ?? array();
493            $block_images = self::get_images_from_block_attributes( $block_type, $attributes, $html_info, $width, $height );
494
495            if ( ! empty( $block_images ) ) {
496                $images = array_merge( $images, $block_images );
497            }
498        }
499
500        /**
501         * Returning a filtered array because get_attachment_data returns false
502         * for unsuccessful attempts.
503         */
504        return array_filter( $images );
505    }
506
507    /**
508     * Extract images from block attributes based on block type.
509     *
510     * @since jetpack-14.8
511     *
512     * @param string $block_type Block type name.
513     * @param array  $attributes Block attributes.
514     * @param array  $html_info  Info about the post where the block is found.
515     * @param int    $width      Desired image width.
516     * @param int    $height     Desired image height.
517     *
518     * @return array Array of images found.
519     */
520    private static function get_images_from_block_attributes( $block_type, $attributes, $html_info, $width, $height ) {
521        $images = array();
522
523        // Skip blocks marked with the jetpack-ignore-thumbnail CSS class
524        // (set via the block editor's "Advanced > Additional CSS class" panel).
525        $class_name = $attributes['className'] ?? '';
526        if ( str_contains( $class_name, 'jetpack-ignore-thumbnail' ) ) {
527            return $images;
528        }
529
530        switch ( $block_type ) {
531            case 'core/image':
532            case 'core/media-text':
533                $id_key = 'core/image' === $block_type ? 'id' : 'mediaId';
534                if ( ! empty( $attributes[ $id_key ] ) ) {
535                    $image = self::get_attachment_data( $attributes[ $id_key ], $html_info['post_url'], $width, $height );
536                    if ( false !== $image ) {
537                        /** This filter is documented in class-images.php */
538                        if ( apply_filters( 'jetpack_postimages_exclude_image', false, $image ) ) {
539                            break;
540                        }
541                        $images[] = $image;
542                    }
543                }
544                break;
545
546            case 'core/gallery':
547            case 'jetpack/tiled-gallery':
548            case 'jetpack/slideshow':
549                if ( ! empty( $attributes['ids'] ) && is_array( $attributes['ids'] ) ) {
550                    foreach ( $attributes['ids'] as $img_id ) {
551                        $image = self::get_attachment_data( $img_id, $html_info['post_url'], $width, $height );
552                        if ( false !== $image ) {
553                            /** This filter is documented in class-images.php */
554                            if ( apply_filters( 'jetpack_postimages_exclude_image', false, $image ) ) {
555                                continue;
556                            }
557                            $images[] = $image;
558                        }
559                    }
560                }
561                break;
562
563            case 'jetpack/story':
564                if ( ! empty( $attributes['mediaFiles'] ) && is_array( $attributes['mediaFiles'] ) ) {
565                    foreach ( $attributes['mediaFiles'] as $media_file ) {
566                        if ( ! empty( $media_file['id'] ) ) {
567                            $image = self::get_attachment_data( $media_file['id'], $html_info['post_url'], $width, $height );
568                            if ( false !== $image ) {
569                                /** This filter is documented in class-images.php */
570                                if ( apply_filters( 'jetpack_postimages_exclude_image', false, $image ) ) {
571                                    continue;
572                                }
573                                $images[] = $image;
574                            }
575                        }
576                    }
577                }
578                break;
579        }
580
581        return $images;
582    }
583
584    /**
585     * Very raw -- just parse the HTML and pull out any/all img tags and return their src
586     *
587     * @param mixed $html_or_id The HTML string to parse for images, or a post id.
588     * @param int   $width      Minimum Image width.
589     * @param int   $height     Minimum Image height.
590     *
591     * @uses DOMDocument
592     *
593     * @return array containing images
594     */
595    public static function from_html( $html_or_id, $width = 200, $height = 200 ) {
596        $images = array();
597
598        $html_info = self::get_post_html( $html_or_id );
599
600        if ( empty( $html_info['html'] ) ) {
601            return $images;
602        }
603
604        // Do not go any further if DOMDocument is disabled on the server.
605        if ( ! class_exists( 'DOMDocument' ) ) {
606            return $images;
607        }
608
609        // Let's grab all image tags from the HTML.
610        $dom_doc = new \DOMDocument();
611
612        // DOMDocument defaults to ISO-8859 because we're loading only the post content, without head tag.
613        // Fix: Enforce encoding with meta tag.
614        $charset = get_option( 'blog_charset' );
615        if ( empty( $charset ) || ! preg_match( '/^[a-zA-Z0-9_-]+$/', $charset ) ) {
616            $charset = 'UTF-8';
617        }
618        $html_prefix = sprintf( '<meta http-equiv="Content-Type" content="text/html; charset=%s">', esc_attr( $charset ) );
619
620        // The @ is not enough to suppress errors when dealing with libxml,
621        // we have to tell it directly how we want to handle errors.
622        libxml_use_internal_errors( true );
623        @$dom_doc->loadHTML( $html_prefix . $html_info['html'] ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
624        libxml_use_internal_errors( false );
625
626        $image_tags = $dom_doc->getElementsByTagName( 'img' );
627
628        // For each image Tag, make sure it can be added to the $images array, and add it.
629        foreach ( $image_tags as $image_tag ) {
630            $img_src = $image_tag->getAttribute( 'src' );
631
632            if ( empty( $img_src ) ) {
633                continue;
634            }
635
636            // Do not grab smiley images that were automatically created by WP when entering text smilies.
637            if ( stripos( $img_src, '/smilies/' ) ) {
638                continue;
639            }
640
641            // Do not grab Gravatar images.
642            if ( stripos( $img_src, 'gravatar.com' ) ) {
643                continue;
644            }
645
646            // Allow users to exclude images by adding a CSS class to the img tag.
647            if ( str_contains( $image_tag->getAttribute( 'class' ) ?? '', 'jetpack-ignore-thumbnail' ) ) {
648                continue;
649            }
650
651            // 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
652            $width  = (int) $image_tag->getAttribute( 'width' );
653            $height = (int) $image_tag->getAttribute( 'height' );
654            if ( 0 === $width && 0 === $height ) {
655                preg_match( '/-([0-9]{1,5})x([0-9]{1,5})\.(?:jpg|jpeg|png|gif|webp)$/i', $img_src, $matches );
656                if ( ! empty( $matches[1] ) ) {
657                    $width = (int) $matches[1];
658                }
659                if ( ! empty( $matches[2] ) ) {
660                    $height = (int) $matches[2];
661                }
662            }
663            // If width and height are still 0, try to get the id of the image from the class, e.g. wp-image-1234
664            if ( 0 === $width && 0 === $height ) {
665
666                preg_match( '/wp-image-([0-9]+)/', $image_tag->getAttribute( 'class' ), $matches );
667                if ( ! empty( $matches[1] ) ) {
668                    $attachment_id = (int) $matches[1];
669                    $meta          = wp_get_attachment_metadata( $attachment_id );
670                    $height        = $meta['height'] ?? 0;
671                    $width         = $meta['width'] ?? 0;
672                }
673            }
674
675            $meta = array(
676                'width'    => $width,
677                'height'   => $height,
678                'alt_text' => $image_tag->getAttribute( 'alt' ),
679            );
680
681            /**
682             * Filters the switch to ignore minimum image size requirements. Can be used
683             * to add custom logic to image dimensions, like only enforcing one of the dimensions,
684             * or disabling it entirely.
685             *
686             * @since jetpack-6.4.0
687             *
688             * @param bool $ignore Should the image dimensions be ignored?
689             * @param array $meta Array containing image dimensions parsed from the markup.
690             */
691            $ignore_dimensions = apply_filters( 'jetpack_postimages_ignore_minimum_dimensions', false, $meta );
692
693            // Must be larger than 200x200 (or user-specified).
694            if (
695                ! $ignore_dimensions
696                && (
697                    empty( $meta['width'] )
698                    || empty( $meta['height'] )
699                    || $meta['width'] < $width
700                    || $meta['height'] < $height
701                )
702            ) {
703                continue;
704            }
705
706            $image = array(
707                'type'       => 'image',
708                'from'       => 'html',
709                'src'        => $img_src,
710                'src_width'  => $meta['width'],
711                'src_height' => $meta['height'],
712                'href'       => $html_info['post_url'],
713            );
714            if ( ! empty( $meta['alt_text'] ) ) {
715                $image['alt_text'] = $meta['alt_text'];
716            }
717
718            /**
719             * Filters whether to exclude a specific image from post image discovery.
720             *
721             * This filter runs inside the Images class, which powers image selection
722             * for Related Posts, Open Graph tags, and other features. Returning a truthy
723             * value causes the image to be skipped.
724             *
725             * @since 0.1.0
726             *
727             * @param bool  $exclude Whether to exclude the image. Default false.
728             * @param array $image   {
729             *     Image data.
730             *
731             *     @type string $type       The type of the image (always 'image').
732             *     @type string $from       The source method ('html', 'attachment', 'thumbnail', etc.).
733             *     @type string $src        The image URL.
734             *     @type int    $src_width  The image width in pixels.
735             *     @type int    $src_height The image height in pixels.
736             *     @type string $href       The permalink of the post containing the image.
737             *     @type string $alt_text   The image alt text, if available.
738             * }
739             */
740            if ( apply_filters( 'jetpack_postimages_exclude_image', false, $image ) ) {
741                continue;
742            }
743
744            $images[] = $image;
745        }
746        return $images;
747    }
748
749    /**
750     * Data from blavatar.
751     *
752     * @param    int $post_id The post ID to check.
753     * @param    int $size Size.
754     * @return array containing details of the image, or empty array if none.
755     */
756    public static function from_blavatar( $post_id, $size = 96 ) {
757
758        $permalink = get_permalink( $post_id );
759
760        if ( function_exists( 'blavatar_domain' ) && function_exists( 'blavatar_exists' ) && function_exists( 'blavatar_url' ) ) {
761            $domain = blavatar_domain( $permalink ); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists().
762
763            if ( ! blavatar_exists( $domain ) ) { // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists().
764                return array();
765            }
766
767            $url = blavatar_url( $domain, 'img', $size ); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists().
768        } else {
769            $url = get_site_icon_url( $size );
770            if ( ! $url ) {
771                return array();
772            }
773        }
774
775        return array(
776            array(
777                'type'       => 'image',
778                'from'       => 'blavatar',
779                'src'        => $url,
780                'src_width'  => $size,
781                'src_height' => $size,
782                'href'       => $permalink,
783                'alt_text'   => '',
784            ),
785        );
786    }
787
788    /**
789     * Gets a post image from the author avatar.
790     *
791     * @param int          $post_id The post ID to check.
792     * @param int          $size The size of the avatar to get.
793     * @param string|false $default The default image to use.
794     * @return array containing details of the image, or empty array if none.
795     */
796    public static function from_gravatar( $post_id, $size = 96, $default = false ) {
797        $post = get_post( $post_id );
798        if ( ! $post instanceof \WP_Post ) {
799            return array();
800        }
801
802        $permalink = get_permalink( $post_id );
803
804        if ( function_exists( 'wpcom_get_avatar_url' ) ) {
805            $url = wpcom_get_avatar_url( $post->post_author, $size, $default, true ); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists().
806            if ( $url && is_array( $url ) ) {
807                $url = $url[0];
808            }
809        } else {
810            $url = get_avatar_url(
811                $post->post_author,
812                array(
813                    'size'    => $size,
814                    'default' => $default,
815                )
816            );
817        }
818
819        return array(
820            array(
821                'type'       => 'image',
822                'from'       => 'gravatar',
823                'src'        => $url,
824                'src_width'  => $size,
825                'src_height' => $size,
826                'href'       => $permalink,
827                'alt_text'   => '',
828            ),
829        );
830    }
831
832    /**
833     * Run through the different methods that we have available to try to find a single good
834     * display image for this post.
835     *
836     * @param int   $post_id Post ID.
837     * @param array $args Other arguments (currently width and height required for images where possible to determine).
838     * @return array|null containing details of the best image to be used, or null if no image is found.
839     */
840    public static function get_image( $post_id, $args = array() ) {
841        $image = null;
842
843        /**
844         * Fires before we find a single good image for a specific post.
845         *
846         * @since jetpack-2.2.0
847         *
848         * @param int $post_id Post ID.
849         */
850        do_action( 'jetpack_postimages_pre_get_image', $post_id );
851        $media = self::get_images( $post_id, $args );
852
853        if ( is_array( $media ) ) {
854            foreach ( $media as $item ) {
855                if ( 'image' === $item['type'] ) {
856                    $image = $item;
857                    break;
858                }
859            }
860        }
861
862        /**
863         * Fires after we find a single good image for a specific post.
864         *
865         * @since jetpack-2.2.0
866         *
867         * @param int $post_id Post ID.
868         */
869        do_action( 'jetpack_postimages_post_get_image', $post_id );
870
871        return $image;
872    }
873
874    /**
875     * Get an array containing a collection of possible images for this post, stopping once we hit a method
876     * that returns something useful.
877     *
878     * @param  int   $post_id Post ID.
879     * @param  array $args Optional args, see defaults list for details.
880     * @return array containing images that would be good for representing this post
881     */
882    public static function get_images( $post_id, $args = array() ) {
883        // Figure out which image to attach to this post.
884        $media = array();
885
886        /**
887         * Filters the array of images that would be good for a specific post.
888         * This filter is applied before options ($args) filter the original array.
889         *
890         * @since jetpack-2.0.0
891         *
892         * @param array $media Array of images that would be good for a specific post.
893         * @param int $post_id Post ID.
894         * @param array $args Array of options to get images.
895         */
896        $media = apply_filters( 'jetpack_images_pre_get_images', $media, $post_id, $args );
897        if ( $media ) {
898            return $media;
899        }
900
901        $defaults = array(
902            'width'               => 200, // Required minimum width (if possible to determine).
903            'height'              => 200, // Required minimum height (if possible to determine).
904
905            'fallback_to_avatars' => false, // Optionally include Blavatar and Gravatar (in that order) in the image stack.
906            'avatar_size'         => 96, // Used for both Grav and Blav.
907            'gravatar_default'    => false, // Default image to use if we end up with no Gravatar.
908
909            'from_thumbnail'      => true, // Use these flags to specify which methods to use to find an image.
910            'from_slideshow'      => true,
911            'from_gallery'        => true,
912            'from_attachment'     => true,
913            'from_blocks'         => true,
914            'from_html'           => true,
915
916            'html_content'        => '', // HTML string to pass to from_html().
917        );
918        $args     = wp_parse_args( $args, $defaults );
919
920        $media = array();
921        if ( $args['from_thumbnail'] ) {
922            $media = self::from_thumbnail( $post_id, $args['width'], $args['height'] );
923        }
924        if ( ! $media && $args['from_slideshow'] ) {
925            $media = self::from_slideshow( $post_id, $args['width'], $args['height'] );
926        }
927        if ( ! $media && $args['from_gallery'] ) {
928            $media = self::from_gallery( $post_id );
929        }
930        if ( ! $media && $args['from_attachment'] ) {
931            $media = self::from_attachment( $post_id, $args['width'], $args['height'] );
932        }
933        if ( ! $media && $args['from_blocks'] ) {
934            if ( empty( $args['html_content'] ) ) {
935                $media = self::from_blocks( $post_id, $args['width'], $args['height'] ); // Use the post_id, which will load the content.
936            } else {
937                $media = self::from_blocks( $args['html_content'], $args['width'], $args['height'] ); // If html_content is provided, use that.
938            }
939        }
940        if ( ! $media && $args['from_html'] ) {
941            if ( empty( $args['html_content'] ) ) {
942                $media = self::from_html( $post_id, $args['width'], $args['height'] ); // Use the post_id, which will load the content.
943            } else {
944                $media = self::from_html( $args['html_content'], $args['width'], $args['height'] ); // If html_content is provided, use that.
945            }
946        }
947
948        if ( ! $media && $args['fallback_to_avatars'] ) {
949            $media = self::from_blavatar( $post_id, $args['avatar_size'] );
950            if ( ! $media ) {
951                $media = self::from_gravatar( $post_id, $args['avatar_size'], $args['gravatar_default'] );
952            }
953        }
954
955        /**
956         * Filters the array of images that would be good for a specific post.
957         * This filter is applied after options ($args) filter the original array.
958         *
959         * @since jetpack-2.0.0
960         *
961         * @param array $media Array of images that would be good for a specific post.
962         * @param int $post_id Post ID.
963         * @param array $args Array of options to get images.
964         */
965        return apply_filters( 'jetpack_images_get_images', $media, $post_id, $args );
966    }
967
968    /**
969     * Takes an image and base pixel dimensions and returns a srcset for the
970     * resized and cropped images, based on a fixed set of multipliers.
971     *
972     * @param  array $image Array containing details of the image.
973     * @param  int   $base_width Base image width (i.e., the width at 1x).
974     * @param  int   $base_height Base image height (i.e., the height at 1x).
975     * @param  bool  $use_widths Whether to generate the srcset with widths instead of multipliers.
976     * @return string The srcset for the image.
977     */
978    public static function generate_cropped_srcset( $image, $base_width, $base_height, $use_widths = false ) {
979        $srcset = '';
980
981        if ( ! is_array( $image ) || empty( $image['src'] ) || empty( $image['src_width'] ) ) {
982            return $srcset;
983        }
984
985        $multipliers   = array( 1, 1.5, 2, 3, 4 );
986        $srcset_values = array();
987        foreach ( $multipliers as $multiplier ) {
988            $srcset_width  = (int) ( $base_width * $multiplier );
989            $srcset_height = (int) ( $base_height * $multiplier );
990            if ( $srcset_width < 1 || $srcset_width > $image['src_width'] ) {
991                break;
992            }
993
994            $srcset_url = self::fit_image_url(
995                $image['src'],
996                $srcset_width,
997                $srcset_height
998            );
999
1000            if ( $use_widths ) {
1001                $srcset_values[] = "{$srcset_url} {$srcset_width}w";
1002            } else {
1003                $srcset_values[] = "{$srcset_url} {$multiplier}x";
1004            }
1005        }
1006
1007        if ( count( $srcset_values ) > 1 ) {
1008            $srcset = implode( ', ', $srcset_values );
1009        }
1010
1011        return $srcset;
1012    }
1013
1014    /**
1015     * Takes an image URL and pixel dimensions then returns a URL for the
1016     * resized and cropped image.
1017     *
1018     * @param  string $src Image URL.
1019     * @param  int    $width Image width.
1020     * @param  int    $height Image height.
1021     * @return string Transformed image URL
1022     */
1023    public static function fit_image_url( $src, $width, $height ) {
1024        $width  = (int) $width;
1025        $height = (int) $height;
1026
1027        if ( $width < 1 || $height < 1 ) {
1028            return $src;
1029        }
1030
1031        // See if we should bypass WordPress.com SaaS resizing.
1032        if ( has_filter( 'jetpack_images_fit_image_url_override' ) ) {
1033            /**
1034             * Filters the image URL used after dimensions are set by Photon.
1035             *
1036             * @since jetpack-3.3.0
1037             *
1038             * @param string $src Image URL.
1039             * @param int $width Image width.
1040             * @param int $width Image height.
1041             */
1042            return apply_filters( 'jetpack_images_fit_image_url_override', $src, $width, $height );
1043        }
1044
1045        // If WPCOM hosted image use native transformations.
1046        $img_host = wp_parse_url( $src, PHP_URL_HOST );
1047        if ( $img_host && str_ends_with( $img_host, '.files.wordpress.com' ) ) {
1048            return add_query_arg(
1049                array(
1050                    'w'    => $width,
1051                    'h'    => $height,
1052                    'crop' => 1,
1053                ),
1054                set_url_scheme( $src )
1055            );
1056        }
1057
1058        // Use image cdn magic.
1059        if ( class_exists( Image_CDN_Core::class ) && method_exists( Image_CDN_Core::class, 'cdn_url' ) ) {
1060            return Image_CDN_Core::cdn_url( $src, array( 'resize' => "$width,$height" ) );
1061        }
1062
1063        // Arg... no way to resize image using WordPress.com infrastructure!
1064        return $src;
1065    }
1066
1067    /**
1068     * Get HTML from given post content.
1069     *
1070     * @since jetpack-6.9.0
1071     *
1072     * @param mixed $html_or_id The HTML string to parse for images, or a post id.
1073     *
1074     * @return array $html_info {
1075     * @type string $html     Post content.
1076     * @type string $post_url Post URL.
1077     * }
1078     */
1079    public static function get_post_html( $html_or_id ) {
1080        if ( is_numeric( $html_or_id ) ) {
1081            $post = get_post( $html_or_id );
1082            if ( ! $post instanceof \WP_Post || ! empty( $post->post_password ) ) {
1083                return array();
1084            }
1085
1086            $html_info = array(
1087                'html'     => $post->post_content, // DO NOT apply the_content filters here, it will cause loops.
1088                'post_url' => get_permalink( $post->ID ),
1089            );
1090        } else {
1091            $html_info = array(
1092                'html'     => $html_or_id,
1093                'post_url' => '',
1094            );
1095        }
1096        return $html_info;
1097    }
1098
1099    /**
1100     * Get info about a WordPress attachment.
1101     *
1102     * @since jetpack-6.9.0
1103     *
1104     * @param int    $attachment_id Attachment ID.
1105     * @param string $post_url      URL of the post, if we have one.
1106     * @param int    $width         Minimum Image width.
1107     * @param int    $height        Minimum Image height.
1108     * @return array|bool           Image data or false if unavailable.
1109     */
1110    public static function get_attachment_data( $attachment_id, $post_url, $width, $height ) {
1111        if ( empty( $attachment_id ) ) {
1112            return false;
1113        }
1114
1115        $meta = wp_get_attachment_metadata( $attachment_id );
1116
1117        if ( empty( $meta ) ) {
1118            return false;
1119        }
1120
1121        if ( ! empty( $meta['videopress'] ) ) {
1122            // Use poster image for VideoPress videos.
1123            $url         = $meta['videopress']['poster'];
1124            $meta_width  = $meta['videopress']['width'];
1125            $meta_height = $meta['videopress']['height'];
1126        } elseif ( ! empty( $meta['thumb'] ) ) {
1127            // On WordPress.com, VideoPress videos have a 'thumb' property with the
1128            // poster image filename instead.
1129            $media_url   = wp_get_attachment_url( $attachment_id );
1130            $url         = str_replace( wp_basename( $media_url ), $meta['thumb'], $media_url );
1131            $meta_width  = $meta['width'];
1132            $meta_height = $meta['height'];
1133        } elseif ( wp_attachment_is( 'video', $attachment_id ) ) {
1134            // We don't have thumbnail images for non-VideoPress videos - skip them.
1135            return false;
1136        } else {
1137            if ( ! isset( $meta['width'] ) || ! isset( $meta['height'] ) ) {
1138                return false;
1139            }
1140            $url         = wp_get_attachment_url( $attachment_id );
1141            $meta_width  = $meta['width'];
1142            $meta_height = $meta['height'];
1143        }
1144
1145        if ( $meta_width < $width || $meta_height < $height ) {
1146            return false;
1147        }
1148
1149        return array(
1150            'type'       => 'image',
1151            'from'       => 'attachment',
1152            'src'        => $url,
1153            'src_width'  => $meta_width,
1154            'src_height' => $meta_height,
1155            'href'       => $post_url,
1156            'alt_text'   => self::get_alt_text( $attachment_id ),
1157        );
1158    }
1159
1160    /**
1161     * Get the alt text for an image or other media from the Media Library.
1162     *
1163     * @since jetpack-7.1
1164     *
1165     * @param int $attachment_id The Post ID of the media.
1166     * @return string The alt text value or an empty string.
1167     */
1168    public static function get_alt_text( $attachment_id ) {
1169        return (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
1170    }
1171
1172    /**
1173     * Determine the size to use with Photon for a thumbnail image.
1174     * Images larger than the maximum thumbnail dimension in either dimension are resized to maintain aspect ratio.
1175     *
1176     * @since jetpack-14.6
1177     * @see https://github.com/Automattic/jetpack/issues/40349
1178     *
1179     * @param int $width Original image width.
1180     * @param int $height Original image height.
1181     * @return array Array containing the width and height to use with Photon (null means auto).
1182     */
1183    public static function determine_thumbnail_size_for_photon( $width, $height ) {
1184        $max_dimension = self::get_max_thumbnail_dimension();
1185
1186        // If neither dimension exceeds max size, return original dimensions.
1187        if ( $width <= $max_dimension && $height <= $max_dimension ) {
1188            return array(
1189                'width'  => $width,
1190                'height' => $height,
1191            );
1192        }
1193
1194        if ( $width >= $height ) {
1195            // For landscape or square images.
1196            $dims = image_resize_dimensions( $width, $height, $max_dimension, 0 ); // Height will be calculated automatically.
1197        } else {
1198            // For portrait images.
1199            $dims = image_resize_dimensions( $width, $height, 0, $max_dimension ); // Width will be calculated automatically.
1200        }
1201
1202        // $dims can be false if the image is virtually the same size as the max dimension, e.g. wp_fuzzy_number_match.
1203        if ( $dims && isset( $dims[4] ) && isset( $dims[5] ) ) {
1204            return array(
1205                'width'  => $dims[4],
1206                'height' => $dims[5],
1207            );
1208        }
1209
1210        return array(
1211            'width'  => $width,
1212            'height' => $height,
1213        );
1214    }
1215
1216    /**
1217     * Function to provide the maximum dimension for a thumbnail image.
1218     * Filterable via the `jetpack_post_images_max_dimension` filter.
1219     *
1220     * @since jetpack-14.6
1221     * @see https://github.com/Automattic/jetpack/issues/40349
1222     *
1223     * @return int The maximum dimension for a thumbnail image.
1224     */
1225    public static function get_max_thumbnail_dimension() {
1226        /**
1227         * Filter the maximum dimension allowed for a thumbnail image.
1228         * The default value is 1200 pixels.
1229         *
1230         * @since jetpack-14.6
1231         *
1232         * @param int $max_dimension Maximum dimension in pixels.
1233         */
1234        return (int) apply_filters( 'jetpack_post_images_max_thumbnail_dimension', 1200 );
1235    }
1236}