Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.38% covered (success)
94.38%
151 / 160
57.14% covered (warning)
57.14%
8 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
LCP_Optimize_Img_Tag
94.38% covered (success)
94.38%
151 / 160
57.14% covered (warning)
57.14%
8 / 14
96.61
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 optimize_buffer
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
5.02
 optimize_image
88.89% covered (warning)
88.89%
24 / 27
0.00% covered (danger)
0.00%
0 / 1
11.17
 add_missing_dimensions
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
7
 get_local_file_dimensions
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 is_attachment_size
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
12
 add_responsive_image_attributes
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
6.03
 get_object_fit
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
6
 get_marked_object_fit
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
 get_aspect_ratio
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 to_dimension
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
6
 get_srcset
94.74% covered (success)
94.74%
36 / 38
0.00% covered (danger)
0.00%
0 / 1
17.04
 reduce_widths
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
3.01
 get_sizes
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
8.09
1<?php
2
3namespace Automattic\Jetpack_Boost\Modules\Optimizations\Lcp;
4
5use Automattic\Jetpack\Image_CDN\Image_CDN;
6use Automattic\Jetpack\Image_CDN\Image_CDN_Core;
7use Automattic\Jetpack_Boost\Lib\Minify\Dependency_Path_Mapping;
8use WP_HTML_Tag_Processor;
9
10class LCP_Optimize_Img_Tag {
11
12    /**
13     * LCP data.
14     *
15     * @var array
16     */
17    private $lcp_data;
18
19    public function __construct( $lcp_data ) {
20        $this->lcp_data = $lcp_data;
21    }
22
23    /**
24     * Optimize a viewport's LCP HTML.
25     *
26     * @param string $buffer The buffer/html to optimize.
27     * @return string The optimized buffer, or the original buffer if no optimization was needed
28     *
29     * @since 4.0.0
30     */
31    public function optimize_buffer( $buffer ) {
32        $optimization_util = new LCP_Optimization_Util( $this->lcp_data );
33        if ( ! $optimization_util->can_optimize() ) {
34            return $buffer;
35        }
36
37        // Defensive check to ensure the LCP HTML is not empty.
38        if ( empty( $this->lcp_data['html'] ) ) {
39            return $buffer;
40        }
41
42        // Only optimize if the type is one we know how to handle.
43        if ( $this->lcp_data['type'] !== LCP::TYPE_IMAGE ) {
44            return $buffer;
45        }
46
47        $buffer_processor = $optimization_util->find_element( $buffer );
48        if ( ! $buffer_processor ) {
49            return $buffer;
50        }
51
52        // Create the optimized tag with required attributes.
53        return $this->optimize_image( $buffer_processor );
54    }
55
56    /**
57     * Optimize an image tag by adding required attributes.
58     *
59     * @param WP_HTML_Tag_Processor $buffer_processor The original HTML chunk of the page..
60     *
61     * @return string The optimized buffer.
62     *
63     * @since 4.0.0
64     */
65    private function optimize_image( $buffer_processor ) {
66        // Check optimizations object for fetchpriority.
67        // If no optimizations object exists (old cloud response), default to applying.
68        $apply_fetchpriority = LCP_Optimization_Util::should_apply_optimization( $this->lcp_data, 'fetchpriority' );
69
70        if ( $apply_fetchpriority ) {
71            $buffer_processor->set_attribute( 'fetchpriority', 'high' );
72        }
73
74        // Check optimizations object for loading.
75        $apply_loading = LCP_Optimization_Util::should_apply_optimization( $this->lcp_data, 'loading' );
76
77        if ( $apply_loading ) {
78            $buffer_processor->set_attribute( 'loading', 'eager' );
79        }
80
81        $buffer_processor->set_attribute( 'data-jp-lcp-optimized', 'true' );
82
83        $image_url = $buffer_processor->get_attribute( 'src' );
84        // Ensure the image URL is valid.
85        if ( ! wp_http_validate_url( $image_url ) ) {
86            return $buffer_processor->get_updated_html();
87        }
88
89        $resized_src = '';
90
91        // If the image isn't photonized, it might be resized by WP.
92        // We need the original image URL, as we'll be generating
93        // the necessary sizes based on it.
94        if ( ! Image_CDN_Core::is_cdn_url( $image_url ) ) {
95            $original_src = (string) $image_url;
96            $image_url    = Image_CDN::strip_image_dimensions_maybe( $original_src );
97
98            // Its -WxH suffix names a WordPress size if stripping found the original, or the attachment lists it.
99            if ( $image_url !== $original_src || $this->is_attachment_size( $buffer_processor, $original_src ) ) {
100                $resized_src = $original_src;
101            }
102
103            $this->add_missing_dimensions( $buffer_processor, $original_src, $resized_src );
104        } else {
105            // In case it's Photonized, we need to remove any size change arguments.
106            $image_url = remove_query_arg( array( 'w', 'h' ), $image_url );
107        }
108
109        // Additional validation after cleaning.
110        if ( ! wp_http_validate_url( $image_url ) ) {
111            return $buffer_processor->get_updated_html();
112        }
113
114        // Check optimizations object for cdnUrl.
115        $apply_cdn = LCP_Optimization_Util::should_apply_optimization( $this->lcp_data, 'cdnUrl' );
116
117        if ( $apply_cdn ) {
118            $buffer_processor->set_attribute( 'src', Image_CDN_Core::cdn_url( $image_url ) );
119        }
120
121        // Check optimizations object for srcset.
122        // The cloud sets srcset to false when custom focal points are detected
123        // (resize would use center-crop, losing the author's object-position).
124        $apply_srcset = LCP_Optimization_Util::should_apply_optimization( $this->lcp_data, 'srcset' );
125
126        // srcset uses CDN URLs internally (via Image_CDN_Core::cdn_url), so skip if CDN is disabled.
127        if ( $apply_srcset && $apply_cdn ) {
128            $this->add_responsive_image_attributes( $buffer_processor, $image_url, $resized_src );
129        }
130
131        return $buffer_processor->get_updated_html();
132    }
133
134    /**
135     * Give an image with neither width nor height its file's dimensions, so the browser reserves its space.
136     *
137     * @param WP_HTML_Tag_Processor $element     The image tag.
138     * @param string                $src         The image src, before any CDN rewrite.
139     * @param string                $resized_src The src, if its -WxH suffix names a WordPress size.
140     */
141    private function add_missing_dimensions( $element, $src, $resized_src ) {
142        if ( null !== $element->get_attribute( 'width' ) || null !== $element->get_attribute( 'height' ) ) {
143            return;
144        }
145
146        list( $width, $height ) = Image_CDN::parse_dimensions_from_filename( (string) $resized_src );
147        if ( ! $width || ! $height ) {
148            list( $width, $height ) = $this->get_local_file_dimensions( $src );
149        }
150
151        $width  = $this->to_dimension( $width );
152        $height = $this->to_dimension( $height );
153        if ( $width && $height ) {
154            $element->set_attribute( 'width', (string) $width );
155            $element->set_attribute( 'height', (string) $height );
156        }
157    }
158
159    /**
160     * Read the pixel size of an image served from this site.
161     *
162     * @param string $url The image URL.
163     * @return array Width and height, or nulls when the URL is not a readable local image.
164     */
165    private function get_local_file_dimensions( $url ) {
166        $file = ( new Dependency_Path_Mapping() )->dependency_src_to_fs_path( $url );
167        $size = $file ? wp_getimagesize( $file ) : false;
168
169        return is_array( $size ) ? array( (int) $size[0], (int) $size[1] ) : array( null, null );
170    }
171
172    /**
173     * Whether the image's attachment lists the src's file as one of its sizes, as when the
174     * original is offloaded or deleted and there is no file on disk to confirm it.
175     *
176     * @param WP_HTML_Tag_Processor $element The image tag.
177     * @param string                $src     The image src.
178     * @return bool
179     */
180    private function is_attachment_size( $element, $src ) {
181        list( $width ) = Image_CDN::parse_dimensions_from_filename( $src );
182        if ( ! $width ) {
183            return false;
184        }
185
186        $attachment_id = 0;
187        foreach ( $element->class_list() ?? array() as $class_name ) {
188            if ( preg_match( '/^wp-image-([1-9][0-9]*)$/', $class_name, $matches ) ) {
189                $attachment_id = (int) $matches[1];
190                break;
191            }
192        }
193
194        $meta = $attachment_id ? wp_get_attachment_metadata( $attachment_id ) : false;
195        if ( ! is_array( $meta ) || empty( $meta['sizes'] ) || ! is_array( $meta['sizes'] ) ) {
196            return false;
197        }
198
199        $file = rawurldecode( wp_basename( (string) wp_parse_url( $src, PHP_URL_PATH ) ) );
200        foreach ( $meta['sizes'] as $size ) {
201            if ( is_array( $size ) && isset( $size['file'] ) && $size['file'] === $file ) {
202                return true;
203            }
204        }
205
206        return false;
207    }
208
209    /**
210     * Optimize an image tag by adding srcset and sizes attributes.
211     *
212     * @param WP_HTML_Tag_Processor $element The original image tag.
213     * @param string                $image_url The image URL.
214     * @param string                $resized_src The src, if its -WxH suffix names a WordPress size.
215     * @return WP_HTML_Tag_Processor The optimized image tag.
216     *
217     * @since 4.0.0
218     */
219    private function add_responsive_image_attributes( $element, $image_url, $resized_src = '' ) {
220        // is_array() as well as empty(): empty( 'not-an-array' ) is false, so a string
221        // breakpoints field would reach the foreach in get_srcset() and get_sizes().
222        if ( empty( $this->lcp_data['breakpoints'] ) || ! is_array( $this->lcp_data['breakpoints'] ) ) {
223            return $element;
224        }
225
226        $object_fit = $this->get_object_fit( $element );
227
228        // Under cover, a file cropped to the box shows the same picture and is smaller.
229        $aspect_ratio = 'cover' === $object_fit ? null : $this->get_aspect_ratio( $element, $resized_src );
230
231        $srcset = $this->get_srcset( $image_url, $aspect_ratio, 'contain' === $object_fit );
232        if ( ! empty( $srcset ) ) {
233            $element->set_attribute( 'srcset', $srcset );
234        }
235
236        $sizes = $this->get_sizes();
237        if ( ! empty( $sizes ) ) {
238            $element->set_attribute( 'sizes', $sizes );
239        }
240
241        return $element;
242    }
243
244    /**
245     * Get the image's object-fit: the computed one the cloud reports, which sees stylesheets too,
246     * else the one the markup sets, for reports from before the cloud sent it.
247     *
248     * @param WP_HTML_Tag_Processor $element The image tag.
249     * @return string|null 'cover', 'contain', or null for any other fit.
250     */
251    private function get_object_fit( $element ) {
252        $fit = $this->get_marked_object_fit( $element );
253
254        if ( isset( $this->lcp_data['objectFit'] ) && is_string( $this->lcp_data['objectFit'] ) ) {
255            $reported = strtolower( $this->lcp_data['objectFit'] );
256
257            // A template save doesn't redo the analysis, so when the markup disagrees, assume no fit: it never crops.
258            $fit = null === $fit || $fit === $reported ? $reported : null;
259        }
260
261        return in_array( $fit, array( 'cover', 'contain' ), true ) ? $fit : null;
262    }
263
264    /**
265     * Get the object-fit the markup sets, as core's Featured Image (inline style) and Cover
266     * (data-object-fit) blocks do.
267     *
268     * @param WP_HTML_Tag_Processor $element The image tag.
269     * @return string|null The fit, lowercased, or null if the markup sets none.
270     */
271    private function get_marked_object_fit( $element ) {
272        // Inline style first: its last !important declaration, else its last, as CSS applies them.
273        $style = $element->get_attribute( 'style' );
274        if ( is_string( $style ) && preg_match_all( '/(?:^|;)\s*object-fit\s*:\s*([a-z-]+)\s*(!important\s*)?(?=;|$)/i', $style, $matches ) ) {
275            $important = array_filter( $matches[2] );
276            $fits      = $important ? array_intersect_key( $matches[1], $important ) : $matches[1];
277            return strtolower( end( $fits ) );
278        }
279
280        if ( 'cover' === $element->get_attribute( 'data-object-fit' ) ) {
281            return 'cover';
282        }
283
284        return null;
285    }
286
287    /**
288     * Get the aspect ratio of the file the page asked for.
289     *
290     * @param WP_HTML_Tag_Processor $element     The image tag.
291     * @param string                $resized_src The src, if its -WxH suffix names a WordPress size.
292     * @return float|null Width divided by height, or null if neither source gives both.
293     */
294    private function get_aspect_ratio( $element, $resized_src ) {
295        // The size's -WxH suffix first: the attributes can describe a different size than the file.
296        list( $width, $height ) = Image_CDN::parse_dimensions_from_filename( (string) $resized_src );
297        if ( ! $width || ! $height ) {
298            $width  = $element->get_attribute( 'width' );
299            $height = $element->get_attribute( 'height' );
300        }
301
302        $width  = $this->to_dimension( $width );
303        $height = $this->to_dimension( $height );
304
305        return $width && $height ? $width / $height : null;
306    }
307
308    /**
309     * Read a pixel size, as digits only like Image CDN does.
310     *
311     * @param mixed $value An attribute or filename value.
312     * @return int|null The size, or null if it is not a whole number from 1 to 65535.
313     */
314    private function to_dimension( $value ) {
315        if ( is_int( $value ) ) {
316            $value = (string) $value;
317        }
318
319        // The cap keeps the widened sizes below in int range.
320        if ( ! is_string( $value ) || ! ctype_digit( $value ) || (int) $value < 1 || (int) $value > 65535 ) {
321            return null;
322        }
323
324        return (int) $value;
325    }
326
327    /**
328     * Get the srcsets for an image.
329     *
330     * @param string     $original_url The original image URL.
331     * @param float|null $aspect_ratio The image's width divided by its height, if known.
332     * @param bool       $fit_inside   Whether the image is drawn inside the box (object-fit: contain).
333     * @return string The srcset for the image.
334     *
335     * @since 4.1.0
336     */
337    private function get_srcset( $original_url, $aspect_ratio = null, $fit_inside = false ) {
338        $dimensions = array();
339        foreach ( $this->lcp_data['breakpoints'] as $breakpoint ) {
340            // The field is optional; the background-image sibling has always carried
341            // this guard, and without it an absent one is a foreach() TypeError on
342            // wp_head.
343            if ( empty( $breakpoint['imageDimensions'] ) || ! is_array( $breakpoint['imageDimensions'] ) ) {
344                continue;
345            }
346
347            foreach ( $breakpoint['imageDimensions'] as $breakpoint_dimensions ) {
348                if ( ! is_array( $breakpoint_dimensions ) ) {
349                    continue;
350                }
351
352                // isset() as well as is_numeric(): is_numeric( $absent ) is an undefined
353                // key warning before it is false.
354                if ( ! isset( $breakpoint_dimensions['width'] ) || ! isset( $breakpoint_dimensions['height'] ) ) {
355                    continue;
356                }
357
358                if ( ! is_numeric( $breakpoint_dimensions['width'] ) || ! is_numeric( $breakpoint_dimensions['height'] ) ) {
359                    continue;
360                }
361
362                $width  = (int) $breakpoint_dimensions['width'];
363                $height = (int) $breakpoint_dimensions['height'];
364
365                // Resize to the image's own proportions, covering the box or fitting inside it: a box
366                // shaped differently would otherwise be cropped into the file, where CSS cannot undo it.
367                $file_width  = $width;
368                $file_height = $height;
369                if ( $aspect_ratio ) {
370                    $width_at_box_height = (int) ceil( $height * $aspect_ratio );
371
372                    $file_width  = $fit_inside ? min( $width, $width_at_box_height ) : max( $width, $width_at_box_height );
373                    $file_height = (int) round( $file_width / $aspect_ratio );
374                }
375
376                // Keyed by the box width, not the file's: the w descriptors must match `sizes`,
377                // or object-fit: cover draws the widened file at a lower density than the DPR.
378                $add = function ( $dpr ) use ( &$dimensions, $width, $file_width, $file_height ) {
379                    $dimensions[ (int) round( $width * $dpr ) ] = array( (int) round( $file_width * $dpr ), (int) round( $file_height * $dpr ) );
380                };
381
382                $add( 1 );
383
384                // If it's a Moto G Power, include a 1.75 DPR for accurate lighthouse representation of the optimized image.
385                if ( isset( $breakpoint['maxWidth'] ) && $breakpoint['maxWidth'] === 412 ) {
386                    $add( 1.75 );
387                }
388
389                // Include 2x DPR.
390                $add( 2 );
391
392                // If it's a mobile breakpoint, include 3x DPR.
393                if ( isset( $breakpoint['maxWidth'] ) && $breakpoint['maxWidth'] <= 480 ) {
394                    $add( 3 );
395                }
396            }
397        }
398
399        // Remove unnecessary widths to save some bytes in the HTML.
400        $reduced_widths = $this->reduce_widths( array_keys( $dimensions ) );
401
402        $srcset = array();
403        foreach ( $reduced_widths as $width ) {
404            $srcset[] = Image_CDN_Core::cdn_url(
405                $original_url,
406                array(
407                    'resize' => $dimensions[ $width ],
408                )
409            ) . " {$width}w";
410        }
411
412        return implode( ', ', $srcset );
413    }
414
415    /**
416     * Remove any width if we have another higher width that is within 20px.
417     *
418     * @param array $widths The widths to reduce.
419     * @return array The reduced widths.
420     */
421    private function reduce_widths( $widths ) {
422        rsort( $widths );
423        $reduced_widths = array();
424        $previous_width = 999999;
425        foreach ( $widths as $width ) {
426            if ( $previous_width - 20 < $width ) {
427                continue;
428            }
429
430            $previous_width   = $width;
431            $reduced_widths[] = $width;
432        }
433        return $reduced_widths;
434    }
435
436    /**
437     * Get the sizes for an image.
438     *
439     * @return string The sizes for the image.
440     *
441     * @since 4.1.0
442     */
443    private function get_sizes() {
444        $sizes = array();
445        foreach ( $this->lcp_data['breakpoints'] as $breakpoint ) {
446            // is_string() as well as isset(): an array widthValue is a TypeError from
447            // preg_match(), inside the output buffer callback.
448            if ( ! isset( $breakpoint['widthValue'] ) || ! is_string( $breakpoint['widthValue'] ) || ! preg_match( '/^[0-9]+(?:\.[0-9]+)?(?:px|vw)$/', $breakpoint['widthValue'] ) ) {
449                continue;
450            }
451
452            // Make sure minWidth is valid if set.
453            if ( isset( $breakpoint['minWidth'] ) && ! is_numeric( $breakpoint['minWidth'] ) ) {
454                continue;
455            }
456
457            $min_width_query = isset( $breakpoint['minWidth'] ) ? '(min-width: ' . $breakpoint['minWidth'] . 'px) ' : '';
458
459            $sizes[] = $min_width_query . $breakpoint['widthValue'];
460        }
461
462        return implode( ', ', $sizes );
463    }
464}