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