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