Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
15.30% covered (danger)
15.30%
69 / 451
0.00% covered (danger)
0.00%
0 / 28
CRAP
0.00% covered (danger)
0.00%
0 / 1
Tiled_Gallery
15.40% covered (danger)
15.40%
69 / 448
0.00% covered (danger)
0.00%
0 / 28
14513.03
0.00% covered (danger)
0.00%
0 / 1
 register
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 render
73.02% covered (warning)
73.02%
46 / 63
0.00% covered (danger)
0.00%
0 / 1
27.86
 get_source_file_dimensions
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 interactive_markup
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 is_squareish_layout
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 render_email
92.00% covered (success)
92.00%
23 / 25
0.00% covered (danger)
0.00%
0 / 1
9.04
 get_email_target_width
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
42
 process_tiled_gallery_images_for_email
0.00% covered (danger)
0.00%
0 / 50
0.00% covered (danger)
0.00%
0 / 1
600
 is_resizable_image_url
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 get_layout_style_from_attributes
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
132
 build_email_layout_content
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
42
 build_square_layout_content
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
12
 build_columns_layout_content
0.00% covered (danger)
0.00%
0 / 42
0.00% covered (danger)
0.00%
0 / 1
56
 build_mosaic_layout_content
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
12
 get_mosaic_row_image_sizes
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 get_image_ratio
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 has_known_dimensions
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 get_image_size
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 split_width
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 get_cell_width_percent
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 generate_mosaic_rows
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 group_mosaic_rows
0.00% covered (danger)
0.00%
0 / 37
0.00% covered (danger)
0.00%
0 / 1
72
 generate_column_mosaic_rows
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
72
 generate_border_radius_style
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 generate_image_styles
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 generate_image_html
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
30
 get_image_link_href
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
56
 create_hierarchical_chunks
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
1<?php //phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * Tiled Gallery block.
4 * Relies on Photon, but can be used even when the module is not active.
5 *
6 * @since 6.9.0
7 *
8 * @package automattic/jetpack
9 */
10
11namespace Automattic\Jetpack\Extensions;
12
13use Automattic\Jetpack\Blocks;
14use Automattic\Jetpack\Image_CDN\Image_CDN_Core;
15use Automattic\Jetpack\Status;
16use Automattic\Jetpack\Status\Host;
17use Jetpack;
18use Jetpack_Gutenberg;
19
20if ( ! defined( 'ABSPATH' ) ) {
21    exit( 0 );
22}
23
24/**
25 * Jetpack Tiled Gallery Block class
26 *
27 * @since 7.3
28 */
29class Tiled_Gallery {
30    /* Values for building srcsets */
31    const IMG_SRCSET_WIDTH_MAX  = 2000;
32    const IMG_SRCSET_WIDTH_MIN  = 600;
33    const IMG_SRCSET_WIDTH_STEP = 300;
34
35    /* Aspect ratio from which an image is a panorama, matching isPanoramic() in layout/mosaic/ratios.js */
36    const PANORAMIC_RATIO = 2;
37
38    /**
39     * Register the block
40     */
41    public static function register() {
42        if (
43            ( defined( 'IS_WPCOM' ) && IS_WPCOM )
44            || Jetpack::is_connection_ready()
45            || ( new Status() )->is_offline_mode()
46        ) {
47            Blocks::jetpack_register_block(
48                __DIR__,
49                array(
50                    'render_callback'       => array( __CLASS__, 'render' ),
51                    'render_email_callback' => array( __CLASS__, 'render_email' ),
52                )
53            );
54        }
55    }
56
57    /**
58     * Tiled gallery block registration
59     *
60     * @param array  $attr    Array containing the block attributes.
61     * @param string $content String containing the block content.
62     *
63     * @return string
64     */
65    public static function render( $attr, $content ) {
66        Jetpack_Gutenberg::load_assets_as_required( __DIR__ );
67
68        /*
69         * Note that the image host here comes from whatever the editor baked into $content when the post
70         * was last saved, so galleries published on a VIP site before the editor honoured that setting
71         * still serve unreachable i0.wp.com URLs until someone saves the post again. Rewriting the host
72         * from the data-url attribute below would fix those without an edit:
73         * https://github.com/Automattic/jetpack/issues/51075
74         */
75        $is_squareish_layout = self::is_squareish_layout( $attr );
76
77        if ( preg_match_all( '/<img [^>]+>/', $content, $images ) ) {
78            /**
79             * This block processes all of the images that are found and builds $find and $replace.
80             *
81             * The original img is added to the $find array and the replacement is made and added
82             * to the $replace array. This is so that the same find and replace operations can be
83             * made on the entire $content.
84             */
85            $find          = array();
86            $replace       = array();
87            $image_index   = 0;
88            $number_images = count( $images[0] );
89
90            foreach ( $images[0] as $image_html ) {
91                if (
92                    preg_match( '/data-width="([0-9]+)"/', $image_html, $img_width )
93                    && preg_match( '/data-height="([0-9]+)"/', $image_html, $img_height )
94                    && preg_match( '/src="([^"]+)"/', $image_html, $img_src )
95                ) {
96                    ++$image_index;
97                    // Drop img src query string so it can be used as a base to add photon params
98                    // for the srcset.
99                    $src_parts   = explode( '?', $img_src[1], 2 );
100                    $orig_src    = $src_parts[0];
101                    $orig_height = absint( $img_height[1] );
102                    $orig_width  = absint( $img_width[1] );
103
104                    // Because URLs are already "photon", the photon function used short-circuits
105                    // before ssl is added. Detect ssl and add is if necessary.
106                    $is_ssl = ! empty( $src_parts[1] ) && str_contains( $src_parts[1], 'ssl=1' );
107
108                    if ( ! $orig_width || ! $orig_height || ! $orig_src ) {
109                        continue;
110                    }
111
112                    // data-width and data-height describe the original upload, but the
113                    // candidates below are built on the src, which is usually a smaller
114                    // intermediate size. Photon never upscales, so sizing the srcset from
115                    // the original would advertise widths that resolve to a narrower image
116                    // than the browser was told to expect, and the tile renders soft on a
117                    // high density screen. Cap both to what the source file can produce.
118                    $source_dimensions = self::get_source_file_dimensions( $orig_src );
119                    if ( null !== $source_dimensions ) {
120                        $orig_width  = min( $orig_width, $source_dimensions[0] );
121                        $orig_height = min( $orig_height, $source_dimensions[1] );
122                    }
123
124                    $srcset_parts = array();
125                    if ( $is_squareish_layout ) {
126                        $min_width = min( self::IMG_SRCSET_WIDTH_MIN, $orig_width, $orig_height );
127                        $max_width = min( self::IMG_SRCSET_WIDTH_MAX, $orig_width, $orig_height );
128
129                        for ( $w = $min_width; $w <= $max_width; $w = min( $max_width, $w + self::IMG_SRCSET_WIDTH_STEP ) ) {
130                            $srcset_src = add_query_arg(
131                                array(
132                                    'resize' => $w . ',' . $w,
133                                    'strip'  => 'info',
134                                ),
135                                $orig_src
136                            );
137                            if ( $is_ssl ) {
138                                $srcset_src = add_query_arg( 'ssl', '1', $srcset_src );
139                            }
140                            $srcset_parts[] = esc_url( $srcset_src ) . ' ' . $w . 'w';
141                            if ( $w >= $max_width ) {
142                                break;
143                            }
144                        }
145                    } else {
146                        $min_width = min( self::IMG_SRCSET_WIDTH_MIN, $orig_width );
147                        $max_width = min( self::IMG_SRCSET_WIDTH_MAX, $orig_width );
148
149                        for ( $w = $min_width; $w <= $max_width; $w = min( $max_width, $w + self::IMG_SRCSET_WIDTH_STEP ) ) {
150                            $srcset_src = add_query_arg(
151                                array(
152                                    'strip' => 'info',
153                                    'w'     => $w,
154                                ),
155                                $orig_src
156                            );
157                            if ( $is_ssl ) {
158                                $srcset_src = add_query_arg( 'ssl', '1', $srcset_src );
159                            }
160                            $srcset_parts[] = esc_url( $srcset_src ) . ' ' . $w . 'w';
161                            if ( $w >= $max_width ) {
162                                break;
163                            }
164                        }
165                    }
166
167                    $img_element = self::interactive_markup( $image_index, $number_images );
168
169                    if ( ! empty( $srcset_parts ) ) {
170                        $srcset = 'srcset="' . esc_attr( implode( ',', $srcset_parts ) ) . '"';
171
172                        $find[]    = $image_html;
173                        $replace[] = str_replace( '<img', $img_element . $srcset, $image_html );
174                    }
175                }
176            }
177
178            if ( ! empty( $find ) ) {
179                $content = str_replace( $find, $replace, $content );
180            }
181        }
182
183        /**
184         * Filter the output of the Tiled Galleries content.
185         *
186         * @module tiled-gallery
187         *
188         * @since 6.9.0
189         *
190         * @param string $content Tiled Gallery block content.
191         */
192        return apply_filters( 'jetpack_tiled_galleries_block_content', $content );
193    }
194
195    /**
196     * Dimensions of the file an image URL points at, when it names a WordPress intermediate size.
197     *
198     * WordPress appends -WIDTHxHEIGHT to the file name of every size it generates, so
199     * a URL ending that way tells us how large the file behind it actually is. Returns
200     * null for anything else, including the original upload, whose size is unknowable
201     * from the URL alone.
202     *
203     * @param string $url Image URL, with any query string already removed.
204     * @return array|null Array of width and height, or null if the URL names no size.
205     */
206    private static function get_source_file_dimensions( $url ) {
207        if ( ! preg_match( '/-(\d+)x(\d+)\.[a-zA-Z0-9]+$/', $url, $dimensions ) ) {
208            return null;
209        }
210
211        return array( absint( $dimensions[1] ), absint( $dimensions[2] ) );
212    }
213
214    /**
215     * Adds tabindex, role and aria-label markup for images that should be interactive (front-end only).
216     *
217     * @param integer $image_index Integer The current image index.
218     * @param integer $number_images Integer The total number of images.
219     */
220    private static function interactive_markup( $image_index, $number_images ) {
221
222        $host             = new Host();
223        $is_module_active = $host->is_wpcom_simple()
224        ? get_option( 'carousel_enable_it' )
225        : Jetpack::is_module_active( 'carousel' );
226
227        if ( $is_module_active ) {
228            $aria_label_content = sprintf(
229                /* Translators: %1$d is the current image index, %2$d is the total number of images. */
230                __( 'Open image %1$d of %2$d in full-screen', 'jetpack' ),
231                $image_index,
232                $number_images
233            );
234            // The trailing space matters: render() appends the srcset directly onto
235            // this string, and without it the two run together as aria-label="…"srcset="…".
236            $img_element = '<img role="button" tabindex="0" aria-label="' . esc_attr( $aria_label_content ) . '" ';
237        } else {
238            $img_element = '<img ';
239        }
240        return $img_element;
241    }
242
243    /**
244     * Determines whether a Tiled Gallery block uses square or circle images (1:1 ratio)
245     *
246     * Layouts are block styles and will be available as `is-style-[LAYOUT]` in the className
247     * attribute. The default (rectangular) will be omitted.
248     *
249     * @param array $attr Attributes key/value array.
250     * @return boolean True if layout is squareish, otherwise false.
251     */
252    private static function is_squareish_layout( $attr ) {
253        return isset( $attr['className'] )
254            && (
255                'is-style-square' === $attr['className']
256                || 'is-style-circle' === $attr['className']
257            );
258    }
259
260    /**
261     * Render tiled gallery block for email.
262     *
263     * @since 15.0
264     *
265     * @param string $block_content     The original block HTML content.
266     * @param array  $parsed_block      The parsed block data including attributes.
267     * @param object $rendering_context Email rendering context.
268     *
269     * @return string
270     */
271    public static function render_email( $block_content, array $parsed_block, $rendering_context ) {
272        // Validate input parameters and required dependencies
273        if ( ! isset( $parsed_block['attrs'] ) || ! is_array( $parsed_block['attrs'] ) ||
274            ! class_exists( '\Automattic\WooCommerce\EmailEditor\Integrations\Utils\Styles_Helper' ) ||
275            ! class_exists( '\Automattic\WooCommerce\EmailEditor\Integrations\Utils\Table_Wrapper_Helper' ) ) {
276            return '';
277        }
278
279        // Get spacing from email_attrs for better consistency with core blocks
280        $email_attrs        = $parsed_block['email_attrs'] ?? array();
281        $table_margin_style = '';
282
283        if ( ! empty( $email_attrs ) && class_exists( '\WP_Style_Engine' ) ) {
284            // Get margin for table styling
285            $table_margin_style = \WP_Style_Engine::compile_css( array_intersect_key( $email_attrs, array_flip( array( 'margin' ) ) ), '' ) ?? '';
286        }
287
288        // Email cell padding
289        $email_cell_padding = 2;  // Cell padding
290
291        $attr = $parsed_block['attrs'];
292
293        // Determine layout style and columns from attributes (needed for both image processing and layout building)
294        $layout_info = self::get_layout_style_from_attributes( $attr );
295
296        // Process images for email rendering
297        $images = self::process_tiled_gallery_images_for_email( $attr, $layout_info );
298
299        if ( empty( $images ) ) {
300            return '';
301        }
302
303        // Determine target width from the email layout if available
304        $target_width = self::get_email_target_width( $rendering_context );
305
306        // Build layout content based on style and columns
307        $grid_content = self::build_email_layout_content( $images, $layout_info, $email_cell_padding, $attr, $target_width );
308
309        // Use Table_Wrapper_Helper for consistent email rendering
310        $table_style = sprintf( 'width: 100%%; max-width: %dpx; padding: 0; border-collapse: collapse;', $target_width );
311        if ( ! empty( $table_margin_style ) ) {
312            $table_style = $table_margin_style . '; ' . $table_style;
313        } else {
314            $table_style = 'margin: 16px 0; ' . $table_style;
315        }
316
317        $image_table_attrs = array(
318            'style' => $table_style,
319        );
320
321        $html = \Automattic\WooCommerce\EmailEditor\Integrations\Utils\Table_Wrapper_Helper::render_table_wrapper( $grid_content, $image_table_attrs );
322
323        return $html;
324    }
325
326    /**
327     * Get target width for email rendering.
328     *
329     * @param object $rendering_context Email rendering context.
330     * @return int Target width in pixels.
331     */
332    private static function get_email_target_width( $rendering_context ) {
333        $target_width = 600; // Default
334
335        if ( ! empty( $rendering_context ) && is_object( $rendering_context ) && method_exists( $rendering_context, 'get_layout_width_without_padding' ) ) {
336            $layout_width_px = $rendering_context->get_layout_width_without_padding();
337            if ( is_string( $layout_width_px ) ) {
338                $parsed_width = \Automattic\WooCommerce\EmailEditor\Integrations\Utils\Styles_Helper::parse_value( $layout_width_px );
339                if ( $parsed_width > 0 ) {
340                    $target_width = $parsed_width;
341                }
342            }
343        }
344
345        return $target_width;
346    }
347
348    /**
349     * Process tiled gallery images for email rendering.
350     *
351     * @param array $attr Block attributes containing image data.
352     * @param array $layout_info Layout information from get_layout_style_from_attributes.
353     * @return array Processed image data for email rendering.
354     */
355    private static function process_tiled_gallery_images_for_email( $attr, $layout_info ) {
356        $images = array();
357
358        // Determine if this is a squareish layout
359        $is_squareish = in_array( $layout_info['style'], array( 'square', 'circle' ), true );
360
361        // Get images from IDs (primary data source)
362        if ( ! empty( $attr['ids'] ) && is_array( $attr['ids'] ) ) {
363            foreach ( $attr['ids'] as $id ) {
364                // Validate ID is a positive integer and attachment exists
365                $id = absint( $id );
366                if ( ! $id || ! wp_attachment_is_image( $id ) ) {
367                    continue;
368                }
369
370                $width  = 0;
371                $height = 0;
372
373                // For square/circle layouts, get a high-quality square crop
374                if ( $is_squareish ) {
375                    // Start with full size image for better quality when resizing
376                    $image_url = wp_get_attachment_image_url( $id, 'full' );
377
378                    // If we have Photon/Jetpack image processing, request high-quality square crop.
379                    // A site's own uploads URL ignores resize, so the crop has to go through Photon.
380                    if ( class_exists( Image_CDN_Core::class ) && $image_url ) {
381                        $image_url = Image_CDN_Core::cdn_url(
382                            remove_query_arg( array( 'w', 'h', 'fit', 'resize', 'crop' ), $image_url ),
383                            array( 'resize' => '1300,1300' ),
384                            'https'
385                        );
386
387                        // Photon skips some URLs, such as a private site's; leave those sizes unknown so Outlook keeps their proportions.
388                        if ( self::is_resizable_image_url( $image_url ) ) {
389                            $width  = 1300;
390                            $height = 1300;
391                        }
392                    }
393                } else {
394                    $image_src = wp_get_attachment_image_src( $id, 'large' );
395                    $image_url = $image_src ? $image_src[0] : false;
396                    $width     = $image_src ? (int) $image_src[1] : 0;
397                    $height    = $image_src ? (int) $image_src[2] : 0;
398                }
399
400                // Sanitize alt text from post meta
401                $alt_text = get_post_meta( $id, '_wp_attachment_image_alt', true );
402                $alt_text = sanitize_text_field( $alt_text );
403
404                if ( $image_url ) {
405                    $images[] = array(
406                        'url'    => $image_url,
407                        'alt'    => $alt_text,
408                        'id'     => $id,
409                        'width'  => $width,
410                        'height' => $height,
411                    );
412                }
413            }
414        } elseif ( ! empty( $attr['images'] ) && is_array( $attr['images'] ) ) {
415            // Fall back to images array if IDs aren't available
416            foreach ( $attr['images'] as $image_data ) {
417                if ( ! empty( $image_data['url'] ) ) {
418                    // Validate and sanitize URL
419                    $url = esc_url_raw( $image_data['url'] );
420                    if ( ! $url || ! wp_http_validate_url( $url ) ) {
421                        continue;
422                    }
423
424                    // Sanitize alt text
425                    $alt_text = ! empty( $image_data['alt'] ) ? sanitize_text_field( $image_data['alt'] ) : '';
426
427                    // Validate ID if present
428                    $id = ! empty( $image_data['id'] ) ? absint( $image_data['id'] ) : 0;
429
430                    $images[] = array(
431                        'url'    => $url,
432                        'alt'    => $alt_text,
433                        'id'     => $id,
434                        'width'  => ! empty( $image_data['width'] ) ? absint( $image_data['width'] ) : 0,
435                        'height' => ! empty( $image_data['height'] ) ? absint( $image_data['height'] ) : 0,
436                    );
437                }
438            }
439        }
440
441        return $images;
442    }
443
444    /**
445     * Whether an image URL is served by a host that honors its resize arguments: Photon or WordPress.com files.
446     *
447     * @param string $url Image URL.
448     * @return bool
449     */
450    private static function is_resizable_image_url( $url ) {
451        return Image_CDN_Core::is_cdn_url( $url ) || str_ends_with( strtolower( (string) wp_parse_url( $url, PHP_URL_HOST ) ), '.files.wordpress.com' );
452    }
453
454    /**
455     * Get layout style and columns from block attributes.
456     *
457     * @param array $attr Block attributes.
458     * @return array Array with 'style', 'columns', and 'border_radius' keys.
459     */
460    private static function get_layout_style_from_attributes( $attr ) {
461        $layout_info = array(
462            'style'         => 'rectangular', // Default to rectangular/mosaic layout
463            'columns'       => 3, // Default to 3 columns
464            'border_radius' => 0, // Default to no border radius
465        );
466
467        // Get number of columns from attributes with validation
468        if ( ! empty( $attr['columns'] ) && is_numeric( $attr['columns'] ) ) {
469            $columns = absint( $attr['columns'] );
470            // Clamp columns between 1 and 6 for reasonable layouts
471            $layout_info['columns'] = max( 1, min( 6, $columns ) );
472        }
473
474        // Get border radius from roundedCorners attribute (preferred method)
475        if ( ! empty( $attr['roundedCorners'] ) && is_numeric( $attr['roundedCorners'] ) ) {
476            $border_radius_value = absint( $attr['roundedCorners'] );
477            // Clamp value between 0 and 20
478            $layout_info['border_radius'] = max( 0, min( 20, $border_radius_value ) );
479        }
480
481        // Get layout style and border radius from className
482        if ( ! empty( $attr['className'] ) ) {
483            if ( str_contains( $attr['className'], 'is-style-square' ) ) {
484                $layout_info['style'] = 'square';
485            } elseif ( str_contains( $attr['className'], 'is-style-circle' ) ) {
486                $layout_info['style'] = 'circle';
487            } elseif ( str_contains( $attr['className'], 'is-style-columns' ) ) {
488                $layout_info['style'] = 'columns';
489            }
490
491            // Extract border radius from has-rounded-corners-{value} class (fallback method)
492            if ( $layout_info['border_radius'] === 0 && preg_match( '/has-rounded-corners-(\d+)/', $attr['className'], $matches ) ) {
493                $border_radius_value = absint( $matches[1] );
494                    // Clamp value between 0 and 20
495                $layout_info['border_radius'] = max( 0, min( 20, $border_radius_value ) );
496            }
497        }
498
499        return $layout_info;
500    }
501
502    /**
503     * Build email layout content based on layout style and columns.
504     *
505     * @param array $images Array of image data.
506     * @param array $layout_info Array with 'style' and 'columns' keys.
507     * @param int   $cell_padding Cell padding.
508     * @param array $attr Block attributes.
509     * @param int   $target_width Email content width in pixels.
510     * @return string HTML content.
511     */
512    private static function build_email_layout_content( $images, $layout_info, $cell_padding, $attr, $target_width ) {
513        $layout_style  = $layout_info['style'];
514        $columns       = $layout_info['columns'];
515        $border_radius = $layout_info['border_radius'];
516
517        switch ( $layout_style ) {
518            case 'square':
519                return self::build_square_layout_content( $images, $cell_padding, $columns, 'square', $border_radius, $attr, $target_width );
520            case 'circle':
521                return self::build_square_layout_content( $images, $cell_padding, $columns, 'circle', $border_radius, $attr, $target_width );
522            case 'columns':
523                return self::build_columns_layout_content( $images, $cell_padding, $columns, $border_radius, $attr, $target_width );
524            case 'rectangular':
525            default:
526                return self::build_mosaic_layout_content( $images, $cell_padding, $border_radius, $attr, $target_width );
527        }
528    }
529
530    /**
531     * Build square/circle layout content.
532     *
533     * @param array  $images Array of image data.
534     * @param int    $cell_padding Cell padding.
535     * @param int    $columns Number of columns for the layout.
536     * @param string $style Layout style (square or circle).
537     * @param int    $border_radius Border radius value (0-20).
538     * @param array  $attr Block attributes.
539     * @param int    $target_width Email content width in pixels.
540     * @return string HTML content.
541     */
542    private static function build_square_layout_content( $images, $cell_padding, $columns, $style, $border_radius, $attr, $target_width ) {
543        $content_parts = array();
544
545        // Create rows of images with hierarchical chunks for square/circle layouts
546        $image_chunks = self::create_hierarchical_chunks( $images, $columns );
547
548        $border_radius_style = self::generate_border_radius_style( $style, $border_radius );
549
550        foreach ( $image_chunks as $row_images ) {
551            $image_widths = self::split_width( $target_width - 2 * $cell_padding * count( $row_images ), count( $row_images ) );
552
553            // Build table cells for this row
554            $row_cells = '';
555            foreach ( $row_images as $index => $image ) {
556                // Calculate cell attributes with consistent padding
557                $cell_attrs = array(
558                    'style' => sprintf(
559                        'width: %s%%; padding: %dpx; vertical-align: top; text-align: center;',
560                        self::get_cell_width_percent( $image_widths[ $index ], $cell_padding, $target_width ),
561                        $cell_padding
562                    ),
563                );
564
565                // Clients that support it crop an uncropped source to the square; Outlook relies on the cropped source.
566                $image_styles = self::generate_image_styles( $image_widths[ $index ] . 'px' ) . ' aspect-ratio: 1 / 1; object-fit: cover;';
567
568                $cell_content = self::generate_image_html( $image, $image_styles, $border_radius_style, $attr, self::get_image_size( $image, $image_widths[ $index ] ) );
569
570                $row_cells .= \Automattic\WooCommerce\EmailEditor\Integrations\Utils\Table_Wrapper_Helper::render_table_cell(
571                    $cell_content,
572                    $cell_attrs
573                );
574            }
575
576            // Use Table_Wrapper_Helper for email-compatible table rendering
577            $table_attrs = array(
578                'style' => 'width: 100%; border-collapse: collapse;',
579            );
580
581            $content_parts[] = \Automattic\WooCommerce\EmailEditor\Integrations\Utils\Table_Wrapper_Helper::render_table_wrapper(
582                $row_cells,
583                $table_attrs
584            );
585        }
586
587        // Use Table_Wrapper_Helper for consistent email rendering
588        $wrapper_attrs = array(
589            'style' => 'width: 100%; border-collapse: collapse;',
590        );
591
592        return \Automattic\WooCommerce\EmailEditor\Integrations\Utils\Table_Wrapper_Helper::render_table_wrapper(
593            implode( '', $content_parts ),
594            $wrapper_attrs
595        );
596    }
597
598    /**
599     * Build columns layout content using mosaic logic organized into columns.
600     *
601     * @param array $images Array of image data.
602     * @param int   $cell_padding Cell padding.
603     * @param int   $columns Number of columns for the layout.
604     * @param int   $border_radius Border radius value (0-20).
605     * @param array $attr Block attributes.
606     * @param int   $target_width Email content width in pixels.
607     * @return string HTML content.
608     */
609    private static function build_columns_layout_content( $images, $cell_padding, $columns, $border_radius, $attr, $target_width ) {
610        $content_parts       = array();
611        $border_radius_style = self::generate_border_radius_style( '', $border_radius );
612        $column_widths       = self::split_width( $target_width - 2 * $cell_padding * $columns, $columns );
613
614        // Distribute images across columns using round-robin approach for better balance
615        $column_arrays = array_fill( 0, $columns, array() );
616        foreach ( $images as $index => $image ) {
617            $column_index                     = $index % $columns;
618            $column_arrays[ $column_index ][] = $image;
619        }
620
621        // Build table cells for columns layout
622        $row_cells = '';
623        foreach ( $column_arrays as $column_index => $column_images ) {
624            // An empty column still gets its cell, for balance.
625            $cell_attrs = array(
626                'style' => sprintf(
627                    'width: %s%%; padding: %dpx; vertical-align: top;',
628                    self::get_cell_width_percent( $column_widths[ $column_index ], $cell_padding, $target_width ),
629                    $cell_padding
630                ),
631            );
632
633            // Generate mosaic-style groupings within this column
634            $column_rows = self::generate_column_mosaic_rows( $column_images );
635
636            $cell_content = '';
637            foreach ( $column_rows as $row_index => $row_images ) {
638                foreach ( $row_images as $image ) {
639                    $image_styles = self::generate_image_styles( $column_widths[ $column_index ] . 'px' );
640
641                    // Add top margin to all images except the first one in the column
642                    if ( $row_index > 0 || $cell_content !== '' ) {
643                        $image_styles .= ' margin-top: ' . ( $cell_padding * 2 ) . 'px;';
644                    }
645
646                    $cell_content .= self::generate_image_html( $image, $image_styles, $border_radius_style, $attr, self::get_image_size( $image, $column_widths[ $column_index ] ) );
647                }
648            }
649
650            $row_cells .= \Automattic\WooCommerce\EmailEditor\Integrations\Utils\Table_Wrapper_Helper::render_table_cell(
651                $cell_content,
652                $cell_attrs
653            );
654        }
655
656        // Use Table_Wrapper_Helper for email-compatible table rendering
657        $table_attrs = array(
658            'style' => 'width: 100%; border-collapse: collapse;',
659        );
660
661        $content_parts[] = \Automattic\WooCommerce\EmailEditor\Integrations\Utils\Table_Wrapper_Helper::render_table_wrapper(
662            $row_cells,
663            $table_attrs
664        );
665
666        // Use Table_Wrapper_Helper for consistent email rendering
667        $wrapper_attrs = array(
668            'style' => 'width: 100%; border-collapse: collapse;',
669        );
670
671        return \Automattic\WooCommerce\EmailEditor\Integrations\Utils\Table_Wrapper_Helper::render_table_wrapper(
672            implode( '', $content_parts ),
673            $wrapper_attrs
674        );
675    }
676
677    /**
678     * Build mosaic layout content with flexible row/column structure.
679     *
680     * @param array $images Array of image data.
681     * @param int   $cell_padding Cell padding.
682     * @param int   $border_radius Border radius value (0-20).
683     * @param array $attr Block attributes.
684     * @param int   $target_width Email content width in pixels.
685     * @return string HTML content.
686     */
687    private static function build_mosaic_layout_content( $images, $cell_padding, $border_radius, $attr, $target_width ) {
688        $border_radius_style = self::generate_border_radius_style( '', $border_radius );
689
690        // Generate mosaic layout rows
691        $rows = self::generate_mosaic_rows( $images );
692
693        // Build each row as a separate table to match flexbox behavior
694        $content_parts = array();
695        foreach ( $rows as $row ) {
696            $sizes = self::get_mosaic_row_image_sizes( $row, $target_width - 2 * $cell_padding * count( $row ) );
697
698            // Build table cells for this row
699            $row_cells = '';
700            foreach ( $row as $index => $image ) {
701                list( $image_width, $image_height ) = $sizes[ $index ];
702
703                $cell_style = sprintf(
704                    'width: %s%%; padding: %dpx; vertical-align: top; text-align: center;',
705                    self::get_cell_width_percent( $image_width, $cell_padding, $target_width ),
706                    $cell_padding
707                );
708
709                $image_styles = self::generate_image_styles( $image_width . 'px' );
710
711                // Outlook ignores CSS widths, so it sizes the image from the width and height attributes.
712                $cell_content = self::generate_image_html( $image, $image_styles, $border_radius_style, $attr, array( $image_width, $image_height ) );
713
714                $row_cells .= sprintf(
715                    '<td style="%s">%s</td>',
716                    esc_attr( $cell_style ),
717                    $cell_content
718                );
719            }
720
721            // Create a separate table for each row with flexible height for alignment
722            $row_table = sprintf(
723                '<table role="presentation" style="width: 100%%; border-collapse: collapse; table-layout: fixed;"><tr>%s</tr></table>',
724                $row_cells
725            );
726
727            $content_parts[] = $row_table;
728        }
729
730        // Use Table_Wrapper_Helper for the main container
731        $table_attrs = array(
732            'style' => 'width: 100%; border-collapse: collapse;',
733        );
734
735        return \Automattic\WooCommerce\EmailEditor\Integrations\Utils\Table_Wrapper_Helper::render_table_wrapper(
736            implode( '', $content_parts ),
737            $table_attrs
738        );
739    }
740
741    /**
742     * Size a mosaic row's images to share one height and fill the given width.
743     *
744     * @param array $row Images in the row.
745     * @param int   $width Width the row's images fill, in pixels.
746     * @return array Width and height in pixels for each image; the height is null when the image's own is unknown.
747     */
748    private static function get_mosaic_row_image_sizes( $row, $width ) {
749        $ratios = array_map( array( __CLASS__, 'get_image_ratio' ), $row );
750
751        $row_height = $width / array_sum( $ratios );
752        $sizes      = array();
753        $remaining  = $width;
754        foreach ( $ratios as $index => $ratio ) {
755            // The last image takes the rounding remainder so the row fills the width exactly.
756            $image_width = $index === count( $ratios ) - 1 ? $remaining : (int) floor( $ratio * $row_height );
757            $remaining  -= $image_width;
758            // Don't hand Outlook a guessed height, which would stretch the image to it.
759            $sizes[] = array( max( 1, $image_width ), self::has_known_dimensions( $row[ $index ] ) ? max( 1, (int) round( $row_height ) ) : null );
760        }
761
762        return $sizes;
763    }
764
765    /**
766     * Get an image's aspect ratio, treating an image with unknown dimensions as square.
767     *
768     * @param array $image Image data.
769     * @return float Width divided by height.
770     */
771    private static function get_image_ratio( $image ) {
772        return self::has_known_dimensions( $image ) ? $image['width'] / $image['height'] : 1;
773    }
774
775    /**
776     * Whether an image's width and height are known.
777     *
778     * @param array $image Image data.
779     * @return bool
780     */
781    private static function has_known_dimensions( $image ) {
782        return $image['width'] > 0 && $image['height'] > 0;
783    }
784
785    /**
786     * Size an image to a width, with the height its aspect ratio gives, or null when unknown.
787     *
788     * @param array $image Image data.
789     * @param int   $width Width in pixels.
790     * @return array Width and height in pixels.
791     */
792    private static function get_image_size( $image, $width ) {
793        return array( $width, self::has_known_dimensions( $image ) ? max( 1, (int) round( $width / self::get_image_ratio( $image ) ) ) : null );
794    }
795
796    /**
797     * Split a width into equal whole-pixel parts, the last taking the rounding remainder.
798     *
799     * @param int $width Width in pixels.
800     * @param int $count Number of parts.
801     * @return array Width of each part in pixels.
802     */
803    private static function split_width( $width, $count ) {
804        $part                = (int) floor( $width / $count );
805        $parts               = array_fill( 0, $count, $part );
806        $parts[ $count - 1 ] = $width - $part * ( $count - 1 );
807        return $parts;
808    }
809
810    /**
811     * Get a cell's width as a percentage of the email width, for an image plus its padding on both sides.
812     *
813     * @param int $image_width Image width in pixels.
814     * @param int $cell_padding Cell padding in pixels.
815     * @param int $target_width Email content width in pixels.
816     * @return float
817     */
818    private static function get_cell_width_percent( $image_width, $cell_padding, $target_width ) {
819        return round( ( $image_width + 2 * $cell_padding ) * 100 / $target_width, 4 );
820    }
821
822    /**
823     * Generate mosaic layout rows, giving each panorama a row of its own.
824     *
825     * A panorama sharing a row would shrink the row's height, and its row-mates with it.
826     *
827     * @param array $images Array of image data.
828     * @return array Array of rows, each containing images.
829     */
830    private static function generate_mosaic_rows( $images ) {
831        $rows    = array();
832        $pending = array();
833        foreach ( $images as $image ) {
834            if ( self::get_image_ratio( $image ) >= self::PANORAMIC_RATIO ) {
835                $rows    = array_merge( $rows, self::group_mosaic_rows( $pending ), array( array( $image ) ) );
836                $pending = array();
837            } else {
838                $pending[] = $image;
839            }
840        }
841
842        return array_merge( $rows, self::group_mosaic_rows( $pending ) );
843    }
844
845    /**
846     * Group images into mosaic rows based on image count.
847     *
848     * @param array $images Array of image data.
849     * @return array Array of rows, each containing images.
850     */
851    private static function group_mosaic_rows( $images ) {
852        $rows        = array();
853        $image_count = count( $images );
854
855        // More sophisticated mosaic algorithm based on image count
856        if ( 0 === $image_count ) {
857            return $rows;
858        } elseif ( $image_count <= 3 ) {
859            // For 3 or fewer images, use simple layout
860            $rows[] = $images;
861        } else {
862            // For more images, create varied row patterns
863            $patterns = array(
864                4 => array( 2, 2 ),      // 4 images: 2 + 2
865                5 => array( 2, 3 ),      // 5 images: 2 + 3
866                6 => array( 3, 3 ),      // 6 images: 3 + 3
867                7 => array( 3, 2, 2 ),   // 7 images: 3 + 2 + 2
868                8 => array( 3, 3, 2 ),   // 8 images: 3 + 3 + 2
869                9 => array( 3, 3, 3 ),   // 9 images: 3 + 3 + 3
870            );
871
872            if ( isset( $patterns[ $image_count ] ) ) {
873                // Use predefined pattern for 4-9 images
874                $pattern     = $patterns[ $image_count ];
875                $image_index = 0;
876
877                foreach ( $pattern as $images_in_row ) {
878                    $row = array();
879                    for ( $i = 0; $i < $images_in_row; $i++ ) {
880                        $row[] = $images[ $image_index ];
881                        ++$image_index;
882                    }
883                    $rows[] = $row;
884                }
885            } else {
886                // For 10+ images, create rows of 3 with remainder handling
887                $full_rows = intval( $image_count / 3 );
888                $remainder = $image_count % 3;
889
890                $image_index = 0;
891
892                // Create full rows of 3
893                for ( $row = 0; $row < $full_rows; $row++ ) {
894                    $rows[]       = array(
895                        $images[ $image_index ],
896                        $images[ $image_index + 1 ],
897                        $images[ $image_index + 2 ],
898                    );
899                    $image_index += 3;
900                }
901
902                // Handle remainder
903                if ( $remainder > 0 ) {
904                    $remaining = array_slice( $images, $image_index );
905                    $rows[]    = $remaining;
906                }
907            }
908        }
909
910        return $rows;
911    }
912
913    /**
914     * Generate mosaic-style rows within a single column for columns layout.
915     *
916     * @param array $images Array of image data for this column.
917     * @return array Array of rows, each containing 1-2 images for variety.
918     */
919    private static function generate_column_mosaic_rows( $images ) {
920        $rows        = array();
921        $image_count = count( $images );
922
923        if ( $image_count <= 2 ) {
924            // For 2 or fewer images, each gets its own row
925            foreach ( $images as $image ) {
926                $rows[] = array( $image );
927            }
928        } else {
929            // Create varied patterns: mix of single and paired images
930            $image_index = 0;
931
932            while ( $image_index < $image_count ) {
933                $remaining = $image_count - $image_index;
934
935                if ( $remaining === 1 ) {
936                    // Last image - single row
937                    $rows[] = array( $images[ $image_index ] );
938                    ++$image_index;
939                } elseif ( $remaining === 3 ) {
940                    // 3 remaining - do 1 + 2 for better balance
941                    $rows[] = array( $images[ $image_index ] );
942                    ++$image_index;
943                    $rows[]       = array( $images[ $image_index ], $images[ $image_index + 1 ] );
944                    $image_index += 2;
945                } else {
946                    // 2 or more remaining - alternate between single and pairs
947                    $use_pair = ( count( $rows ) % 2 === 1 ); // Alternate pattern
948
949                    if ( $use_pair && $remaining >= 2 ) {
950                        // Create a pair
951                        $rows[]       = array( $images[ $image_index ], $images[ $image_index + 1 ] );
952                        $image_index += 2;
953                    } else {
954                        // Single image
955                        $rows[] = array( $images[ $image_index ] );
956                        ++$image_index;
957                    }
958                }
959            }
960        }
961
962        return $rows;
963    }
964
965    /**
966     * Generate border radius style based on layout style and border radius value.
967     *
968     * @param string $style Layout style (square, circle, etc.).
969     * @param int    $border_radius Border radius value.
970     * @return string CSS border-radius style.
971     */
972    private static function generate_border_radius_style( $style, $border_radius ) {
973        if ( 'circle' === $style ) {
974            return 'border-radius:50%;';
975        } elseif ( $border_radius > 0 ) {
976            return 'border-radius:' . $border_radius . 'px;';
977        }
978        return '';
979    }
980
981    /**
982     * Generate image styles for email rendering.
983     *
984     * @param string $max_width CSS max-width value.
985     * @return string CSS style string.
986     */
987    private static function generate_image_styles( $max_width ) {
988        return 'margin: 0; width: 100%; max-width: ' . $max_width . '; display: block; height: auto;';
989    }
990
991    /**
992     * Generate image HTML with consistent styling.
993     *
994     * @param array  $image Image data array.
995     * @param string $additional_styles Additional CSS styles.
996     * @param string $border_radius_style Border radius CSS.
997     * @param array  $attr Block attributes (optional, for link processing).
998     * @param array  $size Optional width and height attributes in pixels; a null height is left out.
999     * @return string Image HTML.
1000     */
1001    private static function generate_image_html( $image, $additional_styles = '', $border_radius_style = '', $attr = array(), $size = array() ) {
1002        $base_styles     = 'border:none;background-color:#0000001a;display:block;height:auto;max-width:100%;padding:0;';
1003        $combined_styles = $base_styles . $additional_styles . $border_radius_style;
1004        $size_attributes = $size ? sprintf( ' width="%d"', $size[0] ) : '';
1005        if ( isset( $size[1] ) ) {
1006            $size_attributes .= sprintf( ' height="%d"', $size[1] );
1007        }
1008
1009        $img_html = sprintf(
1010            '<img alt="%s" src="%s"%s style="%s" />',
1011            esc_attr( $image['alt'] ),
1012            esc_url( $image['url'] ),
1013            $size_attributes,
1014            $combined_styles
1015        );
1016
1017        // Handle link settings for email
1018        $link_to = ! empty( $attr['linkTo'] ) ? $attr['linkTo'] : 'none';
1019        $href    = self::get_image_link_href( $image, $attr, $link_to );
1020
1021        if ( ! empty( $href ) ) {
1022            return sprintf( '<a href="%s">%s</a>', esc_url( $href ), $img_html );
1023        }
1024
1025        return $img_html;
1026    }
1027
1028    /**
1029     * Get the href for an image based on link settings (used for email rendering).
1030     * Excludes custom links which email clients will replace with the image.
1031     *
1032     * @since 15.0
1033     *
1034     * @param array  $image Image data array.
1035     * @param array  $attr Block attributes.
1036     * @param string $link_to Link setting.
1037     * @return string The href URL or empty string.
1038     */
1039    private static function get_image_link_href( $image, $attr, $link_to ) {
1040        switch ( $link_to ) {
1041            case 'media':
1042                return ! empty( $image['url'] ) ? $image['url'] : '';
1043
1044            case 'attachment':
1045                // For email, we need to generate the attachment page URL from the image ID
1046                if ( ! empty( $image['id'] ) ) {
1047                    $attachment_url = get_permalink( $image['id'] );
1048                    return $attachment_url ? $attachment_url : '';
1049                }
1050                return '';
1051            default:
1052                return '';
1053        }
1054    }
1055
1056    /**
1057     * Create hierarchical chunks for square/circle layouts with larger items first.
1058     *
1059     * @param array $images Array of image data.
1060     * @param int   $columns Number of columns for the layout.
1061     * @return array Array of rows with different sized chunks.
1062     */
1063    private static function create_hierarchical_chunks( $images, $columns ) {
1064        $image_count = count( $images );
1065        $chunks      = array();
1066
1067        if ( $image_count <= $columns ) {
1068            // For column count or fewer, single row
1069            $chunks[] = $images;
1070        } else {
1071            // Calculate remainder when dividing by columns
1072            $remainder   = $image_count % $columns;
1073            $start_index = 0;
1074
1075            // Handle all remainder cases to create proper hierarchy
1076            if ( $remainder > 0 ) {
1077                // Create a row with the remainder images (larger items first)
1078                $chunks[]    = array_slice( $images, 0, $remainder );
1079                $start_index = $remainder;
1080            }
1081            // If remainder === 0, start_index stays 0
1082
1083            // Rest in groups of $columns
1084            $remaining        = array_slice( $images, $start_index );
1085            $remaining_chunks = array_chunk( $remaining, $columns );
1086            $chunks           = array_merge( $chunks, $remaining_chunks );
1087        }
1088
1089        return $chunks;
1090    }
1091}
1092
1093add_action( 'init', array( Tiled_Gallery::class, 'register' ) );