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