Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
68.00% covered (warning)
68.00%
1154 / 1697
42.39% covered (danger)
42.39%
39 / 92
CRAP
0.00% covered (danger)
0.00%
0 / 1
Contact_Form
68.12% covered (warning)
68.12%
1154 / 1694
42.39% covered (danger)
42.39%
39 / 92
12421.21
0.00% covered (danger)
0.00%
0 / 1
 set_ref_id
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 clear_ref_id
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_ref_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 has_seen
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 reset_seen_refs
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 render_synced_form
80.00% covered (warning)
80.00%
12 / 15
0.00% covered (danger)
0.00%
0 / 1
7.39
 render_synced_form_content
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
3.01
 render_frontend_status_notice
0.00% covered (danger)
0.00%
0 / 37
0.00% covered (danger)
0.00%
0 / 1
42
 is_collecting_responses
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
8
 attribute_is_truthy
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
4.03
 render_not_collecting_notice
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 __construct
96.15% covered (success)
96.15%
75 / 78
0.00% covered (danger)
0.00%
0 / 1
18
 harvest_container_logic
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 is_current_submission
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
8.06
 apply_initial_field_visibility
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
9
 get_instance_from_jwt
69.74% covered (warning)
69.74%
53 / 76
0.00% covered (danger)
0.00%
0 / 1
33.22
 set_source
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 set_is_preview_submission
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_preview_submission
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_context
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
8.06
 increment_form_context_count
60.00% covered (warning)
60.00%
3 / 5
0.00% covered (danger)
0.00%
0 / 1
2.26
 register_post_type
100.00% covered (success)
100.00%
69 / 69
100.00% covered (success)
100.00%
1 / 1
1
 get_forms_count
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 compute_id
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 get_secret
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
5.02
 get_default_thank_you_heading
28.57% covered (danger)
28.57%
2 / 7
0.00% covered (danger)
0.00%
0 / 1
6.28
 get_attributes
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_jwt
91.38% covered (success)
91.38%
53 / 58
0.00% covered (danger)
0.00%
0 / 1
9.05
 get_source
50.00% covered (danger)
50.00%
2 / 4
0.00% covered (danger)
0.00%
0 / 1
2.50
 get_forms_context_count
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_default_to
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
5.02
 get_default_to_with_source
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
6.01
 get_default_to_for_editor
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_post_property
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
6
 get_default_subject
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
6
 store_shortcode
n/a
0 / 0
n/a
0 / 0
1
 style
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 style_on
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 add_quick_link_to_admin_bar
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
6
 parse
73.43% covered (warning)
73.43%
152 / 207
0.00% covered (danger)
0.00%
0 / 1
196.07
 prepare_submit_button
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
6.05
 add_submit_button_interactivity_attributes
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 render_noscript_success_message
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
12
 format_submission_data
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
5
 get_submission_display_value
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_url
28.57% covered (danger)
28.57%
2 / 7
0.00% covered (danger)
0.00%
0 / 1
24.86
 get_rating
14.29% covered (danger)
14.29%
2 / 14
0.00% covered (danger)
0.00%
0 / 1
37.86
 get_field_type_icon_key
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_field_type_icon
95.83% covered (success)
95.83%
23 / 24
0.00% covered (danger)
0.00%
0 / 1
7
 render_error_wrapper
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 render_ajax_success_wrapper
22.86% covered (danger)
22.86%
24 / 105
0.00% covered (danger)
0.00%
0 / 1
415.09
 success_message
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
4
 get_compiled_form
73.68% covered (warning)
73.68%
14 / 19
0.00% covered (danger)
0.00%
0 / 1
5.46
 get_json_data
n/a
0 / 0
n/a
0 / 0
3
 get_raw_compiled_form_data
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
3.33
 get_compiled_form_for_email
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 escape_and_sanitize_field_value
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
18
 remove_empty
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_file_upload_fields
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 delete_feedback_files
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 esc_shortcode_val
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 parse_contact_field
77.78% covered (warning)
77.78%
42 / 54
0.00% covered (danger)
0.00%
0 / 1
35.00
 is_file_upload_field
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
 get_default_label_from_type
44.68% covered (danger)
44.68%
21 / 47
0.00% covered (danger)
0.00%
0 / 1
65.92
 get_field_ids
72.97% covered (warning)
72.97%
27 / 37
0.00% covered (danger)
0.00%
0 / 1
16.34
 process_submission
83.24% covered (warning)
83.24%
154 / 185
0.00% covered (danger)
0.00%
0 / 1
81.67
 has_custom_redirect
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 get_redirect_url
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
6.05
 get_permalink
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 wp_mail
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 add_name_to_address
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_mail_content_type
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 wrap_message_in_html_tags
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 add_plain_text_alternative
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 addslashes_deep
50.00% covered (danger)
50.00%
4 / 8
0.00% covered (danger)
0.00%
0 / 1
6.00
 get_block_container_classes
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
3.04
 get_block_alignment_class
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 process_file_upload_field
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
90
 maybe_transform_value
22.73% covered (danger)
22.73%
5 / 22
0.00% covered (danger)
0.00%
0 / 1
134.12
 get_images
12.50% covered (danger)
12.50%
2 / 16
0.00% covered (danger)
0.00%
0 / 1
30.12
 get_files
11.11% covered (danger)
11.11%
2 / 18
0.00% covered (danger)
0.00%
0 / 1
31.28
 escape_and_sanitize_field_label
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 add_theme_json_data_for_classic_themes
0.00% covered (danger)
0.00%
0 / 59
0.00% covered (danger)
0.00%
0 / 1
12
 validate
92.31% covered (success)
92.31%
12 / 13
0.00% covered (danger)
0.00%
0 / 1
9.04
 get_conditional_logic_context
95.83% covered (success)
95.83%
23 / 24
0.00% covered (danger)
0.00%
0 / 1
8
 get_resolved_field_visibility
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 compute_field_visibility
86.36% covered (warning)
86.36%
19 / 22
0.00% covered (danger)
0.00%
0 / 1
7.12
 validate_ref
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
4.37
 reset_errors
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 add_error
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 has_errors
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 get_error_messages
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_confirmation_type
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_disable_summary
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * Contact_Form class.
4 *
5 * @package automattic/jetpack-forms
6 */
7
8namespace Automattic\Jetpack\Forms\ContactForm;
9
10use Automattic\Jetpack\Connection\Tokens;
11use Automattic\Jetpack\Forms\Dashboard\Dashboard as Forms_Dashboard;
12use Automattic\Jetpack\Forms\Jetpack_Forms;
13use Automattic\Jetpack\JWT;
14use Automattic\Jetpack\Sync\Settings;
15use PHPMailer\PHPMailer\PHPMailer;
16use WP_Block;
17use WP_Error;
18use WP_Post;
19
20// Load the Form_Submission_Error class.
21require_once __DIR__ . '/class-form-submission-error.php';
22
23if ( ! defined( 'ABSPATH' ) ) {
24    exit( 0 );
25}
26
27/**
28 * Class for the contact-form shortcode.
29 * Parses shortcode to output the contact form as HTML
30 * Sends email and stores the contact form response (a.k.a. "feedback")
31 */
32class Contact_Form extends Contact_Form_Shortcode {
33
34    /**
35     * The shortcode name.
36     *
37     * @var string
38     */
39    public $shortcode_name = 'contact-form';
40
41    /**
42     * The custom post type for forms.
43     *
44     * @var string
45     */
46    const POST_TYPE = 'jetpack_form';
47
48    /**
49     * Meta key for the source post ID.
50     *
51     * @var string
52     */
53    const SOURCE_META_KEY = '_jetpack_forms_source_post_id';
54
55    /**
56     *
57     * Stores form submission errors.
58     *
59     * @var WP_Error
60     */
61    public $errors;
62
63    /**
64     * The SHA1 hash of the attributes that comprise the form.
65     *
66     * @var string
67     */
68    public $hash;
69
70    /**
71     * The most recent (inclusive) contact-form shortcode processed.
72     *
73     * @var Contact_Form|null
74     */
75    public static $last;
76
77    /**
78     * Form we are currently looking at. If processed, will become $last
79     *
80     * @var Contact_Form|null
81     */
82    public static $current_form;
83
84    /**
85     * All found forms, indexed by hash.
86     *
87     * @var array
88     */
89    public static $forms = array();
90
91    /**
92     * The context for the forms, indexed by context.
93     * This is used to keep track of how many forms are in a specific context.
94     *
95     * @var array
96     */
97    public static $forms_context = array();
98
99    /**
100     * Array of WP_Error objects that are keyed by form id.
101     *
102     * @var array
103     */
104    public static $static_errors = array();
105
106    /**
107     * Whether to print the grunion.css style when processing the contact-form shortcode
108     *
109     * @var bool
110     */
111    public static $style = false;
112
113    /**
114     * When printing the submit button, what tags are allowed
115     *
116     * @var array
117     */
118    public static $allowed_html_tags_for_submit_button = array( 'br' => array() );
119
120    /**
121     * Whether to enable response without reloading the page.
122     *
123     * @var bool
124     */
125    public $is_response_without_reload_enabled = true;
126
127    /**
128     * The current post object for this form.
129     *
130     * @var WP_Post|null
131     */
132    public $current_post;
133
134    /**
135     * Whether the form has a verified JWT token.
136     *
137     * @var bool
138     */
139    public $has_verified_jwt = false;
140
141    /**
142     * Whether the current submission originated from an authenticated form preview.
143     *
144     * When true, the resulting feedback is marked as a test submission — Akismet
145     * is skipped, the notification email is annotated, and the response is
146     * excluded from the default CSV export.
147     *
148     * @var bool
149     */
150    private $is_preview_submission = false;
151
152    /**
153     * The source of the feedback entry.
154     *
155     * @var Feedback_Source
156     */
157    private $source;
158
159    /**
160     * Cached map of field id to conditional-logic visibility for this submission.
161     *
162     * Null until resolved. Shared by validation and storage so the two cannot disagree.
163     *
164     * @var array|null
165     */
166    private $resolved_field_visibility = null;
167
168    /**
169     * The reference ID for the contact form.
170     *
171     * @var int|null
172     */
173    private static $ref_id = null;
174
175    /**
176     * Seen reference IDs for the contact form.
177     *
178     * @var array
179     */
180    private static $seen_ref = array();
181
182    /**
183     * Set the reference ID for the contact form.
184     *
185     * @param int $ref_id The reference ID.
186     */
187    public static function set_ref_id( $ref_id ) {
188        self::$ref_id              = $ref_id;
189        self::$seen_ref[ $ref_id ] = true;
190    }
191
192    /**
193     * Clear the reference ID for the contact form.
194     *
195     * @param int $ref_id The reference ID to clear.
196     */
197    public static function clear_ref_id( $ref_id ) {
198        self::$ref_id              = null;
199        self::$seen_ref[ $ref_id ] = false;
200    }
201
202    /**
203     * Get the reference ID for the contact form.
204     *
205     * @return int|null The reference ID.
206     */
207    public static function get_ref_id() {
208        return self::$ref_id;
209    }
210
211    /**
212     * Check if the reference ID has been seen for the contact form.
213     *
214     * @param int $ref_id The reference ID.
215     * @return bool True if the reference ID has been seen, false otherwise.
216     */
217    public static function has_seen( $ref_id ) {
218        return isset( self::$seen_ref[ $ref_id ] ) && self::$seen_ref[ $ref_id ];
219    }
220
221    /**
222     * Reset the seen reference IDs for the contact form.
223     */
224    public static function reset_seen_refs() {
225        self::$seen_ref = array();
226        self::$ref_id   = null;
227    }
228
229    /**
230     * Render a synced form by reference ID.
231     *
232     * This handles loading a form from a jetpack_form post and rendering it.
233     * Used by both the shortcode [contact-form ref="123"] and the block.
234     *
235     * @param int $ref_id The jetpack_form post ID.
236     * @return string Rendered form HTML.
237     */
238    public static function render_synced_form( $ref_id ) {
239        // Circular reference prevention.
240        if ( self::has_seen( $ref_id ) ) {
241            return '';
242        }
243
244        // Load the jetpack_form post.
245        $synced_form = get_post( $ref_id );
246
247        // Validate post.
248        if ( ! $synced_form || self::POST_TYPE !== $synced_form->post_type ) {
249            return '';
250        }
251
252        $status = $synced_form->post_status;
253
254        // Trashed forms are always hidden.
255        if ( 'trash' === $status ) {
256            return '';
257        }
258
259        // Published forms render normally for everyone.
260        if ( 'publish' === $status ) {
261            return self::render_synced_form_content( $ref_id, $synced_form );
262        }
263
264        // For non-published statuses (draft, pending, future, private), only show preview to users who can edit the form.
265        if ( ! current_user_can( 'edit_post', $ref_id ) ) {
266            return '';
267        }
268
269        // Render the form with a status notice for editors.
270        $notice       = self::render_frontend_status_notice( $synced_form );
271        $form_content = self::render_synced_form_content( $ref_id, $synced_form );
272
273        return $notice . $form_content;
274    }
275
276    /**
277     * Render the actual form content for a synced form.
278     *
279     * @param int      $ref_id The jetpack_form post ID.
280     * @param \WP_Post $synced_form The synced form post object.
281     * @return string Rendered form HTML.
282     */
283    private static function render_synced_form_content( $ref_id, $synced_form ) {
284        if ( $ref_id === self::get_ref_id() ) {
285            return '';
286        }
287        // Mark as seen for circular reference prevention.
288        self::set_ref_id( $ref_id );
289        $output = '';
290        try {
291            // Parse and render blocks from post_content.
292            $blocks = parse_blocks( $synced_form->post_content );
293            foreach ( $blocks as $block ) {
294                $output .= render_block( $block );
295            }
296        } finally {
297            // Clean up.
298            self::clear_ref_id( $ref_id );
299        }
300        return $output;
301    }
302
303    /**
304     * Render a frontend status notice for non-published forms.
305     *
306     * @param \WP_Post $synced_form The synced form post object.
307     * @return string Notice HTML.
308     */
309    private static function render_frontend_status_notice( $synced_form ) {
310        $status = $synced_form->post_status;
311
312        if ( 'publish' === $status || 'private' === $status ) {
313            return '';
314        }
315
316        $status_config = array(
317            'draft'   => array(
318                'type'    => 'warning',
319                'message' => __( 'This form is a draft and is only visible to you. Publish it to make it visible to site visitors.', 'jetpack-forms' ),
320            ),
321            'pending' => array(
322                'type'    => 'warning',
323                'message' => __( 'This form is pending review and is only visible to you. It will be visible to site visitors once approved and published.', 'jetpack-forms' ),
324            ),
325            'future'  => array(
326                'type'    => 'info',
327                'message' => sprintf(
328                    /* translators: %s: scheduled publish date */
329                    __( 'This form is scheduled for %s and is only visible to you until then.', 'jetpack-forms' ),
330                    wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), get_post_time( 'U', true, $synced_form ) )
331                ),
332            ),
333        );
334
335        if ( ! isset( $status_config[ $status ] ) ) {
336            return '';
337        }
338
339        wp_enqueue_style( 'jetpack-form-status-notice' );
340
341        $config     = $status_config[ $status ];
342        $type_class = 'info' === $config['type'] ? 'jetpack-form-status-notice--info' : 'jetpack-form-status-notice--warning';
343        $edit_url   = get_edit_post_link( $synced_form->ID, 'raw' );
344        $edit_link  = $edit_url ? sprintf(
345            ' <a href="%s" class="jetpack-form-status-notice__edit-link">%s</a>',
346            esc_url( $edit_url ),
347            esc_html__( 'Edit form', 'jetpack-forms' )
348        ) : '';
349
350        return sprintf(
351            '<div class="jetpack-form-status-notice %s"><p>%s%s</p></div>',
352            esc_attr( $type_class ),
353            esc_html( $config['message'] ),
354            $edit_link
355        );
356    }
357
358    /**
359     * Determine whether a form is configured to collect its responses anywhere.
360     *
361     * A form "collects responses" when submissions are delivered to at least one
362     * destination: emailed to a recipient, saved to the responses dashboard, or
363     * routed to an active data integration. When all three are off, submissions
364     * are silently dropped.
365     *
366     * This must run on the RAW block attributes (as authored), not the values
367     * merged with Contact_Form's runtime defaults — e.g. `jetpackCRM` defaults to
368     * `true` at render time but is only "on" when explicitly enabled on the form.
369     *
370     * Keep this in sync with the JS helper `isCollectingResponses()` in
371     * blocks/contact-form/util/is-collecting-responses.ts.
372     *
373     * @since 7.23.0
374     *
375     * @param mixed $attributes Raw contact-form block attributes. Non-arrays are
376     *                          treated as collecting (no warning).
377     * @return bool True when the form has at least one response destination.
378     */
379    public static function is_collecting_responses( $attributes ) {
380        if ( ! is_array( $attributes ) ) {
381            return true;
382        }
383
384        // Email destination: on by default. A blank or invalid recipient is not a
385        // dead end — submissions fall back to the site admin email at send time —
386        // so email being on always counts as a real destination.
387        $email_active = self::attribute_is_truthy( $attributes, 'emailNotifications', true );
388
389        // Saving to the responses dashboard: on by default.
390        $saving_active = self::attribute_is_truthy( $attributes, 'saveResponses', true );
391
392        // Integrations that actually persist or route the submission. Akismet
393        // (spam filtering) and Google Drive (exports already-saved responses) are
394        // intentionally excluded — neither is an independent destination.
395        //
396        // Webhooks (`postToUrl`/`webhooks`) are also excluded: they only fire when
397        // the form author has `manage_options` (see
398        // Jetpack_Forms::should_honor_content_destinations()), so whether they're a
399        // real destination depends on author capability, not the attributes alone.
400        // This shared helper is intentionally context-free so PHP and JS agree, so
401        // counting them here would wrongly silence the warning for editor-authored
402        // forms whose webhook never runs.
403        $integration_active = self::attribute_is_truthy( $attributes, 'jetpackCRM', false )
404            || ! empty( $attributes['mailpoet']['enabledForForm'] )
405            || ! empty( $attributes['hostingerReach']['enabledForForm'] )
406            || (
407                ! empty( $attributes['salesforceData']['sendToSalesforce'] )
408                && ! empty( $attributes['salesforceData']['organizationId'] )
409            );
410
411        return $email_active || $saving_active || $integration_active;
412    }
413
414    /**
415     * Normalize a possibly-boolean-or-string block attribute to a boolean.
416     *
417     * Toggle attributes arrive as JS booleans from the editor but are persisted
418     * as `'yes'`/`'no'` strings in some contexts, so both forms must be handled.
419     *
420     * @since 7.23.0
421     *
422     * @param array  $attributes Block attributes.
423     * @param string $key        Attribute name.
424     * @param bool   $default    Value to use when the attribute is absent.
425     * @return bool
426     */
427    private static function attribute_is_truthy( $attributes, $key, $default ) {
428        if ( ! array_key_exists( $key, $attributes ) ) {
429            return $default;
430        }
431
432        $value = $attributes[ $key ];
433
434        if ( is_bool( $value ) ) {
435            return $value;
436        }
437
438        if ( is_string( $value ) ) {
439            return ! in_array( strtolower( trim( $value ) ), array( '', 'no', 'false', '0' ), true );
440        }
441
442        return (bool) $value;
443    }
444
445    /**
446     * Render an admin-only notice when a form isn't collecting responses.
447     *
448     * Shown on the live front-end form and in form previews, but only to users
449     * who can manage forms (`edit_pages`) — never to visitors.
450     *
451     * @since 7.23.0
452     *
453     * @param array $attributes Raw contact-form block attributes.
454     * @return string Notice HTML, or an empty string.
455     */
456    private static function render_not_collecting_notice( $attributes ) {
457        if ( ! current_user_can( 'edit_pages' ) ) {
458            return '';
459        }
460
461        if ( self::is_collecting_responses( $attributes ) ) {
462            return '';
463        }
464
465        wp_enqueue_style( 'jetpack-form-status-notice' );
466
467        return sprintf(
468            '<div class="jetpack-form-status-notice jetpack-form-status-notice--warning jetpack-form-not-collecting-notice"><p>%s</p></div>',
469            esc_html__( 'Only you can see this. This form isn’t collecting responses. Turn on email notifications or response storage in form settings.', 'jetpack-forms' )
470        );
471    }
472
473    /**
474     * Construction function.
475     *
476     * @param array  $attributes - the attributes.
477     * @param string $content - the content.
478     * @param bool   $set_id - whether to set the ID for the form.
479     */
480    public function __construct( $attributes, $content = null, $set_id = true ) {
481        global $post, $page;
482
483        // AJAX requests don't have a post object, so we need to get the post object from the $_POST['contact-form-id']
484        $this->current_post = $post;
485
486        // phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce verification happens in process_form_submission() for logged-in users
487        if ( ! $this->current_post && isset( $_POST['contact-form-id'] ) ) {
488            $contact_form_id    = sanitize_text_field( wp_unslash( $_POST['contact-form-id'] ) );
489            $this->current_post = get_post( $contact_form_id );
490        }
491        // phpcs:enable
492
493        $this->is_response_without_reload_enabled = apply_filters( 'jetpack_forms_enable_ajax_submission', true );
494
495        // Initialize the source before setting defaults
496        if ( ! $this->source ) {
497            $attributes   = is_array( $attributes ) ? $attributes : array();
498            $this->source = Feedback_Source::get_current( $attributes );
499        }
500
501        // Set up the default subject and recipient for this form.
502        $post_author_id  = self::get_post_property( $this->current_post, 'post_author' );
503        $default_to      = self::get_default_to( $post_author_id, $this->source );
504        $default_subject = self::get_default_subject( $attributes, $this->current_post );
505
506        if ( ! isset( $attributes ) || ! is_array( $attributes ) ) {
507            $attributes = array();
508        }
509
510        if ( $set_id ) {
511            $page_number      = is_numeric( $page ) ? intval( $page ) : 1;
512            $attributes['id'] = self::compute_id( $attributes, $this->current_post, $page_number );
513        }
514        $this->hash = sha1(
515            wp_json_encode(
516                $attributes,
517                0 // phpcs:ignore Jetpack.Functions.JsonEncodeFlags.ZeroFound -- No `json_encode()` flags because we don't want to disrupt the current hash index.
518            )
519        );
520
521        if ( $set_id ) {
522            self::$forms[ $this->hash ] = $this; // This increments the form count.
523            self::increment_form_context_count( $attributes, $this->current_post );
524        }
525
526        // Keep reference to $this for parsing form fields.
527        self::$current_form = $this;
528
529        $this->defaults = array(
530            'to'                     => $default_to,
531            'subject'                => $default_subject,
532            'show_subject'           => 'no', // only used in back-compat mode
533            'widget'                 => 0,    // Not exposed to the user. Works with Contact_Form_Plugin::widget_atts()
534            'block_template'         => null, // Not exposed to the user. Works with template_loader
535            'block_template_part'    => null, // Not exposed to the user. Works with Contact_Form::parse()
536            'id'                     => null, // Not exposed to the user. Set above.
537            'ref'                    => null, // Not exposed to the user. Set above if applicable.
538            'submit_button_text'     => __( 'Submit', 'jetpack-forms' ),
539            // These attributes come from the block editor, so use camel case instead of snake case.
540            'customThankyou'         => '', // Whether to show a custom thankyou response after submitting a form. '' for no, 'noSummary' to disable the summary, 'message' for a custom message, 'redirect' to redirect to a new URL. Deprecated.
541            'customThankyouHeading'  => self::get_default_thank_you_heading(), // The text to show above customThankyouMessage.
542            'customThankyouMessage'  => '', // The message to show when customThankyou is set to 'message'.
543            'customThankyouRedirect' => '', // The URL to redirect to when confirmationType is set to 'redirect'.
544            'confirmationType'       => 'text', // The type of confirmation to show after submitting a form. 'text' for a text message, 'redirect' for a redirect link.
545            'jetpackCRM'             => true, // Whether Jetpack CRM should store the form submission.
546            'mailpoet'               => null,
547            'hostingerReach'         => null,
548            'className'              => null,
549            'postToUrl'              => null,
550            'salesforceData'         => null,
551            'hiddenFields'           => null,
552            'stepTransition'         => 'fade-slide', // The transition style for multi-step forms. Options: none, fade, slide, fade-slide
553            'saveResponses'          => 'yes',
554            'emailNotifications'     => 'yes',
555            'notificationRecipients' => array(), // Array of user IDs who should receive form response notifications.
556            'webhooks'               => array(), // Array of webhooks to send the form data to.
557            'disableGoBack'          => $attributes['disableGoBack'] ?? false,
558            'disableSummary'         => $attributes['disableSummary'] ?? false,
559            'formTitle'              => $attributes['formTitle'] ?? '',
560        );
561
562        $attributes = shortcode_atts( $this->defaults, $attributes, 'contact-form' );
563
564        // Transform boolean saveResponses to string for backend compatibility
565        if ( isset( $attributes['saveResponses'] ) && is_bool( $attributes['saveResponses'] ) ) {
566            $attributes['saveResponses'] = $attributes['saveResponses'] ? 'yes' : 'no';
567        }
568
569        // Transform boolean emailNotifications to string for backend compatibility
570        if ( isset( $attributes['emailNotifications'] ) && is_bool( $attributes['emailNotifications'] ) ) {
571            $attributes['emailNotifications'] = $attributes['emailNotifications'] ? 'yes' : 'no';
572        }
573
574        // We only enable the contact-field shortcode temporarily while processing the contact-form shortcode.
575        Contact_Form_Plugin::$using_contact_form_field = true;
576
577        parent::__construct( $attributes, $content );
578
579        // There were no fields in the contact form. The form was probably just [contact-form /]. Build a default form.
580        if ( empty( $this->fields ) ) {
581            // same as the original Grunion v1 form.
582            $default_form = '
583                [contact-field label="' . __( 'Name', 'jetpack-forms' ) . '" type="name"  required="true" /]
584                [contact-field label="' . __( 'Email', 'jetpack-forms' ) . '" type="email" required="true" /]
585                [contact-field label="' . __( 'Website', 'jetpack-forms' ) . '" type="url" /]';
586
587            if ( 'yes' === strtolower( $this->get_attribute( 'show_subject' ) ) ) {
588                $default_form .= '
589                    [contact-field label="' . __( 'Subject', 'jetpack-forms' ) . '" type="subject" /]';
590            }
591
592            $default_form .= '
593                [contact-field label="' . __( 'Message', 'jetpack-forms' ) . '" type="textarea" /]';
594
595            $this->parse_content( $default_form );
596        }
597
598        // $this->body and $this->fields have been setup.  We no longer need the contact-field shortcode.
599        Contact_Form_Plugin::$using_contact_form_field = false;
600
601        $this->harvest_container_logic();
602        $this->apply_initial_field_visibility();
603    }
604
605    /**
606     * Read conditions off the container blocks in this form's body.
607     *
608     * Has to happen here rather than while the containers render: a container is rendered
609     * before the fields it encloses become fields, so at that point there is nothing to record
610     * a containment against.
611     *
612     * @return void
613     */
614    private function harvest_container_logic() {
615        if ( ! Jetpack_Forms::is_conditional_logic_enabled() || empty( $this->body ) ) {
616            return;
617        }
618
619        $harvested = Conditional_Logic_Container::harvest( $this->body );
620
621        $this->container_logic    = $harvested['logic'];
622        $this->container_contains = $harvested['contains'];
623        $this->body               = $harvested['body'];
624    }
625
626    /**
627     * Whether the current request is submitting this form.
628     *
629     * Normal submissions are identified by their action, ID, and hash. JWT submissions omit
630     * the action, but the plugin validates their token before constructing and validating the
631     * form, so the matching ID and hash identify the submitted form here.
632     *
633     * @return bool
634     */
635    public function is_current_submission() {
636        if ( ! isset( $_POST['contact-form-id'] ) || ! isset( $_POST['contact-form-hash'] ) || ! is_string( $_POST['contact-form-hash'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- no site changes.
637            return false;
638        }
639
640        $form_id   = sanitize_text_field( wp_unslash( $_POST['contact-form-id'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- no site changes.
641        $form_hash = sanitize_text_field( wp_unslash( $_POST['contact-form-hash'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- no site changes.
642
643        if ( (string) $this->get_attribute( 'id' ) !== $form_id || ! hash_equals( $this->hash, $form_hash ) ) {
644            return false;
645        }
646
647        if ( isset( $_POST['jetpack_contact_form_jwt'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- JWT validation happens before form validation.
648            return true;
649        }
650
651        return isset( $_POST['action'] ) // phpcs:ignore WordPress.Security.NonceVerification.Missing -- no site changes.
652            && 'grunion-contact-form' === sanitize_text_field( wp_unslash( $_POST['action'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- no site changes.
653    }
654
655    /**
656     * Conditions on container blocks in this form, keyed by generated container id.
657     *
658     * @var array
659     */
660    private $container_logic = array();
661
662    /**
663     * Field ids enclosed by each container, keyed by container id.
664     *
665     * @var array
666     */
667    private $container_contains = array();
668
669    /**
670     * Mark conditionally hidden fields as hidden in the rendered markup.
671     *
672     * Without this the server sends every field visible and the browser hides them once the
673     * interactivity store hydrates, so the visitor sees the hidden fields flash on screen
674     * first. The class applied here is the same one the client toggles, so the first paint
675     * already matches what the client will compute and nothing moves.
676     *
677     * This runs after the whole form is parsed. It cannot happen while fields render: they
678     * are parsed one at a time, so a rule referring to a field further down the form would be
679     * resolved against a form that does not exist yet.
680     *
681     * Public so it can be exercised directly; it is idempotent and safe to call again.
682     *
683     * @return void
684     */
685    public function apply_initial_field_visibility() {
686        if ( empty( $this->body ) || ! Jetpack_Forms::is_conditional_logic_enabled() ) {
687            return;
688        }
689
690        // Deliberately not get_resolved_field_visibility(): that caches for the submission, and
691        // this runs while the form is still being built. Seeding the cache here would hand a
692        // render-time answer to validation and storage later on.
693        $visibility = $this->compute_field_visibility();
694        $hidden     = array();
695
696        foreach ( $visibility as $field_id => $is_visible ) {
697            if ( false === $is_visible ) {
698                $hidden[ $field_id ] = true;
699            }
700        }
701
702        if ( empty( $hidden ) ) {
703            return;
704        }
705
706        $processor = new \WP_HTML_Tag_Processor( $this->body );
707
708        // Matches the element the runtime hides, which is not always the one carrying
709        // data-jp-field-id: an inset label puts the width class on an outer wrapper, and
710        // hiding the inner div there leaves the wrapper holding its slot in the row.
711        while ( $processor->next_tag( array( 'tag_name' => 'DIV' ) ) ) {
712            $field_id = $processor->get_attribute( 'data-jp-visibility-root' );
713
714            if ( null !== $field_id && isset( $hidden[ $field_id ] ) ) {
715                $processor->add_class( 'jetpack-field--conditionally-hidden' );
716            }
717        }
718
719        $this->body = $processor->get_updated_html();
720    }
721    /**
722     * Get the instance of the contact form from a JWT token.
723     *
724     * @param string $jwt_token The JWT token.
725     * @param bool   $throw_exception Whether to throw an exception if the JWT token is invalid or cannot be decoded.
726     *
727     * @return Contact_Form|null The contact form instance, or null if decoding fails and $throw_exception is false.
728     * @throws \Exception If the JWT token is invalid or cannot be decoded and $throw_exception is true.
729     */
730    public static function get_instance_from_jwt( $jwt_token, $throw_exception = false ) {
731        $secret = self::get_secret();
732
733        // Derive separate keys using HKDF for proper key separation and context binding
734        $jwt_signing_key = hash_hkdf( 'sha256', $secret, 32, 'jetpack-forms-jwt-hmac-v2' );
735        $encryption_key  = hash_hkdf( 'sha256', $secret, 32, 'jetpack-forms-aes-gcm-v2' );
736
737        try {
738            $data = JWT::decode( $jwt_token, $jwt_signing_key, array( 'HS256' ), true );
739        } catch ( \Exception $e ) {
740            try {
741                // Retry to decode the token using the secret key instead of the derived key
742                $data = JWT::decode( $jwt_token, $secret, array( 'HS256' ), true );
743            } catch ( \Exception $e ) {
744                // Re-throw with more context about the failure.
745                if ( $throw_exception ) {
746                    /**
747                     * Filter the failure to decode a JWT token for a contact form.
748                     *
749                     * @param null $value The value to return. Default null.
750                     * @param string      $jwt_token The JWT token that failed to decode.
751                     * @param \Exception  $e The exception that was thrown during decoding.
752                     *
753                     * @return Contact_Form|null The value to return.
754                     */
755                    $filtered = apply_filters( 'jetpack_forms_jwt_decode_failure', null, $jwt_token, $e );
756                    if ( $filtered !== null ) {
757                        return $filtered;
758                    }
759                    throw new \Exception(
760                        sprintf(
761                            /* translators: %s is the original exception message */
762                            __( 'Failed to decode JWT token: %s', 'jetpack-forms' ),
763                            $e->getMessage()
764                        ),
765                        0,
766                        $e
767                    );
768                }
769                return apply_filters( 'jetpack_forms_jwt_decode_failure', null, $jwt_token, $e );
770            }
771        }
772
773        $version = isset( $data['version'] ) ? absint( $data['version'] ) : 1;
774
775        if ( 2 === $version ) {
776            if ( ! isset( $data['encrypted_attributes'] ) ) {
777                throw new \Exception( 'Invalid JWT format - encrypted attributes required' );
778            }
779
780            // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- Base64 decoding required for encrypted data
781            $encrypted_blob = base64_decode( $data['encrypted_attributes'], true ); // Strict mode
782            if ( $encrypted_blob === false ) {
783                throw new \Exception( 'Invalid base64 encoding in encrypted data' );
784            }
785
786            // Determine which cipher was used (stored in JWT or default to GCM)
787            $cipher = $data['cipher'] ?? 'aes-256-gcm';
788
789            // Check if the cipher is available on this server
790            $available_cipher_methods = array_map( 'strtolower', openssl_get_cipher_methods() );
791            if ( ! in_array( strtolower( $cipher ), $available_cipher_methods, true ) ) {
792                throw new \Exception( 'Required encryption cipher ' . $cipher . ' is not available on this server' );
793            }
794
795            // Determine IV and tag sizes based on cipher
796            $is_gcm = stripos( $cipher, 'gcm' ) !== false;
797            if ( $is_gcm ) {
798                // GCM: 12-byte IV + 16-byte tag + ciphertext
799                if ( strlen( $encrypted_blob ) < 29 ) { // 12 + 16 + at least 1 byte
800                    throw new \Exception( 'Invalid encrypted data format - too short for GCM' );
801                }
802                $iv        = substr( $encrypted_blob, 0, 12 );  // 12-byte IV (96-bit)
803                $tag       = substr( $encrypted_blob, 12, 16 ); // 16-byte auth tag
804                $encrypted = substr( $encrypted_blob, 28 );     // Remaining ciphertext
805            } else {
806                // CBC: 16-byte IV + ciphertext (no tag)
807                if ( strlen( $encrypted_blob ) < 17 ) { // 16 + at least 1 byte
808                    throw new \Exception( 'Invalid encrypted data format - too short for CBC' );
809                }
810                $iv        = substr( $encrypted_blob, 0, 16 );  // 16-byte IV (128-bit)
811                $tag       = null; // No tag for CBC
812                $encrypted = substr( $encrypted_blob, 16 );     // Remaining ciphertext
813            }
814
815            $decrypted = openssl_decrypt(
816                $encrypted,
817                $cipher,
818                $encryption_key,
819                OPENSSL_RAW_DATA, // Expect raw binary data
820                $iv,
821                $tag ?? ''
822            );
823
824            if ( $decrypted === false ) {
825                throw new \Exception( 'Decryption failed - invalid token' );
826            }
827
828            $decrypted_attributes = json_decode( $decrypted, true );
829            if ( $decrypted_attributes === null ) {
830                throw new \Exception( 'Invalid attributes format' );
831            }
832
833            // Reconstruct data with decrypted attributes and unencrypted fields
834            $data['attributes'] = $decrypted_attributes;
835            // content, hash, and source are already in $data (unencrypted)
836        } elseif ( ! in_array( $version, array( 0, 1 ), true ) ) {
837            throw new \Exception( 'Unsupported JWT version' );
838        }
839
840        $source = $data['source'] ?? array();
841
842        if ( empty( $source ) ) {
843            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- check done by caller process_form_submission()
844            $source_post_id = ! empty( $_POST['contact-form-id'] ) && is_numeric( $_POST['contact-form-id'] ) ? absint( wp_unslash( $_POST['contact-form-id'] ) ) : 0;
845            $post           = get_post( $source_post_id );
846
847            if ( $post !== null && $source_post_id > 0 ) {
848                // create a fallback source
849                $source = array(
850                    'source_id'   => $post->ID,
851                    'entry_title' => html_entity_decode( $post->post_title, ENT_QUOTES | ENT_HTML5, 'UTF-8' ),
852                    'entry_page'  => 1,
853                    'source_type' => 'single',
854                    'request_url' => get_permalink( $post ),
855                );
856            }
857        }
858
859        $form                   = new self( $data['attributes'], $data['content'], empty( $data['attributes']['id'] ) );
860        $form->source           = Feedback_Source::from_serialized( $source );
861        $form->hash             = $data['hash'];
862        $form->has_verified_jwt = true;
863
864        return $form;
865    }
866
867    /**
868     * Set the source object for the contact form.
869     *
870     * @param Feedback_Source $source The source object.
871     *
872     * @return void
873     */
874    public function set_source( $source ) {
875        $this->source = $source;
876    }
877
878    /**
879     * Flag whether the current submission originated from an authenticated form preview.
880     *
881     * @param bool $is_preview_submission Whether the submission came from form preview.
882     * @return void
883     */
884    public function set_is_preview_submission( $is_preview_submission ) {
885        $this->is_preview_submission = (bool) $is_preview_submission;
886    }
887
888    /**
889     * Whether the current submission is a test submission coming from form preview.
890     *
891     * @return bool
892     */
893    public function is_preview_submission() {
894        return $this->is_preview_submission;
895    }
896
897    /**
898     * Get the context for the contact form based on the attributes and post.
899     *
900     * @param array        $attributes The attributes of the contact form.
901     * @param WP_Post|null $post The post object, if available.
902     *
903     * @return string The context for the contact form.
904     */
905    public static function get_context( $attributes, $post = null ) {
906        $context = 'jp-form';
907        if ( ! empty( $attributes['widget'] ) && $attributes['widget'] ) {
908            $context = 'widget-' . $attributes['widget'];
909        } elseif ( ! empty( $attributes['block_template'] ) && $attributes['block_template'] ) {
910            $context = 'block-template-' . $attributes['block_template'];
911        } elseif ( ! empty( $attributes['block_template_part'] ) && $attributes['block_template_part'] ) {
912            $context = 'block-template-part-' . $attributes['block_template_part'];
913        } elseif ( $post instanceof WP_Post ) {
914            $context = (string) $post->ID;
915        }
916
917        return $context;
918    }
919
920    /**
921     * Increment the count of forms for a specific context.
922     *
923     * @param array        $attributes The attributes of the contact form.
924     * @param WP_Post|null $post The post object, if available.
925     *
926     * @return void
927     */
928    public static function increment_form_context_count( $attributes, $post ) {
929        $context = self::get_context( $attributes, $post );
930        if ( ! isset( self::$forms_context[ $context ] ) ) {
931            self::$forms_context[ $context ] = 1;
932            return;
933        }
934        self::$forms_context[ $context ] = self::get_forms_context_count( $context ) + 1;
935    }
936
937    /**
938     * Register the jetpack_form custom post type.
939     */
940    public static function register_post_type() {
941
942        $labels = array(
943            'name'                     => __( 'Forms', 'jetpack-forms' ),
944            'singular_name'            => __( 'Form', 'jetpack-forms' ),
945            'add_new'                  => __( 'Add Form', 'jetpack-forms' ),
946            'add_new_item'             => __( 'Add Form', 'jetpack-forms' ),
947            'new_item'                 => __( 'New Form', 'jetpack-forms' ),
948            'edit_item'                => __( 'Edit Block Form', 'jetpack-forms' ),
949            'view_item'                => __( 'View Form', 'jetpack-forms' ),
950            'view_items'               => __( 'View Forms', 'jetpack-forms' ),
951            'all_items'                => __( 'All Forms', 'jetpack-forms' ),
952            'search_items'             => __( 'Search Forms', 'jetpack-forms' ),
953            'not_found'                => __( 'No forms found.', 'jetpack-forms' ),
954            'not_found_in_trash'       => __( 'No forms found in Trash.', 'jetpack-forms' ),
955            'filter_items_list'        => __( 'Filter forms list', 'jetpack-forms' ),
956            'items_list_navigation'    => __( 'Forms list navigation', 'jetpack-forms' ),
957            'items_list'               => __( 'Forms list', 'jetpack-forms' ),
958            'item_published'           => __( 'Form published.', 'jetpack-forms' ),
959            'item_published_privately' => __( 'Form published privately.', 'jetpack-forms' ),
960            'item_reverted_to_draft'   => __( 'Form reverted to draft.', 'jetpack-forms' ),
961            'item_scheduled'           => __( 'Form scheduled.', 'jetpack-forms' ),
962            'item_updated'             => __( 'Form updated.', 'jetpack-forms' ),
963        );
964
965        $capabilities = array(
966            // You need to be able to edit posts, in order to read blocks in their raw form.
967            'read'                   => 'edit_posts',
968            // You need to be able to publish posts, in order to create blocks.
969            'create_posts'           => 'publish_posts',
970            'edit_posts'             => 'edit_posts',
971            'edit_published_posts'   => 'edit_published_posts',
972            'delete_published_posts' => 'delete_published_posts',
973            // Enables trashing draft posts as well.
974            'delete_posts'           => 'delete_posts',
975            'edit_others_posts'      => 'edit_others_posts',
976            'delete_others_posts'    => 'delete_others_posts',
977        );
978
979        $args = array(
980            'public'                => false,
981            'show_ui'               => true, // not sure we need this.
982            'show_in_menu'          => false,
983            'rewrite'               => false,
984            'query_var'             => false,
985            'show_in_rest'          => true,
986            'rest_base'             => 'jetpack-forms',
987            'rest_controller_class' => 'Automattic\Jetpack\Forms\ContactForm\Jetpack_Form_Endpoint',
988            'capability_type'       => 'post',
989            'capabilities'          => $capabilities,
990            'map_meta_cap'          => true,
991            'labels'                => $labels,
992            'hierarchical'          => false,
993            'template'              => array( array( 'jetpack/contact-form' ) ),
994            'supports'              => array(
995                'title',
996                'editor',
997                'revisions',
998                'author',
999                'custom-fields',
1000            ),
1001        );
1002
1003        register_post_type( self::POST_TYPE, $args );
1004
1005        // Register post meta for tracking the source post that created this form.
1006        register_post_meta(
1007            self::POST_TYPE,
1008            self::SOURCE_META_KEY,
1009            array(
1010                'type'              => 'integer',
1011                'single'            => true,
1012                'show_in_rest'      => true,
1013                'sanitize_callback' => 'absint',
1014                'auth_callback'     => function () {
1015                    return current_user_can( 'edit_posts' );
1016                },
1017            )
1018        );
1019    }
1020
1021    /**
1022     * Get the count of forms.
1023     *
1024     * @return int The count of forms.
1025     */
1026    public static function get_forms_count() {
1027        return count( self::$forms );
1028    }
1029
1030    /**
1031     * Compute the ID for the contact form based on the attributes and post.
1032     *
1033     * @param array        $attributes The attributes of the contact form.
1034     * @param WP_Post|null $post The post object, if available.
1035     * @param int          $page_number The page number, if available.
1036     *
1037     * @return string The ID for the contact form.
1038     */
1039    public static function compute_id( $attributes, $post = null, $page_number = 1 ) {
1040
1041        $context = self::get_context( $attributes, $post );
1042        $id_part = array( $context );
1043
1044        if ( self::get_forms_context_count( $context ) > 0 ) {
1045            $id_part[] = self::get_forms_context_count( $context );
1046        }
1047
1048        $page_num = max( 1, intval( $page_number ) );
1049        if ( $page_num > 1 ) {
1050            $id_part[] = $page_num;
1051        }
1052
1053        return implode( '-', $id_part );
1054    }
1055
1056    /**
1057     * Helper function to get the secret from the Tokens class.
1058     *
1059     * @return string The secret from the Tokens class, or a default secret if not available.
1060     */
1061    private static function get_secret() {
1062
1063        /**
1064         * Filter the secret used for signing contact form JWT tokens.
1065         *
1066         * @param string $secret Passes a empty string by default so that we can fall back to other methods if the filter is not used.
1067         *
1068         * @return string The secret used for signing contact form JWT tokens.
1069         */
1070        $secret = apply_filters( 'jetpack_forms_secret_jwt', '' );
1071        if ( is_string( $secret ) && ! empty( $secret ) ) {
1072            return $secret;
1073        }
1074
1075        $token = ( new Tokens() )->get_access_token();
1076
1077        if ( ! empty( $token->secret ) ) {
1078            return $token->secret;
1079        }
1080
1081        $secret = get_option( 'jetpack_forms_secret_key', false );
1082        if ( empty( $secret ) ) {
1083            // Generate a fallback secret if we don't have one from Tokens.
1084            $secret = wp_generate_password( 64, true, true );
1085            update_option( 'jetpack_forms_secret_key', $secret );
1086        }
1087
1088        return $secret;
1089    }
1090
1091    /**
1092     * Get the default thank you heading with conditional sparkle.
1093     *
1094     * Returns the new copy with sparkle emoji if translated, otherwise
1095     * falls back to the old copy without sparkle.
1096     *
1097     * TEMPORARY: This method can be removed once the new copy has been translated.
1098     * Replace the call with: __( 'Thank you for your response.', 'jetpack-forms' ) . ' ✨'
1099     *
1100     * @return string The translated heading.
1101     */
1102    private static function get_default_thank_you_heading() {
1103        // English locales always get the new copy with sparkle.
1104        if ( str_starts_with( get_locale(), 'en' ) ) {
1105            return __( 'Thank you for your response.', 'jetpack-forms' ) . ' ✨';
1106        }
1107
1108        // Check if new string has a translation by comparing with the original.
1109        $original   = 'Thank you for your response.';
1110        $translated = __( 'Thank you for your response.', 'jetpack-forms' );
1111
1112        if ( $translated !== $original ) {
1113            return $translated . ' ✨';
1114        }
1115
1116        // Fall back to old string without sparkle.
1117        return __( 'Your message has been sent', 'jetpack-forms' );
1118    }
1119
1120    /**
1121     * Helper function to get the attributes of the contact form.
1122     *
1123     * @return array The attributes of the contact form.
1124     */
1125    public function get_attributes() {
1126        return $this->attributes;
1127    }
1128
1129    /**
1130     * Get the JWT token for the contact form instance.
1131     *
1132     * @return string The JWT token.
1133     * @throws \Exception If encryption fails.
1134     */
1135    public function get_jwt() {
1136        $secret = self::get_secret();
1137
1138        // Derive separate keys using HKDF for proper key separation and context binding
1139        $jwt_signing_key = hash_hkdf( 'sha256', $secret, 32, 'jetpack-forms-jwt-hmac-v2' );
1140        $encryption_key  = hash_hkdf( 'sha256', $secret, 32, 'jetpack-forms-aes-gcm-v2' );
1141
1142        $attributes   = $this->attributes;
1143        $this->source = Feedback_Source::get_current( $attributes );
1144
1145        // Only encrypt the attributes field as it contains sensitive information
1146        // Content, hash, and source are not sensitive and can remain unencrypted
1147
1148        // Check cipher availability with fallback support
1149        $available_cipher_methods = openssl_get_cipher_methods();
1150        $cipher                   = null;
1151        $cipher_fallback          = null;
1152        $use_encryption           = false;
1153        $iv_length                = 12; // Default for GCM
1154
1155        // Try to find AES-256-GCM first (case-insensitive search)
1156        foreach ( $available_cipher_methods as $method ) {
1157            if ( strtolower( $method ) === 'aes-256-gcm' ) {
1158                $cipher         = $method; // Use the actual name with original casing
1159                $use_encryption = true;
1160                // IV length already set to 12 (NIST recommended for AES-GCM)
1161                break;
1162            }
1163            // If AES-256-GCM not found, try fallback to AES-256-CBC
1164            if ( strtolower( $method ) === 'aes-256-cbc' ) {
1165                $cipher_fallback = $method; // Use the actual name with original casing
1166                $use_encryption  = true;
1167            }
1168        }
1169
1170        // Use the fallback cipher if the primary cipher is not available.
1171        if ( $cipher === null && $cipher_fallback !== null ) {
1172            $cipher    = $cipher_fallback;
1173            $iv_length = 16; // 16-byte (128-bit) IV for AES-CBC
1174        }
1175
1176        // Lazy fallback payload in case encryption fails or is unavailable.
1177        $unencrypted_payload = array(
1178            'attributes' => $attributes,
1179            'content'    => $this->content,
1180            'hash'       => $this->hash,
1181            'source'     => $this->source->serialize(),
1182            // No version field = version 1 (unencrypted)
1183        );
1184
1185        if ( $use_encryption ) {
1186            $iv        = random_bytes( $iv_length );
1187            $tag       = ''; // Will be populated by openssl_encrypt for GCM
1188            $encrypted = openssl_encrypt(
1189                wp_json_encode(
1190                    $attributes,
1191                    JSON_UNESCAPED_SLASHES
1192                ),
1193                $cipher,
1194                $encryption_key,
1195                OPENSSL_RAW_DATA, // Return raw binary data, not base64
1196                $iv,
1197                $tag
1198            );
1199
1200            if ( $encrypted === false ) {
1201                do_action( 'jetpack_forms_log', 'jwt_encryption_failed', openssl_error_string() );
1202                return JWT::encode( $unencrypted_payload, $jwt_signing_key );
1203            }
1204            // For GCM, include the authentication tag; for CBC, tag will be empty
1205            $encrypted_blob = stripos( $cipher, 'GCM' ) !== false ? $iv . $tag . $encrypted : $iv . $encrypted;
1206
1207            return JWT::encode(
1208                array(
1209                    'encrypted_attributes' => base64_encode( $encrypted_blob ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Base64 encoding required for encrypted data storage
1210                    'content'              => $this->content,
1211                    'hash'                 => $this->hash,
1212                    'source'               => $this->source->serialize(),
1213                    'version'              => 2,
1214                    'cipher'               => $cipher, // Store which cipher was used
1215                ),
1216                $jwt_signing_key
1217            );
1218        }
1219
1220        // No encryption available - fall back to version 1 format (unencrypted)
1221        return JWT::encode( $unencrypted_payload, $jwt_signing_key );
1222    }
1223
1224    /**
1225     * Get the current source obejct. That is relevent to the form and there current request.
1226     *
1227     * @return Feedback_Source Return the current feedback source object.
1228     */
1229    public function get_source() {
1230        if ( ! $this->source ) {
1231            $attributes   = $this->attributes;
1232            $this->source = Feedback_Source::get_current( $attributes );
1233        }
1234        return $this->source;
1235    }
1236
1237    /**
1238     * Get the count of forms.
1239     *
1240     * @param string $context The context for which to get the count of forms.
1241     *
1242     * @return int The count of forms.
1243     */
1244    public static function get_forms_context_count( $context ) {
1245        if ( ! isset( self::$forms_context[ $context ] ) ) {
1246            self::$forms_context[ $context ] = 0;
1247            return 0;
1248        }
1249
1250        return self::$forms_context[ $context ];
1251    }
1252
1253    /**
1254     * Get the default recipient email address for the contact form.
1255     *
1256     * @param int|null             $post_author_id The ID of the post author. If provided, will return the author's email.
1257     * @param Feedback_Source|null $source The source of the feedback entry. Optional, not used currently.
1258     *
1259     * @return string The default recipient email address.
1260     */
1261    public static function get_default_to( $post_author_id = null, $source = null ) {
1262        // Get the default recipient email address.
1263        $default_to = get_option( 'admin_email' );
1264        // Check that the user has edit permissions for this blog and has an email address
1265        if ( ! $post_author_id ) {
1266            return $default_to;
1267        }
1268
1269        // Check that source is of type Feedback_Source
1270        if ( ! $source instanceof Feedback_Source ) {
1271            return $default_to;
1272        }
1273
1274        if ( absint( $source->get_id() ) === 0 ) {
1275            return $default_to;
1276        }
1277
1278        $post = get_post( $source->get_id() );
1279        if ( ! $post ) {
1280            return $default_to;
1281        }
1282
1283        return self::get_default_to_for_editor( $post );
1284    }
1285
1286    /**
1287     * Get the default recipient email address for the editor, together with the rule that produced it.
1288     *
1289     * The editor needs to explain why an address is being suggested, not merely what it is, so the
1290     * resolution branch is returned alongside the address instead of being discarded.
1291     *
1292     * @param mixed|null $post Optional post data (object or array).
1293     *
1294     * @return array{to: string, source: string} The address, and its source: 'post_author' or 'site_admin'.
1295     *
1296     * @since 7.24.0
1297     */
1298    public static function get_default_to_with_source( $post = null ) {
1299        $site_admin = array(
1300            'to'     => get_option( 'admin_email' ),
1301            'source' => 'site_admin',
1302        );
1303
1304        if ( empty( $post ) ) {
1305            return $site_admin;
1306        }
1307
1308        $post_author_id = self::get_post_property( $post, 'post_author' );
1309        $post_id        = self::get_post_property( $post, 'ID' );
1310        $post_author    = get_user( $post_author_id );
1311
1312        // Check that the user has edit permissions for this blog and has an email address
1313        if ( empty( $post_author ) || empty( $post_author->user_email ) ) {
1314            return $site_admin;
1315        }
1316
1317        // Check that the user is still a member of the blog.
1318        if ( ! is_user_member_of_blog( $post_author_id ) ) {
1319            return $site_admin;
1320        }
1321
1322        // Check that the author can still edit the post or page.
1323        if ( user_can( $post_author_id, 'edit_post', $post_id ) ) {
1324            return array(
1325                'to'     => $post_author->user_email,
1326                'source' => 'post_author',
1327            );
1328        }
1329
1330        return $site_admin;
1331    }
1332
1333    /**
1334     * Get the default recipient email address for the contact form based on post data.
1335     *
1336     * This is used when we load the post or page in the editor, and we don't have the post author ID directly.
1337     *
1338     * @param mixed|null $post Optional post data (object or array).
1339     *
1340     * @return string The default recipient email address.
1341     */
1342    public static function get_default_to_for_editor( $post = null ) {
1343        $resolved = self::get_default_to_with_source( $post );
1344
1345        return $resolved['to'];
1346    }
1347
1348    /**
1349     * Safely get a property from post data (object or array).
1350     *
1351     * @param mixed  $post_data Post data (object or array).
1352     * @param string $property  Property name to get.
1353     *
1354     * @return mixed|null The property value or null if not found.
1355     */
1356    public static function get_post_property( $post_data, $property ) {
1357        if ( ! $post_data ) {
1358            return null;
1359        }
1360
1361        if ( is_object( $post_data ) && isset( $post_data->$property ) ) {
1362            return $post_data->$property;
1363        } elseif ( is_array( $post_data ) && isset( $post_data[ $property ] ) ) {
1364            return $post_data[ $property ];
1365        }
1366
1367        return null;
1368    }
1369
1370    /**
1371     * Get the default subject for the contact form.
1372     *
1373     * @param array $attributes The attributes of the contact form.
1374     * @param mixed $post_data Optional post data (object or array).
1375     *
1376     * @return string The default subject for the contact form.
1377     */
1378    public static function get_default_subject( $attributes, $post_data = null ) {
1379        global $post;
1380        // Get the default subject for the contact form.
1381        $default_subject = '[' . get_option( 'blogname' ) . ']';
1382
1383        // Get post title safely
1384        $post_title = self::get_post_property( $post_data, 'post_title' );
1385
1386        if ( ! $post_title && $post ) {
1387            $post_title = self::get_post_property( $post, 'post_title' );
1388        }
1389
1390        if ( $post_title ) {
1391            $default_subject = sprintf(
1392                // translators: the blog name and post title.
1393                _x( '%1$s %2$s', '%1$s = blog name, %2$s = post title', 'jetpack-forms' ),
1394                $default_subject,
1395                Contact_Form_Plugin::strip_tags( $post_title )
1396            );
1397        }
1398
1399        if ( ! empty( $attributes['widget'] ) && $attributes['widget'] ) {
1400            // translators: '%1$s the blog name
1401            $default_subject = sprintf( _x( '%1$s Sidebar', '%1$s = blog name', 'jetpack-forms' ), $default_subject );
1402        }
1403
1404        return $default_subject;
1405    }
1406
1407    /**
1408     * Store shortcode content for recall later
1409     *  - used to receate shortcode when user uses do_shortcode
1410     *
1411     * @deprecated 5.0.0
1412     */
1413    public static function store_shortcode() {
1414        _deprecated_function( __METHOD__, '5.0.0', 'Contact_Form_Plugin::store_shortcode()' );
1415    }
1416
1417    /**
1418     * Toggle for printing the grunion.css stylesheet
1419     *
1420     * @param bool $style - the CSS style.
1421     *
1422     * @return bool
1423     */
1424    public static function style( $style ) {
1425        $previous_style = self::$style;
1426        self::$style    = (bool) $style;
1427        return $previous_style;
1428    }
1429
1430    /**
1431     * Turn on printing of grunion.css stylesheet
1432     *
1433     * @see ::style()
1434     *
1435     * @return bool
1436     */
1437    public static function style_on() {
1438        return self::style( true );
1439    }
1440    /**
1441     * Adds a quick link to the admin bar for the contact form entries.
1442     *
1443     * @param \WP_Admin_Bar $admin_bar The admin bar object.
1444     */
1445    public static function add_quick_link_to_admin_bar( \WP_Admin_Bar $admin_bar ) {
1446
1447        if ( ! current_user_can( 'edit_pages' ) ) {
1448            return;
1449        }
1450
1451        $url = Forms_Dashboard::get_forms_admin_url();
1452
1453        $icon = '<svg class="ab-icon" style="top: 2px; width: 20px; height: 20px; fill: currentColor;" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="m13 7.5 h 5 v 1.5 h -5 v -1.5z"/><path d="m13 15 h 5 v 1.5 h -5 v -1.5z"/><path d="m19.01,3H4.99c-1.1,0-1.99.89-1.99,1.99v14.02c0,1.1.89,1.99,1.99,1.99h14.02c1.1,0,1.99-.89,1.99-1.99V4.99c0-1.1-.89-1.99-1.99-1.99Zm.49,15.99c0,.28-.23.51-.51.51H5.01c-.28,0-.51-.23-.51-.51V5.01c0-.28.23-.51.51-.51h13.98c.28,0,.51.23.51.51v13.98Z"/><path d="m9.46,13h-1.92c-.85,0-1.54.69-1.54,1.54v1.92c0,.85.69,1.54,1.54,1.54h1.92c.85,0,1.54-.69,1.54-1.54v-1.92c0-.85-.69-1.54-1.54-1.54Zm.04,3.5h-2v-2h2v2Z"/><path d="m9.46,6h-1.92c-.85,0-1.54.69-1.54,1.54v1.92c0,.85.69,1.54,1.54,1.54h1.92c.85,0,1.54-.69,1.54-1.54v-1.92c0-.85-.69-1.54-1.54-1.54Zm.04,3.5h-2v-2h2v2Z"/></svg>';
1454
1455        $admin_bar->add_menu(
1456            array(
1457                'id'     => 'jetpack-forms',
1458                'parent' => null,
1459                'group'  => null,
1460                'title'  => $icon . '<span class="ab-label">' . esc_html__( 'Form Responses', 'jetpack-forms' ) . '</span>',
1461                'href'   => $url,
1462                'meta'   => array(
1463                    'title' => esc_attr__( 'View form responses from this page', 'jetpack-forms' ),
1464                ),
1465            )
1466        );
1467
1468        // The icon SVG fills with currentColor. On desktop it inherits the item's full-brightness text color, so
1469        // it renders brighter than the native admin bar icons -- core dims those to rgba(240,246,252,0.6) via
1470        // `.ab-icon::before` rules our SVG can't match. Fade it to 0.6 opacity to match, and restore full opacity
1471        // on hover/focus; using opacity (not a hardcoded color) keeps the hover state tracking the user's admin
1472        // color scheme accent, like the native icons. On mobile (<=782px) core instead dims the item's own text
1473        // color, which the SVG already inherits, so reset opacity to 1 there to avoid dimming the icon twice.
1474        //
1475        // The <=782px block also handles core hiding every non-allowlisted top-level item on mobile: re-show ours
1476        // and size the icon to the native touch target (52px box, centered 28px glyph). The `.ab-icon` sizing uses
1477        // !important because the SVG carries its desktop sizing in an inline style attribute that otherwise wins.
1478        echo '<style>' .
1479            '#wpadminbar #wp-admin-bar-jetpack-forms .ab-icon{opacity:0.6;}' .
1480            '#wpadminbar #wp-admin-bar-jetpack-forms:hover .ab-icon,' .
1481            '#wpadminbar #wp-admin-bar-jetpack-forms .ab-item:focus .ab-icon{opacity:1;}' .
1482            '@media screen and (max-width: 782px){' .
1483            '#wpadminbar li#wp-admin-bar-jetpack-forms{display:block;}' .
1484            '#wpadminbar li#wp-admin-bar-jetpack-forms>.ab-item{display:flex;align-items:center;justify-content:center;width:52px;padding:0;}' .
1485            '#wpadminbar li#wp-admin-bar-jetpack-forms .ab-icon{width:28px!important;height:28px!important;top:0!important;margin:0!important;opacity:1;}' .
1486            '}</style>';
1487    }
1488
1489    /**
1490     * The contact-form shortcode processor
1491     *
1492     * @param array       $attributes Key => Value pairs as parsed by shortcode_parse_atts().
1493     * @param string|null $content The shortcode's inner content: [contact-form]$content[/contact-form].
1494     * @param array       $context An array of context data for the form.
1495     *
1496     * @return string HTML for the concat form.
1497     */
1498    public static function parse( $attributes, $content, $context = array() ) {
1499        global $post, $page, $multipage; // $page is used in the contact-form submission redirect
1500        if ( Settings::is_syncing() ) {
1501            return '';
1502        }
1503
1504        // Handle ref attribute - load form from jetpack_form post
1505        if ( is_array( $attributes ) && isset( $attributes['ref'] ) ) {
1506            $ref_id = absint( $attributes['ref'] );
1507            if ( $ref_id > 0 ) {
1508                return self::render_synced_form( $ref_id );
1509            } else {
1510                return '';
1511            }
1512        }
1513
1514        if ( isset( $GLOBALS['grunion_block_template_part_id'] ) ) {
1515            self::style_on();
1516            if ( is_array( $attributes ) ) {
1517                $attributes['block_template_part'] = $GLOBALS['grunion_block_template_part_id'];
1518            }
1519        }
1520
1521        if ( is_singular() ) {
1522            add_action( 'admin_bar_menu', array( __CLASS__, 'add_quick_link_to_admin_bar' ), 100 ); // We use priority 100 so that the link that is added gets added after the "Edit Page" link.
1523        }
1524        $plugin               = Contact_Form_Plugin::init();
1525        $attributes['widget'] = $plugin->get_current_widget_context();
1526        // Create a new Contact_Form object (this class)
1527        if ( self::$ref_id ) {
1528            $attributes['ref'] = self::$ref_id;
1529        }
1530
1531        $form = new Contact_Form( $attributes, $content );
1532        Contact_Form_Plugin::reset_step();
1533
1534        $id = $form->get_attribute( 'id' );
1535
1536        if ( ! $id ) { // something terrible has happened
1537            return '[contact-form]';
1538        }
1539
1540        if ( is_feed() ) {
1541            return '[contact-form]';
1542        }
1543
1544        self::$last = $form;
1545
1546        // Enqueue the grunion.css stylesheet if self::$style allows it
1547        if ( self::$style && ( empty( $_REQUEST['action'] ) || $_REQUEST['action'] !== 'grunion_shortcode_to_json' ) ) {
1548            // Enqueue the style here instead of printing it, because if some other plugin has run the_post()+rewind_posts(),
1549            // (like VideoPress does), the style tag gets "printed" the first time and discarded, leaving the contact form unstyled.
1550            // when WordPress does the real loop.
1551            wp_enqueue_style( 'grunion.css' );
1552            wp_enqueue_script( 'accessible-form' );
1553        }
1554
1555        $version = \JETPACK__VERSION;
1556
1557        // Extra cache busting strategy for view.js, seems they are left out of cache clearing on deploys
1558        $asset_file = plugin_dir_path( __FILE__ ) . 'dist/modules/form/view.asset.php';
1559        $asset      = file_exists( $asset_file ) ? require $asset_file : null;
1560
1561        if ( $asset && isset( $asset['version'] ) ) {
1562            $version = $asset['version'];
1563        }
1564
1565        $config = array(
1566            'error_types'     => array(
1567                'is_required'        => __( 'This field is required.', 'jetpack-forms' ),
1568                'invalid_form_empty' => __( 'The form you are trying to submit is empty.', 'jetpack-forms' ),
1569                'invalid_form'       => __( 'Please fill out the form correctly.', 'jetpack-forms' ),
1570                'network_error'      => __( 'Connection issue while submitting the form. Check that you are connected to the Internet and try again.', 'jetpack-forms' ),
1571            ),
1572            'admin_ajax_url'  => admin_url( 'admin-ajax.php' ),
1573            // Translated here because the interactivity module is a script module with no
1574            // i18n dependency, and the string has to match what was rendered server-side.
1575            'unchecked_label' => __( 'No', 'jetpack-forms' ),
1576        );
1577        wp_interactivity_config( 'jetpack/form', $config );
1578        \wp_enqueue_script_module(
1579            'jp-forms-view',
1580            plugins_url( 'dist/modules/form/view.js', dirname( __DIR__ ) ),
1581            array( '@wordpress/interactivity' ),
1582            $version
1583        );
1584
1585        $is_single_input_form = is_array( $form->fields ) && count( $form->fields ) === 1;
1586        $is_flex_layout       = isset( $attributes['layout']['type'] ) && $attributes['layout']['type'] === 'flex';
1587        $is_nowrap_layout     = isset( $attributes['layout']['flexWrap'] ) && $attributes['layout']['flexWrap'] === 'nowrap';
1588        $is_forced_horizontal = $is_flex_layout && $is_nowrap_layout
1589            && ( ! isset( $attributes['layout']['orientation'] ) || $attributes['layout']['orientation'] === 'horizontal' );
1590
1591        $extra_container_classes = array();
1592        if ( $is_forced_horizontal ) {
1593            $extra_container_classes[] = 'is-forced-horizontal-form';
1594        }
1595        if ( $is_single_input_form ) {
1596            $extra_container_classes[] = 'is-single-input-form';
1597        }
1598        $container_classes_string = self::get_block_container_classes( $attributes, $extra_container_classes );
1599
1600        $is_reload_after_success = isset( $_GET['contact-form-id'] )
1601        && (int) $_GET['contact-form-id'] === (int) self::$last->get_attribute( 'id' )
1602        && isset( $_GET['contact-form-sent'] )
1603        && isset( $_GET['contact-form-hash'] )
1604        && is_string( $_GET['contact-form-hash'] )
1605        && hash_equals( $form->hash, wp_unslash( $_GET['contact-form-hash'] ) );
1606
1607        $feedback_id           = 0;
1608        $is_reload_nonce_valid = false;
1609
1610        if ( $is_reload_after_success ) {
1611            $feedback_id           = (int) $_GET['contact-form-sent'];
1612            $is_reload_nonce_valid = isset( $_GET['_wpnonce'] )
1613                && wp_verify_nonce( sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ), "contact-form-sent-{$feedback_id}" );
1614        }
1615
1616        $max_steps = 0;
1617        if ( preg_match_all( '/data-wp-context=[\'"]?{"step":(\d+)}[\'"]?/', $content, $matches ) ) {
1618            if ( ! empty( $matches[1] ) ) {
1619                $max_steps = max( array_map( 'intval', $matches[1] ) );
1620            }
1621        }
1622
1623        $is_multistep = $max_steps > 0;
1624        $element_id   = 'jp-form-' . esc_attr( $form->hash );
1625
1626        // Initial data used to render the success message when the page is reloaded after a successful submission
1627        // Don't show the feedback details unless the nonce matches
1628        $submission_data = null;
1629
1630        if ( $is_reload_after_success && $is_reload_nonce_valid ) {
1631            $response = Feedback::get( (int) $_GET['contact-form-sent'] );
1632
1633            if ( $response ) {
1634                $submission_data = $response->get_compiled_fields( 'web', 'collection' );
1635            }
1636        }
1637
1638        $formatted_submission_data = $submission_data ? self::format_submission_data( $submission_data ) : array();
1639        $submission_success        = $form->is_response_without_reload_enabled && $is_reload_after_success;
1640        $has_custom_redirect       = $form->has_custom_redirect();
1641
1642        $default_context = array(
1643            'formId'                  => $id,
1644            'formHash'                => $form->hash,
1645            'showErrors'              => $form->has_errors(), // We toggle this to true when we want to show the user errors right away.
1646            'errors'                  => array(), // This should be a associative array.
1647            'fields'                  => array(),
1648            'isMultiStep'             => $is_multistep, // Whether the form is a multistep form.
1649            'useAjax'                 => $form->is_response_without_reload_enabled && ! $has_custom_redirect,
1650            'submissionData'          => $submission_data,
1651            'formattedSubmissionData' => $formatted_submission_data,
1652            'submissionSuccess'       => $submission_success,
1653            'submissionError'         => null,
1654            'elementId'               => $element_id,
1655            'isSingleInputForm'       => $is_single_input_form,
1656            'isForcedHorizontal'      => $is_forced_horizontal,
1657            'conditionalLogic'        => $form->get_conditional_logic_context(),
1658        );
1659
1660        if ( $is_multistep ) {
1661            $multistep_context = array(
1662                'currentStep' => isset( $_GET[ $id . '-step' ] ) ? absint( $_GET[ $id . '-step' ] ) : 1,
1663                'maxSteps'    => $max_steps,
1664                'direction'   => 'forward', // Default direction for animations
1665                'transition'  => $form->get_attribute( 'stepTransition' ) ? $form->get_attribute( 'stepTransition' ) : 'fade-slide', // Transition style for step animations
1666            );
1667
1668            if ( ! is_array( $context ) ) {
1669                $context = array();
1670            }
1671            $context = array_merge( $context, $multistep_context );
1672        }
1673
1674        $context = is_array( $context ) ? array_merge( $default_context, $context ) : $default_context;
1675
1676        $r  = '';
1677        $r .= "<div data-test='contact-form'
1678            id='contact-form-$id'
1679            class='{$container_classes_string}'
1680            data-wp-interactive='jetpack/form' " . wp_interactivity_data_wp_context( $context ) . "
1681            data-wp-on--focusin=\"actions.trackFirstInteraction\"
1682            data-wp-watch--scroll-to-wrapper=\"callbacks.scrollToWrapper\"
1683        >\n";
1684
1685        if ( $form->is_response_without_reload_enabled ) {
1686            $r .= self::render_ajax_success_wrapper( $form, $submission_success, $formatted_submission_data );
1687        }
1688
1689        if ( $form->has_errors() ) {
1690            // There are errors.  Display them
1691            $r .= "<div class='form-error'>\n<h3>" . __( 'Error!', 'jetpack-forms' ) . "</h3>\n<ul class='form-errors'>\n";
1692            foreach ( $form->get_error_messages() as $message ) {
1693                $r .= "\t<li class='form-error-message'>" . esc_html( $message ) . "</li>\n";
1694            }
1695            $r .= "</ul>\n</div>\n\n";
1696        }
1697
1698        if ( $is_reload_after_success && $form->is_response_without_reload_enabled ) {
1699            $r .= '<noscript>';
1700            $r .= self::render_noscript_success_message( $is_reload_nonce_valid, $feedback_id, $form );
1701            $r .= '</noscript>';
1702        }
1703
1704        if ( $is_reload_after_success && ! $form->is_response_without_reload_enabled ) {
1705            // The contact form was submitted.  Show the success message/results.
1706            $r .= self::render_noscript_success_message( $is_reload_nonce_valid, $feedback_id, $form );
1707        } else {
1708            // Nothing special - show the normal contact form
1709            if ( $form->get_attribute( 'widget' )
1710                || $form->get_attribute( 'block_template' )
1711                || $form->get_attribute( 'block_template_part' ) ) {
1712                // Submit form to the current URL
1713                $url = remove_query_arg( array( 'contact-form-id', 'contact-form-sent', 'action', '_wpnonce' ) );
1714            } else {
1715                // Submit form to the post permalink
1716                $url = get_permalink();
1717                if ( $multipage && $page ) {
1718                    $url = add_query_arg( 'page', $page, $url );
1719                }
1720            }
1721
1722            // For SSL/TLS page. See RFC 3986 Section 4.2
1723            $url = set_url_scheme( $url );
1724
1725            // May eventually want to send this to admin-post.php...
1726            /**
1727             * Filter the contact form action URL.
1728             *
1729             * @module contact-form
1730             *
1731             * @since 1.3.1
1732             *
1733             * @param string $contact_form_id Contact form post URL.
1734             * @param $post $GLOBALS['post'] Post global variable.
1735             * @param int $id Contact Form ID.
1736             */
1737            $url                     = apply_filters( 'grunion_contact_form_form_action', $url, $GLOBALS['post'], $id, $page );
1738            $has_submit_button_block = str_contains( $content, 'wp-block-jetpack-button' ) || str_contains( $content, 'wp-block-button' );
1739            $form_classes            = 'contact-form commentsblock jetpack-contact-form__form';
1740            if ( $submission_success ) {
1741                $form_classes .= ' submission-success';
1742            }
1743
1744            if ( isset( $attributes['layout'] ) ) {
1745                $form_classes .= ' has-jetpack-form-layout';
1746            } else {
1747                $form_classes .= ' has-no-jetpack-form-layout';
1748            }
1749
1750            $post_title           = $post->post_title ?? '';
1751            $form_accessible_name = ! empty( $attributes['formTitle'] ) ? $attributes['formTitle'] : $post_title;
1752            $form_aria_label      = isset( $form_accessible_name ) && ! empty( $form_accessible_name ) ? 'aria-label="' . esc_attr( $form_accessible_name ) . '"' : '';
1753
1754            $r .= "<form action='" . esc_url( $url ) . "'
1755                id='" . $element_id . "'
1756                method='post'
1757                class='" . esc_attr( $form_classes ) . "' $form_aria_label
1758                data-wp-on--submit=\"actions.onFormSubmit\"
1759                data-wp-on--reset=\"actions.onFormReset\"
1760                data-wp-class--submission-success=\"context.submissionSuccess\"
1761                data-wp-class--is-first-step=\"state.isFirstStep\"
1762                data-wp-class--is-last-step=\"state.isLastStep\"
1763                data-wp-class--is-ajax-form=\"context.useAjax\"
1764                novalidate >\n";
1765
1766            if ( $is_multistep ) { // This makes the "enter" key work in multi-step forms as expected.
1767                $r .= '<input type="submit" style="display: none;" />';
1768            }
1769            $r .= "<input type='hidden' name='jetpack_contact_form_jwt' value='" . esc_attr( $form->get_jwt() ) . "' />\n";
1770            // Left empty on purpose: the view script fills this in on submit. An empty
1771            // value is stored as null so "never interacted with" stays distinguishable
1772            // from "filled out in under a second".
1773            $r .= "<input type='hidden' name='" . esc_attr( Feedback::FORM_FILL_DURATION_FIELD ) . "' value='' />\n";
1774            $r .= $form->body;
1775
1776            if ( $is_multistep ) {
1777                $r = preg_replace( '/<div class="wp-block-jetpack-form-step-navigation__wrapper/', self::render_error_wrapper() . ' <div class="wp-block-jetpack-form-step-navigation__wrapper', $r, 1 );
1778            } elseif ( $has_submit_button_block ) {
1779                $r = self::prepare_submit_button( $r );
1780                // Place the error wrapper before the FIRST button block only to avoid duplicates (e.g., navigation buttons in multistep forms).
1781                // Replace only the first occurrence of a wp-block-jetpack-button prepending it with the error wrapper.
1782                // Fallback with same strategy for new core button blocks.
1783                if ( $is_forced_horizontal || $is_single_input_form ) {
1784                    // When user forced a horizontal layout, place the error wrapper
1785                    // after the form body.
1786                    $r .= self::render_error_wrapper( 'is-horizontal' );
1787                } else {
1788                    // Place the error wrapper before the FIRST button block only to avoid duplicates (e.g., navigation buttons in multistep forms).
1789                    // Replace only the first occurrence.
1790                    $r = preg_replace( '/<div class="wp-block-jetpack-button/', self::render_error_wrapper() . ' <div class="wp-block-jetpack-button', $r, 1 );
1791                    if ( str_contains( $r, 'wp-block-button' ) ) {
1792                        $r = preg_replace( '/<div class="wp-block-button/', self::render_error_wrapper() . ' <div class="wp-block-button', $r, 1 );
1793                    }
1794                }
1795            }
1796
1797            // In new versions of the contact form block the button is an inner block
1798            // so the button does not need to be constructed server-side.
1799            if ( ! $has_submit_button_block ) {
1800                $r .= "\t<p class='contact-submit'>\n";
1801
1802                $gutenberg_submit_button_classes = '';
1803                if ( ! empty( $attributes['submitButtonClasses'] ) ) {
1804                    $gutenberg_submit_button_classes = ' ' . $attributes['submitButtonClasses'];
1805                }
1806
1807                /**
1808                 * Filter the contact form submit button class attribute.
1809                 *
1810                 * @module contact-form
1811                 *
1812                 * @since 6.6.0
1813                 *
1814                 * @param string $class Additional CSS classes for button attribute.
1815                 */
1816                $submit_button_class = apply_filters( 'jetpack_contact_form_submit_button_class', 'pushbutton-wide' . $gutenberg_submit_button_classes );
1817
1818                $submit_button_styles = '';
1819                if ( ! empty( $attributes['customBackgroundButtonColor'] ) ) {
1820                    $submit_button_styles .= 'background-color: ' . $attributes['customBackgroundButtonColor'] . '; ';
1821                }
1822                if ( ! empty( $attributes['customTextButtonColor'] ) ) {
1823                    $submit_button_styles .= 'color: ' . $attributes['customTextButtonColor'] . ';';
1824                }
1825                if ( ! empty( $attributes['submitButtonText'] ) ) {
1826                    $submit_button_text = $attributes['submitButtonText'];
1827                } else {
1828                    $submit_button_text = $form->get_attribute( 'submit_button_text' );
1829                }
1830
1831                $r .= self::render_error_wrapper();
1832                $r .= "\t\t<button type='submit' class='" . esc_attr( $submit_button_class ) . "'";
1833                if ( ! empty( $submit_button_styles ) ) {
1834                    $r .= " style='" . esc_attr( $submit_button_styles ) . "'";
1835                }
1836                $r .= '>';
1837                $r .= wp_kses(
1838                    $submit_button_text,
1839                    self::$allowed_html_tags_for_submit_button
1840                ) . '</button>';
1841            }
1842
1843            if ( is_user_logged_in() ) {
1844                $r .= "\t\t" . wp_nonce_field( 'contact-form_' . $id, '_wpnonce', true, false ) . "\n"; // nonce and referer
1845            }
1846
1847            if ( isset( $attributes['hasFormSettingsSet'] ) && $attributes['hasFormSettingsSet'] ) {
1848                $r .= "\t\t<input type='hidden' name='is_block' value='1' />\n";
1849            }
1850            $r .= "\t\t<input type='hidden' name='contact-form-id' value='$id' />\n";
1851            $r .= "\t\t<input type='hidden' name='action' value='grunion-contact-form' />\n";
1852            $r .= "\t\t<input type='hidden' name='contact-form-hash' value='" . esc_attr( $form->hash ) . "' />\n";
1853
1854            if ( ! $has_submit_button_block ) {
1855                $r .= "\t</p>\n";
1856            }
1857
1858            $r .= "</form>\n";
1859        }
1860
1861        $r .= '</div>';
1862
1863        // Surface an admin-only warning above the form when nothing will capture its responses.
1864        $r = self::render_not_collecting_notice( $attributes ) . $r;
1865
1866        /**
1867         * Filter the contact form, allowing plugins to modify the HTML.
1868         *
1869         * @module contact-form
1870         *
1871         * @since 10.2.0
1872         *
1873         * @param string $r The contact form HTML.
1874         */
1875        return apply_filters( 'jetpack_contact_form_html', $r );
1876    }
1877
1878    /**
1879     * Prepare the submit button for the contact form.
1880     * Add interactivity attributes to submit buttons identified by:
1881     * - Legacy: type="submit" attribute
1882     * - New: is-submit or form-button-submit class
1883     *
1884     * @param string $content - the content of the submit button.
1885     *
1886     * @return string - the prepared content of the submit button.
1887     */
1888    private static function prepare_submit_button( $content ) {
1889        if ( ! class_exists( \WP_HTML_Tag_Processor::class ) ) {
1890            return $content;
1891        }
1892
1893        $p = new \WP_HTML_Tag_Processor( $content );
1894        while ( $p->next_tag( 'button' ) ) {
1895            $is_submit_by_type  = 'submit' === $p->get_attribute( 'type' );
1896            $is_submit_by_class = $p->has_class( 'is-submit' ) || $p->has_class( 'form-button-submit' );
1897
1898            if ( $is_submit_by_type || $is_submit_by_class ) {
1899                self::add_submit_button_interactivity_attributes( $p );
1900            }
1901        }
1902
1903        return $p->get_updated_html();
1904    }
1905
1906    /**
1907     * Adds Interactivity API attributes to the current element in a WP_HTML_Tag_Processor.
1908     *
1909     * Sets data-wp-class, data-wp-bind--aria-disabled, and data-wp-bind--disabled
1910     * on the submit button so the Interactivity API can toggle visual feedback
1911     * (spinner class, disabled state) while the form is submitting.
1912     *
1913     * Called from both single-step forms (prepare_submit_button) and multi-step
1914     * forms (gutenblock_render_form_step_navigation) to keep the attribute list
1915     * in one place.
1916     *
1917     * @param \WP_HTML_Tag_Processor $processor Tag processor positioned on a <button> element.
1918     * @return void
1919     */
1920    public static function add_submit_button_interactivity_attributes( $processor ) {
1921        if ( ! $processor || ! is_a( $processor, \WP_HTML_Tag_Processor::class ) ) {
1922            return;
1923        }
1924        $processor->set_attribute( 'data-wp-class--is-submitting', 'state.isSubmitting' );
1925        $processor->set_attribute( 'data-wp-bind--aria-disabled', 'state.isAriaDisabled' );
1926        $processor->set_attribute( 'data-wp-bind--disabled', 'state.isAriaDisabled' );
1927    }
1928
1929    /**
1930     * Renders the success message for the contact form when js is disabled or not desired.
1931     *
1932     * @param bool         $is_reload_nonce_valid - whether the nonce is valid.
1933     * @param int          $feedback_id - the feedback ID.
1934     * @param Contact_Form $form - the contact form.
1935     *
1936     * @return string HTML string for the success message.
1937     */
1938    private static function render_noscript_success_message( $is_reload_nonce_valid, $feedback_id, $form ) {
1939        $back_url        = remove_query_arg( array( 'contact-form-id', 'contact-form-sent', '_wpnonce', 'contact-form-hash' ) );
1940        $contact_form_id = sanitize_text_field( wp_unslash( $_GET['contact-form-id'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1941        $disable_go_back = $form->get_attribute( 'disableGoBack' );
1942
1943        $message = '';
1944
1945        $message .= '<style>
1946            .contact-form-ajax-submission {
1947                display: none;
1948            }
1949
1950            #contact-form-' . $contact_form_id . ' form.contact-form {
1951                display: none;
1952            }
1953        </style>';
1954
1955        $message        .= '<div class="contact-form-submission">';
1956        $success_message = '';
1957
1958        if ( ! $disable_go_back ) {
1959            $success_message = '<p class="go-back-message"> <a class="link" href="' . esc_url( $back_url ) . '">' . esc_html__( '← Back', 'jetpack-forms' ) . '</a> </p>';
1960        }
1961
1962        $success_message .= '<h4 id="contact-form-success-header">' . esc_html( $form->get_attribute( 'customThankyouHeading' ) ) . "</h4>\n\n";
1963
1964        // Don't show the feedback details unless the nonce matches
1965        if ( $is_reload_nonce_valid ) {
1966            $success_message .= self::success_message( $feedback_id, $form );
1967        }
1968
1969        /**
1970         * Filter the message returned after a successful contact form submission.
1971         *
1972         * @module contact-form
1973         *
1974         * @since 1.3.1
1975         *
1976         * @param string $message Success message.
1977         */
1978        $message .= apply_filters( 'grunion_contact_form_success_message', $success_message );
1979        $message .= '</div>';
1980
1981        return $message;
1982    }
1983
1984    /**
1985     * Helper function to format the submission data for the success message.
1986     *
1987     * @param array $data The submission data (in 'collection' format with type).
1988     *
1989     * @return array The formatted submission data.
1990     */
1991    private static function format_submission_data( $data ) {
1992        $formatted_submission_data = array();
1993
1994        foreach ( $data as $field_data ) {
1995            $url    = self::get_url( $field_data['value'] );
1996            $images = self::get_images( $field_data['value'] );
1997            $files  = self::get_files( $field_data['value'] );
1998            $rating = self::get_rating( $field_data['value'] );
1999            $type   = $field_data['type'] ?? 'text';
2000
2001            $formatted_submission_data[] = array(
2002                'label'          => Util::maybe_add_colon_to_label( $field_data['label'] ),
2003                'value'          => self::get_submission_display_value( $field_data['value'], $type ),
2004                // The submitted answer, kept beside the label the summary prints. The checkbox
2005                // icon is chosen from it: `is_checked_value()` recognizes only the ASCII `no`
2006                // sentinel, so a translated "No" would read as ticked in every locale whose
2007                // word for it is not "no".
2008                'rawValue'       => $field_data['value'],
2009                'images'         => $images,
2010                'url'            => $url,
2011                'files'          => $files,
2012                'rating'         => $rating,
2013                'type'           => $type,
2014                'showPlainValue' => empty( $url ) && empty( $images ) && empty( $files ) && empty( $rating ),
2015            );
2016        }
2017
2018        return $formatted_submission_data;
2019    }
2020
2021    /**
2022     * The value a submitted field shows in the confirmation summary.
2023     *
2024     * An unticked checkbox submits nothing, so it arrives empty and the summary drew the
2025     * label over a blank line. The email renderer has always said "No" here.
2026     *
2027     * Mirrored by `getSubmissionDisplayValue()` in src/modules/form/helpers.js, which formats
2028     * the same data for an AJAX submission; the two must produce the same string or the
2029     * summary changes as the Interactivity API hydrates it.
2030     *
2031     * @param mixed  $value The submitted value.
2032     * @param string $type  The field type.
2033     *
2034     * @return mixed The value to display.
2035     */
2036    private static function get_submission_display_value( $value, $type ) {
2037        if ( 'checkbox' === $type && ! Feedback_Field::is_checked_value( $value ) ) {
2038            return __( 'No', 'jetpack-forms' );
2039        }
2040
2041        return self::maybe_transform_value( $value );
2042    }
2043
2044    /**
2045     * Get the URL from a URL field value if present.
2046     *
2047     * @param mixed $value The field value.
2048     *
2049     * @return string|null The URL if this is a URL field, null otherwise.
2050     */
2051    private static function get_url( $value ) {
2052        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'url' && ! empty( $value['url'] ) ) {
2053            $url = $value['url'];
2054
2055            // Prepend https:// if no protocol is specified.
2056            if ( ! preg_match( '#^https?://#i', $url ) ) {
2057                $url = 'https://' . $url;
2058            }
2059
2060            // Validate URL - only http and https protocols are allowed for safety.
2061            $url = esc_url( $url, array( 'http', 'https' ) );
2062            return ! empty( $url ) ? $url : null;
2063        }
2064        return null;
2065    }
2066
2067    /**
2068     * Get the rating data from a rating field value if present.
2069     *
2070     * @param mixed $value The field value.
2071     *
2072     * @return array|null The rating data if this is a rating field, null otherwise.
2073     */
2074    private static function get_rating( $value ) {
2075        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'rating' ) {
2076            $rating     = isset( $value['rating'] ) ? (int) $value['rating'] : 0;
2077            $max_rating = isset( $value['maxRating'] ) ? (int) $value['maxRating'] : 5;
2078            $icon_style = $value['iconStyle'] ?? 'stars';
2079
2080            // Generate translated screen reader text.
2081            $icon_label = 'hearts' === $icon_style
2082                ? _n( 'heart', 'hearts', $max_rating, 'jetpack-forms' )
2083                : _n( 'star', 'stars', $max_rating, 'jetpack-forms' );
2084
2085            return array(
2086                'rating'           => $rating,
2087                'maxRating'        => $max_rating,
2088                'iconStyle'        => $icon_style,
2089                /* translators: 1: rating value, 2: maximum rating, 3: icon type (stars or hearts) */
2090                'screenReaderText' => sprintf( __( 'Rating: %1$d out of %2$d %3$s', 'jetpack-forms' ), $rating, $max_rating, $icon_label ),
2091            );
2092        }
2093        return null;
2094    }
2095
2096    /**
2097     * Get the icon key for a submitted field.
2098     *
2099     * Checkbox fields reflect the respondent's answer, so an unchecked box gets
2100     * the empty-square icon rather than the ticked one. Every other field type
2101     * keys off the type alone. Mirrors `getFieldTypeIconKey()` in
2102     * src/modules/form/field-type-icons.js, which must resolve to the same key
2103     * for AJAX submissions.
2104     *
2105     * @param string $field_type The field type.
2106     * @param mixed  $value      The submitted value.
2107     *
2108     * @return string The icon key.
2109     */
2110    private static function get_field_type_icon_key( $field_type, $value = null ) {
2111        if ( 'checkbox' === $field_type && ! Feedback_Field::is_checked_value( $value ) ) {
2112            return 'checkbox:unchecked';
2113        }
2114
2115        return $field_type;
2116    }
2117
2118    /**
2119     * Get the SVG icon for a field type.
2120     *
2121     * @param string $field_type The field type.
2122     * @param mixed  $value      The submitted value, for field types whose icon
2123     *                           depends on the answer as well as the type.
2124     *
2125     * @return string The SVG icon HTML.
2126     */
2127    private static function get_field_type_icon( $field_type, $value = null ) {
2128        // Reject field types that don't fit the expected 'field-{type}' naming
2129        // convention. Valid types are non-empty strings of lowercase letters,
2130        // digits, and hyphens starting with a letter.
2131        if ( ! is_string( $field_type ) || ! preg_match( '/^[a-z][a-z0-9-]*$/', $field_type ) ) {
2132            return '';
2133        }
2134
2135        // Map field types that don't follow the 'field-{type}' naming convention.
2136        static $type_exceptions = array(
2137            'phone'             => 'field-telephone',
2138            'telephone'         => 'field-telephone',
2139            'radio'             => 'field-single-choice',
2140            'checkbox-multiple' => 'field-multiple-choice',
2141        );
2142
2143        $block_dir = $type_exceptions[ $field_type ] ?? 'field-' . $field_type;
2144
2145        // State variants live alongside the base icon as 'icon-{variant}.svg'.
2146        $icon_name = 'checkbox:unchecked' === self::get_field_type_icon_key( $field_type, $value )
2147            ? 'icon-unchecked'
2148            : 'icon';
2149
2150        // Cache loaded SVG content to avoid re-reading files.
2151        static $icon_cache = array();
2152
2153        $cache_key = $block_dir . '/' . $icon_name;
2154
2155        if ( ! isset( $icon_cache[ $cache_key ] ) ) {
2156            $svg_file = dirname( __DIR__ ) . '/blocks/' . $block_dir . '/' . $icon_name . '.svg';
2157            $svg      = '';
2158
2159            if ( file_exists( $svg_file ) ) {
2160                $svg = file_get_contents( $svg_file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reading local package file, not a remote URL.
2161            }
2162
2163            if ( $svg ) {
2164                $svg = trim( $svg );
2165
2166                $icon_cache[ $cache_key ] = $svg;
2167            } else {
2168                $icon_cache[ $cache_key ] = '';
2169            }
2170        }
2171
2172        return $icon_cache[ $cache_key ];
2173    }
2174
2175    /**
2176     * Helper function that display the error wrapper.
2177     *
2178     * @param string $classes - the class names to add to the error wrapper.
2179     * @return string HTML string for the error wrapper.
2180     */
2181    private static function render_error_wrapper( $classes = '' ) {
2182        $class_attr = $classes ? ' ' . esc_attr( $classes ) : '';
2183        $html       = '<div class="contact-form__error' . $class_attr . '" data-wp-class--show-errors="state.showFormErrors">';
2184        $html      .= '<span class="contact-form__warning-icon" aria-hidden="true"><i></i></span>';
2185        $html      .= '<span class="contact-form__error-message" tabindex="-1" data-wp-watch="callbacks.focusOnValidationError" data-wp-text="state.getFormErrorMessage"></span>';
2186        $html      .= '<ul aria-label="' . esc_attr__( 'Form errors', 'jetpack-forms' ) . '">
2187                <template data-wp-each="state.getErrorList" data-wp-key="context.item.id">
2188                    <li><a data-wp-bind--href="context.item.anchor" data-wp-on--click="actions.scrollIntoView" data-wp-text="context.item.label"></a></li>
2189                </template>
2190                </ul>';
2191        $html      .= '</div>';
2192
2193        $html .= '<div class="contact-form__error" data-wp-class--show-errors="state.showSubmissionError" data-wp-text="context.submissionError" tabindex="-1" data-wp-watch="callbacks.focusOnSubmissionError"></div>';
2194        return $html;
2195    }
2196
2197    /**
2198     * Renders the success wrapper after a form is submitted without reloading the page.
2199     *
2200     * @param Contact_Form $form - the contact form.
2201     * @param bool         $submission_success - whether the form has already been submitted.
2202     * @param array        $formatted_submission_data - the formatted submission data.
2203     *
2204     * @return string HTML string for the success wrapper.
2205     */
2206    private static function render_ajax_success_wrapper( $form, $submission_success = false, $formatted_submission_data = array() ) {
2207        $classes = 'contact-form-submission contact-form-ajax-submission';
2208
2209        if ( $submission_success ) {
2210            $classes .= ' submission-success';
2211        }
2212
2213        $back_url          = remove_query_arg( array( 'contact-form-id', 'contact-form-sent', '_wpnonce', 'contact-form-hash' ) );
2214        $disable_go_back   = $form->get_attribute( 'disableGoBack' );
2215        $disable_summary   = $form->get_disable_summary();
2216        $confirmation_type = $form->get_confirmation_type();
2217
2218        if ( $confirmation_type === 'redirect' ) {
2219            return '';
2220        }
2221
2222        $html = '<div class="' . esc_attr( $classes ) . '" data-wp-bind--aria-hidden="state.isSuccessMessageAriaHidden" data-wp-class--submission-success="context.submissionSuccess" id="contact-form-success-' . esc_attr( $form->hash ) . '" tabindex="-1" aria-labelledby="contact-form-success-header-' . esc_attr( $form->hash ) . '">';
2223
2224        if ( ! $disable_go_back ) {
2225            $html .= '<p class="go-back-message">';
2226            $html .= '<a class="link" role="button" tabindex="0" data-wp-on--click="actions.goBack" href="' . esc_url( $back_url ) . '">' . esc_html__( '← Back', 'jetpack-forms' ) . '</a>';
2227            $html .= '</p>';
2228        }
2229
2230        $html .=
2231            '<h4 data-wp-bind--aria-hidden="state.isSuccessMessageAriaHidden" id="contact-form-success-header-' . esc_attr( $form->hash ) . '">' . esc_html( $form->get_attribute( 'customThankyouHeading' ) ) .
2232            "</h4>\n\n";
2233
2234        if ( 'text' === $confirmation_type ) {
2235            $raw_message = $form->get_attribute( 'customThankyouMessage' );
2236
2237            if ( $raw_message !== '' ) {
2238                // Add more allowed HTML elements for file download links
2239                $allowed_html = array(
2240                    'br'         => array(),
2241                    'blockquote' => array( 'class' => array() ),
2242                    'p'          => array(),
2243                    'div'        => array(
2244                        'class' => array(),
2245                        'style' => array(),
2246                    ),
2247                    'span'       => array(
2248                        'class' => array(),
2249                        'style' => array(),
2250                    ),
2251                );
2252
2253                $message = wp_kses( $raw_message, $allowed_html );
2254                $message = '<div class="jetpack_forms_contact-form-custom-success-message">' . $message . '</div>';
2255
2256                $html .= $message;
2257            }
2258
2259            if ( ! $disable_summary ) {
2260                $html .= '<template data-wp-each--submission="context.formattedSubmissionData">
2261                    <div class="jetpack_forms_contact-form-success-summary">
2262                        <div class="field-name-wrapper">
2263                            <div class="field-type-icon" data-wp-watch="callbacks.watchFieldTypeIcon"></div>
2264                            <div class="field-name" data-wp-text="context.submission.label" data-wp-bind--hidden="!context.submission.label"></div>
2265                        </div>
2266                        <div class="field-value" data-wp-text="context.submission.value" data-wp-bind--hidden="!context.submission.showPlainValue"></div>
2267                        <a class="field-url" data-wp-bind--href="context.submission.url" data-wp-text="context.submission.value" data-wp-bind--hidden="!context.submission.url" target="_blank" rel="noopener noreferrer"></a>
2268                        <div class="field-rating" data-wp-bind--hidden="!context.submission.rating" data-wp-watch="callbacks.watchRatingIcons"></div>
2269                        <div class="field-images" data-wp-bind--hidden="!context.submission.images">
2270                            <template data-wp-each--image="context.submission.images">
2271                                <div class="field-image-option" data-wp-class--is-empty="!context.image.src">
2272                                    <figure class="field-image-option__image" data-wp-class--is-empty="!context.image.src">
2273                                        <img alt="" data-wp-bind--src="context.image.src" data-wp-bind--hidden="!context.image.src" />
2274                                        <img alt="" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-wp-bind--hidden="context.image.src" />
2275                                    </figure>
2276                                    <div class="field-image-option__label-wrapper">
2277                                        <span class="field-image-option__label-code" data-wp-text="context.image.letterCode"></span>
2278                                        <span class="field-image-option__label" data-wp-text="context.image.label" data-wp-bind--hidden="!context.image.label"></span>
2279                                    </div>
2280                                </div>
2281                            </template>
2282                        </div>
2283                        <div class="field-files" data-wp-bind--hidden="!context.submission.files">
2284                            <template data-wp-each--file="context.submission.files">
2285                                <div class="field-file">
2286                                    <div class="field-file__thumbnail" data-wp-style--background-image="context.file.previewUrl" data-wp-style--mask-image="context.file.iconUrl" data-wp-bind--hidden="!context.file.hasPreview"></div>
2287                                    <svg class="field-file__icon" data-wp-bind--hidden="context.file.hasPreview" width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
2288                                        <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.89 22 5.99 22H18C19.1 22 20 21.1 20 20V8L14 2ZM18 20H6V4H13V9H18V20Z" fill="currentColor"/>
2289                                    </svg>
2290                                    <span class="field-file__name" data-wp-text="context.file.name"></span>
2291                                    <span class="field-file__size" data-wp-text="context.file.size"></span>
2292                                </div>
2293                            </template>
2294                        </div>
2295                    </div>
2296                </template>';
2297
2298                // For each entry in the submission data array, render a div with the label and value.
2299                // Structure must match the template above for proper hydration.
2300                foreach ( $formatted_submission_data as $submission ) {
2301                    $has_url        = ! empty( $submission['url'] );
2302                    $has_images     = ! empty( $submission['images'] );
2303                    $has_files      = ! empty( $submission['files'] );
2304                    $has_rating     = ! empty( $submission['rating'] );
2305                    $show_plain_val = ! $has_url && ! $has_images && ! $has_files && ! $has_rating;
2306                    $field_type     = $submission['type'] ?? 'text';
2307
2308                    $html .= '<div data-wp-each-child class="jetpack_forms_contact-form-success-summary">';
2309
2310                    // field-name-wrapper: contains icon and label.
2311                    $html .= '<div class="field-name-wrapper">';
2312                    // field-type-icon: rendered based on field type and, for checkboxes, the answer.
2313                    // The data-rendered-type attribute enables hydration optimization by allowing
2314                    // the JS callback to skip re-rendering when the icon is already correct.
2315                    // The raw answer, not the printed label -- see `rawValue` above.
2316                    $field_value = $submission['rawValue'] ?? '';
2317                    $icon_key    = self::get_field_type_icon_key( $field_type, $field_value );
2318                    $html       .= '<div class="field-type-icon" data-wp-watch="callbacks.watchFieldTypeIcon" data-rendered-type="' . esc_attr( $icon_key ) . '">' . self::get_field_type_icon( $field_type, $field_value ) . '</div>';
2319                    // field-name: always present.
2320                    $html .= '<div class="field-name" data-wp-text="context.submission.label" data-wp-bind--hidden="!context.submission.label">' . esc_html( $submission['label'] ) . '</div>';
2321                    $html .= '</div>'; // Close field-name-wrapper.
2322
2323                    // field-value: always present, hidden when URL, images, or files exist.
2324                    $html .= '<div class="field-value" data-wp-text="context.submission.value" data-wp-bind--hidden="!context.submission.showPlainValue"';
2325                    $html .= $show_plain_val ? '' : ' hidden';
2326                    $html .= '>' . ( $show_plain_val ? esc_html( $submission['value'] ) : '' ) . '</div>';
2327
2328                    // field-url: always present, hidden when no URL.
2329                    $html .= '<a class="field-url" data-wp-bind--href="context.submission.url" data-wp-text="context.submission.value" data-wp-bind--hidden="!context.submission.url" target="_blank" rel="noopener noreferrer"';
2330                    $html .= $has_url ? ' href="' . esc_attr( $submission['url'] ) . '"' : ' hidden';
2331                    $html .= '>' . ( $has_url ? esc_html( $submission['value'] ) : '' ) . '</a>';
2332
2333                    // Field rating - only visible when rating is present. JS renders the SVG icons.
2334                    $html .= '<div class="field-rating" data-wp-bind--hidden="!context.submission.rating" data-wp-watch="callbacks.watchRatingIcons"';
2335                    $html .= $has_rating ? ' data-rating="' . esc_attr( wp_json_encode( $submission['rating'], JSON_UNESCAPED_SLASHES ) ) . '">' : ' hidden>';
2336                    $html .= '</div>';
2337
2338                    // field-images: always present, hidden when no images.
2339                    $html .= '<div class="field-images" data-wp-bind--hidden="!context.submission.images"';
2340                    $html .= $has_images ? '' : ' hidden';
2341                    $html .= '>';
2342
2343                    if ( $has_images ) {
2344                        foreach ( $submission['images'] as $image ) {
2345                            $image_src         = $image['src'] ?? '';
2346                            $image_letter_code = $image['letterCode'] ?? '';
2347                            $image_label       = $image['label'] ?? '';
2348
2349                            $html .= '<div data-wp-each-child class="field-image-option ' . ( empty( $image_src ) ? 'is-empty' : '' ) . '" data-wp-class--is-empty="!context.image.src">';
2350                            $html .= '<figure class="field-image-option__image ' . ( empty( $image_src ) ? 'is-empty' : '' ) . '" data-wp-class--is-empty="!context.image.src">';
2351                            $html .= '<img alt="" data-wp-bind--src="context.image.src" src="' . esc_attr( $image_src ) . '" data-wp-bind--hidden="!context.image.src"' . ( empty( $image_src ) ? ' hidden' : '' ) . '/>';
2352                            $html .= '<img alt="" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-wp-bind--hidden="context.image.src"' . ( empty( $image_src ) ? '' : ' hidden' ) . '/>';
2353                            $html .= '</figure>';
2354                            $html .= '<div class="field-image-option__label-wrapper">';
2355                            $html .= '<span class="field-image-option__label-code" data-wp-text="context.image.letterCode">' . esc_html( $image_letter_code ) . '</span>';
2356                            $html .= '<span class="field-image-option__label" data-wp-text="context.image.label" data-wp-bind--hidden="!context.image.label"' . ( empty( $image_label ) ? ' hidden' : '' ) . '>' . esc_html( $image_label ) . '</span>';
2357                            $html .= '</div></div>';
2358                        }
2359                    } else {
2360                        // Empty template for hydration when no images.
2361                        $html .= '<template data-wp-each--image="context.submission.images"></template>';
2362                    }
2363
2364                    $html .= '</div>'; // Close field-images.
2365
2366                    // field-files: always present, hidden when no files.
2367                    $html .= '<div class="field-files" data-wp-bind--hidden="!context.submission.files"';
2368                    $html .= $has_files ? '' : ' hidden';
2369                    $html .= '>';
2370
2371                    if ( $has_files ) {
2372                        foreach ( $submission['files'] as $file ) {
2373                            $file_name   = $file['name'] ?? '';
2374                            $file_size   = $file['size'] ?? '';
2375                            $has_preview = $file['hasPreview'] ?? false;
2376
2377                            $html .= '<div data-wp-each-child class="field-file">';
2378                            // Thumbnail for AJAX submissions (has preview data)
2379                            $html .= '<div class="field-file__thumbnail" data-wp-style--background-image="context.file.previewUrl" data-wp-style--mask-image="context.file.iconUrl" data-wp-bind--hidden="!context.file.hasPreview"';
2380                            $html .= $has_preview ? '' : ' hidden';
2381                            $html .= '></div>';
2382                            // SVG fallback for non-AJAX submissions
2383                            $html .= '<svg class="field-file__icon" data-wp-bind--hidden="context.file.hasPreview" width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"';
2384                            $html .= $has_preview ? ' hidden' : '';
2385                            $html .= '>';
2386                            $html .= '<path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.89 22 5.99 22H18C19.1 22 20 21.1 20 20V8L14 2ZM18 20H6V4H13V9H18V20Z" fill="currentColor"/>';
2387                            $html .= '</svg>';
2388                            $html .= '<span class="field-file__name" data-wp-text="context.file.name">' . esc_html( $file_name ) . '</span>';
2389                            $html .= '<span class="field-file__size" data-wp-text="context.file.size">' . esc_html( $file_size ) . '</span>';
2390                            $html .= '</div>';
2391                        }
2392                    } else {
2393                        // Empty template for hydration when no files.
2394                        $html .= '<template data-wp-each--file="context.submission.files"></template>';
2395                    }
2396
2397                    $html .= '</div></div>'; // Close field-files and summary.
2398                }
2399            }
2400        }
2401
2402        $html .= '</div>';
2403        return $html;
2404    }
2405
2406    /**
2407     * Returns a success message to be returned if the form is sent via AJAX.
2408     *
2409     * @param int          $feedback_id - the feedback ID.
2410     * @param Contact_Form $form - the contact form.
2411     *
2412     * @return string $message
2413     */
2414    public static function success_message( $feedback_id, $form ) {
2415        $message           = '';
2416        $disable_summary   = $form->get_disable_summary();
2417        $confirmation_type = $form->get_confirmation_type();
2418
2419        if ( 'text' === $confirmation_type ) {
2420            $raw_message = $form->get_attribute( 'customThankyouMessage' );
2421
2422            if ( $raw_message !== '' ) {
2423                // Add more allowed HTML elements for file download links
2424                $allowed_html = array(
2425                    'br'         => array(),
2426                    'blockquote' => array( 'class' => array() ),
2427                    'p'          => array(),
2428                    'div'        => array(
2429                        'class' => array(),
2430                        'style' => array(),
2431                    ),
2432                    'span'       => array(
2433                        'class' => array(),
2434                        'style' => array(),
2435                    ),
2436                );
2437
2438                $message = wp_kses( $raw_message, $allowed_html );
2439                $message = '<div class="jetpack_forms_contact-form-custom-success-message">' . $message . '</div>';
2440            }
2441
2442            if ( ! $disable_summary ) {
2443                $compiled_form = self::get_compiled_form( $feedback_id );
2444
2445                $message .= '<div class="jetpack_forms_contact-form-success-summary"><p>' . implode( '</p><p>', $compiled_form ) . '</p></div>';
2446            }
2447        }
2448
2449        return $message;
2450    }
2451
2452    /**
2453     * Returns a compiled form with labels and values in a form of  an array
2454     * of lines.
2455     *
2456     * @param int          $feedback_id - the feedback ID.
2457     * @param Contact_Form $form - the form. This parameter is deprecated and will be removed in the next version.
2458     *
2459     * @return array $lines
2460     */
2461    public static function get_compiled_form( $feedback_id, $form = null ) {
2462
2463        if ( $form ) {
2464            _deprecated_argument( __METHOD__, '5.1.0', '$form is deprecated' );
2465        }
2466        $compiled_form = self::get_raw_compiled_form_data( $feedback_id );
2467
2468        foreach ( $compiled_form as $field_index => $data ) {
2469            $safe_display_value = self::escape_and_sanitize_field_value( $data['value'] );
2470
2471            if ( '' === $safe_display_value ) {
2472                $safe_display_value = '-';
2473            }
2474
2475            if ( ! empty( $data['label'] ) ) {
2476                $safe_display_label            = self::escape_and_sanitize_field_label( $data['label'] );
2477                $compiled_form[ $field_index ] = sprintf(
2478                    '<div class="field-name">%1$s</div> <div class="field-value">%2$s</div>',
2479                    Util::maybe_add_colon_to_label( $safe_display_label ),
2480                    $safe_display_value
2481                );
2482            } else {
2483                // If there is no label, only output the field value, wrapped in its div.
2484                $compiled_form[ $field_index ] = sprintf(
2485                    '<div class="field-value">%s</div>',
2486                    $safe_display_value
2487                );
2488            }
2489        }
2490
2491        return $compiled_form;
2492    }
2493
2494    /**
2495     * Returns the JSON data for the form submission.
2496     *
2497     * @param int          $feedback_id - the feedback ID.
2498     * @param Contact_Form $form - the form. This parameter is deprecated and will be removed in the next version.
2499     *
2500     * @deprecated 5.1.0
2501     *
2502     * @return array $json_data
2503     */
2504    public static function get_json_data( $feedback_id, $form = null ) {
2505        _deprecated_function( __METHOD__, '5.1.0', 'Feedback::get( $feedback_id )->get_compiled_fields(\'ajax\', \'label|value\' )' );
2506
2507        if ( $form ) {
2508            _deprecated_argument( __METHOD__, '5.1.0', '$form is deprecated' );
2509        }
2510
2511        $response = Feedback::get( $feedback_id );
2512        if ( ! $response ) {
2513            return array();
2514        }
2515
2516        return $response->get_compiled_fields( 'ajax', 'label|value' );
2517    }
2518
2519    /**
2520     * Retrieves raw compiled form data.
2521     *
2522     * @param int          $feedback_id - the feedback ID.
2523     * @param Contact_Form $form - the form. This parameter is deprecated and will be removed in the next version.
2524     *
2525     * @return array $raw_data Associative array where keys are field_index and values are arrays with 'label' and 'value'.
2526     */
2527    private static function get_raw_compiled_form_data( $feedback_id, $form = null ) {
2528
2529        if ( $form ) {
2530            _deprecated_argument( __METHOD__, '5.1.0', '$form is deprecated' );
2531        }
2532
2533        $response = Feedback::get( $feedback_id );
2534        if ( $response instanceof Feedback ) {
2535            // If the response is an instance of Feedback, we can use its method to get compiled fields.
2536            return $response->get_compiled_fields( 'web', 'all' );
2537        }
2538
2539        return array();
2540    }
2541
2542    /**
2543     * Returns a compiled form with labels and values formatted for the email response
2544     * in a form of an array of lines.
2545     *
2546     * @param int          $feedback_id - the feedback ID.
2547     * @param Contact_Form $form - the form.
2548     *
2549     * @return array $lines
2550     */
2551    public static function get_compiled_form_for_email( $feedback_id, $form ) {
2552        return Feedback_Email_Renderer::get_compiled_form_for_email( $feedback_id, $form );
2553    }
2554
2555    /**
2556     * Escape and sanitize a field value.
2557     *
2558     * @param mixed $value - the value to sanitize.
2559     *
2560     * TODO: there's a mix of functionalities in this method. Unsure if it's fixable.
2561     * @return string
2562     */
2563    public static function escape_and_sanitize_field_value( $value ) {
2564        if ( empty( $value ) ) {
2565            return '';
2566        }
2567
2568        // Handle file upload field (new structure with field_id and files array).
2569        if ( self::is_file_upload_field( $value ) ) {
2570            $files = $value['files'];
2571            if ( empty( $files ) ) {
2572                return '';
2573            }
2574
2575            $file_links = array();
2576            foreach ( $files as $file ) {
2577                if ( ! empty( $file['file_id'] ) ) {
2578                    $file_name = $file['name'] ?? __( 'Attached file', 'jetpack-forms' );
2579                    $file_size = isset( $file['size'] ) ? size_format( $file['size'] ) : '';
2580
2581                    $html = esc_html( $file_name );
2582                    if ( ! empty( $file_size ) ) {
2583                        $html .= sprintf( ' <span class="jetpack-forms-file-size">(%s)</span>', esc_html( $file_size ) );
2584                    }
2585
2586                    $file_links[] = $html;
2587                }
2588            }
2589
2590            return implode( '<br>', $file_links );
2591        }
2592
2593        // Handle rating field - return displayValue (e.g., "3/5") as text fallback.
2594        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'rating' ) {
2595            return isset( $value['displayValue'] ) ? esc_html( $value['displayValue'] ) : '';
2596        }
2597
2598        // Handle URL field - return displayValue or url.
2599        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'url' ) {
2600            return isset( $value['displayValue'] ) ? esc_html( $value['displayValue'] ) : ( isset( $value['url'] ) ? esc_html( $value['url'] ) : '' );
2601        }
2602
2603        if ( is_array( $value ) ) {
2604            return implode( ', ', array_map( array( __CLASS__, 'escape_and_sanitize_field_value' ), $value ) );
2605        }
2606
2607        $value = str_replace( array( '[', ']' ), array( '&#91;', '&#93;' ), $value );
2608        return nl2br( wp_kses( $value, array() ) );
2609    }
2610
2611    /**
2612     * Only strip out empty string values and keep all the other values as they are.
2613     *
2614     * @param string $single_value - the single value.
2615     *
2616     * @return bool
2617     */
2618    public static function remove_empty( $single_value ) {
2619        return ( $single_value !== '' );
2620    }
2621
2622    /**
2623     * Get file upload fields
2624     *
2625     * @param int $post_id The feedback post ID.
2626     * @return array Array of file attachments or empty array.
2627     */
2628    public static function get_file_upload_fields( $post_id ) {
2629        $content_fields     = Contact_Form_Plugin::parse_fields_from_content( $post_id );
2630        $file_upload_fields = array();
2631        if ( isset( $content_fields['_feedback_all_fields'] ) ) {
2632            foreach ( $content_fields['_feedback_all_fields'] as $field_value ) {
2633                if ( self::is_file_upload_field( $field_value ) ) {
2634                    $file_upload_fields[] = $field_value;
2635                }
2636            }
2637        }
2638
2639        return $file_upload_fields;
2640    }
2641
2642    /**
2643     * Delete files
2644     *
2645     * @param int $post_id The post ID being deleted.
2646     * @return void
2647     */
2648    public static function delete_feedback_files( $post_id ) {
2649        if ( get_post_type( $post_id ) !== 'feedback' ) {
2650            return;
2651        }
2652        // $file_upload_fields = self::get_file_upload_fields( $post_id );
2653        // TODO: Implement delete_feedback_files() method.
2654    }
2655
2656    /**
2657     * Escape a shortcode value.
2658     *
2659     * Shortcode attribute values have a number of unfortunate restrictions, which fortunately we
2660     * can get around by adding some extra HTML encoding.
2661     *
2662     * The output HTML will have a few extra escapes, but that makes no functional difference.
2663     *
2664     * @since 9.1.0
2665     * @param string|array $val Value to escape.
2666     * @return string
2667     */
2668    public static function esc_shortcode_val( $val ) {
2669        // Sometimes we provide attributes in the form of a collection, hence making the value an array.
2670        // The above case triggers a warning about array to string conversion on formatting.php:1096.
2671        // This chunk will try to get the value from the usual label|value structure. Otherwise, it will try
2672        // recursively to get the first value from the array.
2673        if ( is_array( $val ) ) {
2674            if ( isset( $val['value'] ) ) {
2675                $val = $val['value'];
2676            } else {
2677                return self::esc_shortcode_val( array_shift( $val ) );
2678            }
2679        }
2680
2681        return strtr(
2682            esc_html( $val ),
2683            array(
2684                // Brackets in attribute values break the shortcode parser.
2685                '['  => '&#091;',
2686                ']'  => '&#093;',
2687                // Shortcode parser screws up backslashes too, thanks to calls to `stripcslashes`.
2688                '\\' => '&#092;',
2689                // The existing code here represents arrays as comma-separated strings.
2690                // Rather than trying to change representations now, just escape the commas in values.
2691                ','  => '&#044;',
2692            )
2693        );
2694    }
2695
2696    /**
2697     * The contact-field shortcode processor.
2698     * We use an object method here instead of a static Contact_Form_Field class method to parse contact-field shortcodes so that we can tie them to the contact-form object.
2699     *
2700     * @param array         $attributes Key => Value pairs as parsed by shortcode_parse_atts().
2701     * @param string|null   $content The shortcode's inner content: [contact-field]$content[/contact-field].
2702     * @param WP_Block|null $block The field block object.
2703     * @return string HTML for the contact form field
2704     */
2705    public static function parse_contact_field( $attributes, $content, $block = null ) {
2706        if ( $block ) {
2707            $type = null;
2708        }
2709
2710        // Don't try to parse contact form fields if not inside a contact form (????)
2711        if ( ! Contact_Form_Plugin::$using_contact_form_field ) {
2712            $type = $attributes['type'] ?? null;
2713
2714            if ( $type === 'checkbox-multiple' || $type === 'radio' ) {
2715                preg_match_all( '/' . get_shortcode_regex() . '/s', $content, $matches );
2716
2717                if ( ! empty( $matches[0] ) ) {
2718                    $options = array();
2719                    foreach ( $matches[0] as $shortcode ) {
2720                        $attr = shortcode_parse_atts( $shortcode );
2721                        if ( ! empty( $attr['label'] ) ) {
2722                            $options[] = $attr['label'];
2723                        }
2724                    }
2725
2726                    $attributes['options'] = $options;
2727                }
2728            }
2729
2730            if ( ! isset( $attributes['label'] ) ) {
2731                $attributes['label'] = self::get_default_label_from_type( $type );
2732            }
2733
2734            $att_strs = array();
2735            foreach ( $attributes as $att => $val ) {
2736                if ( is_numeric( $att ) ) { // Is a valueless attribute
2737                    $att_strs[] = self::esc_shortcode_val( $val );
2738                } elseif ( isset( $val ) ) { // A regular attr - value pair
2739                    if ( ( $att === 'options' || $att === 'values' ) && is_string( $val ) ) { // remove any empty strings
2740                        $val = explode( ',', $val );
2741                    }
2742                    if ( is_array( $val ) ) {
2743                        $val        = array_filter( $val, array( __CLASS__, 'remove_empty' ) ); // removes any empty strings
2744                        $att_strs[] = esc_html( $att ) . '="' . implode( ',', array_map( array( __CLASS__, 'esc_shortcode_val' ), $val ) ) . '"';
2745                    } elseif ( is_bool( $val ) ) {
2746                        $att_strs[] = esc_html( $att ) . '="' . ( $val ? '1' : '' ) . '"';
2747                    } else {
2748                        // Allow CSS in known style attributes byut sanitize with safecss_filter_attr.
2749                        $allowed_style_keys = array( 'labelstyles', 'inputstyles', 'optionstyles', 'optionsstyles', 'stylevariationstyles' );
2750                        if ( in_array( $att, $allowed_style_keys, true ) ) {
2751                            $sanitized  = safecss_filter_attr( (string) $val );
2752                            $att_strs[] = esc_attr( $att ) . '="' . esc_html( $sanitized ) . '"';
2753                        } else {
2754                            $att_strs[] = esc_attr( $att ) . '="' . self::esc_shortcode_val( $val ) . '"';
2755                        }
2756                    }
2757                }
2758            }
2759
2760            $shortcode_type = 'contact-field';
2761            if ( $type === 'field-option' ) {
2762                $shortcode_type = 'contact-field-option';
2763            }
2764
2765            $html            = '[' . $shortcode_type . ' ' . implode( ' ', $att_strs );
2766            $trimmed_content = isset( $content ) ? trim( $content ) : '';
2767
2768            if ( ! empty( $trimmed_content ) ) { // If there is content, let's add a closing tag
2769                $html .= ']' . esc_html( $trimmed_content ) . '[/contact-field]';
2770            } else { // Otherwise let's add a closing slash in the first tag
2771                $html .= '/]';
2772            }
2773
2774            return $html;
2775        }
2776
2777        // What does this actually means? What is the case where this is used?
2778        $form = self::$current_form;
2779
2780        $field = new Contact_Form_Field( $attributes, $content, $form );
2781
2782        $field_id = $field->get_attribute( 'id' );
2783        if ( $field_id ) {
2784            $form->fields[ $field_id ] = $field;
2785        } else {
2786            $form->fields[] = $field;
2787        }
2788
2789        if ( // phpcs:disable WordPress.Security.NonceVerification.Missing
2790            ! isset( $_POST['jetpack_contact_form_jwt'] )
2791            && $form->is_current_submission()
2792        ) { // phpcs:enable
2793            // If we're processing a POST submission for this contact form, validate the field value so we can show errors as necessary.
2794            //
2795            // A field carrying conditional logic is skipped here. Whether it is visible depends
2796            // on the answers to other fields, and fields are appended to $form->fields as they
2797            // parse — at this point the form is still incomplete, so the question cannot be
2798            // answered correctly. Validating anyway records an error against a field the visitor
2799            // may never see, which leaves the form permanently unsubmittable: the error is real
2800            // to has_errors(), but invisible on screen and impossible to clear.
2801            //
2802            // Contact_Form::validate() re-validates every field once the form is fully parsed,
2803            // and skips the ones conditional logic resolves as hidden, so nothing is lost by
2804            // deferring: a visible field still gets its error, just a moment later.
2805            $defer_to_full_form_validation = Jetpack_Forms::is_conditional_logic_enabled()
2806                && $field->has_conditional_logic();
2807
2808            if ( ! $defer_to_full_form_validation ) {
2809                $field->validate();
2810            }
2811        }
2812
2813        // Output HTML
2814        return $field->render();
2815    }
2816
2817    /**
2818     * Check if the field is a file upload field.
2819     *
2820     * @param array $field The field to check.
2821     * @return bool True if the field is a file upload field, false otherwise.
2822     */
2823    public static function is_file_upload_field( $field ) {
2824        return ( is_array( $field ) &&
2825                ! empty( $field ) &&
2826                isset( $field['field_id'] ) &&
2827                isset( $field['files'] ) &&
2828                is_array( $field['files'] ) );
2829    }
2830
2831    /**
2832     * Get the default label from type.
2833     *
2834     * @param string $type - the type of label.
2835     *
2836     * @return string
2837     */
2838    public static function get_default_label_from_type( $type ) {
2839        switch ( $type ) {
2840            case 'text':
2841                $str = __( 'Text', 'jetpack-forms' );
2842                break;
2843            case 'name':
2844                $str = __( 'Name', 'jetpack-forms' );
2845                break;
2846            case 'number':
2847                $str = __( 'Number', 'jetpack-forms' );
2848                break;
2849            case 'email':
2850                $str = __( 'Email', 'jetpack-forms' );
2851                break;
2852            case 'url':
2853                $str = __( 'Website', 'jetpack-forms' );
2854                break;
2855            case 'date':
2856                $str = __( 'Date', 'jetpack-forms' );
2857                break;
2858            case 'telephone':
2859                $str = __( 'Phone', 'jetpack-forms' );
2860                break;
2861            case 'textarea':
2862                $str = __( 'Message', 'jetpack-forms' );
2863                break;
2864            case 'checkbox-multiple':
2865                $str = __( 'Choose several options', 'jetpack-forms' );
2866                break;
2867            case 'radio':
2868                $str = __( 'Choose one option', 'jetpack-forms' );
2869                break;
2870            case 'select':
2871                $str = __( 'Select one', 'jetpack-forms' );
2872                break;
2873            case 'consent':
2874                $str = __( 'Consent', 'jetpack-forms' );
2875                break;
2876            case 'file':
2877                $str = __( 'Upload a file', 'jetpack-forms' );
2878                break;
2879            case 'time':
2880                $str = __( 'Time', 'jetpack-forms' );
2881                break;
2882            case 'image-select':
2883                $str = __( 'Select an image', 'jetpack-forms' );
2884                break;
2885            default:
2886                $str = null;
2887        }
2888        return $str;
2889    }
2890
2891    /**
2892     * Loops through $this->fields to generate a (structured) list of field IDs.
2893     *
2894     * Important: Currently the allowed fields are defined as follows:
2895     *  `name`, `email`, `url`, `subject`, `textarea`
2896     *
2897     * If you need to add new fields to the Contact Form, please don't add them
2898     * to the allowed fields and leave them as extra fields.
2899     *
2900     * The reasoning behind this is that both the admin Feedback view and the CSV
2901     * export will not include any fields that are added to the list of
2902     * allowed fields without taking proper care to add them to all the
2903     * other places where they accessed/used/saved.
2904     *
2905     * The safest way to add new fields is to add them to the dropdown and the
2906     * HTML list ( @see Contact_Form_Field::render ) and don't add them
2907     * to the list of allowed fields. This way they will become a part of the
2908     * `extra fields` which are saved in the post meta and will be properly
2909     * handled by the admin Feedback view and the CSV Export without any extra
2910     * work.
2911     *
2912     * If there is need to add a field to the allowed fields, then please
2913     * take proper care to add logic to handle the field in the following places:
2914     *
2915     *  - Below in the switch statement - so the field is recognized as allowed.
2916     *
2917     *  - Contact_Form::process_submission - validation and logic.
2918     *
2919     *  - Contact_Form::process_submission - add the field as an additional
2920     *      field in the `post_content` when saving the feedback content.
2921     *
2922     *  - Contact_Form_Plugin::parse_fields_from_content - add mapping
2923     *      for the field, defined in the above method.
2924     *
2925     *  - Contact_Form_Plugin::map_parsed_field_contents_of_post_to_field_names -
2926     *      add mapping of the field for the CSV Export. Otherwise it will be missing
2927     *      from the exported data.
2928     *
2929     *  - admin.php / grunion_manage_post_columns - add the field to the render logic.
2930     *      Otherwise it will be missing from the admin Feedback view.
2931     *
2932     * @return array
2933     */
2934    public function get_field_ids() {
2935        $field_ids = array(
2936            'all'   => array(), // array of all field_ids.
2937            'extra' => array(), // array of all non-allowed field IDs.
2938
2939            // Allowed "standard" field IDs:
2940            // 'email'    => field_id,
2941            // 'name'     => field_id,
2942            // 'url'      => field_id,
2943            // 'subject'  => field_id,
2944            // 'textarea' => field_id,
2945        );
2946
2947        // Initialize marketing consent
2948        $field_ids['email_marketing_consent']       = null;
2949        $field_ids['email_marketing_consent_field'] = null;
2950
2951        foreach ( $this->fields as $id => $field ) {
2952            $type = $field->get_attribute( 'type' );
2953
2954            // If the field is not renderable, skip it.
2955            if ( ! $field->is_field_renderable( $type ) ) {
2956                continue;
2957            }
2958
2959            $field_ids['all'][] = $id;
2960
2961            if ( isset( $field_ids[ $type ] ) ) {
2962                // This type of field is already present in our allowed list of "standard" fields for this form
2963                // Put it in extra
2964                $field_ids['extra'][] = $id;
2965                continue;
2966            }
2967
2968            /**
2969             * See method description before modifying the switch cases.
2970             */
2971            switch ( $type ) {
2972                case 'email':
2973                case 'name':
2974                case 'url':
2975                case 'subject':
2976                case 'textarea':
2977                    $field_ids[ $type ] = $id;
2978                    break;
2979                case 'consent':
2980                    // Set email marketing consent for the first Consent type field
2981                    if ( null === $field_ids['email_marketing_consent'] ) {
2982                        $field_ids['email_marketing_consent_field'] = $id;
2983                        if ( $field->value ) {
2984                            $field_ids['email_marketing_consent'] = true;
2985                        } else {
2986                            $field_ids['email_marketing_consent'] = false;
2987                        }
2988                    }
2989                    $field_ids['extra'][] = $id;
2990                    break;
2991                default:
2992                    // Put everything else in extra
2993                    $field_ids['extra'][] = $id;
2994            }
2995        }
2996
2997        return $field_ids;
2998    }
2999
3000    /**
3001     * Process the contact form's POST submission
3002     * Stores feedback.  Sends email.
3003     */
3004    public function process_submission() {
3005
3006        $response = Feedback::from_submission( $_POST, $this ); // phpcs:Ignore WordPress.Security.NonceVerification.Missing
3007        $response->set_source( $this->get_source() );
3008
3009        // If the submission came from an authenticated form preview, flag the
3010        // feedback as a test submission. The rest of the pipeline reads the
3011        // flag from the feedback (which also travels into the serialized
3012        // post_content via Feedback_Source).
3013        if ( $this->is_preview_submission ) {
3014            $response->mark_as_test();
3015        }
3016        $is_test_submission = $response->is_test();
3017
3018        $plugin = Contact_Form_Plugin::init();
3019
3020        $id                  = $this->get_attribute( 'id' );
3021        $to                  = $this->get_attribute( 'to' );
3022        $widget              = $this->get_attribute( 'widget' );
3023        $block_template      = $this->get_attribute( 'block_template' );
3024        $block_template_part = $this->get_attribute( 'block_template_part' );
3025
3026        $contact_form_subject = $this->get_attribute( 'subject' );
3027
3028        $to     = str_replace( ' ', '', $to );
3029        $emails = explode( ',', $to );
3030
3031        $valid_emails = array();
3032
3033        foreach ( $emails as $email ) {
3034            if ( ! is_email( $email ) ) {
3035                continue;
3036            }
3037
3038            if ( function_exists( 'is_email_address_unsafe' ) && is_email_address_unsafe( $email ) ) {
3039                continue;
3040            }
3041
3042            $valid_emails[] = $email;
3043        }
3044
3045        // No one to send it to, which means none of the "to" attributes are valid emails.
3046        // Use default email instead.
3047        if ( ! $valid_emails ) {
3048            $valid_emails = $this->defaults['to'];
3049        }
3050
3051        $to = $valid_emails;
3052
3053        // Last ditch effort to set a recipient if somehow none have been set.
3054        if ( empty( $to ) ) {
3055            $to = get_option( 'admin_email' );
3056        }
3057
3058        if ( ! $this->has_verified_jwt ) {
3059            // Make sure we're processing the form we think we're processing... probably a redundant check.
3060            if ( $widget ) {
3061                if ( isset( $_POST['contact-form-id'] ) && 'widget-' . $widget !== $_POST['contact-form-id'] ) { // phpcs:Ignore WordPress.Security.NonceVerification.Missing -- check done by caller process_form_submission()
3062                    return Form_Submission_Error::system_error( 'form_id_mismatch_widget', __( 'Form ID mismatch.', 'jetpack-forms' ) );
3063                }
3064            } elseif ( $block_template ) {
3065                if ( isset( $_POST['contact-form-id'] ) && 'block-template-' . $block_template !== $_POST['contact-form-id'] ) { // phpcs:Ignore WordPress.Security.NonceVerification.Missing -- check done by caller process_form_submission()
3066                    return Form_Submission_Error::system_error( 'form_id_mismatch_block_template', __( 'Form ID mismatch.', 'jetpack-forms' ) );
3067                }
3068            } elseif ( $block_template_part ) {
3069                if ( isset( $_POST['contact-form-id'] ) && 'block-template-part-' . $block_template_part !== $_POST['contact-form-id'] ) { // phpcs:Ignore WordPress.Security.NonceVerification.Missing -- check done by caller process_form_submission()
3070                        return Form_Submission_Error::system_error( 'form_id_mismatch_block_template_part', __( 'Form ID mismatch.', 'jetpack-forms' ) );
3071                }
3072            } elseif ( isset( $_POST['contact-form-id'] ) && ( empty( $this->current_post ) || self::get_post_property( $this->current_post, 'ID' ) !== (int) sanitize_text_field( wp_unslash( $_POST['contact-form-id'] ) ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- check done by caller process_form_submission()
3073                return Form_Submission_Error::system_error( 'form_id_mismatch_post', __( 'Form ID mismatch.', 'jetpack-forms' ) );
3074            }
3075        }
3076
3077        // Initialize all these "standard" fields to null
3078        $comment_author_email = $response->get_author_email();
3079        $comment_author       = $response->get_author();
3080
3081        $contact_form_subject = $response->get_subject();
3082
3083        // Set marketing consent
3084        $email_marketing_consent = $response->has_consent();
3085
3086        if ( null === $email_marketing_consent ) {
3087            $email_marketing_consent = false;
3088        }
3089
3090        $all_values   = $response->get_all_values( 'submit' );
3091        $extra_values = $response->get_legacy_extra_values( 'submit' );
3092
3093        if ( ! empty( $_REQUEST['is_block'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- not changing the site.
3094            $extra_values['is_block'] = true;
3095        }
3096
3097        $contact_form_subject = trim( $contact_form_subject );
3098
3099        $comment_author_ip = Contact_Form_Plugin::get_ip_address();
3100
3101        // Ensure that Akismet gets all of the relevant information from the contact form,
3102        // not just the textarea field and predetermined subject.
3103        $akismet_vars = $response->get_akismet_vars();
3104
3105        $spam           = '';
3106        $akismet_values = $plugin->prepare_for_akismet( $akismet_vars );
3107
3108        // Is it spam? Test submissions (from form preview) skip Akismet entirely —
3109        // the form owner is explicitly running a test and we don't want Akismet
3110        // to learn from synthetic data or bounce the submission.
3111        if ( $is_test_submission ) {
3112            $is_spam = false;
3113        } else {
3114            /** This filter is already documented in \Automattic\Jetpack\Forms\ContactForm\Admin */
3115            $is_spam = apply_filters( 'jetpack_contact_form_is_spam', false, $akismet_values );
3116        }
3117        if ( is_wp_error( $is_spam ) ) { // WP_Error to abort
3118            return $is_spam; // abort
3119        } elseif ( $is_spam === true ) {  // TRUE to flag a spam
3120            $spam = '***SPAM*** ';
3121        }
3122
3123        /**
3124         * Filter whether a submitted contact form is in the comment disallowed list.
3125         *
3126         * @module contact-form
3127         *
3128         * @since 8.9.0
3129         *
3130         * @param bool  $result         Is the submitted feedback in the disallowed list.
3131         * @param array $akismet_values Feedack values returned by the Akismet plugin.
3132         */
3133        $in_comment_disallowed_list = apply_filters( 'jetpack_contact_form_in_comment_disallowed_list', false, $akismet_values );
3134
3135        if ( ! $comment_author ) {
3136            $comment_author = $comment_author_email;
3137        }
3138
3139        /**
3140         * Filter the email where a submitted feedback is sent.
3141         *
3142         * @module contact-form
3143         *
3144         * @since 1.3.1
3145         *
3146         * @param string|array $to Array of valid email addresses, or single email address.
3147         * @param array $all_values Contact form fields
3148         */
3149        $to            = (array) apply_filters( 'contact_form_to', $to, $all_values );
3150        $reply_to_addr = $to[0]; // get just the address part before the name part is added
3151
3152        foreach ( $to as $to_key => $to_value ) {
3153            $to[ $to_key ] = Contact_Form_Plugin::strip_tags( $to_value );
3154            $to[ $to_key ] = self::add_name_to_address( $to_value );
3155        }
3156
3157        // Get the site domain and get rid of www.
3158        $sitename        = wp_parse_url( site_url(), PHP_URL_HOST );
3159        $from_email_addr = 'wordpress@';
3160
3161        if ( null !== $sitename ) {
3162            if ( str_starts_with( $sitename, 'www.' ) ) {
3163                $sitename = substr( $sitename, 4 );
3164            }
3165
3166            $from_email_addr .= $sitename;
3167        }
3168
3169        if ( ! empty( $comment_author_email ) ) {
3170            $reply_to_addr = $comment_author_email;
3171        }
3172
3173        /*
3174         * The email headers here are formatted in a format
3175         * that is the most likely to be accepted by wp_mail(),
3176         * without escaping.
3177         * More info: https://github.com/Automattic/jetpack/pull/19727
3178         */
3179        $headers = 'From: ' . $comment_author . ' <' . $from_email_addr . ">\r\n" .
3180            'Reply-To: ' . $comment_author . ' <' . $reply_to_addr . ">\r\n";
3181
3182        /**
3183         * Allow customizing the email headers.
3184         *
3185         * Warning: DO NOT add headers or header data from the form submission without proper
3186         * escaping and validation, or you're liable to allow abusers to use your site to send spam.
3187         *
3188         * Especially DO NOT take email addresses from the form data to add as CC or BCC headers
3189         * without strictly validating each address against a list of allowed addresses.
3190         *
3191         * @module contact-form
3192         *
3193         * @since 10.2.0
3194         *
3195         * @param string|array $headers        Email headers.
3196         * @param string       $comment_author Name of the author of the submitted feedback, if provided in form.
3197         * @param string       $reply_to_addr  Email of the author of the submitted feedback, if provided in form.
3198         * @param string|array $to             Array of valid email addresses, or single email address, where the form is sent.
3199         */
3200        $headers = apply_filters(
3201            'jetpack_contact_form_email_headers',
3202            $headers,
3203            $comment_author,
3204            $reply_to_addr,
3205            $to
3206        );
3207
3208        $all_values['email_marketing_consent'] = $email_marketing_consent;
3209
3210        $entry_values = $response->get_entry_values();
3211
3212        // Prefix the subject with [TEST] for test submissions so the form owner
3213        // can immediately tell this email came from a preview-mode submission.
3214        if ( $is_test_submission ) {
3215            /**
3216             * Filter the subject prefix applied to test (preview) feedback emails.
3217             *
3218             * @module contact-form
3219             *
3220             * @since 7.19.0
3221             *
3222             * @param string $prefix Default subject prefix for test submissions.
3223             */
3224            $test_prefix          = apply_filters( 'jetpack_forms_test_subject_prefix', '[TEST] ' );
3225            $contact_form_subject = $test_prefix . $contact_form_subject;
3226        }
3227
3228        /** This filter is already documented in \Automattic\Jetpack\Forms\ContactForm\Admin */
3229        $subject = apply_filters( 'contact_form_subject', $contact_form_subject, $all_values );
3230
3231        /*
3232         * Links to the feedback and the post.
3233         */
3234        if ( $block_template || $block_template_part || $widget ) {
3235            $url = home_url( '/' );
3236        } else {
3237            $url = self::get_permalink( $this->current_post ? self::get_post_property( $this->current_post, 'ID' ) : 0 );
3238        }
3239
3240        // translators: the time of the form submission.
3241        $date_time_format = _x( '%1$s \a\t %2$s', '{$date_format} \a\t {$time_format}', 'jetpack-forms' );
3242        $date_time_format = sprintf( $date_time_format, get_option( 'date_format' ), get_option( 'time_format' ) );
3243        $time             = wp_date( $date_time_format );
3244
3245        // Keep a copy of the feedback as a custom post type.
3246        if ( $in_comment_disallowed_list ) {
3247            $feedback_status = 'trash';
3248        } elseif ( $is_spam ) {
3249            $feedback_status = 'spam';
3250        } elseif ( 'no' === $this->get_attribute( 'saveResponses' ) ) {
3251            $feedback_status = 'jp-temp-feedback';
3252        } else {
3253            $feedback_status = 'publish';
3254        }
3255        $response->set_status( $feedback_status );
3256
3257        foreach ( (array) $akismet_values as $av_key => $av_value ) {
3258            $akismet_values[ $av_key ] = Contact_Form_Plugin::strip_tags( $av_value );
3259        }
3260
3261        foreach ( $all_values as $all_key => $all_value ) {
3262            $all_values[ $all_key ] = Contact_Form_Plugin::strip_tags( $all_value );
3263        }
3264
3265        foreach ( $extra_values as $ev_key => $ev_value ) {
3266            $extra_values[ $ev_key ] = Contact_Form_Plugin::strip_tags( $ev_value );
3267        }
3268
3269        /*
3270         * We need to make sure that the post author is always zero for contact
3271         * form submissions.  This prevents export/import from trying to create
3272         * new users based on form submissions from people who were logged in
3273         * at the time.
3274         *
3275         * Unfortunately wp_insert_post() tries very hard to make sure the post
3276         * author gets the currently logged in user id.  That is how we ended up
3277         * with this work around.
3278         */
3279        add_filter( 'wp_insert_post_data', array( $plugin, 'insert_feedback_filter' ), 10, 2 );
3280
3281        /**
3282         * Allows site owners to not include IP addresses in the saved form response.
3283         *
3284         * The IP address is still used as part of spam filtering, if enabled, but it is removed when this filter
3285         * is set to true before saving to the database and e-mailing the form recipients.
3286
3287         * @module contact-form
3288         *
3289         * @param bool $remove_ip_address Should the IP address be removed. Default false.
3290         * @param string $ip_address IP address of the form submission.
3291         *
3292         * @since 0.33.0
3293         */
3294        if ( apply_filters( 'jetpack_contact_form_forget_ip_address', false, $comment_author_ip ) ) {
3295            $comment_author_ip = null;
3296        }
3297
3298        $post_id       = 0;
3299        $feedback_post = $response->save();
3300        if ( $feedback_post instanceof WP_Post ) {
3301            $post_id = $feedback_post->ID;
3302        }
3303
3304        // once insert has finished we don't need this filter any more
3305        remove_filter( 'wp_insert_post_data', array( $plugin, 'insert_feedback_filter' ), 10 );
3306
3307        update_post_meta( $post_id, '_feedback_extra_fields', $this->addslashes_deep( $extra_values ) );
3308
3309        if ( 'publish' === $feedback_status ) {
3310            Contact_Form_Plugin::recalculate_unread_count();
3311        }
3312
3313        if ( defined( 'AKISMET_VERSION' ) ) {
3314            update_post_meta( $post_id, '_feedback_akismet_values', $this->addslashes_deep( $akismet_values ) );
3315        }
3316
3317        // Integrations must not see a field the visitor was never shown. MailPoet in
3318        // particular reads this payload directly for explicit consent and the subscriber's
3319        // email, so a forged POST naming a hidden consent field could otherwise subscribe
3320        // someone off a question that was never on screen.
3321        $visible_fields = $this->fields;
3322        foreach ( $this->get_resolved_field_visibility() as $field_id => $is_visible ) {
3323            if ( false === $is_visible ) {
3324                unset( $visible_fields[ $field_id ] );
3325            }
3326        }
3327
3328        /**
3329         * Fires after the feedback post for the contact form submission has been inserted.
3330         *
3331         * @module contact-form
3332         *
3333         * @since 8.6.0
3334         *
3335         * @param integer $post_id The post id that contains the contact form data.
3336         * @param array   $visible_fields The form's Contact_Form_Field objects, less any that
3337         *                                conditional logic hid from the visitor.
3338         * @param boolean $is_spam Whether the form submission has been identified as spam.
3339         * @param array   $entry_values The feedback entry values.
3340         */
3341        do_action( 'grunion_after_feedback_post_inserted', $post_id, $visible_fields, $is_spam, $entry_values );
3342
3343        // Build the complete email content via the renderer.
3344        $context_data = array(
3345            'time'                 => $time,
3346            'url'                  => $url,
3347            'comment_author'       => $comment_author,
3348            'comment_author_email' => $comment_author_email,
3349            'comment_author_ip'    => $comment_author_ip,
3350            'is_spam'              => $is_spam,
3351            'is_test'              => $is_test_submission,
3352            'feedback_status'      => $feedback_status,
3353        );
3354        $email        = Feedback_Email_Renderer::build_email_content( $post_id, $this, $response, $context_data );
3355        $message      = $email['message'];
3356
3357        // Always store the rendered email for the resend endpoint.
3358        update_post_meta( $post_id, '_feedback_email', $this->addslashes_deep( compact( 'to', 'message' ) ) );
3359
3360        /**
3361         * Filter to choose whether an email should be sent after each successful contact form submission.
3362         * This filter takes precedence over the emailNotifications attribute.
3363         *
3364         * @module contact-form
3365         *
3366         * @since 2.6.0
3367         *
3368         * @param bool|null $should_send Should an email be sent after a form submission.
3369         *                              - true: Send email regardless of emailNotifications setting
3370         *                              - false: Don't send email regardless of emailNotifications setting
3371         *                              - null: Use emailNotifications attribute to determine (default behavior)
3372         * @param int $post_id Post ID.
3373         */
3374        $should_send_email = apply_filters( 'grunion_should_send_email', null, $post_id );
3375
3376        // Determine if email should be sent based on filter precedence.
3377        if ( $should_send_email === true ) {
3378            // Filter explicitly says to send email
3379            $send_email = true;
3380        } elseif ( $should_send_email === false ) {
3381            // Filter explicitly says not to send email
3382            $send_email = false;
3383        } else {
3384            // Filter is null (default), use emailNotifications attribute
3385            $send_email = ( $this->get_attribute( 'emailNotifications' ) !== 'no' );
3386        }
3387
3388        // Test submissions always send the notification email (so the form
3389        // owner can verify their email flow end-to-end) regardless of the
3390        // emailNotifications attribute. Site admins who want to opt out can
3391        // return false from the filter below.
3392        if ( $is_test_submission ) {
3393            /**
3394             * Filter whether test (preview) submissions should trigger the notification email.
3395             *
3396             * @module contact-form
3397             *
3398             * @since 7.19.0
3399             *
3400             * @param bool     $send     Whether to send the test submission email. Default true.
3401             * @param int      $post_id  The feedback post ID.
3402             * @param Feedback $response The feedback response object.
3403             */
3404            $send_email = apply_filters( 'jetpack_forms_send_test_feedback_email', true, $post_id, $response );
3405        }
3406
3407        /**
3408         * Filter to determine if spam should still be emailed.
3409         *
3410         * @module contact-form
3411         */
3412        $send_even_if_spam = apply_filters( 'grunion_still_email_spam', false );
3413
3414        // Only fire send-related side effects when we are actually going to send.
3415        $will_send = ( $is_spam !== true && $send_email ) || ( true === $is_spam && $send_even_if_spam );
3416
3417        if ( $will_send ) {
3418            /**
3419             * Fires right before the contact form message is sent via email to
3420             * the recipient specified in the contact form.
3421             *
3422             * @module contact-form
3423             *
3424             * @since 1.3.1
3425             *
3426             * @param integer $post_id Post contact form lives on
3427             * @param array $all_values Contact form fields
3428             * @param array $extra_values Contact form fields not included in $all_values
3429             */
3430            do_action( 'grunion_pre_message_sent', $post_id, $all_values, $extra_values );
3431
3432            self::wp_mail( $to, "{$spam}{$subject}", $message, $headers );
3433        }
3434
3435        // Schedule deletes of old spam feedbacks.
3436        if ( ! wp_next_scheduled( 'grunion_scheduled_delete' ) ) {
3437            wp_schedule_event( time() + 250, 'daily', 'grunion_scheduled_delete' );
3438        }
3439
3440        // Schedule deletes of old temp feedbacks.
3441        if ( ! wp_next_scheduled( 'grunion_scheduled_delete_temp' ) ) {
3442            wp_schedule_event( time() + 250, 'daily', 'grunion_scheduled_delete_temp' );
3443        }
3444
3445        /**
3446         * Fires an action hook right after the email(s) have been sent.
3447         *
3448         * @module contact-form
3449         *
3450         * @since 7.3.0
3451         *
3452         * @param int $post_id Post contact form lives on.
3453         * @param string|array $to Array of valid email addresses, or single email address.
3454         * @param string $subject Feedback email subject.
3455         * @param string $message Feedback email message.
3456         * @param string|array $headers Optional. Additional headers.
3457         * @param array $all_values Contact form fields.
3458         * @param array $extra_values Contact form fields not included in $all_values
3459         */
3460        do_action( 'grunion_after_message_sent', $post_id, $to, $subject, $message, $headers, $all_values, $extra_values );
3461
3462        $refresh_args = array(
3463            'contact-form-id'   => $id,
3464            'contact-form-sent' => $post_id,
3465            'contact-form-hash' => $this->hash,
3466            '_wpnonce'          => wp_create_nonce( "contact-form-sent-{$post_id}" ), // wp_nonce_url HTMLencodes :( .
3467        );
3468
3469        // If the request accepts JSON, return a JSON response instead of redirecting
3470        $accepts_json = isset( $_SERVER['HTTP_ACCEPT'] ) && false !== strpos( strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_ACCEPT'] ) ) ), 'application/json' );
3471
3472        if ( $this->is_response_without_reload_enabled && $accepts_json ) {
3473            $data = array();
3474            if ( $response instanceof Feedback ) {
3475                $data = $response->get_compiled_fields( 'ajax', 'collection' );
3476            }
3477            wp_send_json(
3478                array(
3479                    'success'     => true,
3480                    'data'        => $data,
3481                    'refreshArgs' => $refresh_args,
3482                ),
3483                null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
3484                JSON_UNESCAPED_SLASHES
3485            );
3486        }
3487
3488        if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
3489            return self::success_message( $post_id, $this );
3490        }
3491
3492        $redirect = $this->get_redirect_url( $refresh_args, $id, $post_id );
3493
3494        // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- We intentially allow external redirects here.
3495        wp_redirect( $redirect );
3496        exit( 0 );
3497    }
3498
3499    /**
3500     * Check if the contact form has a custom redirect.
3501     *
3502     * @return bool True if the contact form has a custom redirect, false otherwise.
3503     */
3504    public function has_custom_redirect() {
3505        $confirmation_type = $this->get_confirmation_type();
3506
3507        if ( ! empty( $this->get_attribute( 'customThankyouRedirect' ) ) && 'redirect' === $confirmation_type ) {
3508            return true;
3509        }
3510        /**
3511         * Filter to check if the contact form has a redirect filter.
3512         *
3513         * @module contact-form
3514         *
3515         * @since 1.9.0
3516         *
3517         * @param bool $has_redirect True if the contact form has a redirect filter, false otherwise.
3518         */
3519        return (bool) has_filter( 'grunion_contact_form_redirect_url' );
3520    }
3521
3522    /**
3523     * Get the URL where the reader is redirected after submitting a form.
3524     *
3525     * @param array $refresh_args The arguments to be added to the redirect URL.
3526     * @param int   $id           Contact Form ID.
3527     * @param int   $post_id      Post ID.
3528     *
3529     * @return string The redirect URL.
3530     */
3531    public function get_redirect_url( $refresh_args, $id, $post_id ) {
3532        $confirmation_type = $this->get_confirmation_type();
3533        $redirect          = '';
3534        $custom_redirect   = false;
3535
3536        if ( 'redirect' === $confirmation_type ) {
3537            $custom_redirect = true;
3538            $redirect        = esc_url_raw( $this->get_attribute( 'customThankyouRedirect' ) );
3539        }
3540
3541        if ( ! $redirect ) {
3542            $custom_redirect = false;
3543            $redirect        = wp_get_referer();
3544        }
3545
3546        if ( ! $redirect ) { // wp_get_referer() returns false if the referer is the same as the current page.
3547            $custom_redirect = false;
3548            $redirect        = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
3549        }
3550
3551        if ( ! $custom_redirect ) {
3552            $redirect = add_query_arg(
3553                urlencode_deep( $refresh_args ),
3554                $redirect
3555            );
3556        }
3557
3558        /**
3559         * Filter the URL where the reader is redirected after submitting a form.
3560         *
3561         * @module contact-form
3562         *
3563         * @since 1.9.0
3564         *
3565         * @param string $redirect Post submission URL.
3566         * @param int $id Contact Form ID.
3567         * @param int $post_id Post ID.
3568         */
3569        return apply_filters( 'grunion_contact_form_redirect_url', $redirect, $id, $post_id );
3570    }
3571
3572    /**
3573     * Get the permalink for the post ID that include the page query parameter if it was set.
3574     *
3575     * @param int $post_id The post ID.
3576     *
3577     * return string The permalink for the post ID.
3578     */
3579    public static function get_permalink( $post_id ) {
3580        $url  = get_permalink( $post_id );
3581        $page = isset( $_POST['page'] ) ? absint( wp_unslash( $_POST['page'] ) ) : null; // phpcs:Ignore WordPress.Security.NonceVerification.Missing
3582        if ( $page ) {
3583            return add_query_arg( 'page', $page, $url );
3584        }
3585        return $url;
3586    }
3587
3588    /**
3589     * Wrapper for wp_mail() that enables HTML messages with text alternatives
3590     *
3591     * @param string|array $to          Array or comma-separated list of email addresses to send message.
3592     * @param string       $subject     Email subject.
3593     * @param string       $message     Message contents.
3594     * @param string|array $headers     Optional. Additional headers.
3595     * @param string|array $attachments Optional. Files to attach.
3596     *
3597     * @return bool Whether the email contents were sent successfully.
3598     */
3599    public static function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
3600        return Feedback_Email_Renderer::wp_mail( $to, $subject, $message, $headers, $attachments );
3601    }
3602
3603    /**
3604     * Add a display name part to an email address
3605     *
3606     * SpamAssassin doesn't like addresses in HTML messages that are missing display names (e.g., `foo@bar.org`
3607     * instead of `Foo Bar <foo@bar.org>`.
3608     *
3609     * @param string $address - the email address.
3610     *
3611     * @return string
3612     */
3613    public function add_name_to_address( $address ) {
3614        // If it's just the address, without a display name
3615        if ( is_email( $address ) ) {
3616            $address_parts = explode( '@', $address );
3617
3618            /*
3619             * The email address format here is formatted in a format
3620             * that is the most likely to be accepted by wp_mail(),
3621             * without escaping.
3622             * More info: https://github.com/Automattic/jetpack/pull/19727
3623             */
3624            $address = sprintf( '%s <%s>', $address_parts[0], $address );
3625        }
3626
3627        return $address;
3628    }
3629
3630    /**
3631     * Get the content type that should be assigned to outbound emails
3632     *
3633     * @return string
3634     */
3635    public static function get_mail_content_type() {
3636        return Feedback_Email_Renderer::get_mail_content_type();
3637    }
3638
3639    /**
3640     * Wrap a message body with the appropriate in HTML tags
3641     *
3642     * This helps to ensure correct parsing by clients, and also helps avoid triggering spam filtering rules
3643     *
3644     * @param string $title - title of the email.
3645     * @param string $body - the message body.
3646     * @param string $footer - the footer containing meta information.
3647     * @param string $actions - HTML for actions displayed in the email.
3648     * @param array  $respondent_info - Optional. Respondent information array with 'name', 'email', 'avatar'.
3649     * @param array  $metadata - Optional. Metadata array with 'date', 'source', 'source_url', 'device', 'ip', 'ip_flag'.
3650     *
3651     * @return string
3652     */
3653    public static function wrap_message_in_html_tags( $title, $body, $footer, $actions = '', $respondent_info = array(), $metadata = array() ) {
3654        return Feedback_Email_Renderer::wrap_message_in_html_tags( $title, $body, $footer, $actions, $respondent_info, $metadata );
3655    }
3656
3657    /**
3658     * Add a plain-text alternative part to an outbound email
3659     *
3660     * This makes the message more accessible to mail clients that aren't HTML-aware, and decreases the likelihood
3661     * that the message will be flagged as spam.
3662     *
3663     * @param PHPMailer $phpmailer - the phpmailer.
3664     */
3665    public static function add_plain_text_alternative( $phpmailer ) {
3666        Feedback_Email_Renderer::add_plain_text_alternative( $phpmailer );
3667    }
3668
3669    /**
3670     * Add deepslashes.
3671     *
3672     * @param array $value - the value.
3673     * @return array The value, with slashes added.
3674     */
3675    public function addslashes_deep( $value ) {
3676        if ( is_array( $value ) ) {
3677            return array_map( array( $this, 'addslashes_deep' ), $value );
3678        } elseif ( is_object( $value ) ) {
3679            $vars = get_object_vars( $value );
3680            foreach ( $vars as $key => $data ) {
3681                $value->{$key} = $this->addslashes_deep( $data );
3682            }
3683            return (array) $value;
3684        }
3685
3686        return addslashes( $value );
3687    }
3688
3689    /**
3690     * Get the block's classes.
3691     * This gathers both the alignment classes and the layout classes,
3692     * which go on the outermost div.
3693     *
3694     * @param array $attributes Block attributes.
3695     * @param array $extra_container_classes Extra container classes.
3696     * @return string The block's classes.
3697     */
3698    public static function get_block_container_classes( $attributes = array(), $extra_container_classes = array() ) {
3699        // using wp-block-jetpack-contact-form-container here
3700        // confuses the layout support process, making it place the CSS classes on the container
3701        // instead of the actual block.
3702        $classes = array( 'jetpack-contact-form-container' );
3703
3704        $classes = array_merge( $classes, $extra_container_classes );
3705
3706        if ( isset( $attributes['variationName'] ) && $attributes['variationName'] === 'multistep' ) {
3707            $classes[] = 'is-multistep';
3708        }
3709
3710        $classes[] = self::get_block_alignment_class( $attributes );
3711
3712        return implode( ' ', $classes );
3713    }
3714
3715    /**
3716     * Rough implementation of Gutenberg's align-attribute-to-css-class map.
3717     * Only allowin "wide" and "full" as "center", "left" and "right" don't
3718     * make much sense for the form.
3719     *
3720     * @param array $attributes Block attributes.
3721     * @return string The CSS alignment class: alignfull | alignwide.
3722     */
3723    public static function get_block_alignment_class( $attributes = array() ) {
3724        $align_to_class_map = array(
3725            'wide' => 'alignwide',
3726            'full' => 'alignfull',
3727        );
3728        if ( empty( $attributes['align'] ) || ! array_key_exists( $attributes['align'], $align_to_class_map ) ) {
3729            return '';
3730        }
3731        return $align_to_class_map[ $attributes['align'] ];
3732    }
3733
3734    /**
3735     * Process a file upload field.
3736     *
3737     * @param string $field_id The field ID.
3738     * @param object $field The field object.
3739     *
3740     * @return array A structured array with field_id and files array.
3741     */
3742    public function process_file_upload_field( $field_id, $field ) {
3743        $field_id = sanitize_key( $field_id );
3744
3745        $raw_data = array();
3746        // phpcs:ignore WordPress.Security.NonceVerification.Missing
3747        if ( isset( $_POST[ $field_id ] ) ) {
3748
3749            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.NonceVerification.Missing
3750            $raw_post_data = wp_unslash( $_POST[ $field_id ] );
3751            if ( is_array( $raw_post_data ) ) {
3752                $raw_data = array_map( 'sanitize_text_field', $raw_post_data );
3753            }
3754        }
3755
3756        $file_data_array = is_array( $raw_data )
3757            ? array_map(
3758                function ( $json_str ) {
3759                    $decoded = json_decode( $json_str, true );
3760                    return array(
3761                        'file_id' => isset( $decoded['file_id'] ) ? sanitize_text_field( $decoded['file_id'] ) : '',
3762                        'name'    => isset( $decoded['name'] ) ? sanitize_text_field( $decoded['name'] ) : '',
3763                        'size'    => isset( $decoded['size'] ) ? absint( $decoded['size'] ) : 0,
3764                        'type'    => isset( $decoded['type'] ) ? sanitize_text_field( $decoded['type'] ) : '',
3765                    );
3766                },
3767                $raw_data
3768            ) : array();
3769
3770        if ( empty( $file_data_array ) ) {
3771            $field->add_error( __( 'Failed to upload file.', 'jetpack-forms' ) );
3772            return array(
3773                'field_id' => $field_id,
3774                'files'    => array(),
3775            );
3776        }
3777
3778        return array(
3779            'field_id' => $field_id,
3780            'files'    => $file_data_array,
3781        );
3782    }
3783
3784    /**
3785     * Ensures a value is formatted as a string, taking into account file upload fields.
3786     *
3787     * @param mixed $value The value to transform.
3788     * @return mixed The transformed value.
3789     */
3790    private static function maybe_transform_value( $value ) {
3791        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'image-select' ) {
3792            return implode(
3793                ', ',
3794                array_map(
3795                    function ( $choice ) {
3796                        $value = $choice['perceived'];
3797
3798                        if ( $choice['showLabels'] && ! empty( $choice['label'] ) ) {
3799                            $value .= ' - ' . $choice['label'];
3800                        }
3801
3802                        return $value;
3803                    },
3804                    $value['choices']
3805                )
3806            );
3807        }
3808
3809        // For URL fields, extract the display text value (original user input without auto-added protocol).
3810        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'url' ) {
3811            // Prefer displayValue (raw input) over url (which may have https:// prepended).
3812            return $value['displayValue'] ?? ( $value['url'] ?? '' );
3813        }
3814
3815        // For rating fields, return the displayValue (e.g., "3/5") for text fallback.
3816        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'rating' ) {
3817            return $value['displayValue'] ?? '';
3818        }
3819
3820        // For file upload fields, we want to show the file name and size
3821        if ( is_array( $value ) && isset( $value['name'] ) && isset( $value['size'] ) ) {
3822            $file_name = $value['name'];
3823            $file_size = $value['size'];
3824            return empty( $file_size ) ? $file_name : $file_name . ' (' . $file_size . ')';
3825        }
3826
3827        return $value;
3828    }
3829
3830    /**
3831     * Helper method to get the images from an image select field.
3832     *
3833     * Returns an array of image choice objects, each containing:
3834     * - src: The image URL
3835     * - letterCode: The letter code (e.g., 'A', 'B', 'C')
3836     * - label: The choice label text (empty string if showLabels is false)
3837     *
3838     * @param array $value The value to get the images from.
3839     * @return array|null The images with metadata, or null if not an image-select field.
3840     */
3841    private static function get_images( $value ) {
3842        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'image-select' ) {
3843            return array_map(
3844                function ( $choice ) {
3845                    $letter_code = $choice['perceived'] ?? '';
3846                    $label       = '';
3847
3848                    if ( ! empty( $choice['showLabels'] ) && ! empty( $choice['label'] ) ) {
3849                        $label = $choice['label'];
3850                    }
3851
3852                    return array(
3853                        'src'        => $choice['image']['src'] ?? '',
3854                        'letterCode' => $letter_code,
3855                        'label'      => $label,
3856                    );
3857                },
3858                $value['choices']
3859            );
3860        }
3861
3862        return null;
3863    }
3864
3865    /**
3866     * Get files from a file field value if present.
3867     *
3868     * @param mixed $value The field value.
3869     *
3870     * @return array|null Array of file data if this is a file field, null otherwise.
3871     */
3872    private static function get_files( $value ) {
3873        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'file' && ! empty( $value['files'] ) ) {
3874            return array_map(
3875                function ( $file ) {
3876                    $preview_url = $file['previewUrl'] ?? null;
3877                    $icon_url    = $file['iconUrl'] ?? null;
3878                    $has_preview = ! empty( $preview_url ) || ! empty( $icon_url );
3879
3880                    return array(
3881                        'name'       => $file['name'] ?? __( 'Attached file', 'jetpack-forms' ),
3882                        'size'       => $file['size'] ?? '',
3883                        'url'        => $file['url'] ?? '',
3884                        // Preview URLs are captured from the DOM for AJAX submissions
3885                        'previewUrl' => $preview_url,
3886                        'iconUrl'    => $icon_url,
3887                        // Boolean flag for easier binding evaluation
3888                        'hasPreview' => $has_preview,
3889                    );
3890                },
3891                $value['files']
3892            );
3893        }
3894
3895        return null;
3896    }
3897
3898    /**
3899     * Helper method to format a raw label string for display, including kses sanitization.
3900     *
3901     * @param string|null $raw_label The raw label input.
3902     * @return string The formatted and kses'd label string, or an empty string if raw_label is empty.
3903     */
3904    public static function escape_and_sanitize_field_label( $raw_label ) {
3905        if ( empty( $raw_label ) ) {
3906            return ''; // kses the empty string
3907        }
3908        return wp_kses( (string) $raw_label, array() );
3909    }
3910
3911    /**
3912     * Enforce required block supports UIs for Classic themes.
3913     *
3914     * @param \WP_Theme_JSON_Data $theme_json_data Theme JSON data object.
3915     *
3916     * @return \WP_Theme_JSON_Data Updated theme JSON settings.
3917     */
3918    public static function add_theme_json_data_for_classic_themes( $theme_json_data ) {
3919        if ( wp_is_block_theme() ) {
3920            return $theme_json_data;
3921        }
3922
3923        $data = $theme_json_data->get_data();
3924
3925        if ( ! isset( $data['settings']['blocks'] ) ) {
3926            $data['settings']['blocks'] = array();
3927        }
3928
3929        $data['settings']['blocks']['jetpack/input'] = array(
3930            'color'      => array(
3931                'text'       => true,
3932                'background' => false,
3933            ),
3934            'border'     => array(
3935                'color'  => true,
3936                'radius' => true,
3937                'style'  => true,
3938                'width'  => true,
3939            ),
3940            'typography' => array(
3941                'fontFamily'     => true,
3942                'fontSize'       => true,
3943                'fontStyle'      => true,
3944                'fontWeight'     => true,
3945                'letterSpacing'  => true,
3946                'lineHeight'     => true,
3947                'textDecoration' => true,
3948                'textTransform'  => true,
3949            ),
3950        );
3951
3952        // maybe need to add support for jetpack/phone-input
3953
3954        $data['settings']['blocks']['jetpack/options'] = array(
3955            'color'  => array(
3956                'text'       => true,
3957                'background' => true,
3958            ),
3959            'border' => array(
3960                'color'  => true,
3961                'radius' => true,
3962                'style'  => true,
3963                'width'  => true,
3964            ),
3965        );
3966
3967        $shared_settings                              = array(
3968            'color'      => array(
3969                'text'       => true,
3970                'background' => false,
3971            ),
3972            'typography' => array(
3973                'fontFamily'     => true,
3974                'fontSize'       => true,
3975                'fontStyle'      => true,
3976                'fontWeight'     => true,
3977                'letterSpacing'  => true,
3978                'lineHeight'     => true,
3979                'textDecoration' => true,
3980                'textTransform'  => true,
3981            ),
3982        );
3983        $data['settings']['blocks']['jetpack/label']  = $shared_settings;
3984        $data['settings']['blocks']['jetpack/option'] = $shared_settings;
3985
3986        $theme_json_class = get_class( $theme_json_data );
3987        return new $theme_json_class( $data, 'default' );
3988    }
3989
3990    /**
3991     * Validate the contact form fields.
3992     *
3993     * This method checks each field for errors and ensures that at least one field has a value.
3994     * If no fields have values and there are no errors, it adds an error indicating that the form is empty.
3995     */
3996    public function validate() {
3997        $has_value = false;
3998        // A field hidden by conditional logic was never shown to the visitor, so validating it
3999        // would block submission on an error they cannot see or clear — most visibly when the
4000        // hidden field is also required.
4001        $visibility = $this->get_resolved_field_visibility();
4002
4003        // Validate the form fields before processing the form.
4004        foreach ( $this->fields as $field_id => $field ) {
4005            if ( isset( $visibility[ $field_id ] ) && false === $visibility[ $field_id ] ) {
4006                continue;
4007            }
4008
4009            $field->validate();
4010            if ( ! $has_value && $field->has_value() ) {
4011                $has_value = true;
4012            }
4013        }
4014
4015        if ( ! $has_value && ! $this->has_errors() ) {
4016            $this->add_error( 'empty', __( 'Please fill out at least one field.', 'jetpack-forms' ) );
4017        }
4018
4019        $ref_id = $this->get_attribute( 'ref' );
4020        if ( ! empty( $ref_id ) ) {
4021            $this->validate_ref( $ref_id );
4022        }
4023    }
4024
4025    /**
4026     * Build the form-level conditional-logic context handed to the front end.
4027     *
4028     * Two maps rather than one: `types` covers every field, because any of them may be the
4029     * subject of a rule, while `logic` covers only the few that carry conditions. Emitting
4030     * types solely for fields that have logic would leave the evaluator unable to resolve the
4031     * subject of most rules, and it ignores rules whose subject it cannot type.
4032     *
4033     * Returns an empty array when no field uses conditional logic, so the common case adds
4034     * nothing to the page.
4035     *
4036     * @return array Either an empty array or `array( 'types' => ..., 'logic' => ... )`.
4037     */
4038    public function get_conditional_logic_context() {
4039        if ( ! Jetpack_Forms::is_conditional_logic_enabled() ) {
4040            return array();
4041        }
4042
4043        $types   = array();
4044        $logic   = array();
4045        $formats = array();
4046
4047        foreach ( $this->fields as $field_id => $field ) {
4048            $types[ $field_id ] = $field->get_attribute( 'type' );
4049
4050            $date_format = $field->get_attribute( 'dateformat' );
4051            if ( ! empty( $date_format ) ) {
4052                $formats[ $field_id ] = $date_format;
4053            }
4054
4055            $field_logic = $field->get_attribute( 'conditionallogic' );
4056            if ( is_array( $field_logic ) && ! empty( $field_logic['enabled'] ) ) {
4057                $logic[ $field_id ] = $field_logic;
4058            }
4059        }
4060
4061        // Containers are targets, never subjects: they hold no value to compare, so they carry
4062        // logic but no meaningful type. They are typed anyway because the evaluator reads a
4063        // type for every descriptor it is given.
4064        foreach ( $this->container_logic as $container_id => $container_logic ) {
4065            $types[ $container_id ] = Conditional_Logic::TYPE_CONTAINER;
4066            $logic[ $container_id ] = $container_logic;
4067        }
4068
4069        if ( empty( $logic ) ) {
4070            return array();
4071        }
4072
4073        return array(
4074            'types'    => $types,
4075            'logic'    => $logic,
4076            // Only date fields appear here; everything else compares without a format.
4077            'formats'  => $formats,
4078            // Which fields each container encloses. The browser needs this for the same reason
4079            // the server does: a required field inside a hidden container must not block
4080            // submission, and the two sides have to agree on which fields those are.
4081            'contains' => $this->container_contains,
4082        );
4083    }
4084
4085    /**
4086     * Resolve which fields are visible for the current submission.
4087     *
4088     * Computed once and cached: validation and storage both consult it, and letting them
4089     * resolve separately would risk them disagreeing about whether a field was shown.
4090     *
4091     * @return array Map of field id to bool visibility.
4092     */
4093    public function get_resolved_field_visibility() {
4094        if ( null !== $this->resolved_field_visibility ) {
4095            return $this->resolved_field_visibility;
4096        }
4097
4098        // With the feature off every field is visible, so validation and storage behave
4099        // exactly as they did before conditional logic existed. This is the single choke
4100        // point for the runtime: callers do not need their own flag checks.
4101        if ( ! Jetpack_Forms::is_conditional_logic_enabled() ) {
4102            $this->resolved_field_visibility = array();
4103
4104            return $this->resolved_field_visibility;
4105        }
4106
4107        $this->resolved_field_visibility = $this->compute_field_visibility();
4108
4109        return $this->resolved_field_visibility;
4110    }
4111
4112    /**
4113     * Resolve which fields are visible, without caching.
4114     *
4115     * @return array Map of field id to bool visibility.
4116     */
4117    private function compute_field_visibility() {
4118        if ( ! Jetpack_Forms::is_conditional_logic_enabled() ) {
4119            return array();
4120        }
4121
4122        // The type check stays unconditional. `$fields` is declared with no default, so it is
4123        // null until add_field() runs, and the loop below would fatal on PHP 8. Only the
4124        // emptiness half may be relaxed: a form with no fields but a conditional container
4125        // still has visibility to resolve.
4126        if ( ! is_array( $this->fields ) ) {
4127            return array();
4128        }
4129
4130        if ( empty( $this->fields ) && empty( $this->container_logic ) ) {
4131            return array();
4132        }
4133
4134        $descriptors = array();
4135        $values      = array();
4136
4137        foreach ( $this->fields as $field_id => $field ) {
4138            $descriptors[ $field_id ] = array(
4139                'logic'  => $field->get_attribute( 'conditionallogic' ),
4140                'type'   => $field->get_attribute( 'type' ),
4141                // A date field's value is written in its own format, and the comparison has
4142                // to read it the same way the datepicker wrote it.
4143                'format' => $field->get_attribute( 'dateformat' ),
4144            );
4145
4146            // Resolve the value exactly as the field itself does when rendering: submitted
4147            // value first, then a `?field_id=value` query parameter, then the configured
4148            // default, then the logged-in user's details. Reading $_POST alone would make a
4149            // prefilled form resolve against an empty one, so a field the visitor can already
4150            // see satisfying a condition would render hidden and then flash into view.
4151            $values[ $field_id ] = $field->get_conditional_logic_value();
4152        }
4153
4154        foreach ( $this->container_logic as $container_id => $container_logic ) {
4155            $descriptors[ $container_id ] = array(
4156                'logic'  => $container_logic,
4157                'type'   => Conditional_Logic::TYPE_CONTAINER,
4158                'format' => null,
4159            );
4160        }
4161
4162        /*
4163         * Containment goes into the evaluator rather than being applied to what it returns. A
4164         * field inside a hidden container has to read as empty for everyone else, the same as a
4165         * field its own rules hid -- otherwise its answer can unlock a field outside the group
4166         * that is then validated and stored, while the answer that unlocked it is dropped.
4167         */
4168        return Conditional_Logic::resolve_visibility( $descriptors, $values, $this->container_contains );
4169    }
4170
4171    /**
4172     * Validate the form reference.
4173     *
4174     * @param int $ref The form reference ID.
4175     */
4176    public function validate_ref( $ref ) {
4177        $form_post = get_post( $ref );
4178        if ( ! $form_post || self::POST_TYPE !== $form_post->post_type ) {
4179            $this->add_error( 'invalid_ref', __( 'Invalid form reference.', 'jetpack-forms' ) );
4180            return;
4181        }
4182        if ( $form_post->post_status !== 'publish' ) {
4183            $this->add_error( 'unpublished_form', __( 'Invalid form reference.', 'jetpack-forms' ) );
4184            return;
4185        }
4186    }
4187
4188    /**
4189     * Reset the static errors for the contact form.
4190     *
4191     * @param string $id The ID of the contact form to reset errors for. If null, resets all static errors.
4192     *
4193     * This method is used to clear the static errors stored in the class.
4194     */
4195    public static function reset_errors( $id = null ) {
4196        if ( $id && isset( self::$static_errors[ $id ] ) ) {
4197            unset( self::$static_errors[ $id ] );
4198            return;
4199        }
4200        self::$static_errors = array();
4201    }
4202
4203    /**
4204     * Add an error to the contact form.
4205     *
4206     * @param string $error_code    The error code.
4207     * @param string $error_message The error message.
4208     */
4209    public function add_error( $error_code, $error_message ) {
4210        $id = $this->get_attribute( 'id' );
4211        if ( ! isset( self::$static_errors[ $id ] ) ) {
4212            self::$static_errors[ $id ] = Form_Submission_Error::validation_error( $error_code, $error_message );
4213        } else {
4214            // If we already have errors, add this error to the existing Form_Submission_Error
4215            self::$static_errors[ $id ]->add( $error_code, $error_message );
4216        }
4217        $this->errors = self::$static_errors[ $id ];
4218    }
4219    /**
4220     * Check if the contact form has errors.
4221     *
4222     * @return bool True if the contact form has errors, false otherwise.
4223     */
4224    public function has_errors() {
4225        $id = $this->get_attribute( 'id' );
4226        if ( ! isset( self::$static_errors[ $id ] ) ) {
4227            return false;
4228        }
4229        return is_wp_error( self::$static_errors[ $id ] ) && ! empty( self::$static_errors[ $id ]->get_error_codes() );
4230    }
4231
4232    /**
4233     * Get the error messages of the contact form.
4234     *
4235     * @return array The errors of the contact form.
4236     */
4237    public function get_error_messages() {
4238        if ( ! $this->has_errors() ) {
4239            return array();
4240        }
4241        $id = $this->get_attribute( 'id' );
4242        return self::$static_errors[ $id ]->get_error_messages();
4243    }
4244
4245    /**
4246     * Get the confirmation type of the contact form from the deprecated customThankyou attribute.
4247     *
4248     * @return string The confirmation type of the contact form.
4249     */
4250    public function get_confirmation_type() {
4251        // Backward compat: customThankyou 'redirect' takes precedence for old forms
4252        if ( 'redirect' === $this->get_attribute( 'customThankyou' ) ) {
4253            return 'redirect';
4254        }
4255
4256        return $this->get_attribute( 'confirmationType' );
4257    }
4258
4259    /**
4260     * Get the disable summary of the contact form from the deprecated customThankyou attribute.
4261     *
4262     * @return string The disable summary of the contact form.
4263     */
4264    public function get_disable_summary() {
4265        $disable_summary = $this->get_attribute( 'disableSummary' );
4266        $custom_thankyou = $this->get_attribute( 'customThankyou' );
4267
4268        if ( '' === $disable_summary ) {
4269            $disable_summary = 'noSummary' === $custom_thankyou || 'message' === $custom_thankyou;
4270        }
4271
4272        return $disable_summary;
4273    }
4274}