Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
66.34% covered (warning)
66.34%
343 / 517
52.38% covered (warning)
52.38%
22 / 42
CRAP
0.00% covered (danger)
0.00%
0 / 1
Feedback_Field
66.34% covered (warning)
66.34%
343 / 517
52.38% covered (warning)
52.38%
22 / 42
1708.67
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 get_key
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_label
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
4.07
 get_value
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_form_field_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_render_value
87.50% covered (warning)
87.50%
14 / 16
0.00% covered (danger)
0.00%
0 / 1
10.20
 get_render_csv_value
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
20
 get_render_web_value
25.81% covered (danger)
25.81%
8 / 31
0.00% covered (danger)
0.00%
0 / 1
82.02
 get_phone_value_with_flag
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 get_country_code_from_phone
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 get_rating_value
91.30% covered (success)
91.30%
21 / 23
0.00% covered (danger)
0.00%
0 / 1
8.04
 get_render_email_value
26.09% covered (danger)
26.09%
6 / 23
0.00% covered (danger)
0.00%
0 / 1
70.15
 get_render_email_html_value
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
12.04
 render_empty_value_html
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 render_email_default
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 render_email_chips
87.50% covered (warning)
87.50%
14 / 16
0.00% covered (danger)
0.00%
0 / 1
8.12
 render_email_consent
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 render_email_phone
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
5
 render_email_url
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
4.01
 render_email_rating
86.67% covered (warning)
86.67%
13 / 15
0.00% covered (danger)
0.00%
0 / 1
8.15
 render_email_file
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
90
 render_email_file_row
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
30
 get_file_thumbnail_html
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 get_file_icon_name
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
6
 render_email_image_select
97.62% covered (success)
97.62%
41 / 42
0.00% covered (danger)
0.00%
0 / 1
15
 get_render_default_value
85.71% covered (warning)
85.71%
12 / 14
0.00% covered (danger)
0.00%
0 / 1
8.19
 get_render_api_value
90.48% covered (success)
90.48%
19 / 21
0.00% covered (danger)
0.00%
0 / 1
8.06
 get_render_submit_value
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
5.01
 is_of_type
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 compile_field
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_type
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_icon_name_for_type
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
1
 get_admin_theme_color
85.71% covered (warning)
85.71%
18 / 21
0.00% covered (danger)
0.00%
0 / 1
4.05
 get_meta
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_meta_key_value
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 serialize
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 from_serialized
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 normalize_unicode
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 is_valid_json_decode
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 from_serialized_v2
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
7
 has_file
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
4.13
 is_previewable_file
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Feedback_Field class.
4 *
5 * @package automattic/jetpack-forms
6 */
7
8namespace Automattic\Jetpack\Forms\ContactForm;
9
10use Automattic\Jetpack\Forms\Jetpack_Forms;
11
12/**
13 * Feedback field class.
14 *
15 * Represents the submitted form data of an individual field.
16 */
17class Feedback_Field {
18    use Country_Code_Utils;
19
20    /**
21     * Cached admin theme color.
22     *
23     * @var string|null
24     */
25    private static $admin_theme_color = null;
26
27    /**
28     * The key of the field.
29     *
30     * @var string
31     */
32    private $key;
33
34    /**
35     * The label of the field.
36     *
37     * @var string
38     */
39    private $label;
40
41    /**
42     * The value of the field.
43     *
44     * @var mixed
45     */
46    private $value;
47
48    /**
49     * The type of the field.
50     *
51     * @var string
52     */
53    private $type;
54
55    /**
56     * Additional metadata for the field.
57     *
58     * @var array
59     */
60    private $meta;
61
62    /**
63     * The original form field ID from the form schema.
64     *
65     * @since 5.5.0
66     *
67     * @var string
68     */
69    protected $form_field_id = '';
70
71    /**
72     * Constructor.
73     *
74     * @param string      $key           The key of the field.
75     * @param mixed       $label         The label of the field. Non-string values will be converted to empty string.
76     * @param mixed       $value         The value of the field.
77     * @param string      $type          The type of the field (default is 'basic').
78     * @param array       $meta          Additional metadata for the field (default is an empty array).
79     * @param string|null $form_field_id The original form field ID (default is null).
80     */
81    public function __construct( $key, $label, $value, $type = 'basic', $meta = array(), $form_field_id = null ) {
82        $this->key           = $key;
83        $this->label         = is_string( $label ) ? html_entity_decode( $label, ENT_QUOTES | ENT_HTML5, 'UTF-8' ) : '';
84        $this->value         = $value;
85        $this->type          = $type;
86        $this->meta          = $meta;
87        $this->form_field_id = is_string( $form_field_id ) ? $form_field_id : '';
88    }
89
90    /**
91     * Get the value of the field.
92     *
93     * @return string
94     */
95    public function get_key() {
96        return $this->key;
97    }
98
99    /**
100     * Get the label of the field.
101     *
102     * @param string $context The context in which the label is being rendered (default is 'default').
103     * @param int    $count   The count of the label occurrences (default is 1).
104     *
105     * @return string
106     */
107    public function get_label( $context = 'default', $count = 1 ) {
108
109        $postfix = $count > 1 ? " ({$count})" : '';
110
111        if ( in_array( $context, array( 'api', 'csv' ), true ) ) {
112            if ( empty( $this->label ) ) {
113                return __( 'Field', 'jetpack-forms' ) . $postfix;
114            }
115
116            return $this->label . $postfix;
117        }
118
119        return $this->label . $postfix;
120    }
121
122    /**
123     * Get the value of the field.
124     *
125     * @return mixed
126     */
127    public function get_value() {
128        return $this->value;
129    }
130
131    /**
132     * Get the original form field ID.
133     *
134     * @since 5.5.0
135     *
136     * @return string
137     */
138    public function get_form_field_id() {
139        return $this->form_field_id;
140    }
141
142    /**
143     * Get the value of the field for rendering.
144     *
145     * @param string $context The context in which the value is being rendered (default is 'default').
146     *
147     * @return string
148     */
149    public function get_render_value( $context = 'default' ) {
150        switch ( $context ) {
151            case 'submit':
152                return $this->get_render_submit_value();
153            case 'api':
154                return $this->get_render_api_value();
155            case 'web': // For the post-submission page screen.
156                return $this->get_render_web_value();
157            case 'email':
158                return $this->get_render_email_value();
159            case 'email_html':
160                return $this->get_render_email_html_value();
161            case 'ajax':
162                return $this->get_render_web_value(); // For now, we use the same value for ajax and web.
163            case 'csv':
164                return $this->get_render_csv_value();
165            case 'default':
166            default:
167                return $this->get_render_default_value();
168        }
169    }
170
171    /**
172     * Get the value of the field for rendering the CSV.
173     *
174     * @return string
175     */
176    private function get_render_csv_value() {
177        if ( $this->is_of_type( 'image-select' ) ) {
178            return implode(
179                ', ',
180                array_map(
181                    function ( $choice ) {
182                        $value = $choice['selected'];
183
184                        if ( ! empty( $choice['label'] ) ) {
185                            $value .= ' - ' . $choice['label'];
186                        }
187
188                        return $value;
189                    },
190                    $this->value['choices']
191                )
192            );
193        }
194
195        if ( $this->value === null ) {
196            return '';
197        }
198
199        return $this->get_render_default_value();
200    }
201
202    /**
203     * Get the value of the field for rendering the post-submission page.
204     *
205     * @return string|array
206     */
207    private function get_render_web_value() {
208        if ( $this->is_of_type( 'image-select' ) ) {
209            return $this->value;
210        }
211
212        // For phone fields, add country flag before the number.
213        if ( $this->is_of_type( 'phone' ) || $this->is_of_type( 'telephone' ) ) {
214            return $this->get_phone_value_with_flag();
215        }
216
217        // For URL fields, return a structured array with the URL for proper link rendering.
218        // 'displayValue' preserves the original user input for display text.
219        // 'url' is used for the href and may have https:// prepended.
220        if ( $this->is_of_type( 'url' ) ) {
221            if ( ! empty( $this->value ) ) {
222                return array(
223                    'type'         => 'url',
224                    'url'          => $this->value,
225                    'displayValue' => $this->value,
226                );
227            }
228        }
229
230        // For file fields, return a structured array with file metadata for proper rendering.
231        if ( $this->is_of_type( 'file' ) ) {
232            $files = array();
233            if ( isset( $this->value['files'] ) && is_array( $this->value['files'] ) ) {
234                foreach ( $this->value['files'] as $file ) {
235                    if ( ! isset( $file['size'] ) || ! isset( $file['file_id'] ) ) {
236                        continue;
237                    }
238                    $file_id = absint( $file['file_id'] );
239                    $files[] = array(
240                        'file_id' => $file_id,
241                        'name'    => $file['name'] ?? __( 'Attached file', 'jetpack-forms' ),
242                        'size'    => size_format( $file['size'] ),
243                        'url'     => apply_filters( 'jetpack_unauth_file_download_url', '', $file_id ),
244                    );
245                }
246            }
247            return array(
248                'type'  => 'file',
249                'files' => $files,
250            );
251        }
252
253        // For rating fields, return a structured array with rating data for star/heart display.
254        if ( $this->is_of_type( 'rating' ) ) {
255            return $this->get_rating_value();
256        }
257
258        return $this->get_render_default_value();
259    }
260
261    /**
262     * Get phone value with country flag emoji.
263     *
264     * @return string Phone number with country flag prefix.
265     */
266    private function get_phone_value_with_flag() {
267        // Field values arrive as `mixed` (per the constructor); short-circuit
268        // to an empty string for non-string values.
269        if ( ! is_string( $this->value ) ) {
270            return '';
271        }
272
273        if ( empty( $this->value ) ) {
274            return $this->value;
275        }
276
277        // Try to extract country code from phone number prefix.
278        $country_code = $this->get_country_code_from_phone( $this->value );
279
280        if ( ! empty( $country_code ) ) {
281            $flag = self::country_code_to_emoji_flag( $country_code );
282            if ( ! empty( $flag ) ) {
283                return $flag . ' ' . $this->value;
284            }
285        }
286
287        return $this->value;
288    }
289
290    /**
291     * Extract country code from phone number based on its prefix.
292     *
293     * @param string $phone_number The phone number with country prefix (e.g., "+49 123456789").
294     *
295     * @return string|null The ISO country code (e.g., "DE") or null if not found.
296     */
297    private function get_country_code_from_phone( $phone_number ) {
298        // Remove spaces and normalize the phone number.
299        $normalized = preg_replace( '/\s+/', '', $phone_number );
300
301        // Must start with + for international format.
302        if ( strpos( $normalized, '+' ) !== 0 ) {
303            return null;
304        }
305
306        $prefix_to_country = self::get_phone_prefix_to_country_map();
307
308        foreach ( $prefix_to_country as $prefix => $country ) {
309            if ( strpos( $normalized, $prefix ) === 0 ) {
310                return $country;
311            }
312        }
313
314        return null;
315    }
316
317    /**
318     * Get rating value as a structured array for web rendering.
319     *
320     * Parses the rating value (format: "rating/max" e.g., "3/5") and returns
321     * a structured array with the rating, max, and iconStyle for star/heart display.
322     *
323     * @return array|string Structured rating data or original value if parsing fails.
324     */
325    private function get_rating_value() {
326        // Field values arrive as `mixed` (per the constructor); short-circuit
327        // to an empty string for non-string values.
328        if ( ! is_string( $this->value ) ) {
329            return '';
330        }
331
332        if ( empty( $this->value ) ) {
333            return $this->value;
334        }
335
336        // Parse the rating value format: "rating/max" (e.g., "3/5").
337        $parts = explode( '/', $this->value );
338        if ( count( $parts ) !== 2 ) {
339            return $this->value;
340        }
341
342        $rating = (int) $parts[0];
343        $max    = (int) $parts[1];
344
345        // Validate parsed values.
346        if ( $rating < 0 || $max <= 0 ) {
347            return $this->value;
348        }
349
350        if ( $rating > $max ) {
351            return $this->value;
352        }
353        // Get icon style from meta data (defaults to 'stars').
354        $icon_style = $this->get_meta_key_value( 'iconStyle' );
355        if ( empty( $icon_style ) ) {
356            $icon_style = 'stars';
357        }
358
359        return array(
360            'type'         => 'rating',
361            'rating'       => $rating,
362            'maxRating'    => $max,
363            'iconStyle'    => $icon_style,
364            'displayValue' => $this->value,
365        );
366    }
367
368    /**
369     * Get the value of the field for rendering the email.
370     *
371     * Returns structured data for type-aware rendering when possible,
372     * similar to get_render_web_value(). The escape_and_sanitize_field_value()
373     * method in Contact_Form already handles all these structured types.
374     *
375     * @return mixed
376     */
377    private function get_render_email_value() {
378        // Phone: string with country flag prefix.
379        if ( $this->is_of_type( 'phone' ) || $this->is_of_type( 'telephone' ) ) {
380            return $this->get_phone_value_with_flag();
381        }
382
383        // URL: structured array for link rendering.
384        if ( $this->is_of_type( 'url' ) && ! empty( $this->value ) ) {
385            return array(
386                'type'         => 'url',
387                'url'          => $this->value,
388                'displayValue' => $this->value,
389            );
390        }
391
392        // File: return raw value (has field_id + files keys).
393        if ( $this->is_of_type( 'file' ) ) {
394            return $this->value;
395        }
396
397        // Rating: structured array with rating data.
398        if ( $this->is_of_type( 'rating' ) ) {
399            return $this->get_rating_value();
400        }
401
402        // Image-select: keep current string format for backward compat.
403        if ( $this->is_of_type( 'image-select' ) ) {
404            $choices = array();
405
406            foreach ( $this->value['choices'] as $choice ) {
407                // On the email, we want to show the actual selected value, not the perceived value, as the options can be shuffled.
408                $value = $choice['selected'];
409
410                if ( ! empty( $choice['label'] ) ) {
411                    $value .= ' - ' . $choice['label'];
412                }
413                $choices[] = $value;
414            }
415
416            return implode( ', ', $choices );
417        }
418
419        // Checkbox-multiple: preserve array for chip rendering.
420        if ( $this->is_of_type( 'checkbox-multiple' ) && is_array( $this->value ) ) {
421            return $this->value;
422        }
423
424        return $this->get_render_default_value();
425    }
426
427    /**
428     * Get the value of the field rendered as final HTML for the email template.
429     *
430     * Unlike get_render_email_value() which returns structured data for the
431     * backward-compat filter path, this returns ready-to-use HTML for the
432     * type-aware email rendering path.
433     *
434     * @return string HTML for the field value.
435     */
436    private function get_render_email_html_value() {
437        if ( $this->is_of_type( 'select' ) || $this->is_of_type( 'radio' ) || $this->is_of_type( 'checkbox-multiple' ) ) {
438            return $this->render_email_chips( $this->value );
439        }
440        if ( $this->is_of_type( 'checkbox' ) || $this->is_of_type( 'consent' ) ) {
441            return $this->render_email_consent();
442        }
443        if ( $this->is_of_type( 'phone' ) || $this->is_of_type( 'telephone' ) ) {
444            return $this->render_email_phone();
445        }
446        if ( $this->is_of_type( 'url' ) ) {
447            return $this->render_email_url();
448        }
449        if ( $this->is_of_type( 'rating' ) ) {
450            return $this->render_email_rating();
451        }
452        if ( $this->is_of_type( 'file' ) ) {
453            return $this->render_email_file();
454        }
455        if ( $this->is_of_type( 'image-select' ) ) {
456            return $this->render_email_image_select();
457        }
458        return $this->render_email_default();
459    }
460
461    /**
462     * Render an empty value HTML.
463     *
464     * @return string HTML for empty values.
465     */
466    private function render_empty_value_html() {
467        return '<span style="color: ' . Feedback_Email_Renderer::TEXT_SECONDARY_COLOR . ';">&mdash;</span>';
468    }
469
470    /**
471     * Render a default text value for email (text, name, email, textarea, date, time, etc).
472     *
473     * @return string Escaped and formatted HTML.
474     */
475    private function render_email_default() {
476        if ( empty( $this->value ) && $this->value !== '0' ) {
477            return $this->render_empty_value_html();
478        }
479
480        return Contact_Form::escape_and_sanitize_field_value( $this->value );
481    }
482
483    /**
484     * Render tag/chip values for select, radio, and checkbox-multiple fields.
485     *
486     * @param mixed $value The field value (string or array).
487     * @return string HTML with rounded chip elements.
488     */
489    private function render_email_chips( $value ) {
490        if ( empty( $value ) && $value !== '0' ) {
491            return $this->render_empty_value_html();
492        }
493
494        $values = is_array( $value ) ? $value : array( $value );
495        $chips  = array();
496
497        foreach ( $values as $item ) {
498            $safe_item = esc_html( is_string( $item ) ? $item : (string) $item );
499            if ( $safe_item === '' ) {
500                continue;
501            }
502            $chips[] = sprintf(
503                '<div style="display: inline-block; height: 24px; padding: 0 8px; margin: 2px 4px 2px 0; background-color: #f0f0f0; border-radius: 2px; font-size: ' . Feedback_Email_Renderer::FONT_SIZE_FIELD_VALUE . '; line-height: 24px; color: %s;">%s</div>',
504                Feedback_Email_Renderer::TEXT_COLOR,
505                $safe_item
506            );
507        }
508
509        if ( empty( $chips ) ) {
510            return $this->render_empty_value_html();
511        }
512
513        return implode( '<br />', $chips );
514    }
515
516    /**
517     * Render a consent/checkbox field value as a Yes/No chip.
518     *
519     * @return string HTML with a colored chip.
520     */
521    private function render_email_consent() {
522        $is_yes = ! empty( $this->value ) && strtolower( trim( (string) $this->value ) ) !== 'no';
523        $label  = $is_yes ? __( 'Yes', 'jetpack-forms' ) : __( 'No', 'jetpack-forms' );
524
525        return sprintf(
526            '<span style="display: inline-block; padding: 0 8px; border-radius: 2px; font-size: ' . Feedback_Email_Renderer::FONT_SIZE_FIELD_VALUE . '; line-height: 1.4; background-color: #f0f0f0; color: %s;">%s</span>',
527            Feedback_Email_Renderer::TEXT_COLOR,
528            esc_html( $label )
529        );
530    }
531
532    /**
533     * Render a phone field value as a clickable tel: link.
534     *
535     * @return string HTML with tel: link.
536     */
537    private function render_email_phone() {
538        // Guard against non-string values for the same reason as
539        // get_phone_value_with_flag().
540        if ( ! is_string( $this->value ) || empty( $this->value ) ) {
541            return $this->render_empty_value_html();
542        }
543
544        $raw_phone    = preg_replace( '/[^\d+]/', '', $this->value );
545        $country_code = $this->get_country_code_from_phone( $this->value );
546        $flag_prefix  = '';
547
548        if ( ! empty( $country_code ) ) {
549            $flag = self::country_code_to_emoji_flag( $country_code );
550            if ( ! empty( $flag ) ) {
551                $flag_prefix = $flag . ' ';
552            }
553        }
554
555        return $flag_prefix . sprintf(
556            '<a href="tel:%1$s" style="color: %3$s; text-decoration: underline;">%2$s</a>',
557            esc_attr( $raw_phone ),
558            esc_html( $this->value ),
559            self::get_admin_theme_color()
560        );
561    }
562
563    /**
564     * Render a URL field value as a clickable link.
565     *
566     * @return string HTML with clickable link.
567     */
568    private function render_email_url() {
569        if ( ! is_string( $this->value ) || empty( $this->value ) ) {
570            return $this->render_empty_value_html();
571        }
572
573        $url = $this->value;
574
575        // Prepend scheme if missing so the href is valid, but display the original input.
576        if ( ! preg_match( '/^https?:\/\//i', $url ) ) {
577            $url = 'https://' . $url;
578        }
579
580        return sprintf(
581            '<a href="%1$s" style="color: %3$s; text-decoration: underline;" target="_blank">%2$s</a>',
582            esc_url( $url ),
583            esc_html( $this->value ),
584            self::get_admin_theme_color()
585        );
586    }
587
588    /**
589     * Render a rating field value as star characters.
590     *
591     * @return string HTML with gold/gray stars.
592     */
593    private function render_email_rating() {
594        if ( empty( $this->value ) || ! is_string( $this->value ) || strpos( $this->value, '/' ) === false ) {
595            return $this->render_email_default();
596        }
597
598        $parts = explode( '/', $this->value );
599        if ( count( $parts ) !== 2 ) {
600            return $this->render_email_default();
601        }
602
603        $rating = (int) $parts[0];
604        $max    = (int) $parts[1];
605
606        if ( $max <= 0 ) {
607            return $this->render_email_default();
608        }
609
610        $stars = '';
611        for ( $i = 1; $i <= $max; $i++ ) {
612            if ( $i <= $rating ) {
613                $stars .= '<span style="color: #e6a117; font-size: 20px;">&#9733;</span>';
614            } else {
615                $stars .= '<span style="color: #cccccc; font-size: 20px;">&#9733;</span>';
616            }
617        }
618
619        return $stars;
620    }
621
622    /**
623     * Render a file field value with thumbnail, file name, size, and download icon.
624     *
625     * @return string HTML with file info.
626     */
627    private function render_email_file() {
628        // We already know the field is type 'file' (dispatched from get_render_email_html_value).
629        // The value may or may not contain 'field_id' depending on how it was loaded,
630        // so we only check for the 'files' array rather than using is_file_upload_field().
631        if ( ! is_array( $this->value ) || ! isset( $this->value['files'] ) || ! is_array( $this->value['files'] ) ) {
632            return $this->render_email_default();
633        }
634
635        $files = $this->value['files'];
636        if ( empty( $files ) ) {
637            return $this->render_empty_value_html();
638        }
639
640        $file_items = array();
641        foreach ( $files as $file ) {
642            if ( empty( $file['file_id'] ) ) {
643                continue;
644            }
645
646            $file_name = $file['name'] ?? __( 'Attached file', 'jetpack-forms' );
647            $file_size = isset( $file['size'] ) ? size_format( $file['size'] ) : '';
648            $file_url  = apply_filters( 'jetpack_unauth_file_download_url', '', absint( $file['file_id'] ) );
649            $file_type = $file['type'] ?? '';
650
651            $file_items[] = $this->render_email_file_row( $file_name, $file_size, $file_url, $file_type );
652        }
653
654        if ( empty( $file_items ) ) {
655            return $this->render_empty_value_html();
656        }
657
658        return implode( '', $file_items );
659    }
660
661    /**
662     * Render a single file row with thumbnail, name/size, and download icon.
663     *
664     * @param string $file_name The file name.
665     * @param string $file_size The formatted file size.
666     * @param string $file_url  The download URL.
667     * @param string $file_type The MIME type of the file.
668     * @return string HTML table for the file row.
669     */
670    private function render_email_file_row( $file_name, $file_size, $file_url, $file_type = '' ) {
671        $thumbnail_html = $this->get_file_thumbnail_html( $file_name, $file_type );
672
673        // File name â€” linked if download URL is available.
674        $name_html = esc_html( $file_name );
675        if ( ! empty( $file_url ) ) {
676            $name_html = sprintf(
677                '<a href="%1$s" style="color: %2$s; text-decoration: underline;" target="_blank">%3$s</a>',
678                esc_url( $file_url ),
679                Feedback_Email_Renderer::TEXT_COLOR,
680                $name_html
681            );
682        }
683
684        // File size on a second line.
685        $size_html = '';
686        if ( ! empty( $file_size ) ) {
687            $size_html = sprintf(
688                '<div style="font-size: 12px; color: %1$s; line-height: 1.4;">%2$s</div>',
689                Feedback_Email_Renderer::TEXT_SECONDARY_COLOR,
690                esc_html( $file_size )
691            );
692        }
693
694        // Download icon (rasterized from @wordpress/icons 'download').
695        $download_icon = '';
696        if ( ! empty( $file_url ) ) {
697            $download_icon_url = Jetpack_Forms::plugin_url() . 'contact-form/images/file-icons/download@2x.png';
698            $download_icon     = sprintf(
699                '<a href="%1$s" target="_blank" style="text-decoration: none;"><img src="%2$s" width="20" height="20" alt="%3$s" style="display: block; width: 20px; height: 20px; -webkit-user-select: none; user-select: none;" /></a>',
700                esc_url( $file_url ),
701                esc_url( $download_icon_url ),
702                esc_attr__( 'Download', 'jetpack-forms' )
703            );
704        }
705
706        // Build the file row as a table: [thumbnail] [name + size] [download icon].
707        $html  = '<table role="presentation" border="0" cellpadding="0" cellspacing="0" width="100%" style="margin-top: 4px;">';
708        $html .= '<tr>';
709
710        // Thumbnail cell.
711        $html .= '<td width="40" valign="middle" style="padding-right: 12px; width: 40px; vertical-align: middle; text-align: center;">';
712        $html .= $thumbnail_html;
713        $html .= '</td>';
714
715        // Name and size cell.
716        $html .= '<td valign="middle" style="font-size: 13px; line-height: 1.4;">';
717        $html .= '<div>' . $name_html . '</div>';
718        $html .= $size_html;
719        $html .= '</td>';
720
721        // Download icon cell.
722        if ( ! empty( $download_icon ) ) {
723            $html .= '<td width="20" valign="middle" align="right" style="padding-left: 12px; width: 20px;">';
724            $html .= $download_icon;
725            $html .= '</td>';
726        }
727
728        $html .= '</tr>';
729        $html .= '</table>';
730
731        return $html;
732    }
733
734    /**
735     * Get the thumbnail HTML for a file attachment.
736     *
737     * For previewable files (images: jpg, jpeg, png, gif, webp), uses the actual
738     * file URL as the thumbnail when available. For other file types, falls back
739     * to a file-type icon from the file-icons directory.
740     *
741     * @param string $file_name The original file name (used for extension-based icon lookup).
742     * @param string $file_type The MIME type of the file.
743     * @return string HTML for the thumbnail.
744     */
745    private function get_file_thumbnail_html( $file_name = '', $file_type = '' ) {
746        $icon_name = self::get_file_icon_name( $file_name, $file_type );
747        $icon_url  = Jetpack_Forms::plugin_url() . 'contact-form/images/file-icons/' . $icon_name . '@2x.png';
748
749        return sprintf(
750            '<img src="%1$s" width="24" height="24" alt=""
751                style="padding: 8px; border-radius: 50%%; width: 24px; height: 24px; background-color: #f0f0f0; -webkit-user-select: none; user-select: none;" />',
752            esc_url( $icon_url )
753        );
754    }
755
756    /**
757     * Map a file to its icon name based on extension then MIME type category.
758     *
759     * Mirrors the JS logic in modules/file-field/view.js getFileIcon().
760     *
761     * @param string $file_name The file name.
762     * @param string $file_type The MIME type.
763     * @return string The icon filename without extension.
764     */
765    private static function get_file_icon_name( $file_name, $file_type ) {
766        $extension = strtolower( pathinfo( $file_name, PATHINFO_EXTENSION ) );
767
768        $extension_map = array(
769            'pdf'  => 'pdf',
770            'doc'  => 'txt',
771            'docx' => 'txt',
772            'txt'  => 'txt',
773            'ppt'  => 'ppt',
774            'pptx' => 'ppt',
775            'xls'  => 'xls',
776            'xlsx' => 'xls',
777            'csv'  => 'xls',
778            'zip'  => 'zip',
779            'sql'  => 'sql',
780            'cal'  => 'cal',
781            'html' => 'html',
782            'mp3'  => 'mp3',
783            'mp4'  => 'mp4',
784            'png'  => 'png',
785            'jpg'  => 'png',
786            'jpeg' => 'png',
787            'gif'  => 'png',
788            'webp' => 'png',
789        );
790
791        if ( isset( $extension_map[ $extension ] ) ) {
792            return $extension_map[ $extension ];
793        }
794
795        // Fall back to MIME type category.
796        $category     = explode( '/', $file_type )[0] ?? '';
797        $category_map = array(
798            'image' => 'png',
799            'video' => 'mp4',
800            'audio' => 'mp3',
801        );
802
803        return $category_map[ $category ] ?? 'txt';
804    }
805
806    /**
807     * Render an image-select field for email.
808     *
809     * Renders each selected choice as a card with an image thumbnail,
810     * letter code, and label arranged horizontally.
811     *
812     * @return string HTML for the image-select field.
813     */
814    private function render_email_image_select() {
815        if ( ! is_array( $this->value ) || empty( $this->value['choices'] ) || ! is_array( $this->value['choices'] ) ) {
816            return $this->render_empty_value_html();
817        }
818
819        $cards = array();
820        foreach ( $this->value['choices'] as $choice ) {
821            $letter     = isset( $choice['selected'] ) ? esc_html( $choice['selected'] ) : '';
822            $label      = ! empty( $choice['label'] ) ? esc_html( $choice['label'] ) : '';
823            $image_src  = ! empty( $choice['image']['src'] ) ? esc_url( $choice['image']['src'] ) : '';
824            $show_label = ! empty( $choice['showLabels'] );
825
826            // Image thumbnail or gray placeholder at 138×144.
827            if ( $image_src !== '' ) {
828                $image_html = sprintf(
829                    '<div style="padding: 8px 8px 0 8px;"><img src="%s" alt="%s" width="138" height="144" style="display: block; width: 138px; height: 144px; object-fit: cover;" /></div>',
830                    $image_src,
831                    $label !== '' ? $label : $letter
832                );
833            } else {
834                $placeholder_icon = Jetpack_Forms::plugin_url() . 'contact-form/images/field-icons/field-image-select@2x.png';
835                $image_html       = sprintf(
836                    '<div style="padding: 8px 8px 0 8px;"><div style="width: 138px; height: 144px; background-color: #f0f0f0; text-align: center; line-height: 144px;"><img src="%s" alt="" width="24" height="24" style="vertical-align: middle;" /></div></div>',
837                    esc_url( $placeholder_icon )
838                );
839            }
840
841            // Letter code box + label.
842            $caption_html = '';
843            if ( $letter !== '' ) {
844                $caption_html .= sprintf(
845                    '<span style="display: inline-block; min-width: 1em; padding: 4px; line-height: 1; text-align: center; border: 1px solid #dcdcde; border-radius: 2px; font-size: 11px; font-weight: 600; color: #1e1e1e; vertical-align: baseline;">%s</span>',
846                    $letter
847                );
848            }
849
850            if ( $show_label && $label !== '' ) {
851                $caption_html .= sprintf(
852                    ' <span style="font-size: 13px; color: #1e1e1e; vertical-align: baseline;">%s</span>',
853                    $label
854                );
855            }
856
857            // Card with fixed width matching the admin preview (138px image + 16px padding).
858            $card  = '<div style="display: inline-block; vertical-align: top; width: 154px; border: 1px solid #dcdcde; border-radius: 8px; margin: 0 8px 8px 0;">';
859            $card .= $image_html;
860            if ( $caption_html !== '' ) {
861                $card .= sprintf(
862                    '<div style="padding: 4px 8px 8px 8px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">%s</div>',
863                    $caption_html
864                );
865            }
866            $card .= '</div>';
867
868            $cards[] = $card;
869        }
870
871        if ( empty( $cards ) ) {
872            return $this->render_empty_value_html();
873        }
874
875        return implode( '', $cards );
876    }
877
878    /**
879     * Get the default value of the field for rendering.
880     *
881     * @return string
882     */
883    private function get_render_default_value() {
884        if ( $this->is_of_type( 'file' ) ) {
885            $files = array();
886            foreach ( $this->value['files'] as &$file ) {
887                if ( ! isset( $file['size'] ) || ! isset( $file['file_id'] ) ) {
888                    // this shouldn't happen, todo: log this
889                    continue;
890                }
891                $file_name = $file['name'] ?? __( 'Attached file', 'jetpack-forms' );
892                $file_size = isset( $file['size'] ) ? size_format( $file['size'] ) : '';
893                $files[]   = $file_name . ' (' . $file_size . ')';
894            }
895            return implode( ', ', $files );
896        }
897
898        if ( $this->is_of_type( 'image-select' ) ) {
899            // Return the array as is.
900            return $this->value;
901        }
902
903        if ( is_array( $this->value ) ) {
904            return implode( ', ', $this->value );
905        }
906
907        return $this->value;
908    }
909
910    /**
911     * Get the value of the field for the API.
912     *
913     * @return string
914     */
915    private function get_render_api_value() {
916        if ( $this->is_of_type( 'file' ) ) {
917            $files = array();
918            $value = $this->value;
919            foreach ( $value['files'] as $file ) {
920                if ( ! isset( $file['size'] ) || ! isset( $file['file_id'] ) ) {
921                    // this shouldn't happen, todo: log this
922                    continue;
923                }
924                $file_id                = absint( $file['file_id'] );
925                $file['file_id']        = $file_id;
926                $file['size']           = size_format( $file['size'] );
927                $file['url']            = apply_filters( 'jetpack_unauth_file_download_url', '', $file_id );
928                $file['is_previewable'] = $this->is_previewable_file( $file );
929                $files[]                = $file;
930            }
931            $value['files'] = $files;
932            return $value;
933        }
934
935        if ( $this->is_of_type( 'image-select' ) ) {
936            // Return the array as is.
937            return $this->value;
938        }
939
940        if ( $this->is_of_type( 'checkbox-multiple' ) ) {
941            // Since API gets format: collection, return the array as is.
942            return $this->value;
943        }
944
945        if ( is_array( $this->value ) ) {
946            // If the value is an array, we can return it as a JSON string.
947            return implode( ', ', $this->value );
948        }
949        // This method is deprecated, use render_value instead.
950        return $this->value;
951    }
952    /**
953     * Get the value of the field for rendering when submitting.
954     *
955     * This method is used to prepare the value for submission, especially for file fields.
956     *
957     * @return array|string The prepared value for submission.
958     */
959    private function get_render_submit_value() {
960        if ( $this->is_of_type( 'file' ) ) {
961            $files = array();
962            foreach ( $this->value['files'] as $file ) {
963                if ( ! isset( $file['size'] ) || ! isset( $file['file_id'] ) ) {
964                    // this shouldn't happen, todo: log this
965                    continue;
966                }
967                $files[] = array(
968                    'file_id' => absint( $file['file_id'] ),
969                    'name'    => $file['name'] ?? '',
970                    'size'    => absint( $file['size'] ),
971                    'type'    => $file['type'] ?? '',
972                );
973            }
974
975            return array(
976                'field_id' => $this->get_form_field_id(),
977                'files'    => $files,
978            );
979        }
980
981        return $this->value;
982    }
983
984    /**
985     * Check if the field is of a specific type.
986     *
987     * @param string $type The type to check against.
988     *
989     * @return bool True if the field is of the specified type, false otherwise.
990     */
991    public function is_of_type( $type ) {
992        return $this->type === $type;
993    }
994
995    /**
996     * Check if the field should be compiled.
997     *
998     * @return bool
999     */
1000    public function compile_field() {
1001        return $this->get_meta_key_value( 'render' ) === false;
1002    }
1003
1004    /**
1005     * Get the type of the field.
1006     *
1007     * @return string
1008     */
1009    public function get_type() {
1010        return $this->type;
1011    }
1012
1013    /**
1014     * Get the icon filename for a given field type.
1015     *
1016     * @param string $type The field type.
1017     * @return string The icon name (without path or extension).
1018     */
1019    public static function get_icon_name_for_type( $type ) {
1020        $map = array(
1021            'text'              => 'field-text',
1022            'name'              => 'field-name',
1023            'email'             => 'field-email',
1024            'textarea'          => 'field-textarea',
1025            'select'            => 'field-select',
1026            'radio'             => 'field-single-choice',
1027            'checkbox'          => 'field-checkbox',
1028            'checkbox-multiple' => 'field-multiple-choice',
1029            'phone'             => 'field-telephone',
1030            'telephone'         => 'field-telephone',
1031            'number'            => 'field-number',
1032            'slider'            => 'field-slider',
1033            'date'              => 'field-date',
1034            'time'              => 'field-time',
1035            'url'               => 'field-url',
1036            'rating'            => 'field-rating',
1037            'image-select'      => 'field-image-select',
1038            'file'              => 'field-file',
1039            'consent'           => 'field-consent',
1040            'hidden'            => 'field-hidden',
1041        );
1042        return $map[ $type ] ?? 'field-text';
1043    }
1044
1045    /**
1046     * Get the WordPress admin theme color for use in email links.
1047     *
1048     * Resolves the site admin's admin_color preference to the matching
1049     * --wp-admin-theme-color hex value so email links visually match
1050     * the Forms dashboard.
1051     *
1052     * @return string Hex color string.
1053     */
1054    public static function get_admin_theme_color() {
1055        if ( self::$admin_theme_color !== null ) {
1056            return self::$admin_theme_color;
1057        }
1058
1059        $color_scheme = 'fresh';
1060        $admin_user   = get_user_by( 'email', get_option( 'admin_email' ) );
1061        if ( $admin_user ) {
1062            $saved = get_user_option( 'admin_color', $admin_user->ID );
1063            if ( $saved ) {
1064                $color_scheme = $saved;
1065            }
1066        }
1067
1068        $map = array(
1069            'fresh'     => '#2271b1',
1070            'light'     => '#0085ba',
1071            'blue'      => '#096484',
1072            'coffee'    => '#c7a589',
1073            'ectoplasm' => '#a3b745',
1074            'midnight'  => '#e14d43',
1075            'ocean'     => '#9ebaa0',
1076            'sunrise'   => '#dd823b',
1077            'modern'    => '#3858e9',
1078        );
1079
1080        self::$admin_theme_color = $map[ $color_scheme ] ?? '#2271b1';
1081        return self::$admin_theme_color;
1082    }
1083
1084    /**
1085     * Get the meta array of the field.
1086     *
1087     * @return array
1088     */
1089    public function get_meta() {
1090        return $this->meta;
1091    }
1092
1093    /**
1094     * Get a specific meta value by key.
1095     *
1096     * @param string $meta_key The key of the meta to retrieve.
1097     *
1098     * @return mixed|null Returns the value of the meta key if it exists, null otherwise.
1099     */
1100    public function get_meta_key_value( $meta_key ) {
1101        if ( isset( $this->meta[ $meta_key ] ) ) {
1102            return $this->meta[ $meta_key ];
1103        }
1104        return null;
1105    }
1106
1107    /**
1108     * Get the serialized representation of the field.
1109     *
1110     * @return array
1111     */
1112    public function serialize() {
1113        return array(
1114            'key'           => $this->get_key(),
1115            'label'         => $this->get_label(),
1116            'value'         => $this->get_value(),
1117            'type'          => $this->get_type(),
1118            'meta'          => $this->get_meta(),
1119            'form_field_id' => $this->get_form_field_id(),
1120        );
1121    }
1122    /**
1123     * Create a Feedback_Field object from serialized data.
1124     *
1125     * @param array $data The serialized data.
1126     *
1127     * @return Feedback_Field|null Returns a Feedback_Field object or null if the data is invalid.
1128     */
1129    public static function from_serialized( $data ) {
1130        if ( ! is_array( $data ) || ! isset( $data['key'] ) || ! isset( $data['value'] ) || ! isset( $data['label'] ) ) {
1131            return null;
1132        }
1133
1134        return new self(
1135            $data['key'],
1136            $data['label'],
1137            $data['value'],
1138            $data['type'] ?? 'basic',
1139            $data['meta'] ?? array(),
1140            $data['form_field_id'] ?? ''
1141        );
1142    }
1143
1144    /**
1145     * Normalize Unicode characters in a string.
1146     *
1147     * This is only used for V2 version of the feedback. Since we didn't escape special characters
1148     *
1149     * @param string $string The string to normalize.
1150     *
1151     * @return string
1152     */
1153    public static function normalize_unicode( $string ) {
1154        // Case 1: JSON-style escapes, e.g. "\u003cstrong\u003e" or "\ud83d\ude48"
1155        if ( strpos( $string, '\u' ) !== false ) {
1156            $decoded = json_decode( '"' . $string . '"' );
1157            if ( self::is_valid_json_decode( $decoded ) ) {
1158                return $decoded;
1159            }
1160        }
1161
1162        // Case 2: Raw surrogate dumps, e.g. "ud83dude48" or "u003cstrongu003e"
1163        if ( preg_match( '/u[0-9a-fA-F]{4}/', $string ) ) {
1164            // Add missing backslashes before each uXXXX
1165            $json_ready = preg_replace( '/u([0-9a-fA-F]{4})/', '\\\\u$1', $string );
1166            $decoded    = json_decode( '"' . $json_ready . '"' );
1167            if ( self::is_valid_json_decode( $decoded ) ) {
1168                return $decoded;
1169            }
1170        }
1171
1172        // Fallback: return unchanged
1173        return $string;
1174    }
1175
1176    /**
1177     * Check if the decoded JSON is valid.
1178     *
1179     * @param mixed $decoded The decoded JSON data.
1180     * @return bool True if there are no errors, false otherwise.
1181     */
1182    private static function is_valid_json_decode( $decoded ) {
1183        return $decoded !== null && json_last_error() === JSON_ERROR_NONE;
1184    }
1185
1186    /**
1187     * Create a Feedback_Field object from serialized data.
1188     *
1189     * @param array $data The serialized data.
1190     *
1191     * @return Feedback_Field|null Returns a Feedback_Field object or null if the data is invalid.
1192     */
1193    public static function from_serialized_v2( $data ) {
1194        if ( ! is_array( $data ) || ! isset( $data['key'] ) || ! isset( $data['value'] ) || ! isset( $data['label'] ) ) {
1195            return null;
1196        }
1197
1198        if ( is_string( $data['value'] ) ) { // just normalize plain string for now.
1199            $data['value'] = self::normalize_unicode( $data['value'] );
1200        }
1201
1202        if ( is_string( $data['label'] ) ) { // just normalize plain string for now.
1203            $data['label'] = self::normalize_unicode( $data['label'] );
1204        }
1205
1206        return new self(
1207            $data['key'],
1208            $data['label'],
1209            $data['value'],
1210            $data['type'] ?? 'basic',
1211            $data['meta'] ?? array(),
1212            $data['form_field_id'] ?? ''
1213        );
1214    }
1215
1216    /**
1217     * Check if the field has a file
1218     *
1219     * @return bool
1220     */
1221    public function has_file() {
1222        if ( $this->is_of_type( 'file' ) ) {
1223            if ( ! isset( $this->value['files'] ) || ! is_array( $this->value['files'] ) ) {
1224                return false;
1225            }
1226            return count( $this->value['files'] ) > 0;
1227        }
1228
1229        return false;
1230    }
1231
1232    /**
1233     * Checks if the file is previewable based on its type or extension.
1234     * Only image formats are allowed to be previewed in the modal. PDFs may be previewed in the browser elsewhere, but not in the modal.
1235     *
1236     * @param array $file File data.
1237     * @return bool True if the file is previewable, false otherwise.
1238     */
1239    private function is_previewable_file( $file ) {
1240        $file_type = strtolower( pathinfo( $file['name'], PATHINFO_EXTENSION ) );
1241        // Check if the file is previewable based on its type or extension.
1242        // Note: This is a simplified check and does not match if the file is allowed to be uploaded by the server.
1243        $previewable_types = array( 'jpg', 'jpeg', 'png', 'gif', 'webp' );
1244        return in_array( $file_type, $previewable_types, true );
1245    }
1246}