PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 16.3-beta
Jetpack – WP Security, Backup, Speed, & Growth v16.3-beta
16.3-beta 16.3-a.5 16.3-a.7 16.3-a.3 16.3-a.1 16.2 16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 All 507 releases
jetpack / jetpack_vendor / automattic / jetpack-forms / src / contact-form / class-feedback-field.php

class-feedback-field.php in Jetpack – WP Security, Backup, Speed, & Growth 16.3-beta, at jetpack_vendor/automattic/jetpack-forms/src/contact-form/class-feedback-field.php

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