Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
83.90% covered (warning)
83.90%
1699 / 2025
62.50% covered (warning)
62.50%
45 / 72
CRAP
0.00% covered (danger)
0.00%
0 / 1
Contact_Form_Field
83.98% covered (warning)
83.98%
1699 / 2023
62.50% covered (warning)
62.50%
45 / 72
1662.63
0.00% covered (danger)
0.00%
0 / 1
 __construct
95.00% covered (success)
95.00%
114 / 120
0.00% covered (danger)
0.00%
0 / 1
26
 add_error
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 is_error
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 has_value
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
4.05
 has_conditional_logic
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 validate
55.17% covered (warning)
55.17%
80 / 145
0.00% covered (danger)
0.00%
0 / 1
349.68
 sanitize_text_field
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_option_value
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 render
69.47% covered (warning)
69.47%
66 / 95
0.00% covered (danger)
0.00%
0 / 1
99.07
 get_computed_field_value
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
21
 get_conditional_logic_value
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 get_filtered_hidden_field_value
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 is_submitted_hidden_field_value
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 render_label
94.12% covered (success)
94.12%
32 / 34
0.00% covered (danger)
0.00%
0 / 1
19.07
 is_label_hidden_by_block_visibility
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_block_visibility_aria_label
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 get_hidden_label_aria_label_attr
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 get_file_dropzone_aria_label
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
4
 render_legend_as_label
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
10.02
 render_input_field
85.71% covered (warning)
85.71%
18 / 21
0.00% covered (danger)
0.00%
0 / 1
8.19
 get_error_message_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_error_div
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 get_help_text
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
3.03
 get_format_hint
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_described_by
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_description_parts
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
3
 get_field_descriptions
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
 set_invalid_message
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 render_email_field
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 render_telephone_field
95.65% covered (success)
95.65%
88 / 92
0.00% covered (danger)
0.00%
0 / 1
9
 render_url_field
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 render_textarea_field
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
3.00
 render_radio_field
82.22% covered (warning)
82.22%
74 / 90
0.00% covered (danger)
0.00%
0 / 1
33.73
 render_other_input_field
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 render_checkbox_field
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
9
 render_consent_field
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
7
 render_file_field
0.00% covered (danger)
0.00%
0 / 66
0.00% covered (danger)
0.00%
0 / 1
12
 sanitize_file_field_content
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
3
 get_file_field_allowed_html
100.00% covered (success)
100.00%
49 / 49
100.00% covered (success)
100.00%
1 / 1
7
 render_hidden_field
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
3
 get_file_field_max_files
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_file_field_max_files_limit
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 get_file_field_max_upload_size
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 get_file_field_accepted_mime_types
100.00% covered (success)
100.00%
29 / 29
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_file_field_assets
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
6
 get_unauth_endpoint_url
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 render_checkbox_multiple_field
82.28% covered (warning)
82.28%
65 / 79
0.00% covered (danger)
0.00%
0 / 1
29.76
 render_select_field
90.91% covered (success)
90.91%
20 / 22
0.00% covered (danger)
0.00%
0 / 1
8.05
 get_date_formats
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 get_date_format
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 render_date_field
91.67% covered (success)
91.67%
66 / 72
0.00% covered (danger)
0.00%
0 / 1
4.01
 render_time_field
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 render_image_select_field
78.12% covered (warning)
78.12%
100 / 128
0.00% covered (danger)
0.00%
0 / 1
58.60
 render_number_field
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 render_default_field
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 get_form_variation_style_properties
93.10% covered (success)
93.10%
54 / 58
0.00% covered (danger)
0.00%
0 / 1
19.12
 render_outline_label
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
5
 render_animated_label
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 render_below_label
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 render_field
92.92% covered (success)
92.92%
105 / 113
0.00% covered (danger)
0.00%
0 / 1
34.41
 get_field_extra
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 maybe_override_type
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
3.02
 is_field_renderable
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
5
 get_form_style
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 has_inset_label
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 type_has_inset_label
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 render_rating_field
84.51% covered (warning)
84.51%
60 / 71
0.00% covered (danger)
0.00%
0 / 1
11.45
 render_slider_field
93.10% covered (success)
93.10%
54 / 58
0.00% covered (danger)
0.00%
0 / 1
8.02
 enqueue_slider_field_assets
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
 get_translatable_countries
100.00% covered (success)
100.00%
241 / 241
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_phone_field_assets
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
3
 trim_image_select_options
78.57% covered (warning)
78.57%
11 / 14
0.00% covered (danger)
0.00%
0 / 1
6.35
1<?php
2/**
3 * Contact_Form_Field class.
4 *
5 * @package automattic/jetpack-forms
6 */
7
8namespace Automattic\Jetpack\Forms\ContactForm;
9
10use Automattic\Jetpack\Assets;
11use Automattic\Jetpack\Constants;
12use Automattic\Jetpack\Forms\Jetpack_Forms;
13
14if ( ! defined( 'ABSPATH' ) ) {
15    exit( 0 );
16}
17
18/**
19 * Class for the contact-field shortcode.
20 * Parses shortcode to output the contact form field as HTML.
21 * Validates input.
22 */
23class Contact_Form_Field extends Contact_Form_Shortcode {
24
25    /**
26     * Number of files a file upload field accepts when its `maxfiles` attribute says nothing.
27     *
28     * One, so that a field authored before the setting existed keeps behaving exactly as it did.
29     *
30     * @var int
31     */
32    const FILE_FIELD_DEFAULT_MAX_FILES = 1;
33
34    /**
35     * Highest number of files a filter may raise a field to.
36     *
37     * Separate from FILE_FIELD_MAX_FILES_LIMIT, which bounds what an author can choose: a site that
38     * wants more headroom than the editor offers can filter its way up to here, and no further. The
39     * endpoint imposes no count limit of its own that refuses anything â€” its per-site budgets log
40     * and alert but still store the file â€” so this is the only thing standing between a filter and
41     * a single site uploading as much as it likes.
42     *
43     * @var int
44     */
45    const FILE_FIELD_MAX_FILES_ABSOLUTE_LIMIT = 25;
46
47    /**
48     * Highest number of files an author can choose for a field, whatever `maxfiles` asks for.
49     *
50     * This bounds how many files can be attached to a response, not how many bytes reach the site.
51     * Each file is uploaded as soon as the visitor picks it, so by the time anything here runs the
52     * transfer has already happened and the submission carries only references â€” and the upload
53     * endpoint is reachable on its own besides. Read this as a limit on the shape of a response,
54     * and look to the endpoint's own quotas for anything to do with volume.
55     *
56     * Keep in sync with `MAX_FILES_LIMIT` in `blocks/field-file/edit.jsx`, which bounds the editor
57     * control; `test_file_field_ceiling_matches_the_editor_control` fails if they drift.
58     *
59     * @var int
60     */
61    const FILE_FIELD_MAX_FILES_LIMIT = 10;
62
63    /**
64     * Maximum size, in bytes, of a single uploaded file.
65     *
66     * @var int
67     */
68    const FILE_FIELD_MAX_UPLOAD_SIZE = 20 * 1024 * 1024;
69
70    /**
71     * The shortcode name.
72     *
73     * @var string
74     */
75    public $shortcode_name = 'contact-field';
76
77    /**
78     * Field types that never render a style-specific label.
79     *
80     * These have no single labellable input â€” they are groups of inputs, or a
81     * control with its own labelling â€” so every non-default form style falls back
82     * to the plain default label.
83     *
84     * @var string[]
85     */
86    const TYPES_WITHOUT_STYLED_LABEL = array( 'checkbox', 'checkbox-multiple', 'radio', 'consent', 'file' );
87
88    /**
89     * Field types that never render an *inset* (Outlined / Animated) label.
90     *
91     * Their input is not a single text-like box for a label to sit inside, so an
92     * inset label would overlap the control. Styles that render the label outside
93     * the field, such as 'below', still apply â€” unlike TYPES_WITHOUT_STYLED_LABEL,
94     * this only opts out of the inset styles.
95     *
96     * Keep in sync with the editor (`blocks/label/edit.jsx`) and the wrapper
97     * exclusion list in `contact-form/css/grunion.scss`.
98     *
99     * @var string[]
100     */
101    const TYPES_WITHOUT_INSET_LABEL = array( 'slider' );
102
103    /**
104     * The parent form.
105     *
106     * @var Contact_Form
107     */
108    public $form;
109
110    /**
111     * Default or POSTed value.
112     *
113     * @var string|string[]
114     */
115    public $value;
116
117    /**
118     * Is the input valid?
119     *
120     * @var bool
121     */
122    public $error = false;
123
124    /**
125     * Styles to be applied to the field
126     *
127     * @var string
128     */
129    public $block_styles = '';
130
131    /**
132     * Classes to be applied to the field
133     *
134     * @var string
135     */
136    public $field_classes = '';
137
138    /**
139     * Styles to be applied to the field
140     *
141     * @var string
142     */
143    public $field_styles = '';
144
145    /**
146     * Classes to be applied to the field option
147     *
148     * @var string
149     */
150    public $option_classes = '';
151
152    /**
153     * Styles to be applied to the field option
154     *
155     * @var string
156     */
157    public $option_styles = '';
158
159    /**
160     * Classes to be applied to the field
161     *
162     * @var string
163     */
164    public $label_classes = '';
165
166    /**
167     * Styles to be applied to the field
168     *
169     * @var string
170     */
171    public $label_styles = '';
172
173    /**
174     * Input tuple used for the cached hidden-field filter result.
175     *
176     * @var array|null
177     */
178    private $hidden_field_filter_input;
179
180    /**
181     * Cached hidden-field filter result.
182     *
183     * @var mixed
184     */
185    private $hidden_field_filter_value;
186
187    /**
188     * Description markup (help text, format hint, error div) built at the input
189     * site but held back so an inset-label wrapper can emit it outside the
190     * field div. Null when nothing has been deferred.
191     *
192     * Building it once, where the input's aria-describedby is built, is what
193     * keeps the emitted ids and the referenced ids identical.
194     *
195     * @since 8.0.0
196     *
197     * @var string|null
198     */
199    private $deferred_descriptions = null;
200
201    /**
202     * Constructor function.
203     *
204     * @param array        $attributes An associative array of shortcode attributes.  @see shortcode_atts().
205     * @param null|string  $content Null for selfclosing shortcodes.  The inner content otherwise.
206     * @param Contact_Form $form The parent form.
207     */
208    public function __construct( $attributes, $content = null, $form = null ) {
209        $attributes = shortcode_atts(
210            array(
211                'label'                        => null,
212                'togglelabel'                  => null,
213                'type'                         => 'text',
214                'required'                     => false,
215                'requiredtext'                 => null,
216                'requiredindicator'            => true,
217                'options'                      => array(),
218                'optionsdata'                  => array(),
219                'allowother'                   => null,
220                'isother'                      => null,
221                'otherplaceholder'             => null,
222                'id'                           => null,
223                'style'                        => null,
224                'fieldbackgroundcolor'         => null,
225                'buttonbackgroundcolor'        => null,
226                'buttonborderradius'           => null,
227                'buttonborderwidth'            => null,
228                'textcolor'                    => null,
229                'default'                      => null,
230                'values'                       => null,
231                'placeholder'                  => null,
232                'class'                        => null,
233                'width'                        => null,
234                'consenttype'                  => null,
235                'dateformat'                   => null,
236                'helptext'                     => null,
237                'implicitconsentmessage'       => null,
238                'explicitconsentmessage'       => null,
239                'borderradius'                 => null,
240                'borderwidth'                  => null,
241                'lineheight'                   => null,
242                'labellineheight'              => null,
243                'bordercolor'                  => null,
244                'inputcolor'                   => null,
245                'labelcolor'                   => null,
246                'labelfontsize'                => null,
247                'fieldfontsize'                => null,
248                'labelclasses'                 => null,
249                'labelstyles'                  => null,
250                'inputclasses'                 => null,
251                'inputstyles'                  => null,
252                'optionclasses'                => null,
253                'optionstyles'                 => null,
254                'min'                          => null,
255                'max'                          => null,
256                'minlabel'                     => null,
257                'maxlabel'                     => null,
258                'step'                         => null,
259                'maxfiles'                     => null,
260                'fieldwrapperclasses'          => null,
261                'stylevariationattributes'     => array(),
262                'stylevariationclasses'        => null,
263                'stylevariationstyles'         => null,
264                'optionsclasses'               => null,
265                'optionsstyles'                => null,
266                'align'                        => null,
267                'variation'                    => null,
268                'iconstyle'                    => null, // For rating field icon style (lowercase for shortcode compatibility)
269                // full phone field attributes, might become a standalone country list input block
270                'showcountryselector'          => false,
271                'searchplaceholder'            => false,
272                // Image select field attributes
273                'ismultiple'                   => null,
274                'showlabels'                   => null,
275                'issupersized'                 => null,
276                'randomizeoptions'             => null,
277                'showotheroption'              => null,
278                // derived from block metadata for blockVisibility support
279                'labelhiddenbyblockvisibility' => null,
280                // JSON-encoded conditional logic config; decoded below.
281                'conditionallogic'             => null,
282            ),
283            $attributes,
284            'contact-field'
285        );
286
287        if ( ! empty( $attributes['conditionallogic'] ) && is_string( $attributes['conditionallogic'] ) ) {
288            $decoded                        = json_decode( html_entity_decode( $attributes['conditionallogic'], ENT_COMPAT ), true );
289            $attributes['conditionallogic'] = is_array( $decoded ) ? $decoded : null;
290        } elseif ( ! is_array( $attributes['conditionallogic'] ) ) {
291            $attributes['conditionallogic'] = null;
292        }
293
294        // special default for subject field
295        if ( 'subject' === $attributes['type'] && $attributes['default'] === null && $form !== null ) {
296            $attributes['default'] = $form->get_attribute( 'subject' );
297        }
298
299        // allow required=1 or required=true
300        if ( '1' === $attributes['required'] || 'true' === strtolower( $attributes['required'] ) ) {
301            $attributes['required'] = true;
302        } else {
303            $attributes['required'] = false;
304        }
305
306        if ( $attributes['requiredtext'] === null ) {
307            $attributes['requiredtext'] = __( '(required)', 'jetpack-forms' );
308        }
309
310        // parse out comma-separated options list (for selects, radios, and checkbox-multiples)
311        if ( ! empty( $attributes['options'] ) && is_string( $attributes['options'] ) ) {
312            $attributes['options'] = array_map( 'trim', explode( ',', $attributes['options'] ) );
313
314            if ( ! empty( $attributes['values'] ) && is_string( $attributes['values'] ) ) {
315                $attributes['values'] = array_map( 'trim', explode( ',', $attributes['values'] ) );
316            }
317        }
318
319        if ( ! empty( $attributes['optionsdata'] ) ) {
320            $attributes['optionsdata'] = json_decode( html_entity_decode( $attributes['optionsdata'], ENT_COMPAT ), true );
321        }
322
323        // allow boolean values for showcountryselector, only if it's set so we don't pollute other fields attrs
324        if ( isset( $attributes['showcountryselector'] ) ) {
325            if ( true === $attributes['showcountryselector'] || '1' === $attributes['showcountryselector'] || 'true' === strtolower( $attributes['showcountryselector'] ) ) {
326                $attributes['showcountryselector'] = true;
327            } else {
328                $attributes['showcountryselector'] = false;
329            }
330        }
331
332        if ( $form ) {
333            // make a unique field ID based on the label, with an incrementing number if needed to avoid clashes
334            $form_id = $form->get_attribute( 'id' );
335            $id      = $attributes['id'] ?? false;
336
337            $unescaped_label = $this->unesc_attr( $attributes['label'] );
338            $unescaped_label = str_replace( '%', '-', $unescaped_label ); // jQuery doesn't like % in IDs?
339            $unescaped_label = preg_replace( '/[^a-zA-Z0-9.-_:]/', '', $unescaped_label );
340
341            if ( empty( $id ) ) {
342                $id        = sanitize_title_with_dashes( 'g' . $form_id . '-' . $unescaped_label );
343                $i         = 0;
344                $max_tries = 99;
345                while ( isset( $form->fields[ $id ] ) ) {
346                    ++$i;
347                    $id = sanitize_title_with_dashes( 'g' . $form_id . '-' . $unescaped_label . '-' . $i );
348
349                    if ( $i > $max_tries ) {
350                        break;
351                    }
352                }
353            } elseif ( isset( $form->fields[ $id ] ) ) {
354                // A manually-set field ID (including the Name field's default IDs
355                // such as "name"/"first-name") is carried verbatim when a field is
356                // duplicated or copy/pasted, so two fields can end up sharing an ID.
357                // Duplicate IDs render the same input name: browsers mirror typing
358                // across the fields and only one value survives submission, dropping
359                // the rest from stored responses and emails. Suffix the later
360                // duplicates ("name" -> "name-2" -> "name-3", â€¦) to keep every field
361                // ID unique, matching generateUniqueFormFieldId() on the editor side.
362                // See FORMS-724.
363                $base = $id;
364                $i    = 2;
365                $id   = $base . '-' . $i;
366                while ( isset( $form->fields[ $id ] ) ) {
367                    ++$i;
368                    $id = $base . '-' . $i;
369                }
370            }
371
372            $attributes['id'] = $id;
373        }
374
375        parent::__construct( $attributes, $content );
376
377        // Store parent form
378        $this->form = $form;
379    }
380
381    /**
382     * This field's input is invalid.  Flag as invalid and add an error to the parent form
383     *
384     * @param string $message The error message to display on the form.
385     */
386    public function add_error( $message ) {
387        $this->error = true;
388        $this->form->add_error( $this->get_attribute( 'id' ), $message );
389    }
390
391    /**
392     * Is the field input invalid?
393     *
394     * @see $error
395     *
396     * @return bool
397     */
398    public function is_error() {
399        return $this->error;
400    }
401
402    /**
403     * Check if the field has a value.
404     *
405     * This is used to determine if the field has been filled out by the user.
406     *
407     * @return bool True if the field has a value, false otherwise.
408     */
409    public function has_value() {
410        $field_id    = $this->get_attribute( 'id' );
411        $field_value = isset( $_POST[ $field_id ] ) ? wp_unslash( $_POST[ $field_id ] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- no site changes.
412
413        if ( is_array( $field_value ) ) {
414            if ( empty( $field_value ) ) {
415                return false;
416            }
417            return ! empty( array_filter( $field_value ) );
418        }
419        return ! empty( trim( $field_value ) );
420    }
421
422    /**
423     * Whether this field's visibility is governed by conditional logic.
424     *
425     * @return bool True when the field carries an enabled conditional-logic config.
426     */
427    public function has_conditional_logic() {
428        $logic = $this->get_attribute( 'conditionallogic' );
429
430        return is_array( $logic ) && ! empty( $logic['enabled'] );
431    }
432
433    /**
434     * Validates the form input
435     */
436    public function validate() {
437        // If the field is already invalid, don't validate it again.
438        if ( $this->is_error() ) {
439            return;
440        }
441
442        $field_type = $this->maybe_override_type();
443        // If it's not required, there's nothing to validate
444        if ( ! $this->get_attribute( 'required' ) && ! $this->has_value() ) {
445            return;
446        }
447
448        if ( ! $this->is_field_renderable( $field_type ) ) {
449            return;
450        }
451
452        $field_id    = $this->get_attribute( 'id' );
453        $field_label = $this->get_attribute( 'label' );
454
455        if ( isset( $_POST[ $field_id ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- no site changes.
456            if ( is_array( $_POST[ $field_id ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- no site changes.
457                $field_value = array_map( 'sanitize_text_field', wp_unslash( $_POST[ $field_id ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verification should happen in caller.
458            } else {
459                $field_value = sanitize_text_field( wp_unslash( $_POST[ $field_id ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verification should happen in caller.
460            }
461        } else {
462            $field_value = '';
463        }
464
465        switch ( $field_type ) {
466            case 'url':
467                if ( ! is_string( $field_value ) || empty( $field_value ) || ! preg_match(
468                    // Changes to this regex should be synced with the regex in the render_url_field method of this class as both validate the same input. Note that this regex is in PCRE format.
469                    '%^(?:(?:https?|ftp)://)?(?:\S+(?::\S*)?@|\d{1,3}(?:\.\d{1,3}){3}|(?:(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)(?:\.(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)*(?:\.[a-z\x{00a1}-\x{ffff}]{2,6}))(?::\d+)?(?:[^\s]*)?$%iu',
470                    $field_value
471                ) ) {
472                    /* translators: %s is the name of a form field */
473                    $this->add_error( sprintf( __( '%s: Please enter a valid URL - https://www.example.com.', 'jetpack-forms' ), $field_label ) );
474                }
475                break;
476            case 'email':
477                // Make sure the email address is valid
478                if ( ! is_string( $field_value ) || ! is_email( $field_value ) ) {
479                    /* translators: %s is the name of a form field */
480                    $this->add_error( sprintf( __( '%s requires a valid email address.', 'jetpack-forms' ), $field_label ) );
481                }
482                break;
483            case 'checkbox-multiple':
484                // Check that there is at least one option selected
485                if ( empty( $field_value ) ) {
486                    /* translators: %s is the name of a form field */
487                    $this->add_error( sprintf( __( '%s requires at least one selection.', 'jetpack-forms' ), $field_label ) );
488                } else {
489
490                    $options_data    = (array) $this->get_attribute( 'optionsdata' );
491                    $possible_values = array();
492                    if ( ! empty( $options_data ) ) {
493                        foreach ( $options_data as $option_index => $option ) {
494                            $option_label = isset( $option['label'] ) ? Contact_Form_Plugin::strip_tags( $option['label'] ) : '';
495                            if ( is_string( $option_label ) && '' !== $option_label ) {
496                                $possible_values[] = $this->get_option_value( $this->get_attribute( 'values' ), $option_index, $option_label );
497                            }
498                        }
499                    } else {
500                        foreach ( (array) $this->get_attribute( 'options' ) as $option_index => $option ) {
501                            $option = Contact_Form_Plugin::strip_tags( $option );
502                            if ( is_string( $option ) && '' !== $option ) {
503                                $possible_values[] = $this->get_option_value( $this->get_attribute( 'values' ), $option_index, $option );
504                            }
505                        }
506                    }
507
508                    $non_empty_options = array_map( array( $this, 'sanitize_text_field' ), $possible_values );
509
510                    foreach ( $field_value  as $field_value_item ) {
511                        if ( ! in_array( $field_value_item, $non_empty_options, true ) ) {
512                            /* translators: %s is the name of a form field */
513                            $this->add_error( sprintf( __( '%s requires at least one selection.', 'jetpack-forms' ), $field_label ) );
514                            break;
515                        }
516                    }
517                }
518                break;
519            case 'radio':
520                // Check that there is at least one option selected
521                if ( empty( $field_value ) ) {
522                    /* translators: %s is the name of a form field */
523                    $this->add_error( sprintf( __( '%s requires at least one selection.', 'jetpack-forms' ), $field_label ) );
524                } else {
525                    // Check that the selected options are valid
526                    $options      = (array) $this->get_attribute( 'options' );
527                    $options_data = (array) $this->get_attribute( 'optionsdata' );
528                    $allow_other  = $this->get_attribute( 'allowother' );
529
530                    if ( ! empty( $options_data ) ) {
531                        $options = array_map(
532                            function ( $option ) {
533                                return $this->sanitize_text_field( trim( $option['label'] ) );
534                            },
535                            $options_data
536                        );
537                    } else {
538                        $options = array_map( array( $this, 'sanitize_text_field' ), $options );
539                    }
540                    $non_empty_options = array_filter(
541                        $options,
542                        function ( $option ) {
543                            return $option !== '';
544                        }
545                    );
546
547                    // Validate Other option values, which may include custom user text.
548                    $is_valid_other = false;
549                    if ( $allow_other ) {
550                        $other_label = null;
551                        foreach ( $options_data as $option ) {
552                            if ( ! empty( $option['isOther'] ) ) {
553                                $other_label = Contact_Form_Plugin::strip_tags( $option['label'] );
554                                break;
555                            }
556                        }
557
558                        if ( ! empty( $other_label ) ) {
559                            $other_prefix = $other_label . ': ';
560
561                            if ( $field_value === $other_label ) {
562                                $is_valid_other = true;
563                            } elseif ( strpos( $field_value, $other_prefix ) === 0 ) {
564                                $custom_text = trim( substr( $field_value, strlen( $other_prefix ) ) );
565
566                                if ( $this->get_attribute( 'required' ) && empty( $custom_text ) ) {
567                                    /* translators: %1$s is the name of a form field, %2$s is the option label */
568                                    $this->add_error( sprintf( __( '%1$s requires a response when "%2$s" is selected.', 'jetpack-forms' ), $field_label, $other_label ) );
569                                    break;
570                                }
571
572                                $is_valid_other = true;
573                            }
574                        }
575                    }
576
577                    if ( ! in_array( $field_value, $non_empty_options, true ) && ! $is_valid_other ) {
578                        /* translators: %s is the name of a form field */
579                        $this->add_error( sprintf( __( '%s requires at least one selection.', 'jetpack-forms' ), $field_label ) );
580                        break;
581                    }
582                }
583                break;
584            case 'image-select':
585                // Check that there is at least one option selected
586                if ( empty( $field_value ) ) {
587                    /* translators: %s is the name of a form field */
588                    $this->add_error( sprintf( __( '%s requires at least one selection.', 'jetpack-forms' ), $field_label ) );
589                } else {
590                    // Check that the selected options are valid
591                    $options      = (array) $this->get_attribute( 'options' );
592                    $options_data = (array) $this->get_attribute( 'optionsdata' );
593
594                    if ( ! empty( $options_data ) ) {
595                        // Extract letters from options_data for validation
596                        $options = array_map(
597                            function ( $option ) {
598                                return sanitize_text_field( trim( $option['letter'] ?? '' ) );
599                            },
600                            $options_data
601                        );
602                    }
603
604                    $non_empty_options = array_filter(
605                        $options,
606                        function ( $option ) {
607                            return $option !== '';
608                        }
609                    );
610
611                    // For single selection (radio), check if the selected value is in the options
612                    if ( ! $this->get_attribute( 'ismultiple' ) ) {
613                        // Decode the JSON response to get the selected value
614                        $decoded_value  = json_decode( $field_value, true );
615                        $selected_value = $decoded_value['selected'] ?? '';
616
617                        if ( ! in_array( $selected_value, $non_empty_options, true ) ) {
618                            /* translators: %s is the name of a form field */
619                            $this->add_error( sprintf( __( '%s requires a valid selection.', 'jetpack-forms' ), $field_label ) );
620                        }
621                    } else {
622                        // For multiple selection (checkbox), check each selected value
623                        foreach ( $field_value as $field_value_item ) {
624                            // Decode the JSON response to get the selected value
625                            $decoded_item   = json_decode( $field_value_item, true );
626                            $selected_value = $decoded_item['selected'] ?? '';
627
628                            if ( ! in_array( $selected_value, $non_empty_options, true ) ) {
629                                /* translators: %s is the name of a form field */
630                                $this->add_error( sprintf( __( '%s requires valid selections.', 'jetpack-forms' ), $field_label ) );
631                                break;
632                            }
633                        }
634                    }
635                }
636                break;
637            case 'number':
638                // Make sure the number address is valid
639                if ( ! is_numeric( $field_value ) ) {
640                    /* translators: %s is the name of a form field */
641                    $this->add_error( sprintf( __( '%s requires a number.', 'jetpack-forms' ), $field_label ) );
642                }
643                break;
644            case 'time':
645                // Make sure the number address is valid
646                if ( ! preg_match( '/^(?:2[0-3]|[01][0-9]):[0-5][0-9]$/', $field_value ) ) {
647                    /* translators: %s is the name of a form field */
648                    $this->add_error( sprintf( __( '%s requires a time', 'jetpack-forms' ), $field_label ) );
649                }
650                break;
651            case 'file':
652                // Make sure the file field is not empty
653                if ( ! is_array( $field_value ) || empty( $field_value[0] ) ) {
654                    /* translators: %s is the name of a form field */
655                    $this->add_error( sprintf( __( '%s requires a file to be uploaded.', 'jetpack-forms' ), $field_label ) );
656                    break;
657                }
658
659                /*
660                 * Nothing enforced the count on this side before. The limit lived only in the
661                 * browser, so a submission assembled by hand could carry as many uploaded file
662                 * IDs as it liked and every one of them would be attached to the response.
663                 */
664                $max_files = $this->get_file_field_max_files();
665
666                if ( count( $field_value ) > $max_files ) {
667                    $this->add_error(
668                        sprintf(
669                            /* translators: 1: the name of a form field, 2: the maximum number of files it accepts. */
670                            _n(
671                                '%1$s accepts at most %2$d file.',
672                                '%1$s accepts at most %2$d files.',
673                                $max_files,
674                                'jetpack-forms'
675                            ),
676                            $field_label,
677                            $max_files
678                        )
679                    );
680                }
681                break;
682            default:
683                // Just check for presence of any text
684                if ( ! is_string( $field_value ) || ! strlen( trim( $field_value ) ) ) {
685                    /* translators: %s is the name of a form field */
686                    $this->add_error( sprintf( __( '%s field is required.', 'jetpack-forms' ), $field_label ) );
687                }
688        }
689    }
690    /**
691     * Sanitize a text field value and html_entity_decode the field.
692     *
693     * @param string $field_value The field value to sanitize.
694     * @return string The sanitized field value.
695     */
696    public function sanitize_text_field( $field_value ) {
697        return sanitize_text_field( html_entity_decode( $field_value, ENT_COMPAT ) );
698    }
699
700    /**
701     * Check the default value for options field
702     *
703     * @param string $value - the value we're checking.
704     * @param int    $index - the index.
705     * @param string $options - default field option.
706     *
707     * @return string
708     */
709    public function get_option_value( $value, $index, $options ) {
710        if ( empty( $value[ $index ] ) ) {
711            return $options;
712        }
713        return $value[ $index ];
714    }
715
716    /**
717     * Outputs the HTML for this form field
718     *
719     * @return string HTML
720     */
721    public function render() {
722
723        $field_id                 = $this->get_attribute( 'id' );
724        $field_type               = $this->maybe_override_type();
725        $field_label              = $this->get_attribute( 'label' );
726        $field_required           = $this->get_attribute( 'required' );
727        $field_required_text      = $this->get_attribute( 'requiredtext' );
728        $field_required_indicator = (bool) $this->get_attribute( 'requiredindicator' );
729        $field_placeholder        = $this->get_attribute( 'placeholder' );
730        $field_width              = $this->get_attribute( 'width' );
731        $class                    = 'date' === $field_type ? 'jp-contact-form-date' : $this->get_attribute( 'class' );
732
733        $label_classes  = $this->get_attribute( 'labelclasses' );
734        $label_styles   = $this->get_attribute( 'labelstyles' );
735        $input_classes  = $this->get_attribute( 'inputclasses' );
736        $input_styles   = $this->get_attribute( 'inputstyles' );
737        $option_classes = $this->get_attribute( 'optionclasses' );
738        $option_styles  = $this->get_attribute( 'optionstyles' );
739
740        $has_block_support_styles = ! empty( $label_classes ) || ! empty( $label_styles ) || ! empty( $input_classes ) || ! empty( $input_styles ) || ! empty( $option_classes ) || ! empty( $option_styles );
741
742        if ( $has_block_support_styles ) {
743            // Do any of the block support classes need to be applied at the field wrapper level? Do we need to make the classes etc filterable as per the field classes?
744
745            // Classes.
746            if ( ! empty( $label_classes ) ) {
747                $this->label_classes .= esc_attr( $label_classes );
748            }
749            if ( ! empty( $input_classes ) ) {
750                $class              .= $class ? ' ' . esc_attr( $input_classes ) : esc_attr( $input_classes );
751                $this->field_classes = $input_classes;
752            }
753            if ( ! empty( $option_classes ) ) {
754                $class               .= $class ? ' ' . esc_attr( $option_classes ) : esc_attr( $option_classes );
755                $this->option_classes = $option_classes;
756            }
757
758            // Styles.
759            if ( ! empty( $label_styles ) ) {
760                $this->label_styles .= esc_attr( $label_styles );
761            }
762            if ( ! empty( $input_styles ) ) {
763                $this->field_styles .= esc_attr( $input_styles );
764            }
765            if ( ! empty( $option_styles ) ) {
766                $this->option_styles .= esc_attr( $option_styles );
767            }
768
769            // For Outline style support.
770            $form_style = $this->get_form_style();
771            if ( 'outlined' === $form_style || 'animated' === $form_style ) {
772                $output_data         = $this->get_form_variation_style_properties( $form_style );
773                $this->block_styles .= esc_attr( $output_data['css_vars'] );
774            }
775        } else {
776            if ( is_numeric( $this->get_attribute( 'borderradius' ) ) ) {
777                $this->block_styles .= '--jetpack--contact-form--border-radius: ' . esc_attr( $this->get_attribute( 'borderradius' ) ) . 'px;';
778                $this->field_styles .= 'border-radius: ' . (int) $this->get_attribute( 'borderradius' ) . 'px;';
779            }
780
781            if ( is_numeric( $this->get_attribute( 'borderwidth' ) ) ) {
782                $this->block_styles .= '--jetpack--contact-form--border-size: ' . esc_attr( $this->get_attribute( 'borderwidth' ) ) . 'px;';
783                $this->field_styles .= 'border-width: ' . (int) $this->get_attribute( 'borderwidth' ) . 'px;';
784            }
785
786            if ( is_numeric( $this->get_attribute( 'lineheight' ) ) ) {
787                $this->block_styles  .= '--jetpack--contact-form--line-height: ' . esc_attr( $this->get_attribute( 'lineheight' ) ) . ';';
788                $this->field_styles  .= 'line-height: ' . (int) $this->get_attribute( 'lineheight' ) . ';';
789                $this->option_styles .= 'line-height: ' . (int) $this->get_attribute( 'lineheight' ) . ';';
790            }
791
792            if ( ! empty( $this->get_attribute( 'bordercolor' ) ) ) {
793                $this->block_styles .= '--jetpack--contact-form--border-color: ' . esc_attr( $this->get_attribute( 'bordercolor' ) ) . ';';
794                $this->field_styles .= 'border-color: ' . esc_attr( $this->get_attribute( 'bordercolor' ) ) . ';';
795            }
796
797            if ( ! empty( $this->get_attribute( 'inputcolor' ) ) ) {
798                $this->block_styles  .= '--jetpack--contact-form--text-color: ' . esc_attr( $this->get_attribute( 'inputcolor' ) ) . ';';
799                $this->block_styles  .= '--jetpack--contact-form--button-outline--text-color: ' . esc_attr( $this->get_attribute( 'inputcolor' ) ) . ';';
800                $this->field_styles  .= 'color: ' . esc_attr( $this->get_attribute( 'inputcolor' ) ) . ';';
801                $this->option_styles .= 'color: ' . esc_attr( $this->get_attribute( 'inputcolor' ) ) . ';';
802            }
803
804            if ( ! empty( $this->get_attribute( 'fieldbackgroundcolor' ) ) ) {
805                $this->block_styles .= '--jetpack--contact-form--input-background: ' . esc_attr( $this->get_attribute( 'fieldbackgroundcolor' ) ) . ';';
806                $this->field_styles .= 'background-color: ' . esc_attr( $this->get_attribute( 'fieldbackgroundcolor' ) ) . ';';
807            }
808
809            if ( ! empty( $this->get_attribute( 'fieldfontsize' ) ) ) {
810                $this->block_styles  .= '--jetpack--contact-form--font-size: ' . esc_attr( $this->get_attribute( 'fieldfontsize' ) ) . ';';
811                $this->field_styles  .= 'font-size: ' . esc_attr( $this->get_attribute( 'fieldfontsize' ) ) . ';';
812                $this->option_styles .= 'font-size: ' . esc_attr( $this->get_attribute( 'fieldfontsize' ) ) . ';';
813            }
814
815            if ( ! empty( $this->get_attribute( 'labelcolor' ) ) ) {
816                $this->label_styles .= 'color: ' . esc_attr( $this->get_attribute( 'labelcolor' ) ) . ';';
817            }
818
819            if ( ! empty( $this->get_attribute( 'labelfontsize' ) ) ) {
820                $this->label_styles .= 'font-size: ' . esc_attr( $this->get_attribute( 'labelfontsize' ) ) . ';';
821            }
822
823            if ( is_numeric( $this->get_attribute( 'labellineheight' ) ) ) {
824                $this->label_styles .= 'line-height: ' . (int) $this->get_attribute( 'labellineheight' ) . ';';
825            }
826        }
827
828        if ( ! empty( $this->get_attribute( 'buttonbackgroundcolor' ) ) ) {
829            $this->block_styles .= '--jetpack--contact-form--button-outline--background-color: ' . esc_attr( $this->get_attribute( 'buttonbackgroundcolor' ) ) . ';';
830        }
831        if ( is_numeric( $this->get_attribute( 'buttonborderradius' ) ) ) {
832            $this->block_styles .= '--jetpack--contact-form--button-outline--border-radius: ' . esc_attr( $this->get_attribute( 'buttonborderradius' ) ) . 'px;';
833        }
834        if ( is_numeric( $this->get_attribute( 'buttonborderwidth' ) ) ) {
835            $this->block_styles .= '--jetpack--contact-form--button-outline--border-size: ' . esc_attr( $this->get_attribute( 'buttonborderwidth' ) ) . 'px;';
836
837        }
838
839        if ( ! empty( $field_width ) && ! $this->has_inset_label() ) {
840            $class .= ' grunion-field-width-' . $field_width;
841        }
842
843        /**
844         * Filters the "class" attribute of the contact form input
845         *
846         * @module contact-form
847         *
848         * @since 6.6.0
849         *
850         * @param string $class Additional CSS classes for input class attribute.
851         */
852        $field_class = apply_filters( 'jetpack_contact_form_input_class', $class );
853
854        $this->value = $this->get_computed_field_value( $field_type, $field_id );
855
856        $field_value = Contact_Form_Plugin::strip_tags( $this->value );
857        $field_label = Contact_Form_Plugin::strip_tags( $field_label );
858
859        $extra_attrs = array();
860
861        if ( $field_type === 'number' || $field_type === 'slider' ) {
862            if ( is_numeric( $this->get_attribute( 'min' ) ) ) {
863                $extra_attrs['min'] = $this->get_attribute( 'min' );
864            }
865            if ( is_numeric( $this->get_attribute( 'max' ) ) ) {
866                $extra_attrs['max'] = $this->get_attribute( 'max' );
867            }
868            if ( is_numeric( $this->get_attribute( 'step' ) ) ) {
869                $extra_attrs['step'] = $this->get_attribute( 'step' );
870            }
871        }
872
873        if ( $field_type === 'slider' ) {
874            $minlabel = $this->get_attribute( 'minlabel' );
875            $maxlabel = $this->get_attribute( 'maxlabel' );
876            if ( null !== $minlabel && '' !== $minlabel ) {
877                $extra_attrs['minLabel'] = $minlabel;
878            }
879            if ( null !== $maxlabel && '' !== $maxlabel ) {
880                $extra_attrs['maxLabel'] = $maxlabel;
881            }
882        }
883
884        $rendered_field = $this->render_field( $field_type, $field_id, $field_label, $field_value, $field_class, $field_placeholder, $field_required, $field_required_text, $extra_attrs, $field_required_indicator );
885
886        /**
887         * Filter the HTML of the Contact Form.
888         *
889         * @module contact-form
890         *
891         * @since 2.6.0
892         *
893         * @param string $rendered_field Contact Form HTML output.
894         * @param string $field_label Field label.
895         * @param int|null $id Post ID.
896         */
897        return apply_filters( 'grunion_contact_form_field_html', $rendered_field, $field_label, ( in_the_loop() ? get_the_ID() : null ) );
898    }
899    /**
900     * Returns the computed field value for a field. It uses the POST, GET, Logged in data.
901     *
902     * @module contact-form
903     *
904     * @param string $field_type The field type.
905     * @param string $field_id The field id.
906     *
907     * @return string
908     */
909    public function get_computed_field_value( $field_type, $field_id ) {
910        global $current_user, $user_identity;
911        // Use the POST Field if it is available.
912        if ( isset( $_POST[ $field_id ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- no site changes.
913            if ( is_array( $_POST[ $field_id ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- no site changes.
914                return array_map( 'sanitize_textarea_field', wp_unslash( $_POST[ $field_id ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- no site changes.
915            }
916
917            return sanitize_textarea_field( wp_unslash( $_POST[ $field_id ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- no site changes.
918        }
919
920        // Explicit consent never renders checked, so a missing POST value must remain empty
921        // rather than falling through to a query-string or configured default.
922        if ( 'consent' === $field_type && 'explicit' === $this->get_attribute( 'consenttype' ) ) {
923            return '';
924        }
925
926        // Checkbox controls are omitted from the request when unchecked. During an actual
927        // submission that absence is the submitted value; falling through to a query-string
928        // or configured default would silently check the field again.
929        $is_checkbox_control = in_array( $field_type, array( 'checkbox', 'checkbox-multiple' ), true );
930        if ( $is_checkbox_control && $this->form && $this->form->is_current_submission() ) {
931            return '';
932        }
933
934        // Implicit consent renders as a hidden input with this value, so its computed value
935        // must match what the browser will submit from the first render onward.
936        if ( 'consent' === $field_type && 'explicit' !== $this->get_attribute( 'consenttype' ) ) {
937            return __( 'Yes', 'jetpack-forms' );
938        }
939
940        // Use the GET Field if it is available.
941        if ( isset( $_GET[ $field_id ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no site changes.
942            if ( is_array( $_GET[ $field_id ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no site changes.
943                return array_map( 'sanitize_textarea_field', wp_unslash( $_GET[ $field_id ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no site changes.
944            }
945
946            return sanitize_textarea_field( wp_unslash( $_GET[ $field_id ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no site changes.
947        }
948
949        if ( ! is_user_logged_in() ) {
950            return $this->get_attribute( 'default' );
951        }
952
953        /**
954         * Allow third-party tools to prefill the contact form with the user's details when they're logged in.
955         *
956         * @module contact-form
957         *
958        * @since 3.2.0
959        *
960        * @param bool false Should the Contact Form be prefilled with your details when you're logged in. Default to false.
961        */
962        $filter_value = apply_filters( 'jetpack_auto_fill_logged_in_user', false );
963        if ( ( ! current_user_can( 'manage_options' ) && ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) || $filter_value ) {
964            switch ( $field_type ) {
965                case 'email':
966                    return $current_user->data->user_email;
967
968                case 'name':
969                    return ! empty( $user_identity ) ? $user_identity : $current_user->data->display_name;
970
971                case 'url':
972                    return $current_user->data->user_url;
973            }
974        }
975
976        return $this->get_attribute( 'default' );
977    }
978
979    /**
980     * Get the field value used to resolve conditional logic.
981     *
982     * Hidden-field filters affect the value rendered into the browser, so apply the same
983     * filter before the server evaluates a rule that uses a hidden field as its subject.
984     *
985     * @return string|array Field value.
986     */
987    public function get_conditional_logic_value() {
988        $field_type = $this->get_attribute( 'type' );
989        $field_id   = $this->get_attribute( 'id' );
990        $value      = $this->get_computed_field_value( $field_type, $field_id );
991
992        if ( 'hidden' === $field_type && ! $this->is_submitted_hidden_field_value( $field_id ) ) {
993            $value = $this->get_filtered_hidden_field_value( $value, $this->get_attribute( 'label' ), $field_id );
994        }
995
996        return $value;
997    }
998
999    /**
1000     * Filter the value of a hidden field once per input tuple.
1001     *
1002     * Rendering and conditional logic must use the exact same filtered value. Caching also
1003     * prevents stateful filters from returning a different value on their second invocation.
1004     *
1005     * @param mixed  $value The value of the hidden field.
1006     * @param string $label The label of the hidden field.
1007     * @param string $id    The ID of the hidden field.
1008     * @return mixed The modified value of the hidden field.
1009     */
1010    private function get_filtered_hidden_field_value( $value, $label, $id ) {
1011        $input = array( $value, $label, $id );
1012
1013        if ( $input === $this->hidden_field_filter_input ) {
1014            return $this->hidden_field_filter_value;
1015        }
1016
1017        /**
1018         * Filter the value of the hidden field.
1019         *
1020         * @since 6.3.0
1021         *
1022         * @param string $value The value of the hidden field.
1023         * @param string $label The label of the hidden field.
1024         * @param string $id The ID of the hidden field.
1025         */
1026        $this->hidden_field_filter_input = $input;
1027        $this->hidden_field_filter_value = apply_filters( 'jetpack_forms_hidden_field_value', $value, $label, $id );
1028
1029        return $this->hidden_field_filter_value;
1030    }
1031
1032    /**
1033     * Whether a hidden value came from a matching form submission.
1034     *
1035     * Hidden values rendered into the browser have already passed through the hidden-field
1036     * filter, so their submitted values must not be filtered a second time.
1037     *
1038     * @param string $id The ID of the hidden field.
1039     * @return bool Whether the submitted value should be treated as already filtered.
1040     */
1041    private function is_submitted_hidden_field_value( $id ) {
1042        return isset( $_POST[ $id ] ) // phpcs:ignore WordPress.Security.NonceVerification.Missing -- no site changes.
1043            && $this->form
1044            && $this->form->is_current_submission();
1045    }
1046
1047    /**
1048     * Return the HTML for the label.
1049     *
1050     * @param string $type - the field type.
1051     * @param int    $id - the ID.
1052     * @param string $label - the label.
1053     * @param bool   $required - if the field is marked as required.
1054     * @param string $required_field_text - the text in the required text field.
1055     * @param array  $extra_attrs Array of key/value pairs to append as attributes to the element.
1056     * @param bool   $always_render - if the label should always be shown.
1057     * @param bool   $required_indicator Whether to display the required indicator.
1058     *
1059     * @return string HTML
1060     */
1061    public function render_label( $type, $id, $label, $required, $required_field_text, $extra_attrs = array(), $always_render = false, $required_indicator = true ) {
1062        if ( $this->attributes['labelhiddenbyblockvisibility'] ) {
1063            return '';
1064        }
1065        $form_style = $this->get_form_style();
1066
1067        if ( ! empty( $form_style ) && $form_style !== 'default' ) {
1068            if ( ! in_array( $type, self::TYPES_WITHOUT_STYLED_LABEL, true ) ) {
1069                switch ( $form_style ) {
1070                    case 'outlined':
1071                        if ( $this->type_has_inset_label( $type ) ) {
1072                            return $this->render_outline_label( $id, $label, $required, $required_field_text, $required_indicator );
1073                        }
1074                        break;
1075                    case 'animated':
1076                        if ( $this->type_has_inset_label( $type ) ) {
1077                            return $this->render_animated_label( $id, $label, $required, $required_field_text, $required_indicator );
1078                        }
1079                        break;
1080                    case 'below':
1081                        return $this->render_below_label( $id, $label, $required, $required_field_text, $required_indicator );
1082                }
1083            }
1084
1085            if ( ! $always_render ) {
1086                return '';
1087            }
1088        }
1089
1090        if ( ! empty( $this->label_styles ) ) {
1091            $extra_attrs['style'] = $this->label_styles;
1092        }
1093
1094        $type_class = $type ? ' ' . $type : '';
1095
1096        $extra_attrs['class'] = "grunion-field-label{$type_class}" . ( $this->is_error() ? ' form-error' : '' );
1097
1098        if ( ! empty( $this->label_classes ) ) {
1099            $extra_attrs['class'] .= ' ' . $this->label_classes;
1100        }
1101
1102        $extra_attrs_string = '';
1103
1104        foreach ( $extra_attrs as $attr => $val ) {
1105            $extra_attrs_string .= sprintf( '%s="%s" ', esc_attr( $attr ), esc_attr( $val ) );
1106        }
1107
1108        $type_class = $type ? ' ' . $type : '';
1109        return "<label
1110                for='" . esc_attr( $id ) . "' "
1111                . $extra_attrs_string
1112                . '>'
1113                . wp_kses_post( $label )
1114                . ( $required && $required_indicator ? '<span class="grunion-label-required" aria-hidden="true">' . $required_field_text . '</span>' : '' ) .
1115            "</label>\n";
1116    }
1117
1118    /**
1119     * Whether the field's label is hidden by block visibility in any mode.
1120     *
1121     * Two modes hide a label: "hide everywhere" (labelhiddenbyblockvisibility,
1122     * the label is not rendered at all) and per-viewport (the label is rendered
1123     * but carries a wp-block-hidden-{viewport} class that display:none's it on
1124     * that viewport). Either way the label is absent from the accessibility tree
1125     * where hidden, so the field needs an aria-label fallback to keep a name.
1126     *
1127     * The visibility control now only survives on the label block (see
1128     * FORMS-694), so this is the single place that decides "is the label hidden?"
1129     *
1130     * @return bool
1131     */
1132    private function is_label_hidden_by_block_visibility() {
1133        if ( $this->get_attribute( 'labelhiddenbyblockvisibility' ) ) {
1134            return true;
1135        }
1136
1137        return strpos( (string) $this->get_attribute( 'labelclasses' ), 'wp-block-hidden-' ) !== false;
1138    }
1139
1140    /**
1141     * The accessible name to fall back to when the label is hidden by block
1142     * visibility. Prefers the label text (it matches what sighted users see on
1143     * viewports where the label is visible, for the per-viewport case) and only
1144     * falls back to a secondary name when there is no label. See FORMS-694.
1145     *
1146     * @param string|null $fallback Secondary name to use when there is no label.
1147     *                              Must be a raw string, not a built attribute
1148     *                              fragment. Defaults to the raw placeholder.
1149     * @return string
1150     */
1151    private function get_block_visibility_aria_label( $fallback = null ) {
1152        $label = Contact_Form_Plugin::strip_tags( (string) $this->get_attribute( 'label' ) );
1153        if ( '' !== $label ) {
1154            return $label;
1155        }
1156
1157        if ( null === $fallback ) {
1158            $fallback = $this->get_attribute( 'placeholder' );
1159        }
1160
1161        return Contact_Form_Plugin::strip_tags( (string) $fallback );
1162    }
1163
1164    /**
1165     * Return an ` aria-label='…'` attribute string when the field's label is
1166     * hidden by block visibility (full or per-viewport), or '' otherwise.
1167     *
1168     * A hidden label (removed on full-hide, display:none per-viewport) is absent
1169     * from the a11y tree, so every field that renders its own label â€” single
1170     * inputs and the grouped <fieldset> legend alike â€” needs this fallback to
1171     * keep an accessible name. Shared by all paths so none get missed. The
1172     * attribute is skipped when there is no name to give. See FORMS-694.
1173     *
1174     * @param string|null $fallback Secondary name when there is no label (raw
1175     *                              string, not a built attribute fragment).
1176     * @return string
1177     */
1178    private function get_hidden_label_aria_label_attr( $fallback = null ) {
1179        if ( ! $this->is_label_hidden_by_block_visibility() ) {
1180            return '';
1181        }
1182
1183        $name = $this->get_block_visibility_aria_label( $fallback );
1184        if ( '' === $name ) {
1185            return '';
1186        }
1187
1188        return " aria-label='" . esc_attr( $name ) . "'";
1189    }
1190
1191    /**
1192     * Accessible name for the file field's dropzone <div role="button">.
1193     *
1194     * The dropzone is the field's interactive control, but its name is otherwise
1195     * the generic "Select a file to upload.", so two hidden-label upload fields
1196     * would be announced identically. When the label is hidden (full or
1197     * per-viewport), prefix the field name â€” the same fallback the other single
1198     * inputs use. Falls back to the plain instruction when the label is visible
1199     * or there is no name to give. See FORMS-694.
1200     *
1201     * @param int $max_files How many files the field accepts.
1202     *
1203     * @return string
1204     */
1205    private function get_file_dropzone_aria_label( $max_files ) {
1206        /*
1207         * The count belongs in the accessible name rather than only in the visible dropzone text,
1208         * which is an inner block the author writes and may leave saying "a file" for a field that
1209         * takes several.
1210         */
1211        $select_file_text = $max_files > 1
1212            ? sprintf(
1213                /* translators: %d: the maximum number of files the field accepts. */
1214                _n(
1215                    'Select up to %d file to upload.',
1216                    'Select up to %d files to upload.',
1217                    $max_files,
1218                    'jetpack-forms'
1219                ),
1220                $max_files
1221            )
1222            : __( 'Select a file to upload.', 'jetpack-forms' );
1223
1224        if ( ! $this->is_label_hidden_by_block_visibility() ) {
1225            return $select_file_text;
1226        }
1227
1228        $hidden_name = $this->get_block_visibility_aria_label();
1229        if ( '' === $hidden_name ) {
1230            return $select_file_text;
1231        }
1232
1233        return sprintf(
1234            /* translators: 1: the form field's label, 2: the "Select a file to upload." instruction. */
1235            _x( '%1$s: %2$s', 'file upload field accessible name', 'jetpack-forms' ),
1236            $hidden_name,
1237            $select_file_text
1238        );
1239    }
1240
1241    /**
1242     * Return the HTML for a legend that shares the same style as a label.
1243     *
1244     * @param string $type - the field type.
1245     * @param int    $id - the ID.
1246     * @param string $legend - the legend.
1247     * @param bool   $required - if the field is marked as required.
1248     * @param string $required_field_text - the text in the required text field.
1249     * @param array  $extra_attrs Array of key/value pairs to append as attributes to the element.
1250     * @param bool   $required_indicator Whether to display the required indicator.
1251     *
1252     * @return string HTML
1253     */
1254    public function render_legend_as_label( $type, $id, $legend, $required, $required_field_text, $extra_attrs = array(), $required_indicator = true ) {
1255        // Full-hide via blockVisibility, mirroring render_label(). Grouped fields
1256        // (radio, checkbox-multiple, image-select, rating) render their label as a
1257        // legend, so they need the same guard. Per-viewport hiding still works via
1258        // the label_classes applied below.
1259        if ( $this->attributes['labelhiddenbyblockvisibility'] ) {
1260            return '';
1261        }
1262        if ( ! empty( $this->label_styles ) ) {
1263            $extra_attrs['style'] = $this->label_styles;
1264        }
1265
1266        $type_class           = $type ? ' ' . $type : '';
1267        $extra_attrs['class'] = "grunion-field-label{$type_class}" . ( $this->is_error() ? ' form-error' : '' );
1268
1269        if ( ! empty( $this->label_classes ) ) {
1270            $extra_attrs['class'] .= ' ' . $this->label_classes;
1271        }
1272
1273        $extra_attrs_string = '';
1274        if ( is_array( $extra_attrs ) ) {
1275            foreach ( $extra_attrs as $attr => $val ) {
1276                $extra_attrs_string .= sprintf( '%s="%s" ', esc_attr( $attr ), esc_attr( $val ) );
1277            }
1278        }
1279
1280        return '<legend '
1281                . $extra_attrs_string
1282                . '>'
1283                . '<span class="grunion-label-text">' . wp_kses_post( $legend ) . '</span>'
1284                . ( $required && $required_indicator ? '<span class="grunion-label-required">' . $required_field_text . '</span>' : '' )
1285                . "</legend>\n";
1286    }
1287
1288    /**
1289     * Return the HTML for the input field.
1290     *
1291     * @param string $type - the field type.
1292     * @param int    $id - the ID.
1293     * @param string $value - the value of the field.
1294     * @param string $class - the field class.
1295     * @param string $placeholder - the field placeholder content.
1296     * @param bool   $required - if the field is marked as required.
1297     * @param array  $extra_attrs Array of key/value pairs to append as attributes to the element.
1298     *
1299     * @return string HTML
1300     */
1301    public function render_input_field( $type, $id, $value, $class, $placeholder, $required, $extra_attrs = array() ) {
1302        if ( ! is_string( $value ) ) {
1303            $value = '';
1304        }
1305
1306        $extra_attrs_string = '';
1307
1308        if ( ! empty( $this->field_styles ) ) {
1309            $extra_attrs['style'] = $this->field_styles;
1310        }
1311
1312        if ( is_array( $extra_attrs ) && ! empty( $extra_attrs ) ) {
1313            foreach ( $extra_attrs as $attr => $val ) {
1314                $extra_attrs_string .= sprintf( '%s="%s" ', esc_attr( $attr ), esc_attr( $val ) );
1315            }
1316        }
1317
1318        // this is a hack for Firefox to prevent users from falsely entering a something other than a number into a number field.
1319        if ( $type === 'number' ) {
1320            $extra_attrs_string .= " data-wp-on--keypress='actions.handleNumberKeyPress' ";
1321        }
1322
1323        $extra_attrs_string .= $this->get_hidden_label_aria_label_attr();
1324
1325        return "<input
1326                    type='" . esc_attr( $type ) . "'
1327                    name='" . esc_attr( $id ) . "'
1328                    id='" . esc_attr( $id ) . "'
1329                    value='" . esc_attr( $value ) . "'
1330
1331                    data-wp-bind--aria-invalid='state.fieldAriaInvalid'
1332                    data-wp-bind--value='state.getFieldValue'
1333                    aria-describedby='" . esc_attr( $this->get_described_by( $id, $type ) ) . "'
1334                    data-wp-on--input='actions.onFieldChange'
1335                    data-wp-on--blur='actions.onFieldBlur'
1336                    data-wp-class--has-value='state.hasFieldValue'
1337
1338                    " . $class . $placeholder . '
1339                    ' . ( $required ? "required='true' aria-required='true' " : '' ) .
1340                    $extra_attrs_string .
1341                    " />\n " . $this->get_field_descriptions( $id, $type ) . " \n";
1342    }
1343
1344    /**
1345     * Return the id of a field's error message element.
1346     *
1347     * @param string $id   - the field ID.
1348     * @param string $type - the error type passed to get_error_div().
1349     *
1350     * @return string
1351     */
1352    private function get_error_message_id( $id, $type ) {
1353        return $id . '-' . $type . '-error-message';
1354    }
1355
1356    /**
1357     * Return the HTML for the error div.
1358     *
1359     * @param string $id - the field ID.
1360     * @param string $type - the field type.
1361     * @param bool   $override_render - if the error div should be rendered even if the label is inset.
1362     *
1363     * @return string HTML
1364     */
1365    private function get_error_div( $id, $type, $override_render = false ) {
1366
1367        if ( ! $override_render && $this->has_inset_label() ) {
1368            return '';
1369        }
1370        return '
1371            <div id="' . esc_attr( $id ) . '-' . esc_attr( $type ) . '-error" class="contact-form__input-error" data-wp-class--has-errors="state.fieldHasErrors">
1372                <span class="contact-form__warning-icon" aria-hidden="true">
1373                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
1374                        <path d="M8.50015 11.6402H7.50015V10.6402H8.50015V11.6402Z" />
1375                        <path d="M7.50015 9.64018H8.50015V6.30684H7.50015V9.64018Z" />
1376                        <path fill-rule="evenodd" clip-rule="evenodd" d="M6.98331 3.0947C7.42933 2.30177 8.57096 2.30177 9.01698 3.09469L13.8771 11.7349C14.3145 12.5126 13.7525 13.4735 12.8602 13.4735H3.14004C2.24774 13.4735 1.68575 12.5126 2.12321 11.7349L6.98331 3.0947ZM8.14541 3.58496C8.08169 3.47168 7.9186 3.47168 7.85488 3.58496L2.99478 12.2251C2.93229 12.3362 3.01257 12.4735 3.14004 12.4735H12.8602C12.9877 12.4735 13.068 12.3362 13.0055 12.2251L8.14541 3.58496Z" />
1377                    </svg>
1378                </span>
1379                <span data-wp-text="state.errorMessage" id="' . esc_attr( $this->get_error_message_id( $id, $type ) ) . '"></span>
1380            </div>';
1381    }
1382
1383    /**
1384     * The author-supplied help text for this field, or null when unset.
1385     *
1386     * @since 8.0.0
1387     *
1388     * @return string|null
1389     */
1390    private function get_help_text() {
1391        $help_text = $this->get_attribute( 'helptext' );
1392
1393        if ( ! is_string( $help_text ) ) {
1394            return null;
1395        }
1396
1397        $help_text = trim( $help_text );
1398
1399        if ( $help_text === '' ) {
1400            return null;
1401        }
1402
1403        // Contact_Form::esc_shortcode_val() encodes `,` `[` `]` `\` as decimal
1404        // entities so they survive the shortcode parser, but unesc_attr() only
1405        // decodes the hex forms. Other consumers emit through wp_kses_post() or
1406        // into an attribute, so the browser decodes whatever is left over; this
1407        // is the first to emit through esc_html() into a text node, where the
1408        // leftover `&#044;` would be escaped again and shown to the visitor.
1409        // Safe to decode here: the value has already been through
1410        // unesc_attr()'s strip_tags(), and output is still esc_html()'d.
1411        return html_entity_decode( $help_text, ENT_QUOTES );
1412    }
1413
1414    /**
1415     * The format instruction for date fields, or null for every other type.
1416     *
1417     * Note this keys off the field's own `type` attribute, not the type passed
1418     * to the render helpers â€” the date field renders a `text` input.
1419     *
1420     * @since 8.0.0
1421     *
1422     * @return string|null
1423     */
1424    private function get_format_hint() {
1425        if ( $this->get_attribute( 'type' ) !== 'date' ) {
1426            return null;
1427        }
1428
1429        $formats = self::get_date_formats();
1430
1431        return $formats[ $this->get_date_format() ] ?? null;
1432    }
1433
1434    /**
1435     * The aria-describedby value for a field's input.
1436     *
1437     * The error message comes first so screen readers announce it before the
1438     * advisory text; its span is empty until there is an error, so it costs
1439     * nothing the rest of the time.
1440     *
1441     * @since 8.0.0
1442     *
1443     * @param string $id   - the field ID.
1444     * @param string $type - the description type (matches the emitted element ids).
1445     *
1446     * @return string
1447     */
1448    private function get_described_by( $id, $type ) {
1449        $ids = array( $this->get_error_message_id( $id, $type ) );
1450
1451        foreach ( $this->get_description_parts( $id, $type ) as $part ) {
1452            $ids[] = $part['id'];
1453        }
1454
1455        return implode( ' ', $ids );
1456    }
1457
1458    /**
1459     * The advisory descriptions attached to a field, in DOM order.
1460     *
1461     * Single source for both the ids aria-describedby references and the
1462     * markup that carries them â€” building those separately is how they drift,
1463     * and a describedby pointing at an id that was never emitted is exactly
1464     * the failure this class already fixes elsewhere.
1465     *
1466     * @since 8.0.0
1467     *
1468     * @param string $id   - the field ID.
1469     * @param string $type - the description type (matches get_described_by()).
1470     *
1471     * @return array List of array( 'id' => string, 'class' => string, 'text' => string ).
1472     */
1473    private function get_description_parts( $id, $type ) {
1474        $parts     = array();
1475        $help_text = $this->get_help_text();
1476
1477        if ( $help_text !== null ) {
1478            $parts[] = array(
1479                'id'    => $id . '-' . $type . '-help',
1480                'class' => 'contact-form__field-help',
1481                'text'  => $help_text,
1482            );
1483        }
1484
1485        $format_hint = $this->get_format_hint();
1486
1487        if ( $format_hint !== null ) {
1488            $parts[] = array(
1489                'id'    => $id . '-' . $type . '-format',
1490                'class' => 'contact-form__field-format',
1491                'text'  => $format_hint,
1492            );
1493        }
1494
1495        return $parts;
1496    }
1497
1498    /**
1499     * Return the HTML for a field's descriptions: help text, format hint, and
1500     * the error div, in that DOM order.
1501     *
1502     * These travel together because inset-label form styles render them outside
1503     * the field wrapper. In that case the markup is deferred to
1504     * $this->deferred_descriptions and render_field() emits it, so it is only
1505     * ever built here â€” with the same $type the input used for its
1506     * aria-describedby.
1507     *
1508     * @since 8.0.0
1509     *
1510     * @param string $id   - the field ID.
1511     * @param string $type - the description type (matches get_described_by()).
1512     *
1513     * @return string HTML, or an empty string when the markup is deferred.
1514     */
1515    private function get_field_descriptions( $id, $type ) {
1516        $hints = '';
1517
1518        // Deliberately spans, not paragraphs: themes style <p> (margins, size,
1519        // color) and we would have to fight those rules on every theme.
1520        foreach ( $this->get_description_parts( $id, $type ) as $part ) {
1521            $hints .= '<span id="' . esc_attr( $part['id'] ) . '" class="' . esc_attr( $part['class'] ) . '">'
1522                . esc_html( $part['text'] ) . '</span>';
1523        }
1524
1525        $descriptions = '';
1526
1527        if ( $hints !== '' ) {
1528            $descriptions .= '<div class="contact-form__field-hints">' . $hints . '</div>';
1529        }
1530
1531        // Force the error div to build even for inset labels â€” the deferral
1532        // below decides where it lands.
1533        $descriptions .= $this->get_error_div( $id, $type, true );
1534
1535        if ( $this->has_inset_label() ) {
1536            $this->deferred_descriptions = $descriptions;
1537            return '';
1538        }
1539
1540        return $descriptions;
1541    }
1542
1543    /**
1544     * Set the invalid message for specific field types.
1545     *
1546     * @param string $type - the field type.
1547     * @param string $message - the message to display.
1548     *
1549     * @return void
1550     */
1551    private function set_invalid_message( $type, $message ) {
1552        wp_interactivity_config(
1553            'jetpack/form',
1554            array(
1555                'error_types' => array(
1556                    'invalid_' . $type => $message,
1557                ),
1558            )
1559        );
1560    }
1561
1562    /**
1563     * Return the HTML for the email field.
1564     *
1565     * @param int    $id - the ID.
1566     * @param string $label - the label.
1567     * @param string $value - the value of the field.
1568     * @param string $class - the field class.
1569     * @param bool   $required - if the field is marked as required.
1570     * @param string $required_field_text - the text in the required text field.
1571     * @param string $placeholder - the field placeholder content.
1572     * @param bool   $required_indicator Whether to display the required indicator.
1573     *
1574     * @return string HTML
1575     */
1576    public function render_email_field( $id, $label, $value, $class, $required, $required_field_text, $placeholder, $required_indicator = true ) {
1577        $this->set_invalid_message( 'email', __( 'Please enter a valid email address', 'jetpack-forms' ) );
1578        $field  = $this->render_label( 'email', $id, $label, $required, $required_field_text, array(), false, $required_indicator );
1579        $field .= $this->render_input_field( 'email', $id, $value, $class, $placeholder, $required );
1580        return $field;
1581    }
1582
1583    /**
1584     * Return the HTML for the telephone field.
1585     *
1586     * @param int    $id - the ID.
1587     * @param string $label - the label.
1588     * @param string $value - the value of the field.
1589     * @param string $class - the field class.
1590     * @param bool   $required - if the field is marked as required.
1591     * @param string $required_field_text - the text in the required text field.
1592     * @param string $placeholder - the field placeholder content.
1593     * @param bool   $required_indicator Whether to display the required indicator.
1594     *
1595     * @return string HTML
1596     */
1597    public function render_telephone_field( $id, $label, $value, $class, $required, $required_field_text, $placeholder, $required_indicator = true ) {
1598        $show_country_selector = $this->get_attribute( 'showcountryselector' );
1599        $default_country       = $this->get_attribute( 'default' );
1600        $search_placeholder    = $this->get_attribute( 'searchplaceholder' );
1601
1602        if ( ! $show_country_selector ) {
1603            // old telephone field treatment
1604            $this->set_invalid_message( 'telephone', __( 'Please enter a valid phone number', 'jetpack-forms' ) );
1605            $label = $this->render_label( 'telephone', $id, $label, $required, $required_field_text, array(), false, $required_indicator );
1606            $field = $this->render_input_field( 'tel', $id, $value, $class, $placeholder, $required );
1607            return $label . $field;
1608        }
1609
1610        if ( empty( $search_placeholder ) ) {
1611            $search_placeholder = __( 'Search countries…', 'jetpack-forms' );
1612        }
1613
1614        $this->enqueue_phone_field_assets();
1615
1616        // $class is ill-formed, so we need to fix it
1617        // Strip 'class=' and quotes to get just the class names
1618        $class_names = preg_replace( "/^class=['\"]([^'\"]*)['\"].*$/", '$1', $class );
1619        // somehow we are getting the class jetpack-field__input-element on the wrong wrapper
1620        // .jetpack-field__input-element is meant to be applied just to the input element, not its wrapper.
1621        // Remove the jetpack-field__input-element class token regardless of its position and normalize whitespace.
1622        $class_names = preg_replace( '/\s*\bjetpack-field__input-element\b\s*/', ' ', $class_names );
1623        $class_names = trim( preg_replace( '/\s+/', ' ', $class_names ) );
1624
1625        $link_label_id = $id . '-number';
1626
1627        $this->set_invalid_message( 'phone', __( 'Please enter a valid phone number', 'jetpack-forms' ) );
1628        $label = $this->render_label( 'phone', $link_label_id, $label, $required, $required_field_text, array(), false, $required_indicator );
1629        if ( ! is_string( $value ) ) {
1630            $value = '';
1631        }
1632
1633        $translated_countries = $this->get_translatable_countries();
1634        $global_config        = array(
1635            'i18n' => array(
1636                'countryNames' => $translated_countries,
1637            ),
1638        );
1639        wp_interactivity_config( 'jetpack/field-phone', $global_config );
1640        ob_start();
1641        ?>
1642        <div
1643            class="jetpack-field__input-phone-wrapper <?php echo esc_attr( $this->get_attribute( 'stylevariationclasses' ) ); ?> <?php echo esc_attr( $class_names ); ?>"
1644            style="<?php echo ( ! empty( $this->field_styles ) && is_string( $this->field_styles ) ? esc_attr( $this->field_styles ) : '' ); ?>"
1645            data-wp-on--jetpack-form-reset='actions.phoneResetHandler'
1646            data-wp-class--is-combobox-open="context.comboboxOpen"
1647            <?php
1648            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- function is supposed to work this way
1649            echo wp_interactivity_data_wp_context(
1650                array(
1651                    'fieldId'             => $id,
1652                    'defaultCountry'      => $default_country,
1653                    'showCountrySelector' => $this->get_attribute( 'showcountryselector' ),
1654                    // dynamic
1655                    'phoneNumber'         => '',
1656                    'phoneCountryCode'    => $default_country,
1657                    'fullPhoneNumber'     => '',
1658                    'countryPrefix'       => '',
1659                    // combobox state
1660                    'useCombobox'         => true,
1661                    'comboboxOpen'        => false,
1662                    'searchTerm'          => '',
1663                    'allCountries'        => array(),
1664                    'filteredCountries'   => array(),
1665                    'selectedCountry'     => array(),
1666                )
1667            );
1668            ?>
1669            >
1670                <div class="jetpack-field__input-prefix"
1671                    data-wp-bind--hidden="!context.showCountrySelector"
1672                    data-wp-on-document--click="actions.phoneComboboxDocumentClickHandler">
1673                    <div class="jetpack-custom-combobox">
1674
1675                        <button
1676                            class="jetpack-combobox-trigger"
1677                            type="button"
1678                            data-wp-on--click="actions.phoneComboboxToggle"
1679                            data-wp-bind--aria-expanded="context.comboboxOpen">
1680                            <span
1681                                class="jetpack-combobox-selected wp-exclude-emoji"
1682                                data-wp-watch="callbacks.updateSelectedFlag">&#8203;</span>
1683                            <span
1684                                class="jetpack-combobox-trigger-arrow"
1685                                data-wp-class--is-open="context.comboboxOpen">
1686                                <svg width="10" height="6" viewBox="0 0 10 6" fill="none" xmlns="http://www.w3.org/2000/svg">
1687                                    <path d="M1 1L5 5L9 1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
1688                                </svg>
1689                            </span>
1690                            <span
1691                                class="jetpack-combobox-selected"
1692                                data-wp-text="context.selectedCountry.value"></span>
1693                        </button>
1694                        <div
1695                            class="jetpack-combobox-dropdown <?php echo esc_attr( $this->get_attribute( 'stylevariationclasses' ) ); ?>"
1696                            style="<?php echo ( ! empty( $this->field_styles ) && is_string( $this->field_styles ) ? esc_attr( $this->field_styles ) : '' ); ?>"
1697                            data-wp-bind--hidden="!context.comboboxOpen">
1698                            <input
1699                                class="jetpack-combobox-search"
1700                                type="text"
1701                                placeholder="<?php echo esc_attr( $search_placeholder ); ?>"
1702                                data-wp-on--input="actions.phoneComboboxInputHandler"
1703                                data-wp-on--keydown="actions.phoneComboboxKeydownHandler"
1704                                data-wp-init="callbacks.registerPhoneComboboxSearchInput">
1705                            <div class="jetpack-combobox-options" data-wp-init="callbacks.registerPhoneComboboxOptionsList">
1706                                <template
1707                                    data-wp-each--filtered="context.filteredCountries"
1708                                    data-wp-each-key="context.filtered.code">
1709                                    <div
1710                                        class="jetpack-combobox-option"
1711                                        data-wp-key="context.filtered.code"
1712                                        data-wp-class--jetpack-combobox-option-selected="context.filtered.selected"
1713                                        data-wp-on--click="actions.phoneCountryChangeHandler">
1714                                        <span class="jetpack-combobox-option-icon wp-exclude-emoji" data-wp-watch="callbacks.updateOptionFlag">&#8203;</span>
1715                                        <span class="jetpack-combobox-option-value" data-wp-text="context.filtered.value"></span>
1716                                        <span class="jetpack-combobox-option-description" data-wp-text="context.filtered.country"></span>
1717                                    </div>
1718                                </template>
1719                            </div>
1720                        </div>
1721                    </div>
1722                </div>
1723                <input
1724                    class="jetpack-field__input-element"
1725                    <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- both are escaped in calling function ?>
1726                    <?php echo $placeholder; ?>
1727                    type="tel"
1728                    <?php if ( $required ) { ?>
1729                        required="true"
1730                        aria-required="true"
1731                    <?php } ?>
1732                    id="<?php echo esc_attr( $link_label_id ); ?>"
1733                    name="<?php echo esc_attr( $link_label_id ); ?>"
1734                    data-wp-bind--disabled='state.isSubmitting'
1735                    data-wp-bind--aria-invalid='state.fieldAriaInvalid'
1736                    data-wp-bind--value='context.phoneNumber'
1737                    aria-describedby="<?php echo esc_attr( $this->get_described_by( $id, 'telephone' ) ); ?>"
1738                    data-wp-on--input='actions.phoneNumberInputHandler'
1739                    data-wp-on--blur='actions.onFieldBlur'
1740                    data-wp-on--focus='actions.phoneNumberFocusHandler'
1741                    data-wp-class--has-value='context.phoneNumber'
1742                    data-wp-init="callbacks.registerPhoneInput"
1743                    data-wp-init--phone-field-custom-combobox="callbacks.initializePhoneFieldCustomComboBox"
1744                    <?php echo $this->get_hidden_label_aria_label_attr(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- attribute value is escaped in the helper. ?>
1745                    />
1746                <input type="hidden"
1747                    id="<?php echo esc_attr( $id ); ?>"
1748                    name="<?php echo esc_attr( $id ); ?>"
1749                    data-wp-bind--value='context.fullPhoneNumber' />
1750        </div>
1751        <?php
1752        $input = ob_get_clean();
1753
1754        $field = $label . $input . $this->get_field_descriptions( $id, 'telephone' );
1755        return $field;
1756    }
1757
1758    /**
1759     * Return the HTML for the URL field.
1760     *
1761     * @param int    $id - the ID.
1762     * @param string $label - the label.
1763     * @param string $value - the value of the field.
1764     * @param string $class - the field class.
1765     * @param bool   $required - if the field is marked as required.
1766     * @param string $required_field_text - the text in the required text field.
1767     * @param string $placeholder - the field placeholder content.
1768     * @param bool   $required_indicator Whether to display the required indicator.
1769     *
1770     * @return string HTML
1771     */
1772    public function render_url_field( $id, $label, $value, $class, $required, $required_field_text, $placeholder, $required_indicator = true ) {
1773        $this->set_invalid_message( 'url', __( 'Please enter a valid URL - https://www.example.com', 'jetpack-forms' ) );
1774
1775        $field  = $this->render_label( 'url', $id, $label, $required, $required_field_text, array(), false, $required_indicator );
1776        $field .= $this->render_input_field( 'text', $id, $value, $class, $placeholder, $required );
1777        return $field;
1778    }
1779
1780    /**
1781     * Return the HTML for the text area field.
1782     *
1783     * @param int    $id - the ID.
1784     * @param string $label - the label.
1785     * @param string $value - the value of the field.
1786     * @param string $class - the field class.
1787     * @param bool   $required - if the field is marked as required.
1788     * @param string $required_field_text - the text in the required text field.
1789     * @param string $placeholder - the field placeholder content.
1790     * @param bool   $required_indicator Whether to display the required indicator.
1791     *
1792     * @return string HTML
1793     */
1794    public function render_textarea_field( $id, $label, $value, $class, $required, $required_field_text, $placeholder, $required_indicator = true ) {
1795        if ( ! is_string( $value ) ) {
1796            $value = '';
1797        }
1798
1799        $field  = $this->render_label( 'textarea', 'contact-form-comment-' . $id, $label, $required, $required_field_text, array(), false, $required_indicator );
1800        $field .= "<textarea
1801                        style='" . $this->field_styles . "'
1802                        name='" . esc_attr( $id ) . "'
1803                        id='contact-form-comment-" . esc_attr( $id ) . "'
1804                        rows='20'
1805                        data-wp-text='state.getFieldValue'
1806                        data-wp-on--input='actions.onFieldChange'
1807                        data-wp-on--blur='actions.onFieldBlur'
1808                        data-wp-class--has-value='state.hasFieldValue'
1809                        aria-describedby='" . esc_attr( $this->get_described_by( $id, 'textarea' ) ) . "'
1810                        data-wp-bind--aria-invalid='state.fieldAriaInvalid'
1811                        "
1812                        . $this->get_hidden_label_aria_label_attr()
1813                        . $class
1814                        . $placeholder
1815                        . ' ' . ( $required ? "required aria-required='true'" : '' ) .
1816                        '>' . esc_textarea( $value )
1817                . "</textarea>\n " . $this->get_field_descriptions( $id, 'textarea' ) . "\n";
1818        return $field;
1819    }
1820
1821    /**
1822     * Return the HTML for the radio field.
1823     *
1824     * @param string $id - the ID (starts with 'g' - see constructor).
1825     * @param string $label - the label.
1826     * @param string $value - the value of the field.
1827     * @param string $class - the field class.
1828     * @param bool   $required - if the field is marked as required.
1829     * @param string $required_field_text - the text in the required text field.
1830     * @param bool   $required_indicator Whether to display the required indicator.
1831     *
1832     * @return string HTML
1833     */
1834    public function render_radio_field( $id, $label, $value, $class, $required, $required_field_text, $required_indicator = true ) {
1835        $this->set_invalid_message( 'radio', __( 'Please select one of the options.', 'jetpack-forms' ) );
1836        $options_classes   = $this->get_attribute( 'optionsclasses' );
1837        $options_styles    = $this->get_attribute( 'optionsstyles' );
1838        $form_style        = $this->get_form_style();
1839        $is_outlined_style = 'outlined' === $form_style;
1840        $fieldset_id       = "id='" . esc_attr( "$id-label" ) . "'" . $this->get_hidden_label_aria_label_attr();
1841
1842        $error_described_by = " aria-describedby='" . esc_attr( $this->get_error_message_id( $id, 'radio' ) ) . "'";
1843
1844        if ( $is_outlined_style ) {
1845            $style_variation_attributes = $this->get_attribute( 'stylevariationattributes' );
1846
1847            if ( ! empty( $style_variation_attributes ) ) {
1848                $style_variation_attributes = json_decode( html_entity_decode( $style_variation_attributes, ENT_COMPAT ), true );
1849            }
1850
1851            // When there's an outlined style, and border radius is set, the existing inline border radius is overridden to apply
1852            // a limit of `100px` to the radius on the x axis. This achieves the same look and feel as other fields
1853            // that use the notch html (`notched-label__leading` has a max-width of `100px` to prevent it from getting too wide).
1854            // It prevents large border radius values from disrupting the look and feel of the fields.
1855            if ( isset( $style_variation_attributes['border']['radius'] ) ) {
1856                $options_styles        ??= '';
1857                $radius                  = $style_variation_attributes['border']['radius'];
1858                $has_split_radius_values = is_array( $radius );
1859                $top_left_radius         = $has_split_radius_values ? $radius['topLeft'] : $radius;
1860                $top_right_radius        = $has_split_radius_values ? $radius['topRight'] : $radius;
1861                $bottom_left_radius      = $has_split_radius_values ? $radius['bottomLeft'] : $radius;
1862                $bottom_right_radius     = $has_split_radius_values ? $radius['bottomRight'] : $radius;
1863                $options_styles         .= "border-top-left-radius: min(100px, {$top_left_radius}) {$top_left_radius};";
1864                $options_styles         .= "border-top-right-radius: min(100px, {$top_right_radius}) {$top_right_radius};";
1865                $options_styles         .= "border-bottom-left-radius: min(100px, {$bottom_left_radius}) {$bottom_left_radius};";
1866                $options_styles         .= "border-bottom-right-radius: min(100px, {$bottom_right_radius}) {$bottom_right_radius};";
1867            }
1868
1869            /*
1870             * For the "outlined" style, the styles and classes are applied to the fieldset element.
1871             */
1872            $field = "<fieldset {$fieldset_id} class='grunion-radio-options " . esc_attr( $options_classes ) . "' style='" . esc_attr( $options_styles ) . "' data-wp-bind--aria-invalid='state.fieldAriaInvalid'{$error_described_by} >";
1873        } else {
1874            $field = "<fieldset {$fieldset_id} class='jetpack-field-multiple__fieldset' data-wp-bind--aria-invalid='state.fieldAriaInvalid'{$error_described_by} >";
1875        }
1876
1877        $field .= $this->render_legend_as_label( '', $id, $label, $required, $required_field_text, array(), $required_indicator );
1878
1879        if ( ! $is_outlined_style ) {
1880            $field .= "<div class='grunion-radio-options " . esc_attr( $options_classes ) . "' style='" . esc_attr( $options_styles ) . "'>";
1881        }
1882
1883        $options_data  = $this->get_attribute( 'optionsdata' );
1884        $used_html_ids = array();
1885
1886        if ( ! empty( $options_data ) ) {
1887            foreach ( $options_data as $option_index => $option ) {
1888                $option_label = Contact_Form_Plugin::strip_tags( $option['label'] );
1889                if ( is_string( $option_label ) && '' !== $option_label ) {
1890                    $radio_value = $this->get_option_value( $this->get_attribute( 'values' ), $option_index, $option_label );
1891                    $radio_id    = $id . '-' . sanitize_html_class( $radio_value );
1892
1893                    // If exact id was already used in this radio group, append option index.
1894                    // Multiple 'blue' options would give id-blue, id-blue-1, id-blue-2, etc.
1895                    if ( isset( $used_html_ids[ $radio_id ] ) ) {
1896                        $radio_id .= '-' . $option_index;
1897                    }
1898                    $used_html_ids[ $radio_id ] = true;
1899
1900                    $default_classes = 'contact-form-field';
1901                    $option_styles   = empty( $option['style'] ) ? '' : "style='" . esc_attr( $option['style'] ) . "'";
1902                    $option_classes  = empty( $option['class'] ) ? $default_classes : $default_classes . ' ' . esc_attr( $option['class'] );
1903
1904                    $is_other_option  = ! empty( $option['isOther'] );
1905                    $change_action    = $is_other_option ? 'actions.onOtherRadioChange' : 'actions.onFieldChange';
1906                    $other_label_attr = $is_other_option ? " data-other-label='" . esc_attr( $option_label ) . "'" : '';
1907
1908                    $field .= "<label {$option_styles} class='{$option_classes}'>";
1909                    $field .= "<input
1910                                    id='" . esc_attr( $radio_id ) . "'
1911                                    type='radio'
1912                                    name='" . esc_attr( $id ) . "'
1913                                    value='" . esc_attr( $radio_value ) . "'
1914                                    data-wp-on--change='" . $change_action . "'"
1915                                    . $other_label_attr . ' '
1916                                    . $class
1917                                    . checked( $option_label, $value, false ) . ' '
1918                                    . ( $required ? "required aria-required='true'" : '' )
1919                                    . '/> ';
1920                    $field .= "<span class='grunion-radio-label radio" . ( $this->is_error() ? ' form-error' : '' ) . "'>";
1921                    $field .= "<span class='grunion-field-text'>" . esc_html( $option_label ) . '</span>';
1922                    $field .= '</span>';
1923                    $field .= '</label>';
1924
1925                    if ( $is_other_option ) {
1926                        $placeholder = ! empty( $option['otherPlaceholder'] ) ? $option['otherPlaceholder'] : '';
1927                        $field      .= $this->render_other_input_field( $radio_id, $required, $id, $this->field_styles, $placeholder );
1928                    }
1929                }
1930            }
1931        } else {
1932            $field_style = 'style="' . $this->option_styles . '"';
1933
1934            foreach ( (array) $this->get_attribute( 'options' ) as $option_index => $option ) {
1935                $option = Contact_Form_Plugin::strip_tags( $option );
1936                if ( is_string( $option ) && '' !== $option ) {
1937                    $radio_value = $this->get_option_value( $this->get_attribute( 'values' ), $option_index, $option );
1938                    $radio_id    = $id . '-' . sanitize_html_class( $radio_value );
1939
1940                    // If exact id was already used in this radio group, append option index.
1941                    // Multiple 'blue' options would give id-blue, id-blue-1, id-blue-2, etc.
1942                    if ( isset( $used_html_ids[ $radio_id ] ) ) {
1943                        $radio_id .= '-' . $option_index;
1944                    }
1945                    $used_html_ids[ $radio_id ] = true;
1946
1947                    $field .= "<p class='contact-form-field'>";
1948                    $field .= "<input
1949                                    id='" . esc_attr( $radio_id ) . "'
1950                                    type='radio'
1951                                    name='" . esc_attr( $id ) . "'
1952                                    value='" . esc_attr( $radio_value ) . "'
1953                                    data-wp-on--change='actions.onFieldChange' "
1954                                    . $class
1955                                    . checked( $option, $value, false ) . ' '
1956                                    . ( $required ? "required aria-required='true'" : '' )
1957                                    . '/> ';
1958                    $field .= "<label for='" . esc_attr( $radio_id ) . "' {$field_style} class='grunion-radio-label radio" . ( $this->is_error() ? ' form-error' : '' ) . "'>";
1959                    $field .= "<span class='grunion-field-text'>" . esc_html( $option ) . '</span>';
1960                    $field .= '</label>';
1961                    $field .= '</p>';
1962                }
1963            }
1964        }
1965
1966        if ( ! $is_outlined_style ) {
1967            $field .= '</div>';
1968        }
1969        $field .= $this->get_error_div( $id, 'radio' ) . '</fieldset>';
1970        return $field;
1971    }
1972
1973    /**
1974     * Render the "Other" text input field for radio and checkbox fields.
1975     *
1976     * @param string $option_id The ID of the "Other" option.
1977     * @param bool   $required Whether the main field is required.
1978     * @param string $id The base ID of the main field.
1979     * @param string $field_styles The styles to apply to the text input field.
1980     * @param string $placeholder Placeholder text for the input field.
1981     *
1982     * @return string The HTML for the "Other" text input field.
1983     */
1984    private function render_other_input_field( $option_id, $required, $id, $field_styles, $placeholder ) {
1985        $other_text_id      = esc_attr( $option_id ) . '-other-text';
1986        $other_label_id     = esc_attr( $option_id ) . '-other-label';
1987        $other_label_text   = ! empty( $placeholder ) ? $placeholder : __( 'Please specify…', 'jetpack-forms' );
1988        $aria_required_attr = $required ? "aria-required='true'" : '';
1989        $other_input_styles = ! empty( $field_styles ) ? " style='" . esc_attr( $field_styles ) . "' " : '';
1990
1991        $field  = "<div class='jetpack-other-text-input-wrapper' data-wp-class--is-visible='state.isOtherSelected' role='region'>";
1992        $field .= "<label id='" . $other_label_id . "' for='" . $other_text_id . "' class='screen-reader-text'>" . esc_html( $other_label_text ) . '</label>';
1993        $field .= "<input
1994                    id='" . $other_text_id . "'
1995                    name='" . esc_attr( $id ) . "-other-text'
1996                    type='text'
1997                    class='grunion-field'
1998                    " . $other_input_styles . "
1999                    placeholder='" . esc_attr( $placeholder ) . "'
2000                    value=''
2001                    aria-labelledby='" . $other_label_id . "'
2002                    " . $aria_required_attr . "
2003                    data-wp-on--input='actions.onOtherTextInput'
2004                    data-wp-bind--disabled='!state.isOtherSelected'
2005                    data-wp-class--has-value='state.hasFieldValue' />";
2006        $field .= '</div>';
2007
2008        return $field;
2009    }
2010
2011    /**
2012     * Return the HTML for the checkbox field.
2013     *
2014     * @param int    $id - the ID.
2015     * @param string $label - the label.
2016     * @param string $value - the value of the field.
2017     * @param string $class - the field class.
2018     * @param bool   $required - if the field is marked as required.
2019     * @param string $required_field_text - the text in the required text field.
2020     * @param bool   $required_indicator Whether to display the required indicator.
2021     *
2022     * @return string HTML
2023     */
2024    public function render_checkbox_field( $id, $label, $value, $class, $required, $required_field_text, $required_indicator = true ) {
2025        $label_class                   = 'grunion-field-label checkbox';
2026        $label_class                  .= $this->is_error() ? ' form-error' : '';
2027        $label_class                  .= $this->label_classes ? ' ' . $this->label_classes : '';
2028        $label_class                  .= $this->option_classes ? ' ' . $this->option_classes : '';
2029        $has_inner_block_option_styles = ! empty( $this->get_attribute( 'optionstyles' ) );
2030
2031        $field  = "<div class='contact-form__checkbox-wrap' style='" . ( $has_inner_block_option_styles ? esc_attr( $this->option_styles ) : '' ) . "' >";
2032        $field .= "<input id='" . esc_attr( $id ) . "' type='checkbox' data-wp-on--change='actions.onFieldChange' name='" . esc_attr( $id ) . "' value='" . esc_attr__( 'Yes', 'jetpack-forms' ) . "' " . $class . checked( (bool) $value, true, false ) . ' ' . ( $required ? "required aria-required='true'" : '' ) . "/> \n";
2033        $field .= "<label for='" . esc_attr( $id ) . "' class='" . esc_attr( $label_class ) . "' style='" . esc_attr( $this->label_styles ) . ( $has_inner_block_option_styles ? esc_attr( $this->option_styles ) : '' ) . "'>";
2034        $field .= wp_kses_post( $label ) . ( $required && $required_indicator ? '<span class="grunion-label-required" aria-hidden="true">' . $required_field_text . '</span>' : '' );
2035        $field .= "</label>\n";
2036        $field .= "<div class='clear-form'></div>\n";
2037        $field .= '</div>';
2038        return $field . $this->get_error_div( $id, 'checkbox' );
2039    }
2040
2041    /**
2042     * Return the HTML for the consent field.
2043     *
2044     * @param string $id field id.
2045     * @param string $class html classes (can be set by the admin).
2046     */
2047    private function render_consent_field( $id, $class ) {
2048        $consent_type                  = 'explicit' === $this->get_attribute( 'consenttype' ) ? 'explicit' : 'implicit';
2049        $consent_message               = 'explicit' === $consent_type ? $this->get_attribute( 'explicitconsentmessage' ) : $this->get_attribute( 'implicitconsentmessage' );
2050        $label_class                   = 'grunion-field-label consent consent-' . esc_attr( $consent_type );
2051        $label_class                  .= $this->option_classes ? ' ' . $this->option_classes : '';
2052        $label_class                  .= $this->is_error() ? ' form-error' : '';
2053        $has_inner_block_option_styles = ! empty( $this->get_attribute( 'optionstyles' ) );
2054
2055        $field = "<label class='" . esc_attr( $label_class ) . "' style='" . esc_attr( $this->label_styles ) . ( $has_inner_block_option_styles ? esc_attr( $this->option_styles ) : '' ) . "'>";
2056
2057        if ( 'implicit' === $consent_type ) {
2058            $field .= "\t\t<input type='hidden' name='" . esc_attr( $id ) . "' value='" . esc_attr__( 'Yes', 'jetpack-forms' ) . "' /> \n";
2059        } else {
2060            $field .= "\t\t<input type='checkbox' data-wp-on--change='actions.onFieldChange' name='" . esc_attr( $id ) . "' value='" . esc_attr__( 'Yes', 'jetpack-forms' ) . "' " . $class . "/> \n";
2061        }
2062        $field .= "\t\t" . wp_kses_post( $consent_message );
2063        $field .= "</label>\n";
2064        $field .= "<div class='clear-form'></div>\n";
2065        return $field . $this->get_error_div( $id, 'checkbox' );
2066    }
2067
2068    /**
2069     * Return the HTML for the file field.
2070     *
2071     * Renders a file upload field with drag-and-drop functionality.
2072     *
2073     * @since 0.45.0
2074     *
2075     * @param string $id - the field ID.
2076     * @param string $label - the field label.
2077     * @param string $class - unused. Kept for signature parity with the other render_*_field()
2078     *                        methods; this field writes its input inline rather than from an
2079     *                        attribute array.
2080     * @param bool   $required - if the field is marked as required.
2081     * @param string $required_field_text - the text in the required text field.
2082     * @param bool   $required_indicator Whether to display the required indicator.
2083     *
2084     * @return string HTML for the file upload field.
2085     */
2086    private function render_file_field( $id, $label, $class, $required, $required_field_text, $required_indicator = true ) {
2087        // Check if Jetpack is active
2088        if ( ! defined( 'JETPACK__PLUGIN_DIR' ) ) {
2089            return '<div class="jetpack-form-field-error">' .
2090                esc_html__( 'File upload field requires Jetpack to be active.', 'jetpack-forms' ) .
2091                '</div>';
2092        }
2093
2094        $this->set_invalid_message( 'file_uploading', __( 'Please wait a moment, file is currently uploading.', 'jetpack-forms' ) );
2095        $this->set_invalid_message( 'file_has_errors', __( 'Please remove any file upload errors.', 'jetpack-forms' ) );
2096
2097        // Enqueue necessary scripts and styles.
2098        $this->enqueue_file_field_assets();
2099
2100        $accept_attribute_value = implode( ', ', self::get_file_field_accepted_mime_types() );
2101        $max_files              = $this->get_file_field_max_files();
2102        $max_upload_size        = self::get_file_field_max_upload_size();
2103
2104        $file_size_units = array(
2105            _x( 'B', 'unit symbol', 'jetpack-forms' ),
2106            _x( 'KB', 'unit symbol', 'jetpack-forms' ),
2107            _x( 'MB', 'unit symbol', 'jetpack-forms' ),
2108            _x( 'GB', 'unit symbol', 'jetpack-forms' ),
2109        );
2110
2111        $global_config = array(
2112            'i18n'          => array(
2113                'language'           => get_bloginfo( 'language' ),
2114                'fileSizeUnits'      => $file_size_units,
2115                'zeroBytes'          => __( '0 Bytes', 'jetpack-forms' ),
2116                'uploadError'        => __( 'Error uploading file', 'jetpack-forms' ),
2117                'folderNotSupported' => __( 'Folder uploads are not supported', 'jetpack-forms' ),
2118                // translators: %s is the formatted maximum file size.
2119                'fileTooLarge'       => sprintf( __( 'File is too large. Maximum allowed size is %s.', 'jetpack-forms' ), size_format( $max_upload_size ) ),
2120                'invalidType'        => __( 'This file type is not allowed.', 'jetpack-forms' ),
2121                'maxFiles'           => __( 'You have exceeded the number of files that you can upload.', 'jetpack-forms' ),
2122                'uploadFailed'       => __( 'File upload failed, try again.', 'jetpack-forms' ),
2123            ),
2124            'endpoint'      => $this->get_unauth_endpoint_url(),
2125            'iconsPath'     => Jetpack_Forms::plugin_url() . 'contact-form/images/file-icons/',
2126            'maxUploadSize' => $max_upload_size,
2127        );
2128
2129        wp_interactivity_config( 'jetpack/field-file', $global_config );
2130
2131        // Only genuinely dynamic state lives in the context. The field's static configuration
2132        // (`maxFiles`, `allowedMimeTypes`) travels in `fieldExtra` alongside every other field's
2133        // config, and `fieldId` already comes from the wrapper that `render_field()` opens.
2134        $context = array(
2135            'isDropping' => false,
2136            'files'      => array(),
2137            // Field-level message that belongs to no single file â€” currently only the result of
2138            // offering more files than the field accepts. Per-file problems stay on their preview.
2139            'fileNotice' => '',
2140        );
2141
2142        $field = $this->render_label( 'file', $id, $label, $required, $required_field_text, array(), true, $required_indicator );
2143
2144        $dropzone_aria_label = $this->get_file_dropzone_aria_label( $max_files );
2145
2146        ob_start();
2147        ?>
2148        <div
2149            class="jetpack-form-file-field__container"
2150            id="<?php echo esc_attr( $id ); ?>"
2151            name="dropzone-<?php echo esc_attr( $id ); ?>"
2152            <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- output is pre-escaped by method ?>
2153            <?php echo wp_interactivity_data_wp_context( $context ); ?>
2154            data-wp-on--dragover="actions.onFileDragOver"
2155            data-wp-on--dragleave="actions.onFileDragLeave"
2156            data-wp-on--mouseleave="actions.onFileDragLeave"
2157            data-wp-on--drop="actions.fileDropped"
2158            data-wp-on--jetpack-form-reset="actions.resetFiles"
2159            data-is-required="<?php echo esc_attr( $required ); ?>"
2160        >
2161            <div class="jetpack-form-file-field__dropzone" data-wp-class--is-dropping="context.isDropping" data-wp-class--is-hidden="state.isFileFieldFull">
2162                <div class="jetpack-form-file-field__dropzone-inner" data-wp-on--click="actions.openFilePicker" data-wp-on--keydown="actions.onFileDropzoneKeyDown" tabindex="0" role="button" aria-label="<?php echo esc_attr( $dropzone_aria_label ); ?>"></div>
2163                <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Decoded dropzone markup is filtered through an allowlist by sanitize_file_field_content(). ?>
2164                <?php echo $this->sanitize_file_field_content( $this->content ); ?>
2165                <input
2166                    type="file" class="jetpack-form-file-field"
2167                    accept="<?php echo esc_attr( $accept_attribute_value ); ?>"
2168                    <?php // Without this the picker returns one file at a time however many the field accepts; a drop already could. ?>
2169                    <?php echo $max_files > 1 ? 'multiple' : ''; ?>
2170                    data-wp-on--change="actions.fileAdded"  />
2171            </div>
2172            <div class="jetpack-form-file-field__preview-wrap" name="file-field-<?php echo esc_attr( $id ); ?>" data-wp-class--is-active="state.hasFileFieldFiles">
2173                <template data-wp-each--file="context.files" data-wp-key="context.file.id">
2174                    <div class="jetpack-form-file-field__preview" tabindex="0" data-wp-bind--aria-label="context.file.name" data-wp-init--focus="callbacks.focusFilePreview" data-wp-class--is-error="context.file.hasError" data-wp-class--is-complete="context.file.isUploaded">
2175                        <input type="hidden" name="<?php echo esc_attr( $id ); ?>[]" class="jetpack-form-file-field__hidden include-hidden" data-wp-bind--value='context.file.fileJson' value="">
2176                        <div class="jetpack-form-file-field__image-wrap" data-wp-style----progress="context.file.progress" data-wp-class--has-icon="context.file.hasIcon">
2177                            <div class="jetpack-form-file-field__image" data-wp-style--background-image="context.file.url" data-wp-style--mask-image="context.file.mask"></div>
2178                            <div class="jetpack-form-file-field__progress-bar" ></div>
2179                        </div>
2180
2181                        <div class="jetpack-form-file-field__file-wrap">
2182                            <strong class="jetpack-form-file-field__file-name" data-wp-text="context.file.name"></strong>
2183                            <div class="jetpack-form-file-field__file-info" data-wp-class--is-error="context.file.error" data-wp-class--is-complete="context.file.file_id">
2184                                <span class="jetpack-form-file-field__file-size" data-wp-text="context.file.formattedSize"></span>
2185                                <span class="jetpack-form-file-field__seperator"> &middot; </span>
2186                                <span aria-live="polite">
2187                                    <span class="jetpack-form-file-field__uploading"><?php esc_html_e( 'Uploading…', 'jetpack-forms' ); ?></span>
2188                                    <span class="jetpack-form-file-field__success"><?php esc_html_e( 'Uploaded', 'jetpack-forms' ); ?></span>
2189                                    <span class="jetpack-form-file-field__error" data-wp-text="context.file.error"></span>
2190                                </span>
2191                            </div>
2192                        </div>
2193                        <a href="#" class="jetpack-form-file-field__remove" data-wp-bind--data-id='context.file.id' aria-label="<?php esc_attr_e( 'Remove file', 'jetpack-forms' ); ?>" data-wp-on--click="actions.removeFile" data-wp-on--keydown="actions.removeFileKeydown" title="<?php esc_attr_e( 'Remove', 'jetpack-forms' ); ?>"> </a>
2194                    </div>
2195                </template>
2196            </div>
2197            <p class="jetpack-form-file-field__notice" role="status" data-wp-class--is-visible="state.hasFileFieldNotice" data-wp-text="context.fileNotice"></p>
2198        </div>
2199        <?php
2200        return $field . ob_get_clean() . $this->get_error_div( $id, 'file' );
2201    }
2202
2203    /**
2204     * Sanitize the file field's inner (dropzone) content for output.
2205     *
2206     * The dropzone's inner blocks are serialized into the [contact-field] shortcode with
2207     * esc_html() (see Contact_Form::parse_contact_field()), so the stored content has to be
2208     * entity-decoded before it can render. Decoding is what makes this dangerous: an author
2209     * who cannot post raw HTML can still store entity-encoded markup in the shortcode's inner
2210     * content, which post-save KSES treats as plain text and never inspects. Decoding it would
2211     * turn that text back into live markup, so the decoded result is filtered here instead of
2212     * being echoed as-is.
2213     *
2214     * @since 7.24.0
2215     *
2216     * @param string|null $content The raw (entity-encoded) field content.
2217     *
2218     * @return string Safe HTML.
2219     */
2220    private function sanitize_file_field_content( $content ) {
2221        if ( ! is_string( $content ) || $content === '' ) {
2222            return '';
2223        }
2224
2225        // core/icon serializes its rotation as `rotate: 45deg`, which is not in WordPress's
2226        // safe_style_css list, so safecss_filter_attr() would strip it and render the icon
2227        // unrotated. Allow it just for the duration of this call.
2228        $allow_rotate = static function ( $attrs ) {
2229            $attrs[] = 'rotate';
2230            return $attrs;
2231        };
2232
2233        add_filter( 'safe_style_css', $allow_rotate );
2234
2235        try {
2236            return wp_kses(
2237                html_entity_decode( $content, ENT_COMPAT, 'UTF-8' ),
2238                self::get_file_field_allowed_html()
2239            );
2240        } finally {
2241            remove_filter( 'safe_style_css', $allow_rotate );
2242        }
2243    }
2244
2245    /**
2246     * Build the allowlist of HTML permitted inside the file field's dropzone.
2247     *
2248     * Starts from the standard post allowlist and adds the things the dropzone's allowed inner
2249     * blocks legitimately rely on that wp_kses_post() would otherwise drop:
2250     *
2251     * - `tabindex`, which Contact_Form_Plugin::gutenblock_render_dropzone() sets to "-1" on inner
2252     *   links and buttons so the dropzone stays a single tab stop.
2253     * - `srcset`, `sizes` and `decoding` on images, so core/image keeps serving responsive
2254     *   sources instead of silently degrading to the full-size file.
2255     * - A conservative inline SVG subset, since core/icon is an allowed inner block of the
2256     *   dropzone. Only presentational elements and attributes are listed; because wp_kses() is
2257     *   allowlist-based, event handlers and scripting constructs are dropped automatically.
2258     *
2259     * Note that wp_kses_allowed_html( 'post' ) permits `data-*` globally, so Interactivity API
2260     * directives survive this filter. Their values are store paths rather than executable code,
2261     * and removing them would also break core/image's lightbox markup, so they are left alone.
2262     *
2263     * @since 7.24.0
2264     *
2265     * @return array Allowed HTML, in wp_kses() format.
2266     */
2267    private static function get_file_field_allowed_html() {
2268        $allowed = wp_kses_allowed_html( 'post' );
2269
2270        foreach ( array( 'a', 'button' ) as $tag ) {
2271            if ( isset( $allowed[ $tag ] ) && is_array( $allowed[ $tag ] ) ) {
2272                $allowed[ $tag ]['tabindex'] = true;
2273            }
2274        }
2275
2276        // wp_kses() only runs its protocol check on a fixed set of URL attributes, which does not
2277        // include `srcset`. That is not a script vector - srcset candidates are fetched as images,
2278        // so a `javascript:` candidate never executes - and `src` is still protocol-checked.
2279        if ( isset( $allowed['img'] ) && is_array( $allowed['img'] ) ) {
2280            $allowed['img'] += array(
2281                'srcset'   => true,
2282                'sizes'    => true,
2283                'decoding' => true,
2284            );
2285        }
2286
2287        // `style` is deliberately absent here: safecss_filter_attr() strips the SVG presentation
2288        // properties (fill, stroke) that would justify it, while still permitting things like
2289        // position:fixed. It is allowed on the root <svg> below, where block supports need it.
2290        $svg_common = array(
2291            'class'           => true,
2292            'fill'            => true,
2293            'fill-rule'       => true,
2294            'clip-rule'       => true,
2295            'stroke'          => true,
2296            'stroke-width'    => true,
2297            'stroke-linecap'  => true,
2298            'stroke-linejoin' => true,
2299            'opacity'         => true,
2300            'transform'       => true,
2301        );
2302
2303        $allowed['svg'] = array_merge(
2304            $svg_common,
2305            array(
2306                'style'       => true,
2307                'xmlns'       => true,
2308                'viewbox'     => true,
2309                'width'       => true,
2310                'height'      => true,
2311                'role'        => true,
2312                'focusable'   => true,
2313                'aria-hidden' => true,
2314                'aria-label'  => true,
2315            )
2316        );
2317
2318        // Child elements: the shared presentation attributes plus each element's own geometry.
2319        $svg_children = array(
2320            'g'        => array(),
2321            'path'     => array( 'd' ),
2322            'circle'   => array( 'cx', 'cy', 'r' ),
2323            'ellipse'  => array( 'cx', 'cy', 'rx', 'ry' ),
2324            'line'     => array( 'x1', 'y1', 'x2', 'y2' ),
2325            'polygon'  => array( 'points' ),
2326            'polyline' => array( 'points' ),
2327            'rect'     => array( 'x', 'y', 'width', 'height', 'rx', 'ry' ),
2328        );
2329
2330        foreach ( $svg_children as $tag => $attrs ) {
2331            $allowed[ $tag ] = $svg_common + array_fill_keys( $attrs, true );
2332        }
2333
2334        return $allowed;
2335    }
2336
2337    /**
2338     * Render a hidden field.
2339     *
2340     * @param string $id - the field ID.
2341     * @param string $label - the field label.
2342     * @param string $value - the value of the field.
2343     *
2344     * @return string HTML for the hidden field.
2345     */
2346    private function render_hidden_field( $id, $label, $value ) {
2347        if ( ! $this->is_submitted_hidden_field_value( $id ) ) {
2348            $value = $this->get_filtered_hidden_field_value( $value, $label, $id );
2349        }
2350
2351        $context = array(
2352            'fieldId'         => $id,
2353            'fieldType'       => 'hidden',
2354            'fieldLabel'      => $label,
2355            'fieldValue'      => $value,
2356            'fieldIsRequired' => false,
2357            'fieldExtra'      => array(),
2358            'formHash'        => $this->form ? $this->form->hash : '',
2359        );
2360
2361        $interactivity_attributes = "data-jp-field-id='" . esc_attr( $id ) . "' data-wp-interactive='jetpack/form' "
2362            . wp_interactivity_data_wp_context( $context )
2363            . " data-wp-init='callbacks.initializeField' data-wp-on--jetpack-form-reset='callbacks.initializeField'";
2364
2365        return "<input type='hidden' name='" . esc_attr( $id ) . "' id='" . esc_attr( $id )
2366            . "' value='" . esc_attr( $value ) . "' " . $interactivity_attributes . " />\n";
2367    }
2368
2369    /**
2370     * How many files this file upload field accepts.
2371     *
2372     * Read from the block's `maxfiles` attribute and clamped rather than trusted: the value reaches
2373     * PHP as author-supplied shortcode text, and both the rendered `multiple` attribute and the
2374     * submission-time count check are derived from it.
2375     *
2376     * @since 8.0.0
2377     *
2378     * @return int A number between 1 and FILE_FIELD_MAX_FILES_LIMIT.
2379     */
2380    private function get_file_field_max_files() {
2381        $max_files = $this->get_attribute( 'maxfiles' );
2382
2383        if ( ! is_numeric( $max_files ) ) {
2384            return self::FILE_FIELD_DEFAULT_MAX_FILES;
2385        }
2386
2387        return max( 1, min( (int) $max_files, self::get_file_field_max_files_limit() ) );
2388    }
2389
2390    /**
2391     * The highest number of files an author may set a single file upload field to.
2392     *
2393     * @since 8.0.0
2394     *
2395     * @return int A number between 1 and FILE_FIELD_MAX_FILES_ABSOLUTE_LIMIT.
2396     */
2397    public static function get_file_field_max_files_limit() {
2398        /**
2399         * Filters the highest number of files an author may set a file upload field to.
2400         *
2401         * This raises the ceiling rather than setting the count. A field still takes whatever its
2402         * author chose, so one deliberately set to a single file keeps taking a single file â€” which
2403         * is the whole difference between offering more room and overriding everybody's choice.
2404         *
2405         * The editor's control reads the same number, so what an author is offered is what the site
2406         * will honour. A field already storing a number above the ceiling is clamped down to it, so
2407         * removing this filter returns those fields to the default rather than leaving them on a
2408         * value nothing enforces any more.
2409         *
2410         * Bounded by FILE_FIELD_MAX_FILES_ABSOLUTE_LIMIT. Nothing at the receiving end refuses a
2411         * submission for holding too many files â€” the endpoint's per-site budgets log and alert but
2412         * store the file regardless â€” so this ceiling is the only thing standing in the way.
2413         *
2414         * @since 8.0.0
2415         *
2416         * @param int $limit The highest number of files an author may choose.
2417         */
2418        $limit = (int) apply_filters(
2419            'jetpack_forms_file_field_max_files_limit',
2420            self::FILE_FIELD_MAX_FILES_LIMIT
2421        );
2422
2423        return max( 1, min( $limit, self::FILE_FIELD_MAX_FILES_ABSOLUTE_LIMIT ) );
2424    }
2425
2426    /**
2427     * The largest file a file upload field accepts, in bytes.
2428     *
2429     * @since 8.0.0
2430     *
2431     * @return int Size in bytes.
2432     */
2433    private static function get_file_field_max_upload_size() {
2434        /**
2435         * Filters the largest file a file upload field accepts, in bytes.
2436         *
2437         * Deliberately not bounded by the site's own PHP upload limits. The browser sends each file
2438         * straight to the upload endpoint, so `upload_max_filesize` and `post_max_size` have nothing
2439         * to do with this transfer â€” clamping to them would cap the field at whatever a cheap host
2440         * allows for files that host never receives.
2441         *
2442         * The bound that does matter is the endpoint's own, which rejects anything over
2443         * FILE_FIELD_MAX_UPLOAD_SIZE. So this filter can only lower the limit, never raise it: a
2444         * larger value would have the field accept a file, show the visitor a size allowance in the
2445         * "file is too large" message that nothing can honour, and then fail the upload once they had
2446         * already waited for it. Raising the ceiling means raising it at the endpoint first.
2447         *
2448         * The result reaches the browser as the `maxUploadSize` config value, and the "file is too
2449         * large" message is built from the same number, so the two cannot disagree.
2450         *
2451         * @since 8.0.0
2452         *
2453         * @param int $max_upload_size Maximum size of a single file, in bytes.
2454         */
2455        $max_upload_size = (int) apply_filters(
2456            'jetpack_forms_file_field_max_upload_size',
2457            self::FILE_FIELD_MAX_UPLOAD_SIZE
2458        );
2459
2460        return max( 1, min( $max_upload_size, self::FILE_FIELD_MAX_UPLOAD_SIZE ) );
2461    }
2462
2463    /**
2464     * MIME types the file upload field accepts.
2465     *
2466     * Shared by the input's `accept` attribute and by the field's `fieldExtra` config, so the
2467     * browser-side picker filter and the client-side check can never drift apart.
2468     *
2469     * @since 8.0.0
2470     *
2471     * @return string[] List of accepted MIME types.
2472     */
2473    private static function get_file_field_accepted_mime_types() {
2474        return array_values(
2475            array(
2476                'jpg|jpeg|jpe'    => 'image/jpeg',
2477                'png'             => 'image/png',
2478                'gif'             => 'image/gif',
2479                'pdf'             => 'application/pdf',
2480                'doc'             => 'application/msword',
2481                'docx'            => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
2482                'docm'            => 'application/vnd.ms-word.document.macroEnabled.12',
2483                'pot|pps|ppt'     => 'application/vnd.ms-powerpoint',
2484                'pptx'            => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
2485                'pptm'            => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
2486                'odt'             => 'application/vnd.oasis.opendocument.text',
2487                'ppsx'            => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
2488                'ppsm'            => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
2489                'csv'             => 'text/csv',
2490                'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
2491                'xlsx'            => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
2492                'xlsm'            => 'application/vnd.ms-excel.sheet.macroEnabled.12',
2493                'xlsb'            => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
2494                'key'             => 'application/vnd.apple.keynote',
2495                'webp'            => 'image/webp',
2496                'heic'            => 'image/heic',
2497                'heics'           => 'image/heic-sequence',
2498                'heif'            => 'image/heif',
2499                'heifs'           => 'image/heif-sequence',
2500                'asc'             => 'application/pgp-keys',
2501            )
2502        );
2503    }
2504
2505    /**
2506     * Enqueues scripts and styles needed for the file field.
2507     *
2508     * @since 0.45.0
2509     *
2510     * @return void
2511     */
2512    private function enqueue_file_field_assets() {
2513        $version = Constants::get_constant( 'JETPACK__VERSION' );
2514
2515        // extra cache busting strategy for view.js, seems they are left out of cache clearing on deploys
2516        $asset_file = plugin_dir_path( __FILE__ ) . '../../dist/modules/file-field/view.asset.php';
2517        $asset      = file_exists( $asset_file ) ? require $asset_file : null;
2518        $version   .= $asset['version'] ?? '';
2519
2520        \wp_enqueue_script_module(
2521            'jetpack-form-file-field',
2522            plugins_url( '../../dist/modules/file-field/view.js', __FILE__ ),
2523            // `jp-forms-view` is not decoration: this module contributes `state.validators.file`,
2524            // which `registerField()` reads at `data-wp-init` time. Loading after hydration would
2525            // leave a required file field registering as valid, since the shared `validateField()`
2526            // no longer has a `file` branch to fall back on. Same reason `field-phone` declares it.
2527            array( '@wordpress/interactivity', 'jp-forms-view' ),
2528            $version
2529        );
2530
2531        \wp_enqueue_style(
2532            'jetpack-form-file-field',
2533            plugins_url( '../../dist/contact-form/css/file-field.css', __FILE__ ),
2534            array(),
2535            $version
2536        );
2537    }
2538
2539    /**
2540     * Returns the URL for the unauthenticated file upload endpoint.
2541     *
2542     * @return string
2543     */
2544    private function get_unauth_endpoint_url() {
2545        // Return a placeholder URL if Jetpack is not active
2546        if ( ! defined( 'JETPACK__PLUGIN_DIR' ) ) {
2547            return '#jetpack-not-active';
2548        }
2549
2550        return sprintf( 'https://public-api.wordpress.com/wpcom/v2/sites/%d/unauth-file-upload', \Jetpack_Options::get_option( 'id' ) );
2551    }
2552
2553    /**
2554     * Return the HTML for the multiple checkbox field.
2555     *
2556     * @param string $id - the ID (starts with 'g' - see constructor).
2557     * @param string $label - the label.
2558     * @param string $value - the value of the field.
2559     * @param string $class - the field class.
2560     * @param bool   $required - if the field is marked as required.
2561     * @param string $required_field_text - the text in the required text field.
2562     * @param bool   $required_indicator Whether to display the required indicator.
2563     *
2564     * @return string HTML
2565     */
2566    public function render_checkbox_multiple_field( $id, $label, $value, $class, $required, $required_field_text, $required_indicator = true ) {
2567        $options_classes   = $this->get_attribute( 'optionsclasses' );
2568        $options_styles    = $this->get_attribute( 'optionsstyles' );
2569        $form_style        = $this->get_form_style();
2570        $is_outlined_style = 'outlined' === $form_style;
2571
2572        /*
2573         * The `data-required` attribute is used in `accessible-form.js` to ensure at least one
2574         * checkbox is checked. Unlike radio buttons, for which the required attribute is satisfied if
2575         * any of the radio buttons in the group is selected, adding a required attribute directly to
2576         * a checkbox means that this specific checkbox must be checked.
2577         */
2578        $fieldset_id = "id='" . esc_attr( "$id-label" ) . "'" . $this->get_hidden_label_aria_label_attr();
2579
2580        // Inset-label styles skip this field's 'select' error div; render_field() emits one typed by field type.
2581        $error_type         = $this->has_inset_label() ? 'checkbox-multiple' : 'select';
2582        $error_described_by = " aria-describedby='" . esc_attr( $this->get_error_message_id( $id, $error_type ) ) . "'";
2583
2584        if ( $is_outlined_style ) {
2585            $style_variation_attributes = $this->get_attribute( 'stylevariationattributes' );
2586
2587            if ( ! empty( $style_variation_attributes ) ) {
2588                $style_variation_attributes = json_decode( html_entity_decode( $style_variation_attributes, ENT_COMPAT ), true );
2589            }
2590
2591            /*
2592             * When there's an outlined style, and border radius is set, the existing inline border radius is overridden to apply
2593             * a limit of `100px` to the radius on the x axis. This achieves the same look and feel as other fields
2594             * that use the notch html (`notched-label__leading` has a max-width of `100px` to prevent it from getting too wide).
2595             * It prevents large border radius values from disrupting the look and feel of the fields.
2596             */
2597            if ( isset( $style_variation_attributes['border']['radius'] ) ) {
2598                $options_styles        ??= '';
2599                $radius                  = $style_variation_attributes['border']['radius'];
2600                $has_split_radius_values = is_array( $radius );
2601                $top_left_radius         = $has_split_radius_values ? $radius['topLeft'] : $radius;
2602                $top_right_radius        = $has_split_radius_values ? $radius['topRight'] : $radius;
2603                $bottom_left_radius      = $has_split_radius_values ? $radius['bottomLeft'] : $radius;
2604                $bottom_right_radius     = $has_split_radius_values ? $radius['bottomRight'] : $radius;
2605                $options_styles         .= "border-top-left-radius: min(100px, {$top_left_radius}) {$top_left_radius};";
2606                $options_styles         .= "border-top-right-radius: min(100px, {$top_right_radius}) {$top_right_radius};";
2607                $options_styles         .= "border-bottom-left-radius: min(100px, {$bottom_left_radius}) {$bottom_left_radius};";
2608                $options_styles         .= "border-bottom-right-radius: min(100px, {$bottom_right_radius}) {$bottom_right_radius};";
2609            }
2610
2611            /*
2612             * For the "outlined" style, the styles and classes are applied to the fieldset element.
2613             */
2614            $field = "<fieldset {$fieldset_id} class='grunion-checkbox-multiple-options " . esc_attr( $options_classes ) . "' style='" . esc_attr( $options_styles ) . "' " . ( $required ? 'data-required' : '' ) . ' data-wp-bind--aria-invalid="state.fieldAriaInvalid"' . $error_described_by . '>';
2615        } else {
2616            $field = "<fieldset {$fieldset_id} class='jetpack-field-multiple__fieldset' " . ( $required ? 'data-required' : '' ) . ' data-wp-bind--aria-invalid="state.fieldAriaInvalid"' . $error_described_by . '>';
2617        }
2618
2619        $field .= $this->render_legend_as_label( '', $id, $label, $required, $required_field_text, array(), $required_indicator );
2620
2621        if ( ! $is_outlined_style ) {
2622            $field .= "<div class='grunion-checkbox-multiple-options " . esc_attr( $options_classes ) . "' style='" . esc_attr( $options_styles ) . "' " . '>';
2623        }
2624
2625        $options_data  = $this->get_attribute( 'optionsdata' );
2626        $used_html_ids = array();
2627
2628        if ( ! empty( $options_data ) ) {
2629            foreach ( $options_data as $option_index => $option ) {
2630                $option_label = Contact_Form_Plugin::strip_tags( $option['label'] );
2631                if ( is_string( $option_label ) && '' !== $option_label ) {
2632                    $checkbox_value = $this->get_option_value( $this->get_attribute( 'values' ), $option_index, $option_label );
2633                    $checkbox_id    = $id . '-' . sanitize_html_class( $checkbox_value );
2634
2635                    // If exact id was already used in this checkbox group, append option index.
2636                    // Multiple 'blue' options would give id-blue, id-blue-1, id-blue-2, etc.
2637                    if ( isset( $used_html_ids[ $checkbox_id ] ) ) {
2638                        $checkbox_id .= '-' . $option_index;
2639                    }
2640                    $used_html_ids[ $checkbox_id ] = true;
2641
2642                    $default_classes = 'contact-form-field';
2643                    $option_styles   = empty( $option['style'] ) ? '' : "style='" . esc_attr( $option['style'] ) . "'";
2644                    $option_classes  = empty( $option['class'] ) ? $default_classes : $default_classes . ' ' . esc_attr( $option['class'] );
2645
2646                    $field .= "<label {$option_styles} class='{$option_classes}'>";
2647                    $field .= "<input
2648                                id='" . esc_attr( $checkbox_id ) . "'
2649                                type='checkbox'
2650                                data-wp-on--change='actions.onMultipleFieldChange'
2651                                name='" . esc_attr( $id ) . "[]'
2652                                value='" . esc_attr( $checkbox_value ) . "' "
2653                                . $class
2654                                . checked( in_array( $option_label, (array) $value, true ), true, false )
2655                                . ' /> ';
2656                    $field .= "<span class='grunion-checkbox-multiple-label checkbox-multiple" . ( $this->is_error() ? ' form-error' : '' ) . "'>";
2657                    $field .= "<span class='grunion-field-text'>" . esc_html( $option_label ) . '</span>';
2658                    $field .= '</span>';
2659                    $field .= '</label>';
2660                }
2661            }
2662        } else {
2663            $field_style = 'style="' . $this->option_styles . '"';
2664
2665            foreach ( (array) $this->get_attribute( 'options' ) as $option_index => $option ) {
2666                $option = Contact_Form_Plugin::strip_tags( $option );
2667                if ( is_string( $option ) && '' !== $option ) {
2668                    $checkbox_value = $this->get_option_value( $this->get_attribute( 'values' ), $option_index, $option );
2669                    $checkbox_id    = $id . '-' . sanitize_html_class( $checkbox_value );
2670
2671                    // If exact id was already used in this checkbox group, append option index.
2672                    // Multiple 'blue' options would give id-blue, id-blue-1, id-blue-2, etc.
2673                    if ( isset( $used_html_ids[ $checkbox_id ] ) ) {
2674                        $checkbox_id .= '-' . $option_index;
2675                    }
2676                    $used_html_ids[ $checkbox_id ] = true;
2677
2678                    $field .= "<label class='contact-form-field'>";
2679                    $field .= "<input
2680                                id='" . esc_attr( $checkbox_id ) . "'
2681                                data-wp-on--change='actions.onMultipleFieldChange'
2682                                type='checkbox'
2683                                name='" . esc_attr( $id ) . "[]'
2684                                value='" . esc_attr( $checkbox_value ) . "' "
2685                                . $class
2686                                . checked( in_array( $option, (array) $value, true ), true, false )
2687                                . ' /> ';
2688                    $field .= "<span {$field_style} class='grunion-checkbox-multiple-label checkbox-multiple" . ( $this->is_error() ? ' form-error' : '' ) . "'>";
2689                    $field .= "<span class='grunion-field-text'>" . esc_html( $option ) . '</span>';
2690                    $field .= '</span>';
2691                    $field .= '</label>';
2692                }
2693            }
2694        }
2695        if ( ! $is_outlined_style ) {
2696            $field .= '</div>';
2697        }
2698        $field .= $this->get_error_div( $id, 'select' ) . '</fieldset>';
2699        return $field;
2700    }
2701
2702    /**
2703     * Return the HTML for the select field.
2704     *
2705     * @param int    $id - the ID.
2706     * @param string $label - the label.
2707     * @param string $value - the value of the field.
2708     * @param string $class - the field class.
2709     * @param bool   $required - if the field is marked as required.
2710     * @param string $required_field_text - the text in the required text field.
2711     * @param bool   $required_indicator Whether to display the required indicator.
2712     *
2713     * @return string HTML
2714     */
2715    public function render_select_field( $id, $label, $value, $class, $required, $required_field_text, $required_indicator = true ) {
2716        $field      = $this->render_label( 'select', $id, $label, $required, $required_field_text, array(), false, $required_indicator );
2717        $class      = preg_replace( "/class=['\"]([^'\"]*)['\"]/", 'class="contact-form__select-wrapper $1"', $class );
2718        $field     .= "<div {$class} style='" . esc_attr( $this->field_styles ) . "'>";
2719        $aria_label = ! empty( $this->get_attribute( 'togglelabel' ) )
2720            ? Contact_Form_Plugin::strip_tags( $this->get_attribute( 'togglelabel' ) )
2721            : __( 'Select an option', 'jetpack-forms' ); // selects don't have a default label
2722        $field     .= "\t<span class='contact-form__select-element-wrapper'><select name='" . esc_attr( $id ) . "' id='" . esc_attr( $id ) . "' " . ( $required ? "required aria-required='true'" : '' ) . " data-wp-on--change='actions.onFieldChange' data-wp-bind--aria-invalid='state.fieldAriaInvalid' aria-describedby='" . esc_attr( $this->get_described_by( $id, 'select' ) ) . "' " . $this->get_hidden_label_aria_label_attr( $aria_label ) . ">\n";
2723
2724        if ( $this->get_attribute( 'togglelabel' ) ) {
2725            $field .= "\t\t<option value=''>" . $this->get_attribute( 'togglelabel' ) . "</option>\n";
2726        } elseif ( ! $this->get_attribute( 'default' ) ) {
2727            // For select fields without an explicit togglelabel or default value (e.g., shortcode-based forms),
2728            // add a placeholder option to ensure users must make an explicit selection.
2729            $field .= "\t\t<option value=''>" . esc_html__( 'Select an option', 'jetpack-forms' ) . "</option>\n";
2730        }
2731
2732        foreach ( (array) $this->get_attribute( 'options' ) as $option_index => $option ) {
2733            $option = Contact_Form_Plugin::strip_tags( $option );
2734            if ( is_string( $option ) && $option !== '' ) {
2735                $field .= "\t\t<option"
2736                                . selected( $option, $value, false )
2737                                . " value='" . esc_attr( $this->get_option_value( $this->get_attribute( 'values' ), $option_index, $option ) )
2738                                . "'>" . esc_html( $option )
2739                                . "</option>\n";
2740            }
2741        }
2742        $field .= "\t</select><span class='jetpack-field-dropdown__icon'></span></span>\n";
2743        $field .= "</div>\n";
2744
2745        return $field . $this->get_field_descriptions( $id, 'select' );
2746    }
2747
2748    /**
2749     * The date formats the date field supports, keyed by the jQuery-style
2750     * format string stored in the `dateformat` attribute.
2751     *
2752     * WARNING: sync data with DATE_FORMATS in src/blocks/shared/util/constants.js
2753     *
2754     * @since 8.0.0
2755     *
2756     * @return array
2757     */
2758    private static function get_date_formats() {
2759        return array(
2760            /* translators: date format. DD is the day of the month, MM the month, and YYYY the year (e.g., 12/31/2023). */
2761            'mm/dd/yy' => __( 'MM/DD/YYYY', 'jetpack-forms' ),
2762            /* translators: date format. DD is the day of the month, MM the month, and YYYY the year (e.g., 31/12/2023). */
2763            'dd/mm/yy' => __( 'DD/MM/YYYY', 'jetpack-forms' ),
2764            /* translators: date format. DD is the day of the month, MM the month, and YYYY the year (e.g., 2023-12-31). */
2765            'yy-mm-dd' => __( 'YYYY-MM-DD', 'jetpack-forms' ),
2766        );
2767    }
2768
2769    /**
2770     * The field's date format key, falling back to the default.
2771     *
2772     * Shared by the visible hint and the `data-format` attribute that drives
2773     * the picker, so the two cannot disagree about which format is in effect.
2774     *
2775     * @since 8.0.0
2776     *
2777     * @return string
2778     */
2779    private function get_date_format() {
2780        $date_format = $this->get_attribute( 'dateformat' );
2781
2782        return ! empty( $date_format ) ? $date_format : 'yy-mm-dd';
2783    }
2784
2785    /**
2786     * Return the HTML for the date field.
2787     *
2788     * @param int    $id - the ID.
2789     * @param string $label - the label.
2790     * @param string $value - the value of the field.
2791     * @param string $class - the field class.
2792     * @param bool   $required - if the field is marked as required.
2793     * @param string $required_field_text - the text in the required text field.
2794     * @param string $placeholder - the field placeholder content.
2795     * @param bool   $required_indicator Whether to display the required indicator.
2796     *
2797     * @return string HTML
2798     */
2799    public function render_date_field( $id, $label, $value, $class, $required, $required_field_text, $placeholder, $required_indicator = true ) {
2800        static $is_loaded = false;
2801        $this->set_invalid_message( 'date', __( 'Please enter a valid date.', 'jetpack-forms' ) );
2802
2803        $date_format = $this->get_date_format();
2804        $extra_attrs = array( 'data-format' => $date_format );
2805
2806        $field  = $this->render_label( 'date', $id, $label, $required, $required_field_text, array(), false, $required_indicator );
2807        $field .= $this->render_input_field( 'text', $id, $value, $class, $placeholder, $required, $extra_attrs );
2808
2809        /* For AMP requests, use amp-date-picker element: https://amp.dev/documentation/components/amp-date-picker */
2810        if ( class_exists( 'Jetpack_AMP_Support' ) && \Jetpack_AMP_Support::is_amp_request() ) {
2811            return sprintf(
2812                '<%1$s mode="overlay" layout="container" type="single" input-selector="[name=%2$s]">%3$s</%1$s>',
2813                'amp-date-picker',
2814                esc_attr( $id ),
2815                $field
2816            );
2817        }
2818
2819        Assets::register_script(
2820            'jp-forms-date-picker',
2821            '../../dist/contact-form/js/date-picker.js',
2822            __FILE__,
2823            array(
2824                'enqueue'      => true,
2825                'dependencies' => array(),
2826                'version'      => Constants::get_constant( 'JETPACK__VERSION' ),
2827            )
2828        );
2829
2830        /**
2831         * Filter the localized date picker script.
2832         */
2833        if ( ! $is_loaded ) {
2834            \wp_localize_script(
2835                'jp-forms-date-picker',
2836                'jpDatePicker',
2837                array(
2838                    'offset' => intval( get_option( 'start_of_week', 1 ) ),
2839                    'lang'   => array(
2840                        // translators: These are the two letter abbreviated name of the week.
2841                        'days'      => array(
2842                            __( 'Su', 'jetpack-forms' ),
2843                            __( 'Mo', 'jetpack-forms' ),
2844                            __( 'Tu', 'jetpack-forms' ),
2845                            __( 'We', 'jetpack-forms' ),
2846                            __( 'Th', 'jetpack-forms' ),
2847                            __( 'Fr', 'jetpack-forms' ),
2848                            __( 'Sa', 'jetpack-forms' ),
2849                        ),
2850                        'months'    => array(
2851                            __( 'January', 'jetpack-forms' ),
2852                            __( 'February', 'jetpack-forms' ),
2853                            __( 'March', 'jetpack-forms' ),
2854                            __( 'April', 'jetpack-forms' ),
2855                            __( 'May', 'jetpack-forms' ),
2856                            __( 'June', 'jetpack-forms' ),
2857                            __( 'July', 'jetpack-forms' ),
2858                            __( 'August', 'jetpack-forms' ),
2859                            __( 'September', 'jetpack-forms' ),
2860                            __( 'October', 'jetpack-forms' ),
2861                            __( 'November', 'jetpack-forms' ),
2862                            __( 'December', 'jetpack-forms' ),
2863                        ),
2864                        'today'     => __( 'Today', 'jetpack-forms' ),
2865                        'clear'     => __( 'Clear', 'jetpack-forms' ),
2866                        'close'     => __( 'Close', 'jetpack-forms' ),
2867                        'ariaLabel' => array(
2868                            'dayPicker'         => __( 'You are currently inside the date picker, use the arrow keys to navigate between the dates. Use tab key to jump to more controls.', 'jetpack-forms' ),
2869                            'monthPicker'       => __( 'You are currently inside the month picker, use the arrow keys to navigate between the months. Use the space key to select it.', 'jetpack-forms' ),
2870                            'yearPicker'        => __( 'You are currently inside the year picker, use the up and down arrow keys to navigate between the years. Use the space key to select it.', 'jetpack-forms' ),
2871                            'monthPickerButton' => __( 'Month picker. Use the space key to enter the month picker.', 'jetpack-forms' ),
2872                            'yearPickerButton'  => __( 'Year picker. Use the space key to enter the month picker.', 'jetpack-forms' ),
2873                            'dayButton'         => __( 'Use the space key to select the date.', 'jetpack-forms' ),
2874                            'todayButton'       => __( 'Today button. Use the space key to select the current date.', 'jetpack-forms' ),
2875                            'clearButton'       => __( 'Clear button. Use the space key to clear the date picker.', 'jetpack-forms' ),
2876                            'closeButton'       => __( 'Close button. Use the space key to close the date picker.', 'jetpack-forms' ),
2877                        ),
2878                    ),
2879                )
2880            );
2881            $is_loaded = true;
2882        }
2883
2884        return $field;
2885    }
2886
2887    /**
2888     * Return the HTML for the time field.
2889     *
2890     * @param int    $id - the ID.
2891     * @param string $label - the label.
2892     * @param string $value - the value of the field.
2893     * @param string $class - the field class.
2894     * @param bool   $required - if the field is marked as required.
2895     * @param string $required_field_text - the text in the required text field.
2896     * @param string $placeholder - the field placeholder content.
2897     * @param bool   $required_indicator Whether to display the required indicator.
2898     *
2899     * @return string HTML
2900     */
2901    public function render_time_field( $id, $label, $value, $class, $required, $required_field_text, $placeholder, $required_indicator = true ) {
2902        $this->set_invalid_message( 'time', __( 'Please enter a valid time.', 'jetpack-forms' ) );
2903
2904        $field  = $this->render_label( 'time', $id, $label, $required, $required_field_text, array(), false, $required_indicator );
2905        $field .= $this->render_input_field( 'time', $id, $value, $class, $placeholder, $required );
2906
2907        return $field;
2908    }
2909
2910    /**
2911     * Return the HTML for the image select field.
2912     *
2913     * @param int    $id - the ID.
2914     * @param string $label - the label.
2915     * @param string $value - the value of the field.
2916     * @param string $class - the field class.
2917     * @param bool   $required - if the field is marked as required.
2918     * @param string $required_field_text - the text in the required text field.
2919     * @param bool   $required_indicator Whether to display the required indicator.
2920     *
2921     * @return string HTML
2922     */
2923    public function render_image_select_field( $id, $label, $value, $class, $required, $required_field_text, $required_indicator = true ) {
2924        wp_enqueue_style( 'jetpack-form-field-image-select-style', plugins_url( '../../dist/blocks/field-image-select/style.css', __FILE__ ), array(), Constants::get_constant( 'JETPACK__VERSION' ) );
2925
2926        $is_multiple       = $this->get_attribute( 'ismultiple' );
2927        $show_labels       = $this->get_attribute( 'showlabels' );
2928        $randomize_options = $this->get_attribute( 'randomizeoptions' );
2929        $is_supersized     = $this->get_attribute( 'issupersized' );
2930
2931        $input_type = $is_multiple ? 'checkbox' : 'radio';
2932        $input_name = $is_multiple ? $id . '[]' : $id;
2933
2934        $field = "<div class='jetpack-field jetpack-field-image-select'>";
2935
2936        $fieldset_id = "id='" . esc_attr( "$id-label" ) . "'" . $this->get_hidden_label_aria_label_attr();
2937
2938        $field .= "<fieldset {$fieldset_id} data-wp-bind--aria-invalid='state.fieldAriaInvalid' aria-describedby='" . esc_attr( $this->get_error_message_id( $id, 'image-select' ) ) . "' >";
2939
2940        $field .= $this->render_legend_as_label( '', $id, $label, $required, $required_field_text, array(), $required_indicator );
2941
2942        $options_classes = $this->get_attribute( 'optionsclasses' );
2943        $options_styles  = $this->get_attribute( 'optionsstyles' );
2944
2945        $field .= "<div class='" . esc_attr( $options_classes ) . " jetpack-field jetpack-fieldset-image-options' style='" . esc_attr( $options_styles ) . "'>";
2946        $field .= "<div class='jetpack-fieldset-image-options__wrapper'>";
2947
2948        $options_data = $this->get_attribute( 'optionsdata' );
2949
2950        // Filter out empty options from the end
2951        $options_data = $this->trim_image_select_options( $options_data );
2952
2953        $used_html_ids = array();
2954
2955        // Create a separate array of original letters in sequence (A, B, C...)
2956        $perceived_letters = array();
2957
2958        foreach ( $options_data as $option ) {
2959            $perceived_letters[] = Contact_Form_Plugin::strip_tags( $option['letter'] );
2960        }
2961
2962        // Create a working copy of options for potential randomization
2963        $working_options = $options_data;
2964
2965        // Randomize options if requested, but preserve original letter values
2966        if ( $randomize_options ) {
2967            shuffle( $working_options );
2968
2969            // Trims options after randomization to ensure the last option has a label or image.
2970            $working_options = $this->trim_image_select_options( $working_options );
2971        }
2972
2973        // Calculate row options count for CSS variable
2974        $total_options_count = count( $working_options );
2975        // Those values are halved on mobile via CSS media query
2976        $max_images_per_row = $is_supersized ? 2 : 4;
2977        $row_options_count  = min( $total_options_count, $max_images_per_row );
2978
2979        foreach ( $working_options as $option_index => $option ) {
2980            $option_label  = Contact_Form_Plugin::strip_tags( $option['label'] );
2981            $option_letter = Contact_Form_Plugin::strip_tags( $option['letter'] );
2982            $image_block   = $option['image'] ?? null;
2983            $image_id      = ( is_array( $image_block ) && isset( $image_block['attrs'] ) && is_array( $image_block['attrs'] ) ) ? ( $image_block['attrs']['id'] ?? null ) : null;
2984
2985            $rendered_image_block = is_array( $image_block ) ? render_block( $image_block ) : '';
2986            // Remove any links from the rendered block
2987            $rendered_image_block = preg_replace( '/<a[^>]*>(.*?)<\/a>/s', '$1', $rendered_image_block );
2988
2989            // Extract image src from rendered block
2990            $image_src = '';
2991
2992            if ( ! empty( $rendered_image_block ) ) {
2993                if ( preg_match( '/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i', $rendered_image_block, $matches ) ) {
2994                    $extracted_src = $matches[1];
2995
2996                    if ( filter_var( $extracted_src, FILTER_VALIDATE_URL ) || str_starts_with( $extracted_src, 'data:' ) ) {
2997                        $image_src = $extracted_src;
2998                    }
2999                }
3000            } else {
3001                $rendered_image_block = '<figure class="wp-block-image jetpack-input-image-option__empty-image"><img src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" alt="" style="aspect-ratio:1;object-fit:cover"/></figure>';
3002            }
3003
3004            $option_value                = wp_json_encode(
3005                array(
3006                    'perceived'  => $perceived_letters[ $option_index ],
3007                    'selected'   => $option_letter,
3008                    'label'      => $option_label,
3009                    'showLabels' => $show_labels,
3010                    'image'      => array(
3011                        'id'  => $image_id,
3012                        'src' => $image_src ?? null,
3013                    ),
3014                ),
3015                JSON_HEX_AMP | JSON_UNESCAPED_SLASHES
3016            );
3017            $option_id                   = $id . '-' . $option_letter;
3018            $used_html_ids[ $option_id ] = true;
3019
3020            $figcaption_id = esc_attr( $option_id . '-figcaption' );
3021
3022            // Add id attribute to figcaption for accessibility
3023            if ( ! empty( $rendered_image_block ) && strpos( $rendered_image_block, '<figcaption' ) !== false ) {
3024                $rendered_image_block = preg_replace( '/(<figcaption[^>]*)(>)/', '$1 id="' . $figcaption_id . '"$2', $rendered_image_block );
3025            }
3026
3027            // To be able to apply the backdrop-filter for the hover effect, we need to separate the background into an outer div.
3028            // This outer div needs the color styles separately, and also the border radius to match the inner div without sticking out.
3029            $option_outer_classes = 'jetpack-input-image-option__outer ' . ( $option['classcolor'] ?? '' );
3030
3031            if ( $is_supersized ) {
3032                $option_outer_classes .= ' is-supersized';
3033            }
3034
3035            $border_styles = '';
3036            if ( ! empty( $option['style'] ) ) {
3037                preg_match( '/border-radius:([^;]+)/', $option['style'], $radius_match );
3038                preg_match( '/border-width:([^;]+)/', $option['style'], $width_match );
3039
3040                if ( ! empty( $radius_match[1] ) ) {
3041                    $radius_value = trim( $radius_match[1] );
3042
3043                    if ( ! empty( $width_match[1] ) ) {
3044                            $width_value   = trim( $width_match[1] );
3045                            $border_styles = "border-radius:calc({$radius_value} + {$width_value});";
3046                    } else {
3047                            $border_styles = "border-radius:{$radius_value};";
3048                    }
3049                } else {
3050                    // Handle individual border radius properties when border-radius is not present
3051                    preg_match( '/border-top-left-radius:([^;]+)/', $option['style'], $top_left_match );
3052                    preg_match( '/border-top-right-radius:([^;]+)/', $option['style'], $top_right_match );
3053                    preg_match( '/border-bottom-right-radius:([^;]+)/', $option['style'], $bottom_right_match );
3054                    preg_match( '/border-bottom-left-radius:([^;]+)/', $option['style'], $bottom_left_match );
3055
3056                    if ( ! empty( $top_left_match[1] ) || ! empty( $top_right_match[1] ) || ! empty( $bottom_right_match[1] ) || ! empty( $bottom_left_match[1] ) ) {
3057                        $width_value = ! empty( $width_match[1] ) ? trim( $width_match[1] ) : '1px';
3058
3059                        $top_left     = ! empty( $top_left_match[1] ) ? trim( $top_left_match[1] ) : '4px';
3060                        $top_right    = ! empty( $top_right_match[1] ) ? trim( $top_right_match[1] ) : '4px';
3061                        $bottom_right = ! empty( $bottom_right_match[1] ) ? trim( $bottom_right_match[1] ) : '4px';
3062                        $bottom_left  = ! empty( $bottom_left_match[1] ) ? trim( $bottom_left_match[1] ) : '4px';
3063
3064                        $border_styles = "border-radius:calc({$top_left} + {$width_value}) calc({$top_right} + {$width_value}) calc({$bottom_right} + {$width_value}) calc({$bottom_left} + {$width_value});";
3065                    }
3066                }
3067            }
3068
3069            $option_outer_styles  = ( empty( $option['stylecolor'] ) ? '' : $option['stylecolor'] ) . $border_styles;
3070            $option_outer_styles .= "--row-options-count: {$row_options_count};";
3071            $option_outer_styles  = empty( $option_outer_styles ) ? '' : "style='" . esc_attr( $option_outer_styles ) . "'";
3072
3073            $field .= "<div class='{$option_outer_classes}' {$option_outer_styles}>";
3074
3075            $default_classes = 'jetpack-field jetpack-input-image-option';
3076            $option_styles   = empty( $option['style'] ) ? '' : "style='" . esc_attr( $option['style'] ) . "'";
3077            $option_classes  = "class='" . ( empty( $option['class'] ) ? $default_classes : $default_classes . ' ' . esc_attr( $option['class'] ) ) . "'";
3078
3079            $field .= "<div {$option_classes} {$option_styles} data-wp-on--click='actions.onImageOptionClick' data-wp-init='callbacks.setImageOptionOutlineColor'>";
3080
3081            $input_id = esc_attr( $option_id );
3082            $label_id = esc_attr( $option_id . '-label' );
3083
3084            /* translators: %s is the letter associated with the option, e.g. "Option A" */
3085            $aria_label_parts = array( sprintf( __( 'Option %s', 'jetpack-forms' ), $perceived_letters[ $option_index ] ) );
3086
3087            if ( ! empty( $option_label ) ) {
3088                $aria_label_parts[] = $option_label;
3089            }
3090
3091            $aria_label = implode( ': ', $aria_label_parts );
3092
3093            // Build aria-describedby to reference label and figcaption
3094            $aria_describedby_parts = array( $label_id );
3095
3096            if ( ! empty( $rendered_image_block ) && strpos( $rendered_image_block, '<figcaption' ) !== false ) {
3097                $aria_describedby_parts[] = $figcaption_id;
3098            }
3099
3100            $aria_describedby = implode( ' ', $aria_describedby_parts );
3101
3102            $field .= "<div class='jetpack-input-image-option__wrapper'>";
3103            $field .= "<input
3104            id='" . $input_id . "'
3105            class='jetpack-input-image-option__input'
3106            type='" . esc_attr( $input_type ) . "'
3107            name='" . esc_attr( $input_name ) . "'
3108            value='" . esc_attr( $option_value ) . "'
3109            aria-label='" . esc_attr( $aria_label ) . "'
3110            aria-describedby='" . esc_attr( $aria_describedby ) . "'
3111            data-wp-init='callbacks.setImageOptionCheckColor'
3112            data-wp-on--keydown='actions.onKeyDownImageOption'
3113            data-wp-on--change='" . ( $is_multiple ? 'actions.onMultipleFieldChange' : 'actions.onFieldChange' ) . "' "
3114            . $class
3115            . ( $is_multiple ? checked( in_array( $option_value, (array) $value, true ), true, false ) : checked( $option_value, $value, false ) ) . ' '
3116            . ( $required ? "required aria-required='true'" : '' )
3117            . '/> ';
3118
3119            $field .= $rendered_image_block;
3120            $field .= '</div>';
3121
3122            $field .= "<div class='jetpack-input-image-option__label-wrapper'>";
3123            $field .= "<div class='jetpack-input-image-option__label-code'>" . esc_html( $perceived_letters[ $option_index ] ) . '</div>';
3124
3125            $label_classes  = 'jetpack-input-image-option__label';
3126            $label_classes .= $show_labels ? '' : ' visually-hidden';
3127            $field         .= "<span id='{$label_id}' class='{$label_classes}'>" . esc_html( $option_label ) . '</span>';
3128            $field         .= '</div></div></div>';
3129        }
3130
3131        $field .= '</div></div>';
3132
3133        $field .= $this->get_error_div( $id, 'image-select' );
3134
3135        $field .= '</fieldset>';
3136
3137        $field .= '</div>';
3138
3139        return $field;
3140    }
3141
3142    /**
3143     * Return the HTML for the number field.
3144     *
3145     * @param int    $id - the ID.
3146     * @param string $label - the label.
3147     * @param string $value - the value of the field.
3148     * @param string $class - the field class.
3149     * @param bool   $required - if the field is marked as required.
3150     * @param string $required_field_text - the text in the required text field.
3151     * @param string $placeholder - the field placeholder content.
3152     * @param array  $extra_attrs - Extra attributes used in number field, namely `min` and `max`.
3153     * @param bool   $required_indicator Whether to display the required indicator.
3154     *
3155     * @return string HTML
3156     */
3157    public function render_number_field( $id, $label, $value, $class, $required, $required_field_text, $placeholder, $extra_attrs = array(), $required_indicator = true ) {
3158        $this->set_invalid_message( 'number', __( 'Please enter a valid number', 'jetpack-forms' ) );
3159        if ( isset( $extra_attrs['min'] ) ) {
3160            // translators: %d is the minimum value.
3161            $this->set_invalid_message( 'min_number', __( 'Please select a value that is no less than %d.', 'jetpack-forms' ) );
3162        }
3163        if ( isset( $extra_attrs['max'] ) ) {
3164            // translators: %d is the maximum value.
3165            $this->set_invalid_message( 'max_number', __( 'Please select a value that is no more than %d.', 'jetpack-forms' ) );
3166        }
3167        $field  = $this->render_label( 'number', $id, $label, $required, $required_field_text, array(), false, $required_indicator );
3168        $field .= $this->render_input_field( 'number', $id, $value, $class, $placeholder, $required, $extra_attrs );
3169        return $field;
3170    }
3171
3172    /**
3173     * Return the HTML for the default field.
3174     *
3175     * @param int    $id - the ID.
3176     * @param string $label - the label.
3177     * @param string $value - the value of the field.
3178     * @param string $class - the field class.
3179     * @param bool   $required - if the field is marked as required.
3180     * @param string $required_field_text - the text in the required text field.
3181     * @param string $placeholder - the field placeholder content.
3182     * @param string $type - the type.
3183     * @param bool   $required_indicator Whether to display the required indicator.
3184     *
3185     * @return string HTML
3186     */
3187    public function render_default_field( $id, $label, $value, $class, $required, $required_field_text, $placeholder, $type, $required_indicator = true ) {
3188        $field  = $this->render_label( $type, $id, $label, $required, $required_field_text, array(), false, $required_indicator );
3189        $field .= $this->render_input_field( 'text', $id, $value, $class, $placeholder, $required );
3190        return $field;
3191    }
3192
3193    /**
3194     * Returns the styles, classes and CSS vars necessary to render fields in the "Outlined" style.
3195     * The "Animated" style variation shares the CSS vars, which require similar calculations for the left offset and label left position.
3196     * At the block level, the styles are extracted and added to the shortcode attributes in
3197     * Contact_Form_Plugin::get_outlined_style_attributes().
3198     * This function extracts those styles and applies them to the field,
3199     * and ensures any global or theme styles are applied.
3200     *
3201     * @param string $form_style (optional) The form style.
3202     *
3203     * @return array {
3204     *     @type string $style_attrs The style attributes.
3205     *     @type string $css_vars The CSS variables.
3206     *     @type string $class_name The class name.
3207     * }
3208     */
3209    private function get_form_variation_style_properties( $form_style = 'outlined' ) {
3210        $css_vars             = '';
3211        $variation_attributes = $this->get_attribute( 'stylevariationattributes' );
3212        $variation_attributes = ! empty( $variation_attributes ) ? json_decode( html_entity_decode( $variation_attributes, ENT_COMPAT ), true ) : array();
3213        $variation_classes    = $this->get_attribute( 'stylevariationclasses' );
3214        $variation_style      = $this->get_attribute( 'stylevariationstyles' );
3215        $block_name           = 'jetpack/input';
3216
3217        if ( $this->maybe_override_type() === 'radio' || $this->maybe_override_type() === 'checkbox-multiple' ) {
3218            $block_name = 'jetpack/options';
3219        }
3220
3221        $global_styles = wp_get_global_styles(
3222            array( 'border' ),
3223            array(
3224                'block_name' => $block_name,
3225                'transforms' => array( 'resolve-variables' ),
3226            )
3227        );
3228
3229        /*
3230         * The `borderwidth` attribute contains the border value that forms used before the migration to global styles.
3231         * Any old forms saved in a post will still use this attribute, so it needs to be factored into the css vars for border
3232         * to properly support backwards compatibility. So we check if the attribute is set and if it's not empty or '0', which is a valid width value.
3233         * For newer forms that use global styles or the block supports styles, this value will be empty and is ignored.
3234         */
3235        $border_width_attribute = $this->get_attribute( 'borderwidth' );
3236        $legacy_border_size     = ! empty( $border_width_attribute ) || $border_width_attribute === '0' ? $border_width_attribute . 'px' : null;
3237
3238        $border_radius_attribute = $this->get_attribute( 'borderradius' );
3239        $legacy_border_radius    = ! empty( $border_radius_attribute ) || $border_radius_attribute === '0' ? $border_radius_attribute . 'px' : $variation_attributes['border']['radius'] ?? null;
3240
3241        $border_top_size = $legacy_border_size ??
3242            $variation_attributes['border']['width'] ??
3243            $variation_attributes['border']['top']['width'] ??
3244            $global_styles['width'] ??
3245            $global_styles['top']['width'] ?? null;
3246
3247        $border_right_size = $legacy_border_size ??
3248
3249            $variation_attributes['border']['right']['width'] ??
3250            $global_styles['width'] ??
3251            $global_styles['right']['width'] ?? null;
3252
3253        $border_bottom_size = $legacy_border_size ??
3254            $variation_attributes['border']['width'] ??
3255            $variation_attributes['border']['bottom']['width'] ??
3256            $global_styles['width'] ??
3257            $global_styles['bottom']['width'] ?? null;
3258
3259        $border_left_size = $legacy_border_size ??
3260            $variation_attributes['border']['width'] ??
3261            $variation_attributes['border']['left']['width'] ??
3262            $global_styles['width'] ??
3263            $global_styles['left']['width'] ?? null;
3264
3265        $border_radius = $legacy_border_radius ??
3266            $global_styles['radius'] ?? null;
3267
3268        // Border size to accommodate legacy border width attribute.
3269        $css_vars = $legacy_border_size ? '--jetpack--contact-form--border-size: ' . $legacy_border_size . ';' : '';
3270
3271        // Border side sizes to accommodate global styles split values.
3272        $css_vars .= $border_top_size ? '--jetpack--contact-form--border-top-size: ' . $border_top_size . ';' : '';
3273        $css_vars .= $border_right_size ? '--jetpack--contact-form--border-right-size: ' . $border_right_size . ';' : '';
3274        $css_vars .= $border_bottom_size ? '--jetpack--contact-form--border-bottom-size: ' . $border_bottom_size . ';' : '';
3275        $css_vars .= $border_left_size ? '--jetpack--contact-form--border-left-size: ' . $border_left_size . ';' : '';
3276
3277        // Check if border radius is split or a single value.
3278        if ( is_array( $border_radius ) ) {
3279            // If corner radii are set on the top-left or bottom-left of the block, take the maximum of the two.
3280            // We check the left side due to writing direction—this variable is used to offset text.
3281            // TODO: this should factor in RTL languages.
3282            $css_vars .= $border_radius ? '--jetpack--contact-form--border-radius: max(' . ( $border_radius['topLeft'] ?? '0' ) . ',' . ( $border_radius['bottomLeft'] ?? '0' ) . ');' : '';
3283        } elseif ( isset( $border_radius ) ) {
3284            $css_vars .= $border_radius ? '--jetpack--contact-form--border-radius: ' . $border_radius . ';' : '';
3285        }
3286
3287        if ( 'outlined' === $form_style ) {
3288            $css_vars .= '--jetpack--contact-form--notch-width: max(var(--jetpack--contact-form--input-padding-left, 16px), var(--jetpack--contact-form--border-radius));';
3289        } elseif ( 'animated' === $form_style ) {
3290            $css_vars .= '--jetpack--contact-form--animated-left-offset: 16px;';
3291        }
3292
3293        return array(
3294            'style'      => $variation_style,
3295            'css_vars'   => $css_vars,
3296            'class_name' => $variation_classes,
3297        );
3298    }
3299
3300    /**
3301     * Return the HTML for the outlined label.
3302     *
3303     * @param int    $id - the ID.
3304     * @param string $label - the label.
3305     * @param bool   $required - if the field is marked as required.
3306     * @param string $required_field_text - the text in the required text field.
3307     * @param bool   $required_indicator Whether to display the required indicator.
3308     *
3309     * @return string HTML
3310     */
3311    public function render_outline_label( $id, $label, $required, $required_field_text, $required_indicator = true ) {
3312        $classes  = 'notched-label__label';
3313        $classes .= $this->is_error() ? ' form-error' : '';
3314        $classes .= $this->label_classes ? ' ' . $this->label_classes : '';
3315
3316        $output_data = $this->get_form_variation_style_properties();
3317
3318        return '
3319            <div class="notched-label">
3320                <div class="notched-label__leading' . esc_attr( $output_data['class_name'] ) . '" style="' . esc_attr( $output_data['style'] ) . '"></div>
3321                <div class="notched-label__notch' . esc_attr( $output_data['class_name'] ) . '" style="' . esc_attr( $output_data['style'] ) . '">
3322                    <label
3323                        for="' . esc_attr( $id ) . '"
3324                        class=" ' . $classes . '"
3325                        style="' . $this->label_styles . esc_attr( $output_data['css_vars'] ) . '"
3326                    >
3327                    <span class="grunion-label-text">' . esc_html( $label ) . '</span>'
3328                    . ( $required && $required_indicator ? '<span class="grunion-label-required" aria-hidden="true">' . $required_field_text . '</span>' : '' ) .
3329            '</label>
3330                </div>
3331                <div class="notched-label__filler' . esc_attr( $output_data['class_name'] ) . '" style="' . esc_attr( $output_data['style'] ) . '"></div>
3332                <div class="notched-label__trailing' . esc_attr( $output_data['class_name'] ) . '" style="' . esc_attr( $output_data['style'] ) . '"></div>
3333            </div>';
3334    }
3335
3336    /**
3337     * Return the HTML for the animated label.
3338     *
3339     * @param int    $id - the ID.
3340     * @param string $label - the label.
3341     * @param bool   $required - if the field is marked as required.
3342     * @param string $required_field_text - the text in the required text field.
3343     * @param bool   $required_indicator Whether to display the required indicator.
3344     *
3345     * @return string HTML
3346     */
3347    public function render_animated_label( $id, $label, $required, $required_field_text, $required_indicator = true ) {
3348        $classes  = 'animated-label__label';
3349        $classes .= $this->is_error() ? ' form-error' : '';
3350        $classes .= $this->label_classes ? ' ' . $this->label_classes : '';
3351
3352        return '
3353            <label
3354                for="' . esc_attr( $id ) . '"
3355                class="' . $classes . '"
3356                style="' . $this->label_styles . '"
3357            >
3358                <span class="grunion-label-text">' . wp_kses_post( $label ) . '</span>'
3359                . ( $required && $required_indicator !== 'hidden' ? '<span class="grunion-label-required" aria-hidden="true">' . $required_field_text . '</span>' : '' ) .
3360            '</label>';
3361    }
3362
3363    /**
3364     * Return the HTML for the below label.
3365     *
3366     * @param int    $id - the ID.
3367     * @param string $label - the label.
3368     * @param bool   $required - if the field is marked as required.
3369     * @param string $required_field_text - the text in the required text field.
3370     * @param bool   $required_indicator Whether to display the required indicator.
3371     *
3372     * @return string HTML
3373     */
3374    public function render_below_label( $id, $label, $required, $required_field_text, $required_indicator = true ) {
3375        return '
3376            <label
3377                for="' . esc_attr( $id ) . '"
3378                class="below-label__label ' . ( $this->is_error() ? ' form-error' : '' ) . ( $this->label_classes ? ' ' . esc_attr( $this->label_classes ) : '' ) . '"
3379            >'
3380            . esc_html( $label )
3381            . ( $required && $required_indicator ? '<span>' . $required_field_text . '</span>' : '' ) .
3382            '</label>';
3383    }
3384
3385    /**
3386     * Return the HTML for the email field.
3387     *
3388     * @param string $type - the type.
3389     * @param int    $id - the ID.
3390     * @param string $label - the label.
3391     * @param string $value - the value of the field.
3392     * @param string $class - the field class.
3393     * @param string $placeholder - the field placeholder content.
3394     * @param bool   $required - if the field is marked as required.
3395     * @param string $required_field_text - the text for a field marked as required.
3396     * @param array  $extra_attrs - extra attributes to be passed to render functions.
3397     * @param bool   $required_indicator Whether to display the required indicator.
3398     *
3399     * @return string HTML
3400     */
3401    public function render_field( $type, $id, $label, $value, $class, $placeholder, $required, $required_field_text, $extra_attrs = array(), $required_indicator = true ) {
3402        if ( ! $this->is_field_renderable( $type ) ) {
3403            return '';
3404        }
3405
3406        if ( $type === 'hidden' ) {
3407            // For hidden fields, we don't need to render the label or any other HTML.
3408            return $this->render_hidden_field( $id, $label, $value );
3409        }
3410
3411        $trimmed_type = trim( esc_attr( $type ) );
3412        $class       .= ' grunion-field';
3413
3414        $form_style = $this->get_form_style();
3415        if ( ! empty( $form_style ) && $form_style !== 'default' ) {
3416            if ( isset( $placeholder ) && '' !== $placeholder ) {
3417                $class .= ' has-placeholder';
3418            }
3419        }
3420
3421        // Field classes.
3422        $field_class = "class='" . $trimmed_type . ' ' . esc_attr( $class ) . "' ";
3423
3424        // Shell wrapper classes. Add -wrap to each class.
3425        $wrap_classes          = empty( $class ) ? '' : implode( '-wrap ', array_filter( explode( ' ', $class ) ) ) . '-wrap';
3426        $field_wrapper_classes = $this->get_attribute( 'fieldwrapperclasses' ) ? $this->get_attribute( 'fieldwrapperclasses' ) . ' ' : '';
3427
3428        if ( empty( $label ) && ! $required ) {
3429            $wrap_classes .= ' no-label';
3430        }
3431
3432        // Escape the whole class value, wrapper classes included.
3433        $shell_field_class = "class='" . esc_attr( $field_wrapper_classes . 'grunion-field-' . $trimmed_type . '-wrap ' . $wrap_classes ) . "' ";
3434
3435        /**
3436         * Filter the Contact Form required field text
3437         *
3438         * @module contact-form
3439         *
3440         * @since 3.8.0
3441         *
3442         * @param string $var Required field text. Default is "(required)".
3443         */
3444        $required_field_text = wp_kses_post( apply_filters( 'jetpack_required_field_text', $required_field_text ) );
3445
3446        $block_style       = 'style="' . $this->block_styles . '"';
3447        $has_inset_label   = $this->has_inset_label();
3448        $field             = '';
3449        $field_placeholder = ! empty( $placeholder ) ? "placeholder='" . esc_attr( $placeholder ) . "'" : '';
3450
3451        $context = array(
3452            'fieldId'           => $id,
3453            'fieldType'         => $type,
3454            'fieldLabel'        => $label,
3455            'fieldValue'        => $value,
3456            'fieldPlaceholder'  => $placeholder,
3457            'fieldIsRequired'   => $required,
3458            'fieldErrorMessage' => '',
3459            'fieldExtra'        => $this->get_field_extra( $type, $extra_attrs ),
3460            'formHash'          => $this->form->hash,
3461        );
3462
3463        // Conditional logic is not emitted per field: it cascades, so resolving it needs every
3464        // field's logic and type at once. The form block emits that map once as
3465        // `conditionalLogic`, and this field's wrapper reads its own entry from there.
3466        $interactivity_attrs = ' data-wp-interactive="jetpack/form" ' . wp_interactivity_data_wp_context( $context ) . ' ';
3467
3468        // Hiding a field has to hide whichever element occupies the slot in the row, or the
3469        // field disappears and leaves a hole behind it. For an inset label that is the outer
3470        // wrapper, which is where the width class lives -- the inner div is inside it and
3471        // carries no width of its own.
3472        // data-jp-visibility-root names the element the initial server-side render stamps, so
3473        // the first paint and the runtime always hide the same element. Matching on
3474        // data-jp-field-id instead would stamp the inner div even when the wrapper is the one
3475        // the runtime hides.
3476        $visibility_attrs = " data-jp-visibility-root='" . esc_attr( $id ) . "'"
3477            . ( $this->has_conditional_logic() ? " data-jp-conditional='1'" : '' )
3478            . ' data-wp-class--jetpack-field--conditionally-hidden="state.isFieldHidden"'
3479            // Runs whenever the field's visibility changes, so focus does not fall to <body>
3480            // when the field the visitor is filling in disappears under them.
3481            . ' data-wp-watch--conditional-focus="callbacks.manageConditionalFocus"';
3482
3483        // Fields with an inset label need an extra wrapper to show the error message below the input.
3484        if ( $has_inset_label ) {
3485            $field_width       = $this->get_attribute( 'width' );
3486            $inset_label_class = array( 'contact-form__inset-label-wrap' );
3487
3488            if ( ! empty( $field_width ) ) {
3489                array_push( $inset_label_class, 'grunion-field-width-' . $field_width . '-wrap' );
3490            }
3491
3492            $field              .= "\n<div class='" . esc_attr( implode( ' ', $inset_label_class ) ) . "' {$interactivity_attrs} {$visibility_attrs} >\n";
3493            $interactivity_attrs = ''; // Reset interactivity attributes for the field wrapper.
3494            $visibility_attrs    = ''; // The outer wrapper owns visibility for this layout.
3495        }
3496
3497        $field .= "\n<div {$block_style} {$interactivity_attrs} {$shell_field_class} data-jp-field-id='" . esc_attr( $id ) . "'{$visibility_attrs} data-wp-init='callbacks.initializeField' data-wp-on--jetpack-form-reset='callbacks.initializeField' >\n"; // new in Jetpack 6.8.0
3498
3499        switch ( $type ) {
3500            case 'email':
3501                $field .= $this->render_email_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder, $required_indicator );
3502                break;
3503            case 'phone':
3504            case 'telephone':
3505                $field .= $this->render_telephone_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder, $required_indicator );
3506                break;
3507            case 'url':
3508                $field .= $this->render_url_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder, $required_indicator );
3509                break;
3510            case 'textarea':
3511                $field .= $this->render_textarea_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder, $required_indicator );
3512                break;
3513            case 'radio':
3514                $field .= $this->render_radio_field( $id, $label, $value, $field_class, $required, $required_field_text, $required_indicator );
3515                break;
3516            case 'checkbox':
3517                $field .= $this->render_checkbox_field( $id, $label, $value, $field_class, $required, $required_field_text, $required_indicator );
3518                break;
3519            case 'checkbox-multiple':
3520                $field .= $this->render_checkbox_multiple_field( $id, $label, $value, $field_class, $required, $required_field_text, $required_indicator );
3521                break;
3522            case 'select':
3523                $field .= $this->render_select_field( $id, $label, $value, $field_class, $required, $required_field_text, $required_indicator );
3524                break;
3525            case 'date':
3526                $field .= $this->render_date_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder, $required_indicator );
3527                break;
3528            case 'consent':
3529                $field .= $this->render_consent_field( $id, $field_class );
3530                break;
3531            case 'number':
3532                $field .= $this->render_number_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder, $extra_attrs, $required_indicator );
3533                break;
3534            case 'slider':
3535                $field .= $this->render_slider_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder, $extra_attrs, $required_indicator );
3536                break;
3537            case 'file':
3538                $field .= $this->render_file_field( $id, $label, $field_class, $required, $required_field_text, $required_indicator );
3539                break;
3540            case 'rating':
3541                $field .= $this->render_rating_field(
3542                    $id,
3543                    $label,
3544                    $value,
3545                    $field_class,
3546                    $required,
3547                    $required_field_text,
3548                    $required_indicator
3549                );
3550                break;
3551            case 'time':
3552                $field .= $this->render_time_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder, $required_indicator );
3553                break;
3554            case 'image-select':
3555                $field .= $this->render_image_select_field( $id, $label, $value, $field_class, $required, $required_field_text, $required_indicator );
3556                break;
3557            default: // text field
3558                $field .= $this->render_default_field( $id, $label, $value, $field_class, $required, $required_field_text, $field_placeholder, $type, $required_indicator );
3559                break;
3560        }
3561
3562        $field .= "\t</div>\n";
3563
3564        if ( $has_inset_label ) {
3565            // Description-aware renderers build their markup at the input site,
3566            // where the correct type is known, and defer it here. Field types
3567            // that do not yet do that fall back to the plain error div. Several
3568            // fields render an input whose type differs from the field type
3569            // (date and url render `text`, simple telephone renders `tel`), so
3570            // rebuilding it here from $type would not match the ids the input's
3571            // aria-describedby references.
3572            $field .= $this->deferred_descriptions ?? $this->get_error_div( $id, $type, true );
3573            // Consume it, so a second render cannot replay this one's markup.
3574            $this->deferred_descriptions = null;
3575            // Close the extra wrapper for inset labels.
3576            $field .= "\t</div>\n";
3577        }
3578
3579        return $field;
3580    }
3581
3582    /**
3583     * Returns the extra attributes for the field.
3584     * That are used in field validation.
3585     *
3586     * @param string $type - the field type.
3587     * @param array  $extra_attrs - the extra attributes.
3588     *
3589     * @return string|array The extra attributes.
3590     */
3591    private function get_field_extra( $type, $extra_attrs ) {
3592        if ( 'date' === $type ) {
3593            return $this->get_date_format();
3594        }
3595
3596        if ( 'file' === $type ) {
3597            return array(
3598                'maxFiles'         => $this->get_file_field_max_files(),
3599                'allowedMimeTypes' => self::get_file_field_accepted_mime_types(),
3600            );
3601        }
3602
3603        return $extra_attrs;
3604    }
3605
3606    /**
3607     * Overrides input type (maybe).
3608     *
3609     * @module contact-form
3610     *
3611     * Custom input types, like URL, will rely on browser's implementation to validate
3612     * the value. If the input carries a data-type-override, we allow to override
3613     * the type at render/submit so it can be validated with custom patterns.
3614     * This method will try to match the input's type to a custom data-type-override
3615     * attribute and return it. Defaults to input's type.
3616     *
3617     * @return string The input's type attribute or the overriden type.
3618     */
3619    private function maybe_override_type() {
3620        // Define overridables-to-custom-type, extend as needed.
3621        $overridable_types = array( 'text' => array( 'url' ) );
3622        $type              = $this->get_attribute( 'type' );
3623
3624        if ( ! array_key_exists( $type, $overridable_types ) ) {
3625            return $type;
3626        }
3627
3628        $override_type = $this->get_attribute( 'data-type-override' );
3629
3630        if ( in_array( $override_type, $overridable_types[ $type ], true ) ) {
3631            return $override_type;
3632        }
3633
3634        return $type;
3635    }
3636
3637    /**
3638     * Determines if a form field is valid.
3639     *
3640     * Add checks here to confirm if any given form field
3641     * is configured correctly and thus should be rendered
3642     * on the frontend.
3643     *
3644     * @param string $type - the field type.
3645     *
3646     * @return bool
3647     */
3648    public function is_field_renderable( $type ) {
3649        // Check that radio, select, multiple choice, and image select
3650        // fields have at least one valid option.
3651        if ( $type === 'radio' || $type === 'checkbox-multiple' || $type === 'select' ) {
3652            $options           = (array) $this->get_attribute( 'options' );
3653            $non_empty_options = array_filter(
3654                $options,
3655                function ( $option ) {
3656                    return $option !== '';
3657                }
3658            );
3659            return count( $non_empty_options ) > 0;
3660        }
3661
3662        if ( $type === 'image-select' ) {
3663            $options_data         = (array) $this->get_attribute( 'optionsdata' );
3664            $trimmed_options_data = $this->trim_image_select_options( $options_data );
3665
3666            return ! empty( $trimmed_options_data );
3667        }
3668
3669        return true;
3670    }
3671
3672    /**
3673     * Gets the form style based on its CSS class.
3674     *
3675     * @return string The form style type.
3676     */
3677    private function get_form_style() {
3678        $class_name = $this->form->get_attribute( 'className' );
3679        preg_match( '/is-style-([^\s]+)/i', $class_name, $matches );
3680        return count( $matches ) >= 2 ? $matches[1] : null;
3681    }
3682
3683    /**
3684     * Checks if the form style renders labels inside the field rather than above it.
3685     *
3686     * This is a property of the *style* alone: it stays true for a field type that
3687     * opts out of the inset label itself, because it also governs the extra
3688     * `.contact-form__inset-label-wrap` wrapper, which those fields still need (it
3689     * carries the field width). Use type_has_inset_label() to decide whether a given
3690     * field actually renders an inset label.
3691     *
3692     * @return boolean
3693     */
3694    private function has_inset_label() {
3695        $form_style = $this->get_form_style();
3696
3697        return in_array( $form_style, array( 'outlined', 'animated' ), true );
3698    }
3699
3700    /**
3701     * Checks whether a field type renders an inset label under the current form style.
3702     *
3703     * @param string $type The field type.
3704     *
3705     * @return boolean
3706     */
3707    private function type_has_inset_label( $type ) {
3708        return $this->has_inset_label()
3709            && ! in_array( $type, self::TYPES_WITHOUT_STYLED_LABEL, true )
3710            && ! in_array( $type, self::TYPES_WITHOUT_INSET_LABEL, true );
3711    }
3712
3713    /**
3714     * Return the HTML for the rating (stars/hearts/etc.) field.
3715     *
3716     * This field is purely decorative (spans acting as buttons) and stores the
3717     * selected rating in a hidden input so it is handled by existing form
3718     * validation/submission logic.
3719     *
3720     * @since 0.46.0
3721     *
3722     * @param string $id                 Field ID.
3723     * @param string $label              Field label.
3724     * @param string $value              Current value.
3725     * @param string $class              Additional CSS classes.
3726     * @param bool   $required           Whether field is required.
3727     * @param string $required_field_text Required label text.
3728     * @param bool   $required_indicator Whether to display the required indicator.
3729     * @return string HTML markup.
3730     */
3731    private function render_rating_field( $id, $label, $value, $class, $required, $required_field_text, $required_indicator = true ) {
3732        // Enqueue stylesheet for rating field.
3733        wp_enqueue_style( 'jetpack-form-field-rating-style', plugins_url( '../../dist/blocks/field-rating/style.css', __FILE__ ), array(), Constants::get_constant( 'JETPACK__VERSION' ) );
3734
3735        // Read block attributes needed for rendering.
3736        $max_attr   = $this->get_attribute( 'max' );
3737        $max_rating = is_numeric( $max_attr ) && (int) $max_attr > 0 ? (int) $max_attr : 5;
3738        // The editor caps this, but a hand-edited block or shortcode attribute does not.
3739        $max_rating = min( $max_rating, Feedback_Field::MAX_RATING_ICONS );
3740
3741        $initial_rating = (int) $value ? (int) $value : 0;
3742
3743        $label_html = $this->render_legend_as_label( 'rating', $id, $label, $required, $required_field_text, array(), $required_indicator );
3744
3745        /*
3746         * Determine which icon SVG to use based on the 'iconstyle' attribute.
3747         * Note: attribute name is lowercase due to WordPress shortcode processing
3748         */
3749        $icon_style       = $this->get_attribute( 'iconstyle' );
3750        $has_hearts_style = ( 'hearts' === $icon_style );
3751
3752        // SVG icon definitions - keep in sync with JavaScript icons.js
3753        $star_svg  = '<svg class="jetpack-field-rating__icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.62L12 2 9.19 8.62 2 9.24l5.46 4.73L5.82 21z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"></path></svg>';
3754        $heart_svg = '<svg class="jetpack-field-rating__icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"></path></svg>';
3755
3756        $icon_svg = $has_hearts_style ? $heart_svg : $star_svg;
3757
3758        $options = '';
3759        for ( $i = 1; $i <= $max_rating; $i++ ) {
3760            $radio_id = $id . '-' . $i;
3761            $options .= sprintf(
3762                '<div class="jetpack-field-rating__option">
3763                    <input
3764                        id="%1$s"
3765                        type="radio"
3766                        name="%2$s"
3767                        value="%3$s/%4$s"
3768                        data-wp-on--change="actions.onFieldChange"
3769                        class="jetpack-field-rating__input visually-hidden"
3770                        %5$s
3771                        %6$s />
3772                    <label for="%1$s" class="jetpack-field-rating__label">
3773                        %7$s
3774                    </label>
3775                </div>',
3776                esc_attr( $radio_id ),         // %1$s: id and label for
3777                esc_attr( $id ),               // %2$s: name
3778                esc_attr( $i ),                // %3$s: value (current rating)
3779                esc_attr( $max_rating ),       // %4$s: value (max rating)
3780                checked( $i, $initial_rating, false ), // %5$s: checked attribute
3781                $required ? 'required' : '',   // %6$s: required attribute
3782                $icon_svg                      // %7$s: icon SVG
3783            );
3784        }
3785
3786        $style_attr = '';
3787
3788        $css_styles = array_filter( array_map( 'trim', explode( ';', $this->field_styles ) ) );
3789
3790        $css_key_value_pairs = array_reduce(
3791            $css_styles,
3792            function ( $pairs, $style ) {
3793                list( $key, $value )   = explode( ':', $style );
3794                $pairs[ trim( $key ) ] = trim( $value );
3795                return $pairs;
3796            },
3797            array()
3798        );
3799
3800        // The rating input overwrites the text color, so we are using a custom logic to set the star color as a CSS variable.
3801        $has_star_color = isset( $css_key_value_pairs['color'] );
3802
3803        if ( $has_star_color ) {
3804            $color_value = $css_key_value_pairs['color'];
3805            $style_attr  = 'style="--jetpack--contact-form--rating-star-color: ' . esc_attr( $color_value ) . ';';
3806            unset( $css_key_value_pairs['color'] );
3807        } else {
3808            // Theme colors are set in the field_classes attribute
3809            $preset_colors = array(
3810                'has-base-color'     => '--wp--preset--color--base',
3811                'has-contrast-color' => '--wp--preset--color--contrast',
3812            );
3813
3814            if ( preg_match( '/has-accent-(\d+)-color/', $this->field_classes, $matches ) ) {
3815                $accent_number = $matches[1];
3816                $preset_colors[ 'has-accent-' . $accent_number . '-color' ] = '--wp--preset--color--accent-' . $accent_number;
3817            }
3818
3819            foreach ( $preset_colors as $class => $css_var ) {
3820                if ( strpos( $this->field_classes, $class ) !== false ) {
3821                    $style_attr = 'style="--jetpack--contact-form--rating-star-color: var(' . esc_attr( $css_var ) . ');';
3822
3823                    break;
3824                }
3825            }
3826        }
3827
3828        $remaining_styles = array_map(
3829            function ( $key, $value ) {
3830                return $key . ': ' . $value;
3831            },
3832            array_keys( $css_key_value_pairs ),
3833            array_values( $css_key_value_pairs )
3834        );
3835
3836        $style_attr .= ' ' . implode( ';', $remaining_styles ) . '"';
3837
3838        return sprintf(
3839            '<fieldset id="%4$s-label" class="jetpack-field-multiple__fieldset jetpack-field-rating" aria-describedby="%7$s" %1$s%6$s>
3840                %5$s
3841                <div class="jetpack-field-rating__options %3$s">%2$s</div>
3842            </fieldset>',
3843            $style_attr,
3844            $options,
3845            esc_attr( $this->field_classes ),
3846            esc_attr( $id ),
3847            $label_html,
3848            $this->get_hidden_label_aria_label_attr(),
3849            esc_attr( $this->get_error_message_id( $id, 'rating' ) )
3850        ) . $this->get_error_div( $id, 'rating' );
3851    }
3852
3853    /**
3854     * Return the HTML for the slider field.
3855     *
3856     * @since 5.1.0
3857     *
3858     * @param int    $id The field ID.
3859     * @param string $label The field label.
3860     * @param string $value The field value.
3861     * @param string $class The field class.
3862     * @param bool   $required Whether the field is required.
3863     * @param string $required_field_text The required field text.
3864     * @param string $placeholder The field placeholder.
3865     * @param array  $extra_attrs Extra attributes (e.g., min, max).
3866     * @param bool   $required_indicator Whether to display the required indicator.
3867     *
3868     * @return string HTML for the slider field.
3869     */
3870    public function render_slider_field( $id, $label, $value, $class, $required, $required_field_text, $placeholder, $extra_attrs = array(), $required_indicator = true ) {
3871        $this->enqueue_slider_field_assets();
3872        $this->set_invalid_message( 'slider', __( 'Please select a valid value', 'jetpack-forms' ) );
3873        if ( isset( $extra_attrs['min'] ) ) {
3874            // translators: %d is the minimum value.
3875            $this->set_invalid_message( 'min_slider', __( 'Please select a value that is no less than %d.', 'jetpack-forms' ) );
3876        }
3877        if ( isset( $extra_attrs['max'] ) ) {
3878            // translators: %d is the maximum value.
3879            $this->set_invalid_message( 'max_slider', __( 'Please select a value that is no more than %d.', 'jetpack-forms' ) );
3880        }
3881        $min            = $extra_attrs['min'] ?? 0;
3882        $max            = $extra_attrs['max'] ?? 100;
3883        $starting_value = $extra_attrs['default'] ?? 0;
3884        $step           = $extra_attrs['step'] ?? 1;
3885        $current_value  = ( $value !== '' && $value !== null ) ? $value : $starting_value;
3886        $min_text_label = $extra_attrs['minLabel'] ?? '';
3887        $max_text_label = $extra_attrs['maxLabel'] ?? '';
3888
3889        // $always_render must be true: 'slider' is excluded from inset labels in
3890        // render_label(), so without it the label would be dropped entirely when the
3891        // form uses the Outlined or Animated style.
3892        $field = $this->render_label( 'slider', $id, $label, $required, $required_field_text, array(), true, $required_indicator );
3893
3894        ob_start();
3895        ?>
3896        <div class="jetpack-field-slider__input-row <?php echo esc_attr( $this->field_classes ); ?>"
3897            data-wp-context='
3898            <?php
3899            echo esc_attr(
3900                wp_json_encode(
3901                    array(
3902                        'min'     => $min,
3903                        'max'     => $max,
3904                        'default' => $starting_value,
3905                        'step'    => $step,
3906                    ),
3907                    JSON_HEX_AMP | JSON_UNESCAPED_SLASHES
3908                )
3909            );
3910            ?>
3911            '>
3912            <span class="jetpack-field-slider__min-label"><?php echo esc_html( $min ); ?></span>
3913            <div class="jetpack-field-slider__input-container">
3914                <input
3915                    type="range"
3916                    name="<?php echo esc_attr( $id ); ?>"
3917                    id="<?php echo esc_attr( $id ); ?>"
3918                    value="<?php echo esc_attr( $current_value ); ?>"
3919                    min="<?php echo esc_attr( $min ); ?>"
3920                    max="<?php echo esc_attr( $max ); ?>"
3921                    step="<?php echo esc_attr( $step ); ?>"
3922                    class="<?php echo esc_attr( trim( $class . ' jetpack-field-slider__range' ) ); ?>"
3923                    placeholder="<?php echo esc_attr( $placeholder ); ?>"
3924                    <?php
3925                    if ( $required ) :
3926                        ?>
3927                    required<?php endif; ?>
3928                    data-wp-bind--value="state.getSliderValue"
3929                    data-wp-on--input="actions.onSliderChange"
3930                    data-wp-bind--aria-invalid="state.fieldAriaInvalid"
3931                    aria-describedby="<?php echo esc_attr( $this->get_described_by( $id, 'slider' ) ); ?>"
3932                    <?php echo $this->get_hidden_label_aria_label_attr(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- attribute value is escaped in the helper. ?>
3933                />
3934                <div
3935                    class="jetpack-field-slider__value-indicator"
3936                    data-wp-text="state.getSliderValue"
3937                    data-wp-style--left="state.getSliderPosition"
3938                ><?php echo esc_html( $current_value ); ?></div>
3939            </div>
3940            <span class="jetpack-field-slider__max-label"><?php echo esc_html( $max ); ?></span>
3941        </div>
3942        <?php if ( '' !== $min_text_label || '' !== $max_text_label ) : ?>
3943            <div class="jetpack-field-slider__text-labels <?php echo esc_attr( $this->field_classes ); ?>" aria-hidden="true">
3944                <span class="jetpack-field-slider__min-text-label"><?php echo esc_html( $min_text_label ); ?></span>
3945                <span class="jetpack-field-slider__max-text-label"><?php echo esc_html( $max_text_label ); ?></span>
3946            </div>
3947        <?php endif; ?>
3948        <?php
3949        $field .= ob_get_clean();
3950        return $field . $this->get_field_descriptions( $id, 'slider' );
3951    }
3952
3953    /**
3954     * Enqueues scripts and styles needed for the slider field.
3955     *
3956     * @since 5.1.0
3957     *
3958     * @return void
3959     */
3960    private function enqueue_slider_field_assets() {
3961        $version = defined( 'JETPACK__VERSION' ) ? \JETPACK__VERSION : '0.1';
3962
3963        \wp_enqueue_style(
3964            'jetpack-form-slider-field',
3965            plugins_url( '../../dist/blocks/input-range/style.css', __FILE__ ),
3966            array(),
3967            $version
3968        );
3969
3970        \wp_enqueue_script_module(
3971            'jetpack-form-slider-field',
3972            plugins_url( '../../dist/modules/slider-field/view.js', __FILE__ ),
3973            array( '@wordpress/interactivity' ),
3974            $version
3975        );
3976    }
3977
3978    /**
3979     * Gets an array of translatable country names indexed by their two-letter country codes.
3980     *
3981     * @since 6.2.1
3982     *
3983     * @return array Array of country names with two-letter country codes as keys.
3984     */
3985    public function get_translatable_countries() {
3986        return array(
3987            'AF' => __( 'Afghanistan', 'jetpack-forms' ),
3988            'AL' => __( 'Albania', 'jetpack-forms' ),
3989            'DZ' => __( 'Algeria', 'jetpack-forms' ),
3990            'AS' => __( 'American Samoa', 'jetpack-forms' ),
3991            'AD' => __( 'Andorra', 'jetpack-forms' ),
3992            'AO' => __( 'Angola', 'jetpack-forms' ),
3993            'AI' => __( 'Anguilla', 'jetpack-forms' ),
3994            'AG' => __( 'Antigua and Barbuda', 'jetpack-forms' ),
3995            'AR' => __( 'Argentina', 'jetpack-forms' ),
3996            'AM' => __( 'Armenia', 'jetpack-forms' ),
3997            'AW' => __( 'Aruba', 'jetpack-forms' ),
3998            'AU' => __( 'Australia', 'jetpack-forms' ),
3999            'AT' => __( 'Austria', 'jetpack-forms' ),
4000            'AZ' => __( 'Azerbaijan', 'jetpack-forms' ),
4001            'BS' => __( 'Bahamas', 'jetpack-forms' ),
4002            'BH' => __( 'Bahrain', 'jetpack-forms' ),
4003            'BD' => __( 'Bangladesh', 'jetpack-forms' ),
4004            'BB' => __( 'Barbados', 'jetpack-forms' ),
4005            'BY' => __( 'Belarus', 'jetpack-forms' ),
4006            'BE' => __( 'Belgium', 'jetpack-forms' ),
4007            'BZ' => __( 'Belize', 'jetpack-forms' ),
4008            'BJ' => __( 'Benin', 'jetpack-forms' ),
4009            'BM' => __( 'Bermuda', 'jetpack-forms' ),
4010            'BT' => __( 'Bhutan', 'jetpack-forms' ),
4011            'BO' => __( 'Bolivia', 'jetpack-forms' ),
4012            'BA' => __( 'Bosnia and Herzegovina', 'jetpack-forms' ),
4013            'BW' => __( 'Botswana', 'jetpack-forms' ),
4014            'BR' => __( 'Brazil', 'jetpack-forms' ),
4015            'IO' => __( 'British Indian Ocean Territory', 'jetpack-forms' ),
4016            'VG' => __( 'British Virgin Islands', 'jetpack-forms' ),
4017            'BN' => __( 'Brunei', 'jetpack-forms' ),
4018            'BG' => __( 'Bulgaria', 'jetpack-forms' ),
4019            'BF' => __( 'Burkina Faso', 'jetpack-forms' ),
4020            'BI' => __( 'Burundi', 'jetpack-forms' ),
4021            'KH' => __( 'Cambodia', 'jetpack-forms' ),
4022            'CM' => __( 'Cameroon', 'jetpack-forms' ),
4023            'CA' => __( 'Canada', 'jetpack-forms' ),
4024            'CV' => __( 'Cape Verde', 'jetpack-forms' ),
4025            'KY' => __( 'Cayman Islands', 'jetpack-forms' ),
4026            'CF' => __( 'Central African Republic', 'jetpack-forms' ),
4027            'TD' => __( 'Chad', 'jetpack-forms' ),
4028            'CL' => __( 'Chile', 'jetpack-forms' ),
4029            'CN' => __( 'China', 'jetpack-forms' ),
4030            'CX' => __( 'Christmas Island', 'jetpack-forms' ),
4031            'CC' => __( 'Cocos (Keeling) Islands', 'jetpack-forms' ),
4032            'CO' => __( 'Colombia', 'jetpack-forms' ),
4033            'KM' => __( 'Comoros', 'jetpack-forms' ),
4034            'CG' => __( 'Congo - Brazzaville', 'jetpack-forms' ),
4035            'CD' => __( 'Congo - Kinshasa', 'jetpack-forms' ),
4036            'CK' => __( 'Cook Islands', 'jetpack-forms' ),
4037            'CR' => __( 'Costa Rica', 'jetpack-forms' ),
4038            'HR' => __( 'Croatia', 'jetpack-forms' ),
4039            'CU' => __( 'Cuba', 'jetpack-forms' ),
4040            'CY' => __( 'Cyprus', 'jetpack-forms' ),
4041            'CZ' => __( 'Czech Republic', 'jetpack-forms' ),
4042            'CI' => __( "Côte d'Ivoire", 'jetpack-forms' ),
4043            'DK' => __( 'Denmark', 'jetpack-forms' ),
4044            'DJ' => __( 'Djibouti', 'jetpack-forms' ),
4045            'DM' => __( 'Dominica', 'jetpack-forms' ),
4046            'DO' => __( 'Dominican Republic', 'jetpack-forms' ),
4047            'EC' => __( 'Ecuador', 'jetpack-forms' ),
4048            'EG' => __( 'Egypt', 'jetpack-forms' ),
4049            'SV' => __( 'El Salvador', 'jetpack-forms' ),
4050            'GQ' => __( 'Equatorial Guinea', 'jetpack-forms' ),
4051            'ER' => __( 'Eritrea', 'jetpack-forms' ),
4052            'EE' => __( 'Estonia', 'jetpack-forms' ),
4053            'SZ' => __( 'Eswatini', 'jetpack-forms' ),
4054            'ET' => __( 'Ethiopia', 'jetpack-forms' ),
4055            'FK' => __( 'Falkland Islands', 'jetpack-forms' ),
4056            'FO' => __( 'Faroe Islands', 'jetpack-forms' ),
4057            'FJ' => __( 'Fiji', 'jetpack-forms' ),
4058            'FI' => __( 'Finland', 'jetpack-forms' ),
4059            'FR' => __( 'France', 'jetpack-forms' ),
4060            'GF' => __( 'French Guiana', 'jetpack-forms' ),
4061            'PF' => __( 'French Polynesia', 'jetpack-forms' ),
4062            'GA' => __( 'Gabon', 'jetpack-forms' ),
4063            'GM' => __( 'Gambia', 'jetpack-forms' ),
4064            'GE' => __( 'Georgia', 'jetpack-forms' ),
4065            'DE' => __( 'Germany', 'jetpack-forms' ),
4066            'GH' => __( 'Ghana', 'jetpack-forms' ),
4067            'GI' => __( 'Gibraltar', 'jetpack-forms' ),
4068            'GR' => __( 'Greece', 'jetpack-forms' ),
4069            'GL' => __( 'Greenland', 'jetpack-forms' ),
4070            'GD' => __( 'Grenada', 'jetpack-forms' ),
4071            'GP' => __( 'Guadeloupe', 'jetpack-forms' ),
4072            'GU' => __( 'Guam', 'jetpack-forms' ),
4073            'GT' => __( 'Guatemala', 'jetpack-forms' ),
4074            'GG' => __( 'Guernsey', 'jetpack-forms' ),
4075            'GN' => __( 'Guinea', 'jetpack-forms' ),
4076            'GW' => __( 'Guinea-Bissau', 'jetpack-forms' ),
4077            'GY' => __( 'Guyana', 'jetpack-forms' ),
4078            'HT' => __( 'Haiti', 'jetpack-forms' ),
4079            'HN' => __( 'Honduras', 'jetpack-forms' ),
4080            'HK' => __( 'Hong Kong', 'jetpack-forms' ),
4081            'HU' => __( 'Hungary', 'jetpack-forms' ),
4082            'IS' => __( 'Iceland', 'jetpack-forms' ),
4083            'IN' => __( 'India', 'jetpack-forms' ),
4084            'ID' => __( 'Indonesia', 'jetpack-forms' ),
4085            'IR' => __( 'Iran', 'jetpack-forms' ),
4086            'IQ' => __( 'Iraq', 'jetpack-forms' ),
4087            'IE' => __( 'Ireland', 'jetpack-forms' ),
4088            'IM' => __( 'Isle of Man', 'jetpack-forms' ),
4089            'IL' => __( 'Israel', 'jetpack-forms' ),
4090            'IT' => __( 'Italy', 'jetpack-forms' ),
4091            'JM' => __( 'Jamaica', 'jetpack-forms' ),
4092            'JP' => __( 'Japan', 'jetpack-forms' ),
4093            'JE' => __( 'Jersey', 'jetpack-forms' ),
4094            'JO' => __( 'Jordan', 'jetpack-forms' ),
4095            'KZ' => __( 'Kazakhstan', 'jetpack-forms' ),
4096            'KE' => __( 'Kenya', 'jetpack-forms' ),
4097            'KI' => __( 'Kiribati', 'jetpack-forms' ),
4098            'XK' => __( 'Kosovo', 'jetpack-forms' ),
4099            'KW' => __( 'Kuwait', 'jetpack-forms' ),
4100            'KG' => __( 'Kyrgyzstan', 'jetpack-forms' ),
4101            'LA' => __( 'Laos', 'jetpack-forms' ),
4102            'LV' => __( 'Latvia', 'jetpack-forms' ),
4103            'LB' => __( 'Lebanon', 'jetpack-forms' ),
4104            'LS' => __( 'Lesotho', 'jetpack-forms' ),
4105            'LR' => __( 'Liberia', 'jetpack-forms' ),
4106            'LY' => __( 'Libya', 'jetpack-forms' ),
4107            'LI' => __( 'Liechtenstein', 'jetpack-forms' ),
4108            'LT' => __( 'Lithuania', 'jetpack-forms' ),
4109            'LU' => __( 'Luxembourg', 'jetpack-forms' ),
4110            'MO' => __( 'Macao', 'jetpack-forms' ),
4111            'MG' => __( 'Madagascar', 'jetpack-forms' ),
4112            'MW' => __( 'Malawi', 'jetpack-forms' ),
4113            'MY' => __( 'Malaysia', 'jetpack-forms' ),
4114            'MV' => __( 'Maldives', 'jetpack-forms' ),
4115            'ML' => __( 'Mali', 'jetpack-forms' ),
4116            'MT' => __( 'Malta', 'jetpack-forms' ),
4117            'MH' => __( 'Marshall Islands', 'jetpack-forms' ),
4118            'MQ' => __( 'Martinique', 'jetpack-forms' ),
4119            'MR' => __( 'Mauritania', 'jetpack-forms' ),
4120            'MU' => __( 'Mauritius', 'jetpack-forms' ),
4121            'YT' => __( 'Mayotte', 'jetpack-forms' ),
4122            'MX' => __( 'Mexico', 'jetpack-forms' ),
4123            'FM' => __( 'Micronesia', 'jetpack-forms' ),
4124            'MD' => __( 'Moldova', 'jetpack-forms' ),
4125            'MC' => __( 'Monaco', 'jetpack-forms' ),
4126            'MN' => __( 'Mongolia', 'jetpack-forms' ),
4127            'ME' => __( 'Montenegro', 'jetpack-forms' ),
4128            'MS' => __( 'Montserrat', 'jetpack-forms' ),
4129            'MA' => __( 'Morocco', 'jetpack-forms' ),
4130            'MZ' => __( 'Mozambique', 'jetpack-forms' ),
4131            'MM' => __( 'Myanmar', 'jetpack-forms' ),
4132            'NA' => __( 'Namibia', 'jetpack-forms' ),
4133            'NR' => __( 'Nauru', 'jetpack-forms' ),
4134            'NP' => __( 'Nepal', 'jetpack-forms' ),
4135            'NL' => __( 'Netherlands', 'jetpack-forms' ),
4136            'NC' => __( 'New Caledonia', 'jetpack-forms' ),
4137            'NZ' => __( 'New Zealand', 'jetpack-forms' ),
4138            'NI' => __( 'Nicaragua', 'jetpack-forms' ),
4139            'NE' => __( 'Niger', 'jetpack-forms' ),
4140            'NG' => __( 'Nigeria', 'jetpack-forms' ),
4141            'NU' => __( 'Niue', 'jetpack-forms' ),
4142            'NF' => __( 'Norfolk Island', 'jetpack-forms' ),
4143            'KP' => __( 'North Korea', 'jetpack-forms' ),
4144            'MK' => __( 'North Macedonia', 'jetpack-forms' ),
4145            'MP' => __( 'Northern Mariana Islands', 'jetpack-forms' ),
4146            'NO' => __( 'Norway', 'jetpack-forms' ),
4147            'OM' => __( 'Oman', 'jetpack-forms' ),
4148            'PK' => __( 'Pakistan', 'jetpack-forms' ),
4149            'PW' => __( 'Palau', 'jetpack-forms' ),
4150            'PS' => __( 'Palestine', 'jetpack-forms' ),
4151            'PA' => __( 'Panama', 'jetpack-forms' ),
4152            'PG' => __( 'Papua New Guinea', 'jetpack-forms' ),
4153            'PY' => __( 'Paraguay', 'jetpack-forms' ),
4154            'PE' => __( 'Peru', 'jetpack-forms' ),
4155            'PH' => __( 'Philippines', 'jetpack-forms' ),
4156            'PN' => __( 'Pitcairn Islands', 'jetpack-forms' ),
4157            'PL' => __( 'Poland', 'jetpack-forms' ),
4158            'PT' => __( 'Portugal', 'jetpack-forms' ),
4159            'PR' => __( 'Puerto Rico', 'jetpack-forms' ),
4160            'QA' => __( 'Qatar', 'jetpack-forms' ),
4161            'RO' => __( 'Romania', 'jetpack-forms' ),
4162            'RU' => __( 'Russia', 'jetpack-forms' ),
4163            'RW' => __( 'Rwanda', 'jetpack-forms' ),
4164            'RE' => __( 'Réunion', 'jetpack-forms' ),
4165            'BL' => __( 'Saint Barthélemy', 'jetpack-forms' ),
4166            'SH' => __( 'Saint Helena', 'jetpack-forms' ),
4167            'KN' => __( 'Saint Kitts and Nevis', 'jetpack-forms' ),
4168            'LC' => __( 'Saint Lucia', 'jetpack-forms' ),
4169            'MF' => __( 'Saint Martin', 'jetpack-forms' ),
4170            'PM' => __( 'Saint Pierre and Miquelon', 'jetpack-forms' ),
4171            'VC' => __( 'Saint Vincent and the Grenadines', 'jetpack-forms' ),
4172            'WS' => __( 'Samoa', 'jetpack-forms' ),
4173            'SM' => __( 'San Marino', 'jetpack-forms' ),
4174            'SA' => __( 'Saudi Arabia', 'jetpack-forms' ),
4175            'SN' => __( 'Senegal', 'jetpack-forms' ),
4176            'RS' => __( 'Serbia', 'jetpack-forms' ),
4177            'SC' => __( 'Seychelles', 'jetpack-forms' ),
4178            'SL' => __( 'Sierra Leone', 'jetpack-forms' ),
4179            'SG' => __( 'Singapore', 'jetpack-forms' ),
4180            'SK' => __( 'Slovakia', 'jetpack-forms' ),
4181            'SI' => __( 'Slovenia', 'jetpack-forms' ),
4182            'SB' => __( 'Solomon Islands', 'jetpack-forms' ),
4183            'SO' => __( 'Somalia', 'jetpack-forms' ),
4184            'ZA' => __( 'South Africa', 'jetpack-forms' ),
4185            'GS' => __( 'South Georgia and the South Sandwich Islands', 'jetpack-forms' ),
4186            'KR' => __( 'South Korea', 'jetpack-forms' ),
4187            'ES' => __( 'Spain', 'jetpack-forms' ),
4188            'LK' => __( 'Sri Lanka', 'jetpack-forms' ),
4189            'SD' => __( 'Sudan', 'jetpack-forms' ),
4190            'SR' => __( 'Suriname', 'jetpack-forms' ),
4191            'SJ' => __( 'Svalbard and Jan Mayen', 'jetpack-forms' ),
4192            'SE' => __( 'Sweden', 'jetpack-forms' ),
4193            'CH' => __( 'Switzerland', 'jetpack-forms' ),
4194            'SY' => __( 'Syria', 'jetpack-forms' ),
4195            'ST' => __( 'São Tomé and Príncipe', 'jetpack-forms' ),
4196            'TW' => __( 'Taiwan', 'jetpack-forms' ),
4197            'TJ' => __( 'Tajikistan', 'jetpack-forms' ),
4198            'TZ' => __( 'Tanzania', 'jetpack-forms' ),
4199            'TH' => __( 'Thailand', 'jetpack-forms' ),
4200            'TL' => __( 'Timor-Leste', 'jetpack-forms' ),
4201            'TG' => __( 'Togo', 'jetpack-forms' ),
4202            'TK' => __( 'Tokelau', 'jetpack-forms' ),
4203            'TO' => __( 'Tonga', 'jetpack-forms' ),
4204            'TT' => __( 'Trinidad and Tobago', 'jetpack-forms' ),
4205            'TN' => __( 'Tunisia', 'jetpack-forms' ),
4206            'TR' => __( 'Turkey', 'jetpack-forms' ),
4207            'TM' => __( 'Turkmenistan', 'jetpack-forms' ),
4208            'TC' => __( 'Turks and Caicos Islands', 'jetpack-forms' ),
4209            'TV' => __( 'Tuvalu', 'jetpack-forms' ),
4210            'VI' => __( 'U.S. Virgin Islands', 'jetpack-forms' ),
4211            'UG' => __( 'Uganda', 'jetpack-forms' ),
4212            'UA' => __( 'Ukraine', 'jetpack-forms' ),
4213            'AE' => __( 'United Arab Emirates', 'jetpack-forms' ),
4214            'GB' => __( 'United Kingdom', 'jetpack-forms' ),
4215            'US' => __( 'United States', 'jetpack-forms' ),
4216            'UY' => __( 'Uruguay', 'jetpack-forms' ),
4217            'UZ' => __( 'Uzbekistan', 'jetpack-forms' ),
4218            'VU' => __( 'Vanuatu', 'jetpack-forms' ),
4219            'VA' => __( 'Vatican City', 'jetpack-forms' ),
4220            'VE' => __( 'Venezuela', 'jetpack-forms' ),
4221            'VN' => __( 'Vietnam', 'jetpack-forms' ),
4222            'WF' => __( 'Wallis and Futuna', 'jetpack-forms' ),
4223            'YE' => __( 'Yemen', 'jetpack-forms' ),
4224            'ZM' => __( 'Zambia', 'jetpack-forms' ),
4225            'ZW' => __( 'Zimbabwe', 'jetpack-forms' ),
4226        );
4227    }
4228
4229    /**
4230     * Enqueues scripts and styles needed for the slider field.
4231     *
4232     * @since 6.2.1
4233     *
4234     * @return void
4235     */
4236    private function enqueue_phone_field_assets() {
4237        $version = defined( 'JETPACK__VERSION' ) ? \JETPACK__VERSION : '0.1';
4238
4239        // extra cache busting strategy for view.js, seems they are left out of cache clearing on deploys
4240        $asset_file = plugin_dir_path( __FILE__ ) . '../../dist/modules/field-phone/view.asset.php';
4241        $asset      = file_exists( $asset_file ) ? require $asset_file : null;
4242        $version   .= $asset['version'] ?? '';
4243
4244        // combobox styles
4245        \wp_enqueue_style(
4246            'jetpack-form-combobox',
4247            plugins_url( '../../dist/contact-form/css/combobox.css', __FILE__ ),
4248            array(),
4249            $version
4250        );
4251
4252        \wp_enqueue_style(
4253            'jetpack-form-phone-field',
4254            plugins_url( '../../dist/contact-form/css/phone-field.css', __FILE__ ),
4255            array(),
4256            $version
4257        );
4258
4259        \wp_enqueue_script_module(
4260            'jetpack-form-phone-field',
4261            plugins_url( '../../dist/modules/field-phone/view.js', __FILE__ ),
4262            array( '@wordpress/interactivity', 'jp-forms-view' ),
4263            $version
4264        );
4265    }
4266
4267    /**
4268     * Trims the image select options from the end of the array if they are empty.
4269     *
4270     * @param array $options The options to trim.
4271     *
4272     * @return array The trimmed options array.
4273     */
4274    private function trim_image_select_options( $options ) {
4275        if ( empty( $options ) ) {
4276            return $options;
4277        }
4278
4279        // Work backwards through the array to find the last valid option
4280        $last_valid_index = -1;
4281
4282        for ( $i = count( $options ) - 1; $i >= 0; $i-- ) {
4283            $option = $options[ $i ];
4284
4285            // Check if option has a label
4286            $has_label = ! empty( $option['label'] );
4287
4288            // Check if option has an image with src
4289            $has_image = false;
4290
4291            if ( isset( $option['image']['innerHTML'] ) ) {
4292                // Extract src from innerHTML using regex
4293                preg_match( '/src="([^"]*)"/', $option['image']['innerHTML'], $matches );
4294                $has_image = ! empty( $matches[1] );
4295            }
4296
4297            // If this option has either a label or an image, it's valid
4298            if ( $has_label || $has_image ) {
4299                $last_valid_index = $i;
4300                break;
4301            }
4302        }
4303
4304        return array_slice( $options, 0, $last_valid_index + 1 );
4305    }
4306}