Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
64.78% covered (warning)
64.78%
1017 / 1570
38.55% covered (danger)
38.55%
32 / 83
CRAP
0.00% covered (danger)
0.00%
0 / 1
Contact_Form
64.90% covered (warning)
64.90%
1017 / 1567
38.55% covered (danger)
38.55%
32 / 83
14021.24
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 / 16
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
1315    /**
1316     * The contact-form shortcode processor
1317     *
1318     * @param array       $attributes Key => Value pairs as parsed by shortcode_parse_atts().
1319     * @param string|null $content The shortcode's inner content: [contact-form]$content[/contact-form].
1320     * @param array       $context An array of context data for the form.
1321     *
1322     * @return string HTML for the concat form.
1323     */
1324    public static function parse( $attributes, $content, $context = array() ) {
1325        global $post, $page, $multipage; // $page is used in the contact-form submission redirect
1326        if ( Settings::is_syncing() ) {
1327            return '';
1328        }
1329
1330        // Handle ref attribute - load form from jetpack_form post
1331        if ( is_array( $attributes ) && isset( $attributes['ref'] ) ) {
1332            $ref_id = absint( $attributes['ref'] );
1333            if ( $ref_id > 0 ) {
1334                return self::render_synced_form( $ref_id );
1335            } else {
1336                return '';
1337            }
1338        }
1339
1340        if ( isset( $GLOBALS['grunion_block_template_part_id'] ) ) {
1341            self::style_on();
1342            if ( is_array( $attributes ) ) {
1343                $attributes['block_template_part'] = $GLOBALS['grunion_block_template_part_id'];
1344            }
1345        }
1346
1347        if ( is_singular() ) {
1348            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.
1349        }
1350        $plugin               = Contact_Form_Plugin::init();
1351        $attributes['widget'] = $plugin->get_current_widget_context();
1352        // Create a new Contact_Form object (this class)
1353        if ( self::$ref_id ) {
1354            $attributes['ref'] = self::$ref_id;
1355        }
1356
1357        $form = new Contact_Form( $attributes, $content );
1358        Contact_Form_Plugin::reset_step();
1359
1360        $id = $form->get_attribute( 'id' );
1361
1362        if ( ! $id ) { // something terrible has happened
1363            return '[contact-form]';
1364        }
1365
1366        if ( is_feed() ) {
1367            return '[contact-form]';
1368        }
1369
1370        self::$last = $form;
1371
1372        // Enqueue the grunion.css stylesheet if self::$style allows it
1373        if ( self::$style && ( empty( $_REQUEST['action'] ) || $_REQUEST['action'] !== 'grunion_shortcode_to_json' ) ) {
1374            // Enqueue the style here instead of printing it, because if some other plugin has run the_post()+rewind_posts(),
1375            // (like VideoPress does), the style tag gets "printed" the first time and discarded, leaving the contact form unstyled.
1376            // when WordPress does the real loop.
1377            wp_enqueue_style( 'grunion.css' );
1378            wp_enqueue_script( 'accessible-form' );
1379        }
1380
1381        $version = \JETPACK__VERSION;
1382
1383        // Extra cache busting strategy for view.js, seems they are left out of cache clearing on deploys
1384        $asset_file = plugin_dir_path( __FILE__ ) . 'dist/modules/form/view.asset.php';
1385        $asset      = file_exists( $asset_file ) ? require $asset_file : null;
1386
1387        if ( $asset && isset( $asset['version'] ) ) {
1388            $version = $asset['version'];
1389        }
1390
1391        $config = array(
1392            'error_types'    => array(
1393                'is_required'        => __( 'This field is required.', 'jetpack-forms' ),
1394                'invalid_form_empty' => __( 'The form you are trying to submit is empty.', 'jetpack-forms' ),
1395                'invalid_form'       => __( 'Please fill out the form correctly.', 'jetpack-forms' ),
1396                'network_error'      => __( 'Connection issue while submitting the form. Check that you are connected to the Internet and try again.', 'jetpack-forms' ),
1397            ),
1398            'admin_ajax_url' => admin_url( 'admin-ajax.php' ),
1399        );
1400        wp_interactivity_config( 'jetpack/form', $config );
1401        \wp_enqueue_script_module(
1402            'jp-forms-view',
1403            plugins_url( 'dist/modules/form/view.js', dirname( __DIR__ ) ),
1404            array( '@wordpress/interactivity' ),
1405            $version
1406        );
1407
1408        $is_single_input_form = is_array( $form->fields ) && count( $form->fields ) === 1;
1409        $is_flex_layout       = isset( $attributes['layout']['type'] ) && $attributes['layout']['type'] === 'flex';
1410        $is_nowrap_layout     = isset( $attributes['layout']['flexWrap'] ) && $attributes['layout']['flexWrap'] === 'nowrap';
1411        $is_forced_horizontal = $is_flex_layout && $is_nowrap_layout
1412            && ( ! isset( $attributes['layout']['orientation'] ) || $attributes['layout']['orientation'] === 'horizontal' );
1413
1414        $extra_container_classes = array();
1415        if ( $is_forced_horizontal ) {
1416            $extra_container_classes[] = 'is-forced-horizontal-form';
1417        }
1418        if ( $is_single_input_form ) {
1419            $extra_container_classes[] = 'is-single-input-form';
1420        }
1421        $container_classes_string = self::get_block_container_classes( $attributes, $extra_container_classes );
1422
1423        $is_reload_after_success = isset( $_GET['contact-form-id'] )
1424        && (int) $_GET['contact-form-id'] === (int) self::$last->get_attribute( 'id' )
1425        && isset( $_GET['contact-form-sent'] )
1426        && isset( $_GET['contact-form-hash'] )
1427        && is_string( $_GET['contact-form-hash'] )
1428        && hash_equals( $form->hash, wp_unslash( $_GET['contact-form-hash'] ) );
1429
1430        $feedback_id           = 0;
1431        $is_reload_nonce_valid = false;
1432
1433        if ( $is_reload_after_success ) {
1434            $feedback_id           = (int) $_GET['contact-form-sent'];
1435            $is_reload_nonce_valid = isset( $_GET['_wpnonce'] )
1436                && wp_verify_nonce( sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ), "contact-form-sent-{$feedback_id}" );
1437        }
1438
1439        $max_steps = 0;
1440        if ( preg_match_all( '/data-wp-context=[\'"]?{"step":(\d+)}[\'"]?/', $content, $matches ) ) {
1441            if ( ! empty( $matches[1] ) ) {
1442                $max_steps = max( array_map( 'intval', $matches[1] ) );
1443            }
1444        }
1445
1446        $is_multistep = $max_steps > 0;
1447        $element_id   = 'jp-form-' . esc_attr( $form->hash );
1448
1449        // Initial data used to render the success message when the page is reloaded after a successful submission
1450        // Don't show the feedback details unless the nonce matches
1451        $submission_data = null;
1452
1453        if ( $is_reload_after_success && $is_reload_nonce_valid ) {
1454            $response = Feedback::get( (int) $_GET['contact-form-sent'] );
1455
1456            if ( $response ) {
1457                $submission_data = $response->get_compiled_fields( 'web', 'collection' );
1458            }
1459        }
1460
1461        $formatted_submission_data = $submission_data ? self::format_submission_data( $submission_data ) : array();
1462        $submission_success        = $form->is_response_without_reload_enabled && $is_reload_after_success;
1463        $has_custom_redirect       = $form->has_custom_redirect();
1464
1465        $default_context = array(
1466            'formId'                  => $id,
1467            'formHash'                => $form->hash,
1468            'showErrors'              => $form->has_errors(), // We toggle this to true when we want to show the user errors right away.
1469            'errors'                  => array(), // This should be a associative array.
1470            'fields'                  => array(),
1471            'isMultiStep'             => $is_multistep, // Whether the form is a multistep form.
1472            'useAjax'                 => $form->is_response_without_reload_enabled && ! $has_custom_redirect,
1473            'submissionData'          => $submission_data,
1474            'formattedSubmissionData' => $formatted_submission_data,
1475            'submissionSuccess'       => $submission_success,
1476            'submissionError'         => null,
1477            'elementId'               => $element_id,
1478            'isSingleInputForm'       => $is_single_input_form,
1479            'isForcedHorizontal'      => $is_forced_horizontal,
1480        );
1481
1482        if ( $is_multistep ) {
1483            $multistep_context = array(
1484                'currentStep' => isset( $_GET[ $id . '-step' ] ) ? absint( $_GET[ $id . '-step' ] ) : 1,
1485                'maxSteps'    => $max_steps,
1486                'direction'   => 'forward', // Default direction for animations
1487                'transition'  => $form->get_attribute( 'stepTransition' ) ? $form->get_attribute( 'stepTransition' ) : 'fade-slide', // Transition style for step animations
1488            );
1489
1490            if ( ! is_array( $context ) ) {
1491                $context = array();
1492            }
1493            $context = array_merge( $context, $multistep_context );
1494        }
1495
1496        $context = is_array( $context ) ? array_merge( $default_context, $context ) : $default_context;
1497
1498        $r  = '';
1499        $r .= "<div data-test='contact-form'
1500            id='contact-form-$id'
1501            class='{$container_classes_string}'
1502            data-wp-interactive='jetpack/form' " . wp_interactivity_data_wp_context( $context ) . "
1503            data-wp-watch--scroll-to-wrapper=\"callbacks.scrollToWrapper\"
1504        >\n";
1505
1506        if ( $form->is_response_without_reload_enabled ) {
1507            $r .= self::render_ajax_success_wrapper( $form, $submission_success, $formatted_submission_data );
1508        }
1509
1510        if ( $form->has_errors() ) {
1511            // There are errors.  Display them
1512            $r .= "<div class='form-error'>\n<h3>" . __( 'Error!', 'jetpack-forms' ) . "</h3>\n<ul class='form-errors'>\n";
1513            foreach ( $form->get_error_messages() as $message ) {
1514                $r .= "\t<li class='form-error-message'>" . esc_html( $message ) . "</li>\n";
1515            }
1516            $r .= "</ul>\n</div>\n\n";
1517        }
1518
1519        if ( $is_reload_after_success && $form->is_response_without_reload_enabled ) {
1520            $r .= '<noscript>';
1521            $r .= self::render_noscript_success_message( $is_reload_nonce_valid, $feedback_id, $form );
1522            $r .= '</noscript>';
1523        }
1524
1525        if ( $is_reload_after_success && ! $form->is_response_without_reload_enabled ) {
1526            // The contact form was submitted.  Show the success message/results.
1527            $r .= self::render_noscript_success_message( $is_reload_nonce_valid, $feedback_id, $form );
1528        } else {
1529            // Nothing special - show the normal contact form
1530            if ( $form->get_attribute( 'widget' )
1531                || $form->get_attribute( 'block_template' )
1532                || $form->get_attribute( 'block_template_part' ) ) {
1533                // Submit form to the current URL
1534                $url = remove_query_arg( array( 'contact-form-id', 'contact-form-sent', 'action', '_wpnonce' ) );
1535            } else {
1536                // Submit form to the post permalink
1537                $url = get_permalink();
1538                if ( $multipage && $page ) {
1539                    $url = add_query_arg( 'page', $page, $url );
1540                }
1541            }
1542
1543            // For SSL/TLS page. See RFC 3986 Section 4.2
1544            $url = set_url_scheme( $url );
1545
1546            // May eventually want to send this to admin-post.php...
1547            /**
1548             * Filter the contact form action URL.
1549             *
1550             * @module contact-form
1551             *
1552             * @since 1.3.1
1553             *
1554             * @param string $contact_form_id Contact form post URL.
1555             * @param $post $GLOBALS['post'] Post global variable.
1556             * @param int $id Contact Form ID.
1557             */
1558            $url                     = apply_filters( 'grunion_contact_form_form_action', $url, $GLOBALS['post'], $id, $page );
1559            $has_submit_button_block = str_contains( $content, 'wp-block-jetpack-button' ) || str_contains( $content, 'wp-block-button' );
1560            $form_classes            = 'contact-form commentsblock jetpack-contact-form__form';
1561            if ( $submission_success ) {
1562                $form_classes .= ' submission-success';
1563            }
1564
1565            if ( isset( $attributes['layout'] ) ) {
1566                $form_classes .= ' has-jetpack-form-layout';
1567            } else {
1568                $form_classes .= ' has-no-jetpack-form-layout';
1569            }
1570
1571            $post_title           = $post->post_title ?? '';
1572            $form_accessible_name = ! empty( $attributes['formTitle'] ) ? $attributes['formTitle'] : $post_title;
1573            $form_aria_label      = isset( $form_accessible_name ) && ! empty( $form_accessible_name ) ? 'aria-label="' . esc_attr( $form_accessible_name ) . '"' : '';
1574
1575            $r .= "<form action='" . esc_url( $url ) . "'
1576                id='" . $element_id . "'
1577                method='post'
1578                class='" . esc_attr( $form_classes ) . "$form_aria_label
1579                data-wp-on--submit=\"actions.onFormSubmit\"
1580                data-wp-on--reset=\"actions.onFormReset\"
1581                data-wp-class--submission-success=\"context.submissionSuccess\"
1582                data-wp-class--is-first-step=\"state.isFirstStep\"
1583                data-wp-class--is-last-step=\"state.isLastStep\"
1584                data-wp-class--is-ajax-form=\"context.useAjax\"
1585                novalidate >\n";
1586
1587            if ( $is_multistep ) { // This makes the "enter" key work in multi-step forms as expected.
1588                $r .= '<input type="submit" style="display: none;" />';
1589            }
1590            $r .= "<input type='hidden' name='jetpack_contact_form_jwt' value='" . esc_attr( $form->get_jwt() ) . "' />\n";
1591            $r .= $form->body;
1592
1593            if ( $is_multistep ) {
1594                $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 );
1595            } elseif ( $has_submit_button_block ) {
1596                $r = self::prepare_submit_button( $r );
1597                // Place the error wrapper before the FIRST button block only to avoid duplicates (e.g., navigation buttons in multistep forms).
1598                // Replace only the first occurrence of a wp-block-jetpack-button prepending it with the error wrapper.
1599                // Fallback with same strategy for new core button blocks.
1600                if ( $is_forced_horizontal || $is_single_input_form ) {
1601                    // When user forced a horizontal layout, place the error wrapper
1602                    // after the form body.
1603                    $r .= self::render_error_wrapper( 'is-horizontal' );
1604                } else {
1605                    // Place the error wrapper before the FIRST button block only to avoid duplicates (e.g., navigation buttons in multistep forms).
1606                    // Replace only the first occurrence.
1607                    $r = preg_replace( '/<div class="wp-block-jetpack-button/', self::render_error_wrapper() . ' <div class="wp-block-jetpack-button', $r, 1 );
1608                    if ( str_contains( $r, 'wp-block-button' ) ) {
1609                        $r = preg_replace( '/<div class="wp-block-button/', self::render_error_wrapper() . ' <div class="wp-block-button', $r, 1 );
1610                    }
1611                }
1612            }
1613
1614            // In new versions of the contact form block the button is an inner block
1615            // so the button does not need to be constructed server-side.
1616            if ( ! $has_submit_button_block ) {
1617                $r .= "\t<p class='contact-submit'>\n";
1618
1619                $gutenberg_submit_button_classes = '';
1620                if ( ! empty( $attributes['submitButtonClasses'] ) ) {
1621                    $gutenberg_submit_button_classes = ' ' . $attributes['submitButtonClasses'];
1622                }
1623
1624                /**
1625                 * Filter the contact form submit button class attribute.
1626                 *
1627                 * @module contact-form
1628                 *
1629                 * @since 6.6.0
1630                 *
1631                 * @param string $class Additional CSS classes for button attribute.
1632                 */
1633                $submit_button_class = apply_filters( 'jetpack_contact_form_submit_button_class', 'pushbutton-wide' . $gutenberg_submit_button_classes );
1634
1635                $submit_button_styles = '';
1636                if ( ! empty( $attributes['customBackgroundButtonColor'] ) ) {
1637                    $submit_button_styles .= 'background-color: ' . $attributes['customBackgroundButtonColor'] . '; ';
1638                }
1639                if ( ! empty( $attributes['customTextButtonColor'] ) ) {
1640                    $submit_button_styles .= 'color: ' . $attributes['customTextButtonColor'] . ';';
1641                }
1642                if ( ! empty( $attributes['submitButtonText'] ) ) {
1643                    $submit_button_text = $attributes['submitButtonText'];
1644                } else {
1645                    $submit_button_text = $form->get_attribute( 'submit_button_text' );
1646                }
1647
1648                $r .= self::render_error_wrapper();
1649                $r .= "\t\t<button type='submit' class='" . esc_attr( $submit_button_class ) . "'";
1650                if ( ! empty( $submit_button_styles ) ) {
1651                    $r .= " style='" . esc_attr( $submit_button_styles ) . "'";
1652                }
1653                $r .= '>';
1654                $r .= wp_kses(
1655                    $submit_button_text,
1656                    self::$allowed_html_tags_for_submit_button
1657                ) . '</button>';
1658            }
1659
1660            if ( is_user_logged_in() ) {
1661                $r .= "\t\t" . wp_nonce_field( 'contact-form_' . $id, '_wpnonce', true, false ) . "\n"; // nonce and referer
1662            }
1663
1664            if ( isset( $attributes['hasFormSettingsSet'] ) && $attributes['hasFormSettingsSet'] ) {
1665                $r .= "\t\t<input type='hidden' name='is_block' value='1' />\n";
1666            }
1667            $r .= "\t\t<input type='hidden' name='contact-form-id' value='$id' />\n";
1668            $r .= "\t\t<input type='hidden' name='action' value='grunion-contact-form' />\n";
1669            $r .= "\t\t<input type='hidden' name='contact-form-hash' value='" . esc_attr( $form->hash ) . "' />\n";
1670
1671            if ( ! $has_submit_button_block ) {
1672                $r .= "\t</p>\n";
1673            }
1674
1675            $r .= "</form>\n";
1676        }
1677
1678        $r .= '</div>';
1679
1680        // Surface an admin-only warning above the form when nothing will capture its responses.
1681        $r = self::render_not_collecting_notice( $attributes ) . $r;
1682
1683        /**
1684         * Filter the contact form, allowing plugins to modify the HTML.
1685         *
1686         * @module contact-form
1687         *
1688         * @since 10.2.0
1689         *
1690         * @param string $r The contact form HTML.
1691         */
1692        return apply_filters( 'jetpack_contact_form_html', $r );
1693    }
1694
1695    /**
1696     * Prepare the submit button for the contact form.
1697     * Add interactivity attributes to submit buttons identified by:
1698     * - Legacy: type="submit" attribute
1699     * - New: is-submit or form-button-submit class
1700     *
1701     * @param string $content - the content of the submit button.
1702     *
1703     * @return string - the prepared content of the submit button.
1704     */
1705    private static function prepare_submit_button( $content ) {
1706        if ( ! class_exists( \WP_HTML_Tag_Processor::class ) ) {
1707            return $content;
1708        }
1709
1710        $p = new \WP_HTML_Tag_Processor( $content );
1711        while ( $p->next_tag( 'button' ) ) {
1712            $is_submit_by_type  = 'submit' === $p->get_attribute( 'type' );
1713            $is_submit_by_class = $p->has_class( 'is-submit' ) || $p->has_class( 'form-button-submit' );
1714
1715            if ( $is_submit_by_type || $is_submit_by_class ) {
1716                self::add_submit_button_interactivity_attributes( $p );
1717            }
1718        }
1719
1720        return $p->get_updated_html();
1721    }
1722
1723    /**
1724     * Adds Interactivity API attributes to the current element in a WP_HTML_Tag_Processor.
1725     *
1726     * Sets data-wp-class, data-wp-bind--aria-disabled, and data-wp-bind--disabled
1727     * on the submit button so the Interactivity API can toggle visual feedback
1728     * (spinner class, disabled state) while the form is submitting.
1729     *
1730     * Called from both single-step forms (prepare_submit_button) and multi-step
1731     * forms (gutenblock_render_form_step_navigation) to keep the attribute list
1732     * in one place.
1733     *
1734     * @param \WP_HTML_Tag_Processor $processor Tag processor positioned on a <button> element.
1735     * @return void
1736     */
1737    public static function add_submit_button_interactivity_attributes( $processor ) {
1738        if ( ! $processor || ! is_a( $processor, \WP_HTML_Tag_Processor::class ) ) {
1739            return;
1740        }
1741        $processor->set_attribute( 'data-wp-class--is-submitting', 'state.isSubmitting' );
1742        $processor->set_attribute( 'data-wp-bind--aria-disabled', 'state.isAriaDisabled' );
1743        $processor->set_attribute( 'data-wp-bind--disabled', 'state.isAriaDisabled' );
1744    }
1745
1746    /**
1747     * Renders the success message for the contact form when js is disabled or not desired.
1748     *
1749     * @param bool         $is_reload_nonce_valid - whether the nonce is valid.
1750     * @param int          $feedback_id - the feedback ID.
1751     * @param Contact_Form $form - the contact form.
1752     *
1753     * @return string HTML string for the success message.
1754     */
1755    private static function render_noscript_success_message( $is_reload_nonce_valid, $feedback_id, $form ) {
1756        $back_url        = remove_query_arg( array( 'contact-form-id', 'contact-form-sent', '_wpnonce', 'contact-form-hash' ) );
1757        $contact_form_id = sanitize_text_field( wp_unslash( $_GET['contact-form-id'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1758        $disable_go_back = $form->get_attribute( 'disableGoBack' );
1759
1760        $message = '';
1761
1762        $message .= '<style>
1763            .contact-form-ajax-submission {
1764                display: none;
1765            }
1766
1767            #contact-form-' . $contact_form_id . ' form.contact-form {
1768                display: none;
1769            }
1770        </style>';
1771
1772        $message        .= '<div class="contact-form-submission">';
1773        $success_message = '';
1774
1775        if ( ! $disable_go_back ) {
1776            $success_message = '<p class="go-back-message"> <a class="link" href="' . esc_url( $back_url ) . '">' . esc_html__( '← Back', 'jetpack-forms' ) . '</a> </p>';
1777        }
1778
1779        $success_message .= '<h4 id="contact-form-success-header">' . esc_html( $form->get_attribute( 'customThankyouHeading' ) ) . "</h4>\n\n";
1780
1781        // Don't show the feedback details unless the nonce matches
1782        if ( $is_reload_nonce_valid ) {
1783            $success_message .= self::success_message( $feedback_id, $form );
1784        }
1785
1786        /**
1787         * Filter the message returned after a successful contact form submission.
1788         *
1789         * @module contact-form
1790         *
1791         * @since 1.3.1
1792         *
1793         * @param string $message Success message.
1794         */
1795        $message .= apply_filters( 'grunion_contact_form_success_message', $success_message );
1796        $message .= '</div>';
1797
1798        return $message;
1799    }
1800
1801    /**
1802     * Helper function to format the submission data for the success message.
1803     *
1804     * @param array $data The submission data (in 'collection' format with type).
1805     *
1806     * @return array The formatted submission data.
1807     */
1808    private static function format_submission_data( $data ) {
1809        $formatted_submission_data = array();
1810
1811        foreach ( $data as $field_data ) {
1812            $url    = self::get_url( $field_data['value'] );
1813            $images = self::get_images( $field_data['value'] );
1814            $files  = self::get_files( $field_data['value'] );
1815            $rating = self::get_rating( $field_data['value'] );
1816            $type   = $field_data['type'] ?? 'text';
1817
1818            $formatted_submission_data[] = array(
1819                'label'          => Util::maybe_add_colon_to_label( $field_data['label'] ),
1820                'value'          => self::maybe_transform_value( $field_data['value'] ),
1821                'images'         => $images,
1822                'url'            => $url,
1823                'files'          => $files,
1824                'rating'         => $rating,
1825                'type'           => $type,
1826                'showPlainValue' => empty( $url ) && empty( $images ) && empty( $files ) && empty( $rating ),
1827            );
1828        }
1829
1830        return $formatted_submission_data;
1831    }
1832
1833    /**
1834     * Get the URL from a URL field value if present.
1835     *
1836     * @param mixed $value The field value.
1837     *
1838     * @return string|null The URL if this is a URL field, null otherwise.
1839     */
1840    private static function get_url( $value ) {
1841        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'url' && ! empty( $value['url'] ) ) {
1842            $url = $value['url'];
1843
1844            // Prepend https:// if no protocol is specified.
1845            if ( ! preg_match( '#^https?://#i', $url ) ) {
1846                $url = 'https://' . $url;
1847            }
1848
1849            // Validate URL - only http and https protocols are allowed for safety.
1850            $url = esc_url( $url, array( 'http', 'https' ) );
1851            return ! empty( $url ) ? $url : null;
1852        }
1853        return null;
1854    }
1855
1856    /**
1857     * Get the rating data from a rating field value if present.
1858     *
1859     * @param mixed $value The field value.
1860     *
1861     * @return array|null The rating data if this is a rating field, null otherwise.
1862     */
1863    private static function get_rating( $value ) {
1864        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'rating' ) {
1865            $rating     = isset( $value['rating'] ) ? (int) $value['rating'] : 0;
1866            $max_rating = isset( $value['maxRating'] ) ? (int) $value['maxRating'] : 5;
1867            $icon_style = $value['iconStyle'] ?? 'stars';
1868
1869            // Generate translated screen reader text.
1870            $icon_label = 'hearts' === $icon_style
1871                ? _n( 'heart', 'hearts', $max_rating, 'jetpack-forms' )
1872                : _n( 'star', 'stars', $max_rating, 'jetpack-forms' );
1873
1874            return array(
1875                'rating'           => $rating,
1876                'maxRating'        => $max_rating,
1877                'iconStyle'        => $icon_style,
1878                /* translators: 1: rating value, 2: maximum rating, 3: icon type (stars or hearts) */
1879                'screenReaderText' => sprintf( __( 'Rating: %1$d out of %2$d %3$s', 'jetpack-forms' ), $rating, $max_rating, $icon_label ),
1880            );
1881        }
1882        return null;
1883    }
1884
1885    /**
1886     * Get the SVG icon for a field type.
1887     *
1888     * @param string $field_type The field type.
1889     *
1890     * @return string The SVG icon HTML.
1891     */
1892    private static function get_field_type_icon( $field_type ) {
1893        // Reject field types that don't fit the expected 'field-{type}' naming
1894        // convention. Valid types are non-empty strings of lowercase letters,
1895        // digits, and hyphens starting with a letter.
1896        if ( ! is_string( $field_type ) || ! preg_match( '/^[a-z][a-z0-9-]*$/', $field_type ) ) {
1897            return '';
1898        }
1899
1900        // Map field types that don't follow the 'field-{type}' naming convention.
1901        static $type_exceptions = array(
1902            'phone'             => 'field-telephone',
1903            'telephone'         => 'field-telephone',
1904            'radio'             => 'field-single-choice',
1905            'checkbox-multiple' => 'field-multiple-choice',
1906        );
1907
1908        $block_dir = $type_exceptions[ $field_type ] ?? 'field-' . $field_type;
1909
1910        // Cache loaded SVG content to avoid re-reading files.
1911        static $icon_cache = array();
1912
1913        if ( ! isset( $icon_cache[ $block_dir ] ) ) {
1914            $svg_file = dirname( __DIR__ ) . '/blocks/' . $block_dir . '/icon.svg';
1915            $svg      = '';
1916
1917            if ( file_exists( $svg_file ) ) {
1918                $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.
1919            }
1920
1921            if ( $svg ) {
1922                $svg = trim( $svg );
1923
1924                $icon_cache[ $block_dir ] = $svg;
1925            } else {
1926                $icon_cache[ $block_dir ] = '';
1927            }
1928        }
1929
1930        return $icon_cache[ $block_dir ];
1931    }
1932
1933    /**
1934     * Helper function that display the error wrapper.
1935     *
1936     * @param string $classes - the class names to add to the error wrapper.
1937     * @return string HTML string for the error wrapper.
1938     */
1939    private static function render_error_wrapper( $classes = '' ) {
1940        $class_attr = $classes ? ' ' . esc_attr( $classes ) : '';
1941        $html       = '<div class="contact-form__error' . $class_attr . '" data-wp-class--show-errors="state.showFormErrors">';
1942        $html      .= '<span class="contact-form__warning-icon" aria-hidden="true"><i></i></span>';
1943        $html      .= '<span class="contact-form__error-message" tabindex="-1" data-wp-watch="callbacks.focusOnValidationError" data-wp-text="state.getFormErrorMessage"></span>';
1944        $html      .= '<ul aria-label="' . esc_attr__( 'Form errors', 'jetpack-forms' ) . '">
1945                <template data-wp-each="state.getErrorList" data-wp-key="context.item.id">
1946                    <li><a data-wp-bind--href="context.item.anchor" data-wp-on--click="actions.scrollIntoView" data-wp-text="context.item.label"></a></li>
1947                </template>
1948                </ul>';
1949        $html      .= '</div>';
1950
1951        $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>';
1952        return $html;
1953    }
1954
1955    /**
1956     * Renders the success wrapper after a form is submitted without reloading the page.
1957     *
1958     * @param Contact_Form $form - the contact form.
1959     * @param bool         $submission_success - whether the form has already been submitted.
1960     * @param array        $formatted_submission_data - the formatted submission data.
1961     *
1962     * @return string HTML string for the success wrapper.
1963     */
1964    private static function render_ajax_success_wrapper( $form, $submission_success = false, $formatted_submission_data = array() ) {
1965        $classes = 'contact-form-submission contact-form-ajax-submission';
1966
1967        if ( $submission_success ) {
1968            $classes .= ' submission-success';
1969        }
1970
1971        $back_url          = remove_query_arg( array( 'contact-form-id', 'contact-form-sent', '_wpnonce', 'contact-form-hash' ) );
1972        $disable_go_back   = $form->get_attribute( 'disableGoBack' );
1973        $disable_summary   = $form->get_disable_summary();
1974        $confirmation_type = $form->get_confirmation_type();
1975
1976        if ( $confirmation_type === 'redirect' ) {
1977            return '';
1978        }
1979
1980        $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 ) . '">';
1981
1982        if ( ! $disable_go_back ) {
1983            $html .= '<p class="go-back-message">';
1984            $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>';
1985            $html .= '</p>';
1986        }
1987
1988        $html .=
1989            '<h4 data-wp-bind--aria-hidden="state.isSuccessMessageAriaHidden" id="contact-form-success-header-' . esc_attr( $form->hash ) . '">' . esc_html( $form->get_attribute( 'customThankyouHeading' ) ) .
1990            "</h4>\n\n";
1991
1992        if ( 'text' === $confirmation_type ) {
1993            $raw_message = $form->get_attribute( 'customThankyouMessage' );
1994
1995            if ( $raw_message !== '' ) {
1996                // Add more allowed HTML elements for file download links
1997                $allowed_html = array(
1998                    'br'         => array(),
1999                    'blockquote' => array( 'class' => array() ),
2000                    'p'          => array(),
2001                    'div'        => array(
2002                        'class' => array(),
2003                        'style' => array(),
2004                    ),
2005                    'span'       => array(
2006                        'class' => array(),
2007                        'style' => array(),
2008                    ),
2009                );
2010
2011                $message = wp_kses( $raw_message, $allowed_html );
2012                $message = '<div class="jetpack_forms_contact-form-custom-success-message">' . $message . '</div>';
2013
2014                $html .= $message;
2015            }
2016
2017            if ( ! $disable_summary ) {
2018                $html .= '<template data-wp-each--submission="context.formattedSubmissionData">
2019                    <div class="jetpack_forms_contact-form-success-summary">
2020                        <div class="field-name-wrapper">
2021                            <div class="field-type-icon" data-wp-watch="callbacks.watchFieldTypeIcon"></div>
2022                            <div class="field-name" data-wp-text="context.submission.label" data-wp-bind--hidden="!context.submission.label"></div>
2023                        </div>
2024                        <div class="field-value" data-wp-text="context.submission.value" data-wp-bind--hidden="!context.submission.showPlainValue"></div>
2025                        <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>
2026                        <div class="field-rating" data-wp-bind--hidden="!context.submission.rating" data-wp-watch="callbacks.watchRatingIcons"></div>
2027                        <div class="field-images" data-wp-bind--hidden="!context.submission.images">
2028                            <template data-wp-each--image="context.submission.images">
2029                                <div class="field-image-option" data-wp-class--is-empty="!context.image.src">
2030                                    <figure class="field-image-option__image" data-wp-class--is-empty="!context.image.src">
2031                                        <img data-wp-bind--src="context.image.src" data-wp-bind--hidden="!context.image.src" />
2032                                        <img src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-wp-bind--hidden="context.image.src" />
2033                                    </figure>
2034                                    <div class="field-image-option__label-wrapper">
2035                                        <span class="field-image-option__label-code" data-wp-text="context.image.letterCode"></span>
2036                                        <span class="field-image-option__label" data-wp-text="context.image.label" data-wp-bind--hidden="!context.image.label"></span>
2037                                    </div>
2038                                </div>
2039                            </template>
2040                        </div>
2041                        <div class="field-files" data-wp-bind--hidden="!context.submission.files">
2042                            <template data-wp-each--file="context.submission.files">
2043                                <div class="field-file">
2044                                    <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>
2045                                    <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">
2046                                        <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"/>
2047                                    </svg>
2048                                    <span class="field-file__name" data-wp-text="context.file.name"></span>
2049                                    <span class="field-file__size" data-wp-text="context.file.size"></span>
2050                                </div>
2051                            </template>
2052                        </div>
2053                    </div>
2054                </template>';
2055
2056                // For each entry in the submission data array, render a div with the label and value.
2057                // Structure must match the template above for proper hydration.
2058                foreach ( $formatted_submission_data as $submission ) {
2059                    $has_url        = ! empty( $submission['url'] );
2060                    $has_images     = ! empty( $submission['images'] );
2061                    $has_files      = ! empty( $submission['files'] );
2062                    $has_rating     = ! empty( $submission['rating'] );
2063                    $show_plain_val = ! $has_url && ! $has_images && ! $has_files && ! $has_rating;
2064                    $field_type     = $submission['type'] ?? 'text';
2065
2066                    $html .= '<div data-wp-each-child class="jetpack_forms_contact-form-success-summary">';
2067
2068                    // field-name-wrapper: contains icon and label.
2069                    $html .= '<div class="field-name-wrapper">';
2070                    // field-type-icon: rendered based on field type.
2071                    // The data-rendered-type attribute enables hydration optimization by allowing
2072                    // the JS callback to skip re-rendering when the icon is already correct.
2073                    $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>';
2074                    // field-name: always present.
2075                    $html .= '<div class="field-name" data-wp-text="context.submission.label" data-wp-bind--hidden="!context.submission.label">' . esc_html( $submission['label'] ) . '</div>';
2076                    $html .= '</div>'; // Close field-name-wrapper.
2077
2078                    // field-value: always present, hidden when URL, images, or files exist.
2079                    $html .= '<div class="field-value" data-wp-text="context.submission.value" data-wp-bind--hidden="!context.submission.showPlainValue"';
2080                    $html .= $show_plain_val ? '' : ' hidden';
2081                    $html .= '>' . ( $show_plain_val ? esc_html( $submission['value'] ) : '' ) . '</div>';
2082
2083                    // field-url: always present, hidden when no URL.
2084                    $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"';
2085                    $html .= $has_url ? ' href="' . esc_attr( $submission['url'] ) . '"' : ' hidden';
2086                    $html .= '>' . ( $has_url ? esc_html( $submission['value'] ) : '' ) . '</a>';
2087
2088                    // Field rating - only visible when rating is present. JS renders the SVG icons.
2089                    $html .= '<div class="field-rating" data-wp-bind--hidden="!context.submission.rating" data-wp-watch="callbacks.watchRatingIcons"';
2090                    $html .= $has_rating ? ' data-rating="' . esc_attr( wp_json_encode( $submission['rating'], JSON_UNESCAPED_SLASHES ) ) . '">' : ' hidden>';
2091                    $html .= '</div>';
2092
2093                    // field-images: always present, hidden when no images.
2094                    $html .= '<div class="field-images" data-wp-bind--hidden="!context.submission.images"';
2095                    $html .= $has_images ? '' : ' hidden';
2096                    $html .= '>';
2097
2098                    if ( $has_images ) {
2099                        foreach ( $submission['images'] as $image ) {
2100                            $image_src         = $image['src'] ?? '';
2101                            $image_letter_code = $image['letterCode'] ?? '';
2102                            $image_label       = $image['label'] ?? '';
2103
2104                            $html .= '<div data-wp-each-child class="field-image-option ' . ( empty( $image_src ) ? 'is-empty' : '' ) . '" data-wp-class--is-empty="!context.image.src">';
2105                            $html .= '<figure class="field-image-option__image ' . ( empty( $image_src ) ? 'is-empty' : '' ) . '" data-wp-class--is-empty="!context.image.src">';
2106                            $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' : '' ) . '/>';
2107                            $html .= '<img src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-wp-bind--hidden="context.image.src"' . ( empty( $image_src ) ? '' : ' hidden' ) . '/>';
2108                            $html .= '</figure>';
2109                            $html .= '<div class="field-image-option__label-wrapper">';
2110                            $html .= '<span class="field-image-option__label-code" data-wp-text="context.image.letterCode">' . esc_html( $image_letter_code ) . '</span>';
2111                            $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>';
2112                            $html .= '</div></div>';
2113                        }
2114                    } else {
2115                        // Empty template for hydration when no images.
2116                        $html .= '<template data-wp-each--image="context.submission.images"></template>';
2117                    }
2118
2119                    $html .= '</div>'; // Close field-images.
2120
2121                    // field-files: always present, hidden when no files.
2122                    $html .= '<div class="field-files" data-wp-bind--hidden="!context.submission.files"';
2123                    $html .= $has_files ? '' : ' hidden';
2124                    $html .= '>';
2125
2126                    if ( $has_files ) {
2127                        foreach ( $submission['files'] as $file ) {
2128                            $file_name   = $file['name'] ?? '';
2129                            $file_size   = $file['size'] ?? '';
2130                            $has_preview = $file['hasPreview'] ?? false;
2131
2132                            $html .= '<div data-wp-each-child class="field-file">';
2133                            // Thumbnail for AJAX submissions (has preview data)
2134                            $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"';
2135                            $html .= $has_preview ? '' : ' hidden';
2136                            $html .= '></div>';
2137                            // SVG fallback for non-AJAX submissions
2138                            $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"';
2139                            $html .= $has_preview ? ' hidden' : '';
2140                            $html .= '>';
2141                            $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"/>';
2142                            $html .= '</svg>';
2143                            $html .= '<span class="field-file__name" data-wp-text="context.file.name">' . esc_html( $file_name ) . '</span>';
2144                            $html .= '<span class="field-file__size" data-wp-text="context.file.size">' . esc_html( $file_size ) . '</span>';
2145                            $html .= '</div>';
2146                        }
2147                    } else {
2148                        // Empty template for hydration when no files.
2149                        $html .= '<template data-wp-each--file="context.submission.files"></template>';
2150                    }
2151
2152                    $html .= '</div></div>'; // Close field-files and summary.
2153                }
2154            }
2155        }
2156
2157        $html .= '</div>';
2158        return $html;
2159    }
2160
2161    /**
2162     * Returns a success message to be returned if the form is sent via AJAX.
2163     *
2164     * @param int          $feedback_id - the feedback ID.
2165     * @param Contact_Form $form - the contact form.
2166     *
2167     * @return string $message
2168     */
2169    public static function success_message( $feedback_id, $form ) {
2170        $message           = '';
2171        $disable_summary   = $form->get_disable_summary();
2172        $confirmation_type = $form->get_confirmation_type();
2173
2174        if ( 'text' === $confirmation_type ) {
2175            $raw_message = $form->get_attribute( 'customThankyouMessage' );
2176
2177            if ( $raw_message !== '' ) {
2178                // Add more allowed HTML elements for file download links
2179                $allowed_html = array(
2180                    'br'         => array(),
2181                    'blockquote' => array( 'class' => array() ),
2182                    'p'          => array(),
2183                    'div'        => array(
2184                        'class' => array(),
2185                        'style' => array(),
2186                    ),
2187                    'span'       => array(
2188                        'class' => array(),
2189                        'style' => array(),
2190                    ),
2191                );
2192
2193                $message = wp_kses( $raw_message, $allowed_html );
2194                $message = '<div class="jetpack_forms_contact-form-custom-success-message">' . $message . '</div>';
2195            }
2196
2197            if ( ! $disable_summary ) {
2198                $compiled_form = self::get_compiled_form( $feedback_id );
2199
2200                $message .= '<div class="jetpack_forms_contact-form-success-summary"><p>' . implode( '</p><p>', $compiled_form ) . '</p></div>';
2201            }
2202        }
2203
2204        return $message;
2205    }
2206
2207    /**
2208     * Returns a compiled form with labels and values in a form of  an array
2209     * of lines.
2210     *
2211     * @param int          $feedback_id - the feedback ID.
2212     * @param Contact_Form $form - the form. This parameter is deprecated and will be removed in the next version.
2213     *
2214     * @return array $lines
2215     */
2216    public static function get_compiled_form( $feedback_id, $form = null ) {
2217
2218        if ( $form ) {
2219            _deprecated_argument( __METHOD__, '5.1.0', '$form is deprecated' );
2220        }
2221        $compiled_form = self::get_raw_compiled_form_data( $feedback_id );
2222
2223        foreach ( $compiled_form as $field_index => $data ) {
2224            $safe_display_value = self::escape_and_sanitize_field_value( $data['value'] );
2225
2226            if ( '' === $safe_display_value ) {
2227                $safe_display_value = '-';
2228            }
2229
2230            if ( ! empty( $data['label'] ) ) {
2231                $safe_display_label            = self::escape_and_sanitize_field_label( $data['label'] );
2232                $compiled_form[ $field_index ] = sprintf(
2233                    '<div class="field-name">%1$s</div> <div class="field-value">%2$s</div>',
2234                    Util::maybe_add_colon_to_label( $safe_display_label ),
2235                    $safe_display_value
2236                );
2237            } else {
2238                // If there is no label, only output the field value, wrapped in its div.
2239                $compiled_form[ $field_index ] = sprintf(
2240                    '<div class="field-value">%s</div>',
2241                    $safe_display_value
2242                );
2243            }
2244        }
2245
2246        return $compiled_form;
2247    }
2248
2249    /**
2250     * Returns the JSON data for the form submission.
2251     *
2252     * @param int          $feedback_id - the feedback ID.
2253     * @param Contact_Form $form - the form. This parameter is deprecated and will be removed in the next version.
2254     *
2255     * @deprecated 5.1.0
2256     *
2257     * @return array $json_data
2258     */
2259    public static function get_json_data( $feedback_id, $form = null ) {
2260        _deprecated_function( __METHOD__, '5.1.0', 'Feedback::get( $feedback_id )->get_compiled_fields(\'ajax\', \'label|value\' )' );
2261
2262        if ( $form ) {
2263            _deprecated_argument( __METHOD__, '5.1.0', '$form is deprecated' );
2264        }
2265
2266        $response = Feedback::get( $feedback_id );
2267        if ( ! $response ) {
2268            return array();
2269        }
2270
2271        return $response->get_compiled_fields( 'ajax', 'label|value' );
2272    }
2273
2274    /**
2275     * Retrieves raw compiled form data.
2276     *
2277     * @param int          $feedback_id - the feedback ID.
2278     * @param Contact_Form $form - the form. This parameter is deprecated and will be removed in the next version.
2279     *
2280     * @return array $raw_data Associative array where keys are field_index and values are arrays with 'label' and 'value'.
2281     */
2282    private static function get_raw_compiled_form_data( $feedback_id, $form = null ) {
2283
2284        if ( $form ) {
2285            _deprecated_argument( __METHOD__, '5.1.0', '$form is deprecated' );
2286        }
2287
2288        $response = Feedback::get( $feedback_id );
2289        if ( $response instanceof Feedback ) {
2290            // If the response is an instance of Feedback, we can use its method to get compiled fields.
2291            return $response->get_compiled_fields( 'web', 'all' );
2292        }
2293
2294        return array();
2295    }
2296
2297    /**
2298     * Returns a compiled form with labels and values formatted for the email response
2299     * in a form of an array of lines.
2300     *
2301     * @param int          $feedback_id - the feedback ID.
2302     * @param Contact_Form $form - the form.
2303     *
2304     * @return array $lines
2305     */
2306    public static function get_compiled_form_for_email( $feedback_id, $form ) {
2307        return Feedback_Email_Renderer::get_compiled_form_for_email( $feedback_id, $form );
2308    }
2309
2310    /**
2311     * Escape and sanitize a field value.
2312     *
2313     * @param mixed $value - the value to sanitize.
2314     *
2315     * TODO: there's a mix of functionalities in this method. Unsure if it's fixable.
2316     * @return string
2317     */
2318    public static function escape_and_sanitize_field_value( $value ) {
2319        if ( empty( $value ) ) {
2320            return '';
2321        }
2322
2323        // Handle file upload field (new structure with field_id and files array).
2324        if ( self::is_file_upload_field( $value ) ) {
2325            $files = $value['files'];
2326            if ( empty( $files ) ) {
2327                return '';
2328            }
2329
2330            $file_links = array();
2331            foreach ( $files as $file ) {
2332                if ( ! empty( $file['file_id'] ) ) {
2333                    $file_name = $file['name'] ?? __( 'Attached file', 'jetpack-forms' );
2334                    $file_size = isset( $file['size'] ) ? size_format( $file['size'] ) : '';
2335
2336                    $html = esc_html( $file_name );
2337                    if ( ! empty( $file_size ) ) {
2338                        $html .= sprintf( ' <span class="jetpack-forms-file-size">(%s)</span>', esc_html( $file_size ) );
2339                    }
2340
2341                    $file_links[] = $html;
2342                }
2343            }
2344
2345            return implode( '<br>', $file_links );
2346        }
2347
2348        // Handle rating field - return displayValue (e.g., "3/5") as text fallback.
2349        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'rating' ) {
2350            return isset( $value['displayValue'] ) ? esc_html( $value['displayValue'] ) : '';
2351        }
2352
2353        // Handle URL field - return displayValue or url.
2354        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'url' ) {
2355            return isset( $value['displayValue'] ) ? esc_html( $value['displayValue'] ) : ( isset( $value['url'] ) ? esc_html( $value['url'] ) : '' );
2356        }
2357
2358        if ( is_array( $value ) ) {
2359            return implode( ', ', array_map( array( __CLASS__, 'escape_and_sanitize_field_value' ), $value ) );
2360        }
2361
2362        $value = str_replace( array( '[', ']' ), array( '&#91;', '&#93;' ), $value );
2363        return nl2br( wp_kses( $value, array() ) );
2364    }
2365
2366    /**
2367     * Only strip out empty string values and keep all the other values as they are.
2368     *
2369     * @param string $single_value - the single value.
2370     *
2371     * @return bool
2372     */
2373    public static function remove_empty( $single_value ) {
2374        return ( $single_value !== '' );
2375    }
2376
2377    /**
2378     * Get file upload fields
2379     *
2380     * @param int $post_id The feedback post ID.
2381     * @return array Array of file attachments or empty array.
2382     */
2383    public static function get_file_upload_fields( $post_id ) {
2384        $content_fields     = Contact_Form_Plugin::parse_fields_from_content( $post_id );
2385        $file_upload_fields = array();
2386        if ( isset( $content_fields['_feedback_all_fields'] ) ) {
2387            foreach ( $content_fields['_feedback_all_fields'] as $field_value ) {
2388                if ( self::is_file_upload_field( $field_value ) ) {
2389                    $file_upload_fields[] = $field_value;
2390                }
2391            }
2392        }
2393
2394        return $file_upload_fields;
2395    }
2396
2397    /**
2398     * Delete files
2399     *
2400     * @param int $post_id The post ID being deleted.
2401     * @return void
2402     */
2403    public static function delete_feedback_files( $post_id ) {
2404        if ( get_post_type( $post_id ) !== 'feedback' ) {
2405            return;
2406        }
2407        // $file_upload_fields = self::get_file_upload_fields( $post_id );
2408        // TODO: Implement delete_feedback_files() method.
2409    }
2410
2411    /**
2412     * Escape a shortcode value.
2413     *
2414     * Shortcode attribute values have a number of unfortunate restrictions, which fortunately we
2415     * can get around by adding some extra HTML encoding.
2416     *
2417     * The output HTML will have a few extra escapes, but that makes no functional difference.
2418     *
2419     * @since 9.1.0
2420     * @param string|array $val Value to escape.
2421     * @return string
2422     */
2423    public static function esc_shortcode_val( $val ) {
2424        // Sometimes we provide attributes in the form of a collection, hence making the value an array.
2425        // The above case triggers a warning about array to string conversion on formatting.php:1096.
2426        // This chunk will try to get the value from the usual label|value structure. Otherwise, it will try
2427        // recursively to get the first value from the array.
2428        if ( is_array( $val ) ) {
2429            if ( isset( $val['value'] ) ) {
2430                $val = $val['value'];
2431            } else {
2432                return self::esc_shortcode_val( array_shift( $val ) );
2433            }
2434        }
2435
2436        return strtr(
2437            esc_html( $val ),
2438            array(
2439                // Brackets in attribute values break the shortcode parser.
2440                '['  => '&#091;',
2441                ']'  => '&#093;',
2442                // Shortcode parser screws up backslashes too, thanks to calls to `stripcslashes`.
2443                '\\' => '&#092;',
2444                // The existing code here represents arrays as comma-separated strings.
2445                // Rather than trying to change representations now, just escape the commas in values.
2446                ','  => '&#044;',
2447            )
2448        );
2449    }
2450
2451    /**
2452     * The contact-field shortcode processor.
2453     * 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.
2454     *
2455     * @param array         $attributes Key => Value pairs as parsed by shortcode_parse_atts().
2456     * @param string|null   $content The shortcode's inner content: [contact-field]$content[/contact-field].
2457     * @param WP_Block|null $block The field block object.
2458     * @return string HTML for the contact form field
2459     */
2460    public static function parse_contact_field( $attributes, $content, $block = null ) {
2461        if ( $block ) {
2462            $type = null;
2463        }
2464
2465        // Don't try to parse contact form fields if not inside a contact form (????)
2466        if ( ! Contact_Form_Plugin::$using_contact_form_field ) {
2467            $type = $attributes['type'] ?? null;
2468
2469            if ( $type === 'checkbox-multiple' || $type === 'radio' ) {
2470                preg_match_all( '/' . get_shortcode_regex() . '/s', $content, $matches );
2471
2472                if ( ! empty( $matches[0] ) ) {
2473                    $options = array();
2474                    foreach ( $matches[0] as $shortcode ) {
2475                        $attr = shortcode_parse_atts( $shortcode );
2476                        if ( ! empty( $attr['label'] ) ) {
2477                            $options[] = $attr['label'];
2478                        }
2479                    }
2480
2481                    $attributes['options'] = $options;
2482                }
2483            }
2484
2485            if ( ! isset( $attributes['label'] ) ) {
2486                $attributes['label'] = self::get_default_label_from_type( $type );
2487            }
2488
2489            $att_strs = array();
2490            foreach ( $attributes as $att => $val ) {
2491                if ( is_numeric( $att ) ) { // Is a valueless attribute
2492                    $att_strs[] = self::esc_shortcode_val( $val );
2493                } elseif ( isset( $val ) ) { // A regular attr - value pair
2494                    if ( ( $att === 'options' || $att === 'values' ) && is_string( $val ) ) { // remove any empty strings
2495                        $val = explode( ',', $val );
2496                    }
2497                    if ( is_array( $val ) ) {
2498                        $val        = array_filter( $val, array( __CLASS__, 'remove_empty' ) ); // removes any empty strings
2499                        $att_strs[] = esc_html( $att ) . '="' . implode( ',', array_map( array( __CLASS__, 'esc_shortcode_val' ), $val ) ) . '"';
2500                    } elseif ( is_bool( $val ) ) {
2501                        $att_strs[] = esc_html( $att ) . '="' . ( $val ? '1' : '' ) . '"';
2502                    } else {
2503                        // Allow CSS in known style attributes byut sanitize with safecss_filter_attr.
2504                        $allowed_style_keys = array( 'labelstyles', 'inputstyles', 'optionstyles', 'optionsstyles', 'stylevariationstyles' );
2505                        if ( in_array( $att, $allowed_style_keys, true ) ) {
2506                            $sanitized  = safecss_filter_attr( (string) $val );
2507                            $att_strs[] = esc_attr( $att ) . '="' . esc_html( $sanitized ) . '"';
2508                        } else {
2509                            $att_strs[] = esc_attr( $att ) . '="' . self::esc_shortcode_val( $val ) . '"';
2510                        }
2511                    }
2512                }
2513            }
2514
2515            $shortcode_type = 'contact-field';
2516            if ( $type === 'field-option' ) {
2517                $shortcode_type = 'contact-field-option';
2518            }
2519
2520            $html            = '[' . $shortcode_type . ' ' . implode( ' ', $att_strs );
2521            $trimmed_content = isset( $content ) ? trim( $content ) : '';
2522
2523            if ( ! empty( $trimmed_content ) ) { // If there is content, let's add a closing tag
2524                $html .= ']' . esc_html( $trimmed_content ) . '[/contact-field]';
2525            } else { // Otherwise let's add a closing slash in the first tag
2526                $html .= '/]';
2527            }
2528
2529            return $html;
2530        }
2531
2532        // What does this actually means? What is the case where this is used?
2533        $form = self::$current_form;
2534
2535        $field = new Contact_Form_Field( $attributes, $content, $form );
2536
2537        $field_id = $field->get_attribute( 'id' );
2538        if ( $field_id ) {
2539            $form->fields[ $field_id ] = $field;
2540        } else {
2541            $form->fields[] = $field;
2542        }
2543
2544        if ( // phpcs:disable WordPress.Security.NonceVerification.Missing
2545            ! isset( $_POST['jetpack_contact_form_jwt'] )
2546            &&
2547            isset( $_POST['action'] ) && 'grunion-contact-form' === $_POST['action']
2548            &&
2549            isset( $_POST['contact-form-id'] ) && (string) $form->get_attribute( 'id' ) === $_POST['contact-form-id']
2550            &&
2551            isset( $_POST['contact-form-hash'] ) && is_string( $_POST['contact-form-hash'] ) && hash_equals( $form->hash, wp_unslash( $_POST['contact-form-hash'] ) )
2552        ) { // phpcs:enable
2553            // If we're processing a POST submission for this contact form, validate the field value so we can show errors as necessary.
2554            $field->validate();
2555        }
2556
2557        // Output HTML
2558        return $field->render();
2559    }
2560
2561    /**
2562     * Check if the field is a file upload field.
2563     *
2564     * @param array $field The field to check.
2565     * @return bool True if the field is a file upload field, false otherwise.
2566     */
2567    public static function is_file_upload_field( $field ) {
2568        return ( is_array( $field ) &&
2569                ! empty( $field ) &&
2570                isset( $field['field_id'] ) &&
2571                isset( $field['files'] ) &&
2572                is_array( $field['files'] ) );
2573    }
2574
2575    /**
2576     * Get the default label from type.
2577     *
2578     * @param string $type - the type of label.
2579     *
2580     * @return string
2581     */
2582    public static function get_default_label_from_type( $type ) {
2583        switch ( $type ) {
2584            case 'text':
2585                $str = __( 'Text', 'jetpack-forms' );
2586                break;
2587            case 'name':
2588                $str = __( 'Name', 'jetpack-forms' );
2589                break;
2590            case 'number':
2591                $str = __( 'Number', 'jetpack-forms' );
2592                break;
2593            case 'email':
2594                $str = __( 'Email', 'jetpack-forms' );
2595                break;
2596            case 'url':
2597                $str = __( 'Website', 'jetpack-forms' );
2598                break;
2599            case 'date':
2600                $str = __( 'Date', 'jetpack-forms' );
2601                break;
2602            case 'telephone':
2603                $str = __( 'Phone', 'jetpack-forms' );
2604                break;
2605            case 'textarea':
2606                $str = __( 'Message', 'jetpack-forms' );
2607                break;
2608            case 'checkbox-multiple':
2609                $str = __( 'Choose several options', 'jetpack-forms' );
2610                break;
2611            case 'radio':
2612                $str = __( 'Choose one option', 'jetpack-forms' );
2613                break;
2614            case 'select':
2615                $str = __( 'Select one', 'jetpack-forms' );
2616                break;
2617            case 'consent':
2618                $str = __( 'Consent', 'jetpack-forms' );
2619                break;
2620            case 'file':
2621                $str = __( 'Upload a file', 'jetpack-forms' );
2622                break;
2623            case 'time':
2624                $str = __( 'Time', 'jetpack-forms' );
2625                break;
2626            case 'image-select':
2627                $str = __( 'Select an image', 'jetpack-forms' );
2628                break;
2629            default:
2630                $str = null;
2631        }
2632        return $str;
2633    }
2634
2635    /**
2636     * Loops through $this->fields to generate a (structured) list of field IDs.
2637     *
2638     * Important: Currently the allowed fields are defined as follows:
2639     *  `name`, `email`, `url`, `subject`, `textarea`
2640     *
2641     * If you need to add new fields to the Contact Form, please don't add them
2642     * to the allowed fields and leave them as extra fields.
2643     *
2644     * The reasoning behind this is that both the admin Feedback view and the CSV
2645     * export will not include any fields that are added to the list of
2646     * allowed fields without taking proper care to add them to all the
2647     * other places where they accessed/used/saved.
2648     *
2649     * The safest way to add new fields is to add them to the dropdown and the
2650     * HTML list ( @see Contact_Form_Field::render ) and don't add them
2651     * to the list of allowed fields. This way they will become a part of the
2652     * `extra fields` which are saved in the post meta and will be properly
2653     * handled by the admin Feedback view and the CSV Export without any extra
2654     * work.
2655     *
2656     * If there is need to add a field to the allowed fields, then please
2657     * take proper care to add logic to handle the field in the following places:
2658     *
2659     *  - Below in the switch statement - so the field is recognized as allowed.
2660     *
2661     *  - Contact_Form::process_submission - validation and logic.
2662     *
2663     *  - Contact_Form::process_submission - add the field as an additional
2664     *      field in the `post_content` when saving the feedback content.
2665     *
2666     *  - Contact_Form_Plugin::parse_fields_from_content - add mapping
2667     *      for the field, defined in the above method.
2668     *
2669     *  - Contact_Form_Plugin::map_parsed_field_contents_of_post_to_field_names -
2670     *      add mapping of the field for the CSV Export. Otherwise it will be missing
2671     *      from the exported data.
2672     *
2673     *  - admin.php / grunion_manage_post_columns - add the field to the render logic.
2674     *      Otherwise it will be missing from the admin Feedback view.
2675     *
2676     * @return array
2677     */
2678    public function get_field_ids() {
2679        $field_ids = array(
2680            'all'   => array(), // array of all field_ids.
2681            'extra' => array(), // array of all non-allowed field IDs.
2682
2683            // Allowed "standard" field IDs:
2684            // 'email'    => field_id,
2685            // 'name'     => field_id,
2686            // 'url'      => field_id,
2687            // 'subject'  => field_id,
2688            // 'textarea' => field_id,
2689        );
2690
2691        // Initialize marketing consent
2692        $field_ids['email_marketing_consent']       = null;
2693        $field_ids['email_marketing_consent_field'] = null;
2694
2695        foreach ( $this->fields as $id => $field ) {
2696            $type = $field->get_attribute( 'type' );
2697
2698            // If the field is not renderable, skip it.
2699            if ( ! $field->is_field_renderable( $type ) ) {
2700                continue;
2701            }
2702
2703            $field_ids['all'][] = $id;
2704
2705            if ( isset( $field_ids[ $type ] ) ) {
2706                // This type of field is already present in our allowed list of "standard" fields for this form
2707                // Put it in extra
2708                $field_ids['extra'][] = $id;
2709                continue;
2710            }
2711
2712            /**
2713             * See method description before modifying the switch cases.
2714             */
2715            switch ( $type ) {
2716                case 'email':
2717                case 'name':
2718                case 'url':
2719                case 'subject':
2720                case 'textarea':
2721                    $field_ids[ $type ] = $id;
2722                    break;
2723                case 'consent':
2724                    // Set email marketing consent for the first Consent type field
2725                    if ( null === $field_ids['email_marketing_consent'] ) {
2726                        $field_ids['email_marketing_consent_field'] = $id;
2727                        if ( $field->value ) {
2728                            $field_ids['email_marketing_consent'] = true;
2729                        } else {
2730                            $field_ids['email_marketing_consent'] = false;
2731                        }
2732                    }
2733                    $field_ids['extra'][] = $id;
2734                    break;
2735                default:
2736                    // Put everything else in extra
2737                    $field_ids['extra'][] = $id;
2738            }
2739        }
2740
2741        return $field_ids;
2742    }
2743
2744    /**
2745     * Process the contact form's POST submission
2746     * Stores feedback.  Sends email.
2747     */
2748    public function process_submission() {
2749
2750        $response = Feedback::from_submission( $_POST, $this ); // phpcs:Ignore WordPress.Security.NonceVerification.Missing
2751        $response->set_source( $this->get_source() );
2752
2753        // If the submission came from an authenticated form preview, flag the
2754        // feedback as a test submission. The rest of the pipeline reads the
2755        // flag from the feedback (which also travels into the serialized
2756        // post_content via Feedback_Source).
2757        if ( $this->is_preview_submission ) {
2758            $response->mark_as_test();
2759        }
2760        $is_test_submission = $response->is_test();
2761
2762        $plugin = Contact_Form_Plugin::init();
2763
2764        $id                  = $this->get_attribute( 'id' );
2765        $to                  = $this->get_attribute( 'to' );
2766        $widget              = $this->get_attribute( 'widget' );
2767        $block_template      = $this->get_attribute( 'block_template' );
2768        $block_template_part = $this->get_attribute( 'block_template_part' );
2769
2770        $contact_form_subject = $this->get_attribute( 'subject' );
2771
2772        $to     = str_replace( ' ', '', $to );
2773        $emails = explode( ',', $to );
2774
2775        $valid_emails = array();
2776
2777        foreach ( $emails as $email ) {
2778            if ( ! is_email( $email ) ) {
2779                continue;
2780            }
2781
2782            if ( function_exists( 'is_email_address_unsafe' ) && is_email_address_unsafe( $email ) ) {
2783                continue;
2784            }
2785
2786            $valid_emails[] = $email;
2787        }
2788
2789        // No one to send it to, which means none of the "to" attributes are valid emails.
2790        // Use default email instead.
2791        if ( ! $valid_emails ) {
2792            $valid_emails = $this->defaults['to'];
2793        }
2794
2795        $to = $valid_emails;
2796
2797        // Last ditch effort to set a recipient if somehow none have been set.
2798        if ( empty( $to ) ) {
2799            $to = get_option( 'admin_email' );
2800        }
2801
2802        if ( ! $this->has_verified_jwt ) {
2803            // Make sure we're processing the form we think we're processing... probably a redundant check.
2804            if ( $widget ) {
2805                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()
2806                    return Form_Submission_Error::system_error( 'form_id_mismatch_widget', __( 'Form ID mismatch.', 'jetpack-forms' ) );
2807                }
2808            } elseif ( $block_template ) {
2809                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()
2810                    return Form_Submission_Error::system_error( 'form_id_mismatch_block_template', __( 'Form ID mismatch.', 'jetpack-forms' ) );
2811                }
2812            } elseif ( $block_template_part ) {
2813                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()
2814                        return Form_Submission_Error::system_error( 'form_id_mismatch_block_template_part', __( 'Form ID mismatch.', 'jetpack-forms' ) );
2815                }
2816            } 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()
2817                return Form_Submission_Error::system_error( 'form_id_mismatch_post', __( 'Form ID mismatch.', 'jetpack-forms' ) );
2818            }
2819        }
2820
2821        // Initialize all these "standard" fields to null
2822        $comment_author_email = $response->get_author_email();
2823        $comment_author       = $response->get_author();
2824
2825        $contact_form_subject = $response->get_subject();
2826
2827        // Set marketing consent
2828        $email_marketing_consent = $response->has_consent();
2829
2830        if ( null === $email_marketing_consent ) {
2831            $email_marketing_consent = false;
2832        }
2833
2834        $all_values   = $response->get_all_values( 'submit' );
2835        $extra_values = $response->get_legacy_extra_values( 'submit' );
2836
2837        if ( ! empty( $_REQUEST['is_block'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- not changing the site.
2838            $extra_values['is_block'] = true;
2839        }
2840
2841        $contact_form_subject = trim( $contact_form_subject );
2842
2843        $comment_author_ip = Contact_Form_Plugin::get_ip_address();
2844
2845        // Ensure that Akismet gets all of the relevant information from the contact form,
2846        // not just the textarea field and predetermined subject.
2847        $akismet_vars = $response->get_akismet_vars();
2848
2849        $spam           = '';
2850        $akismet_values = $plugin->prepare_for_akismet( $akismet_vars );
2851
2852        // Is it spam? Test submissions (from form preview) skip Akismet entirely —
2853        // the form owner is explicitly running a test and we don't want Akismet
2854        // to learn from synthetic data or bounce the submission.
2855        if ( $is_test_submission ) {
2856            $is_spam = false;
2857        } else {
2858            /** This filter is already documented in \Automattic\Jetpack\Forms\ContactForm\Admin */
2859            $is_spam = apply_filters( 'jetpack_contact_form_is_spam', false, $akismet_values );
2860        }
2861        if ( is_wp_error( $is_spam ) ) { // WP_Error to abort
2862            return $is_spam; // abort
2863        } elseif ( $is_spam === true ) {  // TRUE to flag a spam
2864            $spam = '***SPAM*** ';
2865        }
2866
2867        /**
2868         * Filter whether a submitted contact form is in the comment disallowed list.
2869         *
2870         * @module contact-form
2871         *
2872         * @since 8.9.0
2873         *
2874         * @param bool  $result         Is the submitted feedback in the disallowed list.
2875         * @param array $akismet_values Feedack values returned by the Akismet plugin.
2876         */
2877        $in_comment_disallowed_list = apply_filters( 'jetpack_contact_form_in_comment_disallowed_list', false, $akismet_values );
2878
2879        if ( ! $comment_author ) {
2880            $comment_author = $comment_author_email;
2881        }
2882
2883        /**
2884         * Filter the email where a submitted feedback is sent.
2885         *
2886         * @module contact-form
2887         *
2888         * @since 1.3.1
2889         *
2890         * @param string|array $to Array of valid email addresses, or single email address.
2891         * @param array $all_values Contact form fields
2892         */
2893        $to            = (array) apply_filters( 'contact_form_to', $to, $all_values );
2894        $reply_to_addr = $to[0]; // get just the address part before the name part is added
2895
2896        foreach ( $to as $to_key => $to_value ) {
2897            $to[ $to_key ] = Contact_Form_Plugin::strip_tags( $to_value );
2898            $to[ $to_key ] = self::add_name_to_address( $to_value );
2899        }
2900
2901        // Get the site domain and get rid of www.
2902        $sitename        = wp_parse_url( site_url(), PHP_URL_HOST );
2903        $from_email_addr = 'wordpress@';
2904
2905        if ( null !== $sitename ) {
2906            if ( str_starts_with( $sitename, 'www.' ) ) {
2907                $sitename = substr( $sitename, 4 );
2908            }
2909
2910            $from_email_addr .= $sitename;
2911        }
2912
2913        if ( ! empty( $comment_author_email ) ) {
2914            $reply_to_addr = $comment_author_email;
2915        }
2916
2917        /*
2918         * The email headers here are formatted in a format
2919         * that is the most likely to be accepted by wp_mail(),
2920         * without escaping.
2921         * More info: https://github.com/Automattic/jetpack/pull/19727
2922         */
2923        $headers = 'From: ' . $comment_author . ' <' . $from_email_addr . ">\r\n" .
2924            'Reply-To: ' . $comment_author . ' <' . $reply_to_addr . ">\r\n";
2925
2926        /**
2927         * Allow customizing the email headers.
2928         *
2929         * Warning: DO NOT add headers or header data from the form submission without proper
2930         * escaping and validation, or you're liable to allow abusers to use your site to send spam.
2931         *
2932         * Especially DO NOT take email addresses from the form data to add as CC or BCC headers
2933         * without strictly validating each address against a list of allowed addresses.
2934         *
2935         * @module contact-form
2936         *
2937         * @since 10.2.0
2938         *
2939         * @param string|array $headers        Email headers.
2940         * @param string       $comment_author Name of the author of the submitted feedback, if provided in form.
2941         * @param string       $reply_to_addr  Email of the author of the submitted feedback, if provided in form.
2942         * @param string|array $to             Array of valid email addresses, or single email address, where the form is sent.
2943         */
2944        $headers = apply_filters(
2945            'jetpack_contact_form_email_headers',
2946            $headers,
2947            $comment_author,
2948            $reply_to_addr,
2949            $to
2950        );
2951
2952        $all_values['email_marketing_consent'] = $email_marketing_consent;
2953
2954        $entry_values = $response->get_entry_values();
2955
2956        // Prefix the subject with [TEST] for test submissions so the form owner
2957        // can immediately tell this email came from a preview-mode submission.
2958        if ( $is_test_submission ) {
2959            /**
2960             * Filter the subject prefix applied to test (preview) feedback emails.
2961             *
2962             * @module contact-form
2963             *
2964             * @since 7.19.0
2965             *
2966             * @param string $prefix Default subject prefix for test submissions.
2967             */
2968            $test_prefix          = apply_filters( 'jetpack_forms_test_subject_prefix', '[TEST] ' );
2969            $contact_form_subject = $test_prefix . $contact_form_subject;
2970        }
2971
2972        /** This filter is already documented in \Automattic\Jetpack\Forms\ContactForm\Admin */
2973        $subject = apply_filters( 'contact_form_subject', $contact_form_subject, $all_values );
2974
2975        /*
2976         * Links to the feedback and the post.
2977         */
2978        if ( $block_template || $block_template_part || $widget ) {
2979            $url = home_url( '/' );
2980        } else {
2981            $url = self::get_permalink( $this->current_post ? self::get_post_property( $this->current_post, 'ID' ) : 0 );
2982        }
2983
2984        // translators: the time of the form submission.
2985        $date_time_format = _x( '%1$s \a\t %2$s', '{$date_format} \a\t {$time_format}', 'jetpack-forms' );
2986        $date_time_format = sprintf( $date_time_format, get_option( 'date_format' ), get_option( 'time_format' ) );
2987        $time             = wp_date( $date_time_format );
2988
2989        // Keep a copy of the feedback as a custom post type.
2990        if ( $in_comment_disallowed_list ) {
2991            $feedback_status = 'trash';
2992        } elseif ( $is_spam ) {
2993            $feedback_status = 'spam';
2994        } elseif ( 'no' === $this->get_attribute( 'saveResponses' ) ) {
2995            $feedback_status = 'jp-temp-feedback';
2996        } else {
2997            $feedback_status = 'publish';
2998        }
2999        $response->set_status( $feedback_status );
3000
3001        foreach ( (array) $akismet_values as $av_key => $av_value ) {
3002            $akismet_values[ $av_key ] = Contact_Form_Plugin::strip_tags( $av_value );
3003        }
3004
3005        foreach ( $all_values as $all_key => $all_value ) {
3006            $all_values[ $all_key ] = Contact_Form_Plugin::strip_tags( $all_value );
3007        }
3008
3009        foreach ( $extra_values as $ev_key => $ev_value ) {
3010            $extra_values[ $ev_key ] = Contact_Form_Plugin::strip_tags( $ev_value );
3011        }
3012
3013        /*
3014         * We need to make sure that the post author is always zero for contact
3015         * form submissions.  This prevents export/import from trying to create
3016         * new users based on form submissions from people who were logged in
3017         * at the time.
3018         *
3019         * Unfortunately wp_insert_post() tries very hard to make sure the post
3020         * author gets the currently logged in user id.  That is how we ended up
3021         * with this work around.
3022         */
3023        add_filter( 'wp_insert_post_data', array( $plugin, 'insert_feedback_filter' ), 10, 2 );
3024
3025        /**
3026         * Allows site owners to not include IP addresses in the saved form response.
3027         *
3028         * The IP address is still used as part of spam filtering, if enabled, but it is removed when this filter
3029         * is set to true before saving to the database and e-mailing the form recipients.
3030
3031         * @module contact-form
3032         *
3033         * @param bool $remove_ip_address Should the IP address be removed. Default false.
3034         * @param string $ip_address IP address of the form submission.
3035         *
3036         * @since 0.33.0
3037         */
3038        if ( apply_filters( 'jetpack_contact_form_forget_ip_address', false, $comment_author_ip ) ) {
3039            $comment_author_ip = null;
3040        }
3041
3042        $post_id       = 0;
3043        $feedback_post = $response->save();
3044        if ( $feedback_post instanceof WP_Post ) {
3045            $post_id = $feedback_post->ID;
3046        }
3047
3048        // once insert has finished we don't need this filter any more
3049        remove_filter( 'wp_insert_post_data', array( $plugin, 'insert_feedback_filter' ), 10 );
3050
3051        update_post_meta( $post_id, '_feedback_extra_fields', $this->addslashes_deep( $extra_values ) );
3052
3053        if ( 'publish' === $feedback_status ) {
3054            Contact_Form_Plugin::recalculate_unread_count();
3055        }
3056
3057        if ( defined( 'AKISMET_VERSION' ) ) {
3058            update_post_meta( $post_id, '_feedback_akismet_values', $this->addslashes_deep( $akismet_values ) );
3059        }
3060
3061        /**
3062         * Fires after the feedback post for the contact form submission has been inserted.
3063         *
3064         * @module contact-form
3065         *
3066         * @since 8.6.0
3067         *
3068         * @param integer $post_id The post id that contains the contact form data.
3069         * @param array   $this->fields An array containg the form's Contact_Form_Field objects.
3070         * @param boolean $is_spam Whether the form submission has been identified as spam.
3071         * @param array   $entry_values The feedback entry values.
3072         */
3073        do_action( 'grunion_after_feedback_post_inserted', $post_id, $this->fields, $is_spam, $entry_values );
3074
3075        // Build the complete email content via the renderer.
3076        $context_data = array(
3077            'time'                 => $time,
3078            'url'                  => $url,
3079            'comment_author'       => $comment_author,
3080            'comment_author_email' => $comment_author_email,
3081            'comment_author_ip'    => $comment_author_ip,
3082            'is_spam'              => $is_spam,
3083            'is_test'              => $is_test_submission,
3084            'feedback_status'      => $feedback_status,
3085        );
3086        $email        = Feedback_Email_Renderer::build_email_content( $post_id, $this, $response, $context_data );
3087        $message      = $email['message'];
3088
3089        // Always store the rendered email for the resend endpoint.
3090        update_post_meta( $post_id, '_feedback_email', $this->addslashes_deep( compact( 'to', 'message' ) ) );
3091
3092        /**
3093         * Filter to choose whether an email should be sent after each successful contact form submission.
3094         * This filter takes precedence over the emailNotifications attribute.
3095         *
3096         * @module contact-form
3097         *
3098         * @since 2.6.0
3099         *
3100         * @param bool|null $should_send Should an email be sent after a form submission.
3101         *                              - true: Send email regardless of emailNotifications setting
3102         *                              - false: Don't send email regardless of emailNotifications setting
3103         *                              - null: Use emailNotifications attribute to determine (default behavior)
3104         * @param int $post_id Post ID.
3105         */
3106        $should_send_email = apply_filters( 'grunion_should_send_email', null, $post_id );
3107
3108        // Determine if email should be sent based on filter precedence.
3109        if ( $should_send_email === true ) {
3110            // Filter explicitly says to send email
3111            $send_email = true;
3112        } elseif ( $should_send_email === false ) {
3113            // Filter explicitly says not to send email
3114            $send_email = false;
3115        } else {
3116            // Filter is null (default), use emailNotifications attribute
3117            $send_email = ( $this->get_attribute( 'emailNotifications' ) !== 'no' );
3118        }
3119
3120        // Test submissions always send the notification email (so the form
3121        // owner can verify their email flow end-to-end) regardless of the
3122        // emailNotifications attribute. Site admins who want to opt out can
3123        // return false from the filter below.
3124        if ( $is_test_submission ) {
3125            /**
3126             * Filter whether test (preview) submissions should trigger the notification email.
3127             *
3128             * @module contact-form
3129             *
3130             * @since 7.19.0
3131             *
3132             * @param bool     $send     Whether to send the test submission email. Default true.
3133             * @param int      $post_id  The feedback post ID.
3134             * @param Feedback $response The feedback response object.
3135             */
3136            $send_email = apply_filters( 'jetpack_forms_send_test_feedback_email', true, $post_id, $response );
3137        }
3138
3139        /**
3140         * Filter to determine if spam should still be emailed.
3141         *
3142         * @module contact-form
3143         */
3144        $send_even_if_spam = apply_filters( 'grunion_still_email_spam', false );
3145
3146        // Only fire send-related side effects when we are actually going to send.
3147        $will_send = ( $is_spam !== true && $send_email ) || ( true === $is_spam && $send_even_if_spam );
3148
3149        if ( $will_send ) {
3150            /**
3151             * Fires right before the contact form message is sent via email to
3152             * the recipient specified in the contact form.
3153             *
3154             * @module contact-form
3155             *
3156             * @since 1.3.1
3157             *
3158             * @param integer $post_id Post contact form lives on
3159             * @param array $all_values Contact form fields
3160             * @param array $extra_values Contact form fields not included in $all_values
3161             */
3162            do_action( 'grunion_pre_message_sent', $post_id, $all_values, $extra_values );
3163
3164            self::wp_mail( $to, "{$spam}{$subject}", $message, $headers );
3165        }
3166
3167        // Schedule deletes of old spam feedbacks.
3168        if ( ! wp_next_scheduled( 'grunion_scheduled_delete' ) ) {
3169            wp_schedule_event( time() + 250, 'daily', 'grunion_scheduled_delete' );
3170        }
3171
3172        // Schedule deletes of old temp feedbacks.
3173        if ( ! wp_next_scheduled( 'grunion_scheduled_delete_temp' ) ) {
3174            wp_schedule_event( time() + 250, 'daily', 'grunion_scheduled_delete_temp' );
3175        }
3176
3177        /**
3178         * Fires an action hook right after the email(s) have been sent.
3179         *
3180         * @module contact-form
3181         *
3182         * @since 7.3.0
3183         *
3184         * @param int $post_id Post contact form lives on.
3185         * @param string|array $to Array of valid email addresses, or single email address.
3186         * @param string $subject Feedback email subject.
3187         * @param string $message Feedback email message.
3188         * @param string|array $headers Optional. Additional headers.
3189         * @param array $all_values Contact form fields.
3190         * @param array $extra_values Contact form fields not included in $all_values
3191         */
3192        do_action( 'grunion_after_message_sent', $post_id, $to, $subject, $message, $headers, $all_values, $extra_values );
3193
3194        $refresh_args = array(
3195            'contact-form-id'   => $id,
3196            'contact-form-sent' => $post_id,
3197            'contact-form-hash' => $this->hash,
3198            '_wpnonce'          => wp_create_nonce( "contact-form-sent-{$post_id}" ), // wp_nonce_url HTMLencodes :( .
3199        );
3200
3201        // If the request accepts JSON, return a JSON response instead of redirecting
3202        $accepts_json = isset( $_SERVER['HTTP_ACCEPT'] ) && false !== strpos( strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_ACCEPT'] ) ) ), 'application/json' );
3203
3204        if ( $this->is_response_without_reload_enabled && $accepts_json ) {
3205            $data = array();
3206            if ( $response instanceof Feedback ) {
3207                $data = $response->get_compiled_fields( 'ajax', 'collection' );
3208            }
3209            wp_send_json(
3210                array(
3211                    'success'     => true,
3212                    'data'        => $data,
3213                    'refreshArgs' => $refresh_args,
3214                ),
3215                null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
3216                JSON_UNESCAPED_SLASHES
3217            );
3218        }
3219
3220        if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
3221            return self::success_message( $post_id, $this );
3222        }
3223
3224        $redirect = $this->get_redirect_url( $refresh_args, $id, $post_id );
3225
3226        // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- We intentially allow external redirects here.
3227        wp_redirect( $redirect );
3228        exit( 0 );
3229    }
3230
3231    /**
3232     * Check if the contact form has a custom redirect.
3233     *
3234     * @return bool True if the contact form has a custom redirect, false otherwise.
3235     */
3236    public function has_custom_redirect() {
3237        $confirmation_type = $this->get_confirmation_type();
3238
3239        if ( ! empty( $this->get_attribute( 'customThankyouRedirect' ) ) && 'redirect' === $confirmation_type ) {
3240            return true;
3241        }
3242        /**
3243         * Filter to check if the contact form has a redirect filter.
3244         *
3245         * @module contact-form
3246         *
3247         * @since 1.9.0
3248         *
3249         * @param bool $has_redirect True if the contact form has a redirect filter, false otherwise.
3250         */
3251        return (bool) has_filter( 'grunion_contact_form_redirect_url' );
3252    }
3253
3254    /**
3255     * Get the URL where the reader is redirected after submitting a form.
3256     *
3257     * @param array $refresh_args The arguments to be added to the redirect URL.
3258     * @param int   $id           Contact Form ID.
3259     * @param int   $post_id      Post ID.
3260     *
3261     * @return string The redirect URL.
3262     */
3263    public function get_redirect_url( $refresh_args, $id, $post_id ) {
3264        $confirmation_type = $this->get_confirmation_type();
3265        $redirect          = '';
3266        $custom_redirect   = false;
3267
3268        if ( 'redirect' === $confirmation_type ) {
3269            $custom_redirect = true;
3270            $redirect        = esc_url_raw( $this->get_attribute( 'customThankyouRedirect' ) );
3271        }
3272
3273        if ( ! $redirect ) {
3274            $custom_redirect = false;
3275            $redirect        = wp_get_referer();
3276        }
3277
3278        if ( ! $redirect ) { // wp_get_referer() returns false if the referer is the same as the current page.
3279            $custom_redirect = false;
3280            $redirect        = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
3281        }
3282
3283        if ( ! $custom_redirect ) {
3284            $redirect = add_query_arg(
3285                urlencode_deep( $refresh_args ),
3286                $redirect
3287            );
3288        }
3289
3290        /**
3291         * Filter the URL where the reader is redirected after submitting a form.
3292         *
3293         * @module contact-form
3294         *
3295         * @since 1.9.0
3296         *
3297         * @param string $redirect Post submission URL.
3298         * @param int $id Contact Form ID.
3299         * @param int $post_id Post ID.
3300         */
3301        return apply_filters( 'grunion_contact_form_redirect_url', $redirect, $id, $post_id );
3302    }
3303
3304    /**
3305     * Get the permalink for the post ID that include the page query parameter if it was set.
3306     *
3307     * @param int $post_id The post ID.
3308     *
3309     * return string The permalink for the post ID.
3310     */
3311    public static function get_permalink( $post_id ) {
3312        $url  = get_permalink( $post_id );
3313        $page = isset( $_POST['page'] ) ? absint( wp_unslash( $_POST['page'] ) ) : null; // phpcs:Ignore WordPress.Security.NonceVerification.Missing
3314        if ( $page ) {
3315            return add_query_arg( 'page', $page, $url );
3316        }
3317        return $url;
3318    }
3319
3320    /**
3321     * Wrapper for wp_mail() that enables HTML messages with text alternatives
3322     *
3323     * @param string|array $to          Array or comma-separated list of email addresses to send message.
3324     * @param string       $subject     Email subject.
3325     * @param string       $message     Message contents.
3326     * @param string|array $headers     Optional. Additional headers.
3327     * @param string|array $attachments Optional. Files to attach.
3328     *
3329     * @return bool Whether the email contents were sent successfully.
3330     */
3331    public static function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
3332        return Feedback_Email_Renderer::wp_mail( $to, $subject, $message, $headers, $attachments );
3333    }
3334
3335    /**
3336     * Add a display name part to an email address
3337     *
3338     * SpamAssassin doesn't like addresses in HTML messages that are missing display names (e.g., `foo@bar.org`
3339     * instead of `Foo Bar <foo@bar.org>`.
3340     *
3341     * @param string $address - the email address.
3342     *
3343     * @return string
3344     */
3345    public function add_name_to_address( $address ) {
3346        // If it's just the address, without a display name
3347        if ( is_email( $address ) ) {
3348            $address_parts = explode( '@', $address );
3349
3350            /*
3351             * The email address format here is formatted in a format
3352             * that is the most likely to be accepted by wp_mail(),
3353             * without escaping.
3354             * More info: https://github.com/Automattic/jetpack/pull/19727
3355             */
3356            $address = sprintf( '%s <%s>', $address_parts[0], $address );
3357        }
3358
3359        return $address;
3360    }
3361
3362    /**
3363     * Get the content type that should be assigned to outbound emails
3364     *
3365     * @return string
3366     */
3367    public static function get_mail_content_type() {
3368        return Feedback_Email_Renderer::get_mail_content_type();
3369    }
3370
3371    /**
3372     * Wrap a message body with the appropriate in HTML tags
3373     *
3374     * This helps to ensure correct parsing by clients, and also helps avoid triggering spam filtering rules
3375     *
3376     * @param string $title - title of the email.
3377     * @param string $body - the message body.
3378     * @param string $footer - the footer containing meta information.
3379     * @param string $actions - HTML for actions displayed in the email.
3380     * @param array  $respondent_info - Optional. Respondent information array with 'name', 'email', 'avatar'.
3381     * @param array  $metadata - Optional. Metadata array with 'date', 'source', 'source_url', 'device', 'ip', 'ip_flag'.
3382     *
3383     * @return string
3384     */
3385    public static function wrap_message_in_html_tags( $title, $body, $footer, $actions = '', $respondent_info = array(), $metadata = array() ) {
3386        return Feedback_Email_Renderer::wrap_message_in_html_tags( $title, $body, $footer, $actions, $respondent_info, $metadata );
3387    }
3388
3389    /**
3390     * Add a plain-text alternative part to an outbound email
3391     *
3392     * This makes the message more accessible to mail clients that aren't HTML-aware, and decreases the likelihood
3393     * that the message will be flagged as spam.
3394     *
3395     * @param PHPMailer $phpmailer - the phpmailer.
3396     */
3397    public static function add_plain_text_alternative( $phpmailer ) {
3398        Feedback_Email_Renderer::add_plain_text_alternative( $phpmailer );
3399    }
3400
3401    /**
3402     * Add deepslashes.
3403     *
3404     * @param array $value - the value.
3405     * @return array The value, with slashes added.
3406     */
3407    public function addslashes_deep( $value ) {
3408        if ( is_array( $value ) ) {
3409            return array_map( array( $this, 'addslashes_deep' ), $value );
3410        } elseif ( is_object( $value ) ) {
3411            $vars = get_object_vars( $value );
3412            foreach ( $vars as $key => $data ) {
3413                $value->{$key} = $this->addslashes_deep( $data );
3414            }
3415            return (array) $value;
3416        }
3417
3418        return addslashes( $value );
3419    }
3420
3421    /**
3422     * Get the block's classes.
3423     * This gathers both the alignment classes and the layout classes,
3424     * which go on the outermost div.
3425     *
3426     * @param array $attributes Block attributes.
3427     * @param array $extra_container_classes Extra container classes.
3428     * @return string The block's classes.
3429     */
3430    public static function get_block_container_classes( $attributes = array(), $extra_container_classes = array() ) {
3431        // using wp-block-jetpack-contact-form-container here
3432        // confuses the layout support process, making it place the CSS classes on the container
3433        // instead of the actual block.
3434        $classes = array( 'jetpack-contact-form-container' );
3435
3436        $classes = array_merge( $classes, $extra_container_classes );
3437
3438        if ( isset( $attributes['variationName'] ) && $attributes['variationName'] === 'multistep' ) {
3439            $classes[] = 'is-multistep';
3440        }
3441
3442        $classes[] = self::get_block_alignment_class( $attributes );
3443
3444        return implode( ' ', $classes );
3445    }
3446
3447    /**
3448     * Rough implementation of Gutenberg's align-attribute-to-css-class map.
3449     * Only allowin "wide" and "full" as "center", "left" and "right" don't
3450     * make much sense for the form.
3451     *
3452     * @param array $attributes Block attributes.
3453     * @return string The CSS alignment class: alignfull | alignwide.
3454     */
3455    public static function get_block_alignment_class( $attributes = array() ) {
3456        $align_to_class_map = array(
3457            'wide' => 'alignwide',
3458            'full' => 'alignfull',
3459        );
3460        if ( empty( $attributes['align'] ) || ! array_key_exists( $attributes['align'], $align_to_class_map ) ) {
3461            return '';
3462        }
3463        return $align_to_class_map[ $attributes['align'] ];
3464    }
3465
3466    /**
3467     * Process a file upload field.
3468     *
3469     * @param string $field_id The field ID.
3470     * @param object $field The field object.
3471     *
3472     * @return array A structured array with field_id and files array.
3473     */
3474    public function process_file_upload_field( $field_id, $field ) {
3475        $field_id = sanitize_key( $field_id );
3476
3477        $raw_data = array();
3478        // phpcs:ignore WordPress.Security.NonceVerification.Missing
3479        if ( isset( $_POST[ $field_id ] ) ) {
3480
3481            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.NonceVerification.Missing
3482            $raw_post_data = wp_unslash( $_POST[ $field_id ] );
3483            if ( is_array( $raw_post_data ) ) {
3484                $raw_data = array_map( 'sanitize_text_field', $raw_post_data );
3485            }
3486        }
3487
3488        $file_data_array = is_array( $raw_data )
3489            ? array_map(
3490                function ( $json_str ) {
3491                    $decoded = json_decode( $json_str, true );
3492                    return array(
3493                        'file_id' => isset( $decoded['file_id'] ) ? sanitize_text_field( $decoded['file_id'] ) : '',
3494                        'name'    => isset( $decoded['name'] ) ? sanitize_text_field( $decoded['name'] ) : '',
3495                        'size'    => isset( $decoded['size'] ) ? absint( $decoded['size'] ) : 0,
3496                        'type'    => isset( $decoded['type'] ) ? sanitize_text_field( $decoded['type'] ) : '',
3497                    );
3498                },
3499                $raw_data
3500            ) : array();
3501
3502        if ( empty( $file_data_array ) ) {
3503            $field->add_error( __( 'Failed to upload file.', 'jetpack-forms' ) );
3504            return array(
3505                'field_id' => $field_id,
3506                'files'    => array(),
3507            );
3508        }
3509
3510        return array(
3511            'field_id' => $field_id,
3512            'files'    => $file_data_array,
3513        );
3514    }
3515
3516    /**
3517     * Ensures a value is formatted as a string, taking into account file upload fields.
3518     *
3519     * @param mixed $value The value to transform.
3520     * @return mixed The transformed value.
3521     */
3522    private static function maybe_transform_value( $value ) {
3523        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'image-select' ) {
3524            return implode(
3525                ', ',
3526                array_map(
3527                    function ( $choice ) {
3528                        $value = $choice['perceived'];
3529
3530                        if ( $choice['showLabels'] && ! empty( $choice['label'] ) ) {
3531                            $value .= ' - ' . $choice['label'];
3532                        }
3533
3534                        return $value;
3535                    },
3536                    $value['choices']
3537                )
3538            );
3539        }
3540
3541        // For URL fields, extract the display text value (original user input without auto-added protocol).
3542        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'url' ) {
3543            // Prefer displayValue (raw input) over url (which may have https:// prepended).
3544            return $value['displayValue'] ?? ( $value['url'] ?? '' );
3545        }
3546
3547        // For rating fields, return the displayValue (e.g., "3/5") for text fallback.
3548        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'rating' ) {
3549            return $value['displayValue'] ?? '';
3550        }
3551
3552        // For file upload fields, we want to show the file name and size
3553        if ( is_array( $value ) && isset( $value['name'] ) && isset( $value['size'] ) ) {
3554            $file_name = $value['name'];
3555            $file_size = $value['size'];
3556            return empty( $file_size ) ? $file_name : $file_name . ' (' . $file_size . ')';
3557        }
3558
3559        return $value;
3560    }
3561
3562    /**
3563     * Helper method to get the images from an image select field.
3564     *
3565     * Returns an array of image choice objects, each containing:
3566     * - src: The image URL
3567     * - letterCode: The letter code (e.g., 'A', 'B', 'C')
3568     * - label: The choice label text (empty string if showLabels is false)
3569     *
3570     * @param array $value The value to get the images from.
3571     * @return array|null The images with metadata, or null if not an image-select field.
3572     */
3573    private static function get_images( $value ) {
3574        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'image-select' ) {
3575            return array_map(
3576                function ( $choice ) {
3577                    $letter_code = $choice['perceived'] ?? '';
3578                    $label       = '';
3579
3580                    if ( ! empty( $choice['showLabels'] ) && ! empty( $choice['label'] ) ) {
3581                        $label = $choice['label'];
3582                    }
3583
3584                    return array(
3585                        'src'        => $choice['image']['src'] ?? '',
3586                        'letterCode' => $letter_code,
3587                        'label'      => $label,
3588                    );
3589                },
3590                $value['choices']
3591            );
3592        }
3593
3594        return null;
3595    }
3596
3597    /**
3598     * Get files from a file field value if present.
3599     *
3600     * @param mixed $value The field value.
3601     *
3602     * @return array|null Array of file data if this is a file field, null otherwise.
3603     */
3604    private static function get_files( $value ) {
3605        if ( is_array( $value ) && isset( $value['type'] ) && $value['type'] === 'file' && ! empty( $value['files'] ) ) {
3606            return array_map(
3607                function ( $file ) {
3608                    $preview_url = $file['previewUrl'] ?? null;
3609                    $icon_url    = $file['iconUrl'] ?? null;
3610                    $has_preview = ! empty( $preview_url ) || ! empty( $icon_url );
3611
3612                    return array(
3613                        'name'       => $file['name'] ?? __( 'Attached file', 'jetpack-forms' ),
3614                        'size'       => $file['size'] ?? '',
3615                        'url'        => $file['url'] ?? '',
3616                        // Preview URLs are captured from the DOM for AJAX submissions
3617                        'previewUrl' => $preview_url,
3618                        'iconUrl'    => $icon_url,
3619                        // Boolean flag for easier binding evaluation
3620                        'hasPreview' => $has_preview,
3621                    );
3622                },
3623                $value['files']
3624            );
3625        }
3626
3627        return null;
3628    }
3629
3630    /**
3631     * Helper method to format a raw label string for display, including kses sanitization.
3632     *
3633     * @param string|null $raw_label The raw label input.
3634     * @return string The formatted and kses'd label string, or an empty string if raw_label is empty.
3635     */
3636    public static function escape_and_sanitize_field_label( $raw_label ) {
3637        if ( empty( $raw_label ) ) {
3638            return ''; // kses the empty string
3639        }
3640        return wp_kses( (string) $raw_label, array() );
3641    }
3642
3643    /**
3644     * Enforce required block supports UIs for Classic themes.
3645     *
3646     * @param \WP_Theme_JSON_Data $theme_json_data Theme JSON data object.
3647     *
3648     * @return \WP_Theme_JSON_Data Updated theme JSON settings.
3649     */
3650    public static function add_theme_json_data_for_classic_themes( $theme_json_data ) {
3651        if ( wp_is_block_theme() ) {
3652            return $theme_json_data;
3653        }
3654
3655        $data = $theme_json_data->get_data();
3656
3657        if ( ! isset( $data['settings']['blocks'] ) ) {
3658            $data['settings']['blocks'] = array();
3659        }
3660
3661        $data['settings']['blocks']['jetpack/input'] = array(
3662            'color'      => array(
3663                'text'       => true,
3664                'background' => false,
3665            ),
3666            'border'     => array(
3667                'color'  => true,
3668                'radius' => true,
3669                'style'  => true,
3670                'width'  => true,
3671            ),
3672            'typography' => array(
3673                'fontFamily'     => true,
3674                'fontSize'       => true,
3675                'fontStyle'      => true,
3676                'fontWeight'     => true,
3677                'letterSpacing'  => true,
3678                'lineHeight'     => true,
3679                'textDecoration' => true,
3680                'textTransform'  => true,
3681            ),
3682        );
3683
3684        // maybe need to add support for jetpack/phone-input
3685
3686        $data['settings']['blocks']['jetpack/options'] = array(
3687            'color'  => array(
3688                'text'       => true,
3689                'background' => true,
3690            ),
3691            'border' => array(
3692                'color'  => true,
3693                'radius' => true,
3694                'style'  => true,
3695                'width'  => true,
3696            ),
3697        );
3698
3699        $shared_settings                              = array(
3700            'color'      => array(
3701                'text'       => true,
3702                'background' => false,
3703            ),
3704            'typography' => array(
3705                'fontFamily'     => true,
3706                'fontSize'       => true,
3707                'fontStyle'      => true,
3708                'fontWeight'     => true,
3709                'letterSpacing'  => true,
3710                'lineHeight'     => true,
3711                'textDecoration' => true,
3712                'textTransform'  => true,
3713            ),
3714        );
3715        $data['settings']['blocks']['jetpack/label']  = $shared_settings;
3716        $data['settings']['blocks']['jetpack/option'] = $shared_settings;
3717
3718        $theme_json_class = get_class( $theme_json_data );
3719        return new $theme_json_class( $data, 'default' );
3720    }
3721
3722    /**
3723     * Validate the contact form fields.
3724     *
3725     * This method checks each field for errors and ensures that at least one field has a value.
3726     * If no fields have values and there are no errors, it adds an error indicating that the form is empty.
3727     */
3728    public function validate() {
3729        $has_value = false;
3730        // Validate the form fields before processing the form.
3731        foreach ( $this->fields as $field ) {
3732            $field->validate();
3733            if ( ! $has_value && $field->has_value() ) {
3734                $has_value = true;
3735            }
3736        }
3737
3738        if ( ! $has_value && ! $this->has_errors() ) {
3739            $this->add_error( 'empty', __( 'Please fill out at least one field.', 'jetpack-forms' ) );
3740        }
3741
3742        $ref_id = $this->get_attribute( 'ref' );
3743        if ( ! empty( $ref_id ) ) {
3744            $this->validate_ref( $ref_id );
3745        }
3746    }
3747
3748    /**
3749     * Validate the form reference.
3750     *
3751     * @param int $ref The form reference ID.
3752     */
3753    public function validate_ref( $ref ) {
3754        $form_post = get_post( $ref );
3755        if ( ! $form_post || self::POST_TYPE !== $form_post->post_type ) {
3756            $this->add_error( 'invalid_ref', __( 'Invalid form reference.', 'jetpack-forms' ) );
3757            return;
3758        }
3759        if ( $form_post->post_status !== 'publish' ) {
3760            $this->add_error( 'unpublished_form', __( 'Invalid form reference.', 'jetpack-forms' ) );
3761            return;
3762        }
3763    }
3764
3765    /**
3766     * Reset the static errors for the contact form.
3767     *
3768     * @param string $id The ID of the contact form to reset errors for. If null, resets all static errors.
3769     *
3770     * This method is used to clear the static errors stored in the class.
3771     */
3772    public static function reset_errors( $id = null ) {
3773        if ( $id && isset( self::$static_errors[ $id ] ) ) {
3774            unset( self::$static_errors[ $id ] );
3775            return;
3776        }
3777        self::$static_errors = array();
3778    }
3779
3780    /**
3781     * Add an error to the contact form.
3782     *
3783     * @param string $error_code    The error code.
3784     * @param string $error_message The error message.
3785     */
3786    public function add_error( $error_code, $error_message ) {
3787        $id = $this->get_attribute( 'id' );
3788        if ( ! isset( self::$static_errors[ $id ] ) ) {
3789            self::$static_errors[ $id ] = Form_Submission_Error::validation_error( $error_code, $error_message );
3790        } else {
3791            // If we already have errors, add this error to the existing Form_Submission_Error
3792            self::$static_errors[ $id ]->add( $error_code, $error_message );
3793        }
3794        $this->errors = self::$static_errors[ $id ];
3795    }
3796    /**
3797     * Check if the contact form has errors.
3798     *
3799     * @return bool True if the contact form has errors, false otherwise.
3800     */
3801    public function has_errors() {
3802        $id = $this->get_attribute( 'id' );
3803        if ( ! isset( self::$static_errors[ $id ] ) ) {
3804            return false;
3805        }
3806        return is_wp_error( self::$static_errors[ $id ] ) && ! empty( self::$static_errors[ $id ]->get_error_codes() );
3807    }
3808
3809    /**
3810     * Get the error messages of the contact form.
3811     *
3812     * @return array The errors of the contact form.
3813     */
3814    public function get_error_messages() {
3815        if ( ! $this->has_errors() ) {
3816            return array();
3817        }
3818        $id = $this->get_attribute( 'id' );
3819        return self::$static_errors[ $id ]->get_error_messages();
3820    }
3821
3822    /**
3823     * Get the confirmation type of the contact form from the deprecated customThankyou attribute.
3824     *
3825     * @return string The confirmation type of the contact form.
3826     */
3827    public function get_confirmation_type() {
3828        // Backward compat: customThankyou 'redirect' takes precedence for old forms
3829        if ( 'redirect' === $this->get_attribute( 'customThankyou' ) ) {
3830            return 'redirect';
3831        }
3832
3833        return $this->get_attribute( 'confirmationType' );
3834    }
3835
3836    /**
3837     * Get the disable summary of the contact form from the deprecated customThankyou attribute.
3838     *
3839     * @return string The disable summary of the contact form.
3840     */
3841    public function get_disable_summary() {
3842        $disable_summary = $this->get_attribute( 'disableSummary' );
3843        $custom_thankyou = $this->get_attribute( 'customThankyou' );
3844
3845        if ( '' === $disable_summary ) {
3846            $disable_summary = 'noSummary' === $custom_thankyou || 'message' === $custom_thankyou;
3847        }
3848
3849        return $disable_summary;
3850    }
3851}