Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
47.71% covered (danger)
47.71%
772 / 1618
34.82% covered (danger)
34.82%
39 / 112
CRAP
0.00% covered (danger)
0.00%
0 / 1
Contact_Form_Plugin
47.77% covered (danger)
47.77%
772 / 1616
34.82% covered (danger)
34.82%
39 / 112
47019.91
0.00% covered (danger)
0.00%
0 / 1
 init
60.00% covered (warning)
60.00%
3 / 5
0.00% covered (danger)
0.00%
0 / 1
2.26
 daily_akismet_meta_cleanup
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 strip_tags
84.62% covered (warning)
84.62%
11 / 13
0.00% covered (danger)
0.00%
0 / 1
4.06
 __construct
90.15% covered (success)
90.15%
119 / 132
0.00% covered (danger)
0.00%
0 / 1
13.16
 get_global_styles_label_object
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
6.05
 add_global_styles_label_css
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 build_global_styles_label_css
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
12
 has_editor_feature_flag
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 remove_from_related_posts_allowed_post_types
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 disable_forms_view_script_concat
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 register_contact_form_blocks
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_block_support_classes_and_styles
97.14% covered (success)
97.14%
34 / 35
0.00% covered (danger)
0.00%
0 / 1
10
 get_block_style_classes
76.47% covered (warning)
76.47%
13 / 17
0.00% covered (danger)
0.00%
0 / 1
5.33
 block_attributes_to_shortcode_attributes
52.84% covered (warning)
52.84%
93 / 176
0.00% covered (danger)
0.00%
0 / 1
397.76
 get_image_option_letter
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 reset_step
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 gutenblock_render_form_step
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
30
 gutenblock_render_form_step_navigation
87.93% covered (warning)
87.93%
51 / 58
0.00% covered (danger)
0.00%
0 / 1
19.63
 gutenblock_render_form_progress_indicator
0.00% covered (danger)
0.00%
0 / 53
0.00% covered (danger)
0.00%
0 / 1
182
 get_style_variation_shortcode_attributes
82.35% covered (warning)
82.35%
14 / 17
0.00% covered (danger)
0.00%
0 / 1
8.35
 gutenblock_render_field_text
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 gutenblock_render_field_name
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 gutenblock_render_field_email
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 gutenblock_render_field_url
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 gutenblock_render_field_date
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 gutenblock_render_field_telephone
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 gutenblock_render_field_textarea
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 gutenblock_render_field_checkbox
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 gutenblock_render_field_checkbox_multiple
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 gutenblock_render_field_option
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 gutenblock_render_field_radio
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 gutenblock_render_field_select
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 gutenblock_render_field_consent
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 gutenblock_render_field_file
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 gutenblock_render_dropzone
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
56
 gutenblock_render_field_hidden
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 gutenblock_render_field_number
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 gutenblock_render_field_time
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 gutenblock_render_field_image_select
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 admin_menu
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
12
 allow_feedback_rest_api_type
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 unread_count
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
 get_unread_count
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 recalculate_unread_count
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 process_form_submission
25.53% covered (danger)
25.53%
36 / 141
0.00% covered (danger)
0.00%
0 / 1
1125.12
 ajax_request
0.00% covered (danger)
0.00%
0 / 46
0.00% covered (danger)
0.00%
0 / 1
110
 reconcile_content_destinations
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
6
 validate_parent_post
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
5
 insert_feedback_filter
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 add_shortcode
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 tokenize_label
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 sanitize_value
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 format_value_for_display
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 replace_tokens_with_input
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
3.03
 track_current_widget
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 track_current_widget_before
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 track_current_widget_after
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 get_current_widget_context
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 widget_atts
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 widget_shortcode_hack
n/a
0 / 0
n/a
0 / 0
2
 is_spam_blocklist
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 is_in_disallowed_list
83.33% covered (warning)
83.33%
10 / 12
0.00% covered (danger)
0.00%
0 / 1
3.04
 prepare_for_akismet
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
9
 is_spam_akismet
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
156
 akismet_submit
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 form_posts_dropdown
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 get_post_content_for_csv_export
n/a
0 / 0
n/a
0 / 0
1
 get_post_meta_for_csv_export
0.00% covered (danger)
0.00%
0 / 31
0.00% covered (danger)
0.00%
0 / 1
240
 get_parsed_field_contents_of_post
n/a
0 / 0
n/a
0 / 0
1
 map_parsed_field_contents_of_post_to_field_names
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
30
 register_personal_data_exporter
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 register_personal_data_eraser
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 personal_data_exporter
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 internal_personal_data_exporter
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 internal_personal_data_formater
97.67% covered (success)
97.67%
42 / 43
0.00% covered (danger)
0.00%
0 / 1
5
 personal_data_eraser
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 _internal_personal_data_eraser
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
72
 personal_data_post_ids_by_email
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
6
 set_pde_email_address
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 personal_data_search_filter
90.48% covered (success)
90.48%
19 / 21
0.00% covered (danger)
0.00%
0 / 1
6.03
 get_export_feedback_data
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
 get_export_rows
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 prepare_export
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 get_prepared_export_rows
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 get_export_feedback_batches
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
8
 get_export_row
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
3
 get_export_data_for_posts
n/a
0 / 0
n/a
0 / 0
1
 get_well_known_column_names
n/a
0 / 0
n/a
0 / 0
1
 get_feedback_entries_from_post
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 get_export_rows_from_post
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 get_export_feedback_ids_from_post
51.52% covered (warning)
51.52%
17 / 33
0.00% covered (danger)
0.00%
0 / 1
54.93
 get_export_feedback_ids
84.44% covered (warning)
84.44%
38 / 45
0.00% covered (danger)
0.00%
0 / 1
15.85
 download_feedback_as_csv
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
30
 create_new_form
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
110
 record_tracks_event
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
56
 write_export_csv
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 esc_csv
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 get_all_parent_post_ids
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
2
 get_feedbacks_as_options
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
 get_field_names
n/a
0 / 0
n/a
0 / 0
3
 has_json_data
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 parse_feedback_content
n/a
0 / 0
n/a
0 / 0
10
 parse_fields_from_content
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 make_csv_row_from_feedback
n/a
0 / 0
n/a
0 / 0
6
 get_ip_address
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 use_block_editor_for_post_type
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 use_block_editor_for_post
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 restrict_feedback_comments_to_logged_in
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 reverse_that_print
100.00% covered (success)
100.00%
30 / 30
100.00% covered (success)
100.00%
1 / 1
9
 untrash_feedback_status_handler
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 track_spam_status_change
n/a
0 / 0
n/a
0 / 0
3
 track_feedback_status_change
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
3.04
 purge_edge_cache_on_form_status_change
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 track_spam_status
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
5
 track_recount_unread
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
6
 can_use_analytics
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 gutenblock_render_field_rating
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 gutenblock_render_field_slider
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 redirect_edit_feedback_to_jetpack_forms
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
72
 validate_export_to_gdrive_request
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 export_to_gdrive
0.00% covered (danger)
0.00%
0 / 49
0.00% covered (danger)
0.00%
0 / 1
132
1<?php
2/**
3 * Contact_Form_Plugin class.
4 *
5 * @package automattic/jetpack-forms
6 */
7
8namespace Automattic\Jetpack\Forms\ContactForm;
9
10use Automattic\Jetpack\Connection\Manager as Connection_Manager;
11use Automattic\Jetpack\Constants;
12use Automattic\Jetpack\Extensions\Contact_Form\Contact_Form_Block;
13use Automattic\Jetpack\Forms\Dashboard\Dashboard;
14use Automattic\Jetpack\Forms\Editor\Form_Editor;
15use Automattic\Jetpack\Forms\Jetpack_Forms;
16use Automattic\Jetpack\Forms\Service\Form_Webhooks;
17use Automattic\Jetpack\Forms\Service\Google_Drive;
18use Automattic\Jetpack\Forms\Service\Hostinger_Reach_Integration;
19use Automattic\Jetpack\Forms\Service\MailPoet_Integration;
20use Automattic\Jetpack\Forms\Service\Post_To_Url;
21use Automattic\Jetpack\Status;
22use Automattic\Jetpack\Terms_Of_Service;
23use Automattic\Jetpack\Tracking;
24use Jetpack_Options;
25use WP_Block;
26use WP_Block_Patterns_Registry;
27use WP_Block_Type_Registry;
28use WP_Error;
29use WP_Post;
30
31// Load the Form_Submission_Error class.
32require_once __DIR__ . '/class-form-submission-error.php';
33
34// Load the Form_Preview class.
35require_once __DIR__ . '/class-form-preview.php';
36
37/**
38 * Sets up various actions, filters, post types, post statuses, shortcodes.
39 */
40class Contact_Form_Plugin {
41
42    /**
43     *
44     * The Widget ID of the widget currently being processed.  Used to build the unique contact-form ID for forms embedded in widgets.
45     *
46     * @var string
47     */
48    public $current_widget_id;
49
50    /**
51     * The Sidebar ID of the sidebar currently being processed.  Used to build the unique contact-form ID for forms embedded in sidebars.
52     *
53     * @var string
54     */
55    public $current_sidebar_id;
56
57    /**
58     * If the contact form field is being used.
59     *
60     * @var bool
61     */
62    public static $using_contact_form_field = false;
63
64    /**
65     *
66     * The last Feedback Post ID Erased as part of the Personal Data Eraser.
67     * Helps with pagination.
68     *
69     * @var int
70     */
71    private $pde_last_post_id_erased = 0;
72
73    /**
74     *
75     * The email address for which we are deleting/exporting all feedbacks
76     * as part of a Personal Data Eraser or Personal Data Exporter request.
77     *
78     * @var string
79     */
80    private $pde_email_address = '';
81
82    /**
83     * The number of steps in the form.
84     *
85     * This is used to determine how many steps are in the form when using the multi-step feature.
86     * It is incremented each time a new step is added.
87     *
88     * @var int
89     */
90    public static $step_count = 0;
91
92    /*
93     * Field keys that might be present in the entry json but we don't want to show to the admin
94     * since they not something that the visitor entered into the form.
95     *
96     * @var array
97     */
98    const NON_PRINTABLE_FIELDS = array(
99        'entry_title'             => '',
100        'email_marketing_consent' => '',
101        'entry_permalink'         => '',
102        'entry_page'              => '',
103        'feedback_id'             => '',
104    );
105
106    /**
107     * Number of responses loaded into memory at once while exporting.
108     *
109     * @var int
110     */
111    const EXPORT_BATCH_SIZE = 100;
112
113    /**
114     * GDrive export nonce field name
115     *
116     * @var string The nonce field name for GDrive export.
117     */
118    private $export_nonce_field_gdrive = 'feedback_export_nonce_gdrive';
119
120    /**
121     * Initializing function.
122     */
123    public static function init() {
124        static $instance = false;
125
126        if ( ! $instance ) {
127            $instance = new Contact_Form_Plugin();
128
129            // Schedule our daily cleanup
130            add_action( 'wp_scheduled_delete', array( $instance, 'daily_akismet_meta_cleanup' ) );
131        }
132
133        return $instance;
134    }
135
136    /**
137     * Runs daily to clean up spam detection metadata after 15 days.  Keeps your DB squeaky clean.
138     */
139    public function daily_akismet_meta_cleanup() {
140        global $wpdb;
141
142        $feedback_ids = $wpdb->get_col( "SELECT p.ID FROM {$wpdb->posts} as p INNER JOIN {$wpdb->postmeta} as m on m.post_id = p.ID WHERE p.post_type = 'feedback' AND m.meta_key = '_feedback_akismet_values' AND DATE_SUB(NOW(), INTERVAL 15 DAY) > p.post_date_gmt LIMIT 10000" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
143
144        if ( empty( $feedback_ids ) ) {
145            return;
146        }
147
148        /**
149         * Fires right before deleting the _feedback_akismet_values post meta on $feedback_ids
150         *
151         * @module contact-form
152         *
153         * @since 6.1.0
154         *
155         * @param array $feedback_ids list of feedback post ID
156         */
157        do_action( 'jetpack_daily_akismet_meta_cleanup_before', $feedback_ids );
158        foreach ( $feedback_ids as $feedback_id ) {
159            delete_post_meta( $feedback_id, '_feedback_akismet_values' );
160        }
161
162        /**
163         * Fires right after deleting the _feedback_akismet_values post meta on $feedback_ids
164         *
165         * @module contact-form
166         *
167         * @since 6.1.0
168         *
169         * @param array $feedback_ids list of feedback post ID
170         */
171        do_action( 'jetpack_daily_akismet_meta_cleanup_after', $feedback_ids );
172    }
173
174    /**
175     * Strips HTML tags from input.  Output is NOT HTML safe.
176     *
177     * @param mixed $data_with_tags - data we're stripping HTML tags from.
178     * @return mixed
179     */
180    public static function strip_tags( $data_with_tags ) {
181        $data_without_tags = array();
182        if ( is_array( $data_with_tags ) ) {
183            foreach ( $data_with_tags as $index => $value ) {
184                if ( is_array( $value ) ) {
185                    $data_without_tags[ $index ] = self::strip_tags( $value );
186                    continue;
187                }
188
189                $index = sanitize_text_field( (string) $index );
190                $value = wp_kses_post( (string) $value );
191                $value = str_replace( '&amp;', '&', $value ); // undo damage done by wp_kses_normalize_entities()
192
193                $data_without_tags[ $index ] = $value;
194            }
195        } else {
196            $data_without_tags = wp_kses_post( (string) $data_with_tags );
197            $data_without_tags = str_replace( '&amp;', '&', $data_without_tags ); // undo damage done by wp_kses_normalize_entities()
198        }
199
200        return $data_without_tags;
201    }
202
203    /**
204     * Class uses singleton pattern; use Contact_Form_Plugin::init() to initialize.
205     */
206    protected function __construct() {
207        $this->add_shortcode();
208
209        // While generating the output of a text widget with a contact-form shortcode, we need to know its widget ID.
210        add_action( 'dynamic_sidebar', array( $this, 'track_current_widget' ) );
211        add_action( 'dynamic_sidebar_before', array( $this, 'track_current_widget_before' ) );
212        add_action( 'dynamic_sidebar_after', array( $this, 'track_current_widget_after' ) );
213
214        add_filter( 'jetpack_contact_form_is_spam', array( $this, 'is_spam_blocklist' ), 10, 2 );
215        add_filter( 'jetpack_contact_form_in_comment_disallowed_list', array( $this, 'is_in_disallowed_list' ), 10, 2 );
216        // Akismet to the rescue
217        if ( defined( 'AKISMET_VERSION' ) || function_exists( 'akismet_http_post' ) ) {
218            add_filter( 'jetpack_contact_form_is_spam', array( $this, 'is_spam_akismet' ), 10, 2 );
219            add_action( 'contact_form_akismet', array( $this, 'akismet_submit' ), 10, 2 );
220        }
221
222        add_action( 'loop_start', array( '\Automattic\Jetpack\Forms\ContactForm\Contact_Form', 'style_on' ) );
223        add_action( 'pre_amp_render_post', array( '\Automattic\Jetpack\Forms\ContactForm\Contact_Form', 'style_on' ) );
224
225        add_action( 'wp_ajax_grunion-contact-form', array( $this, 'ajax_request' ) );
226        add_action( 'wp_ajax_nopriv_grunion-contact-form', array( $this, 'ajax_request' ) );
227
228        // GDPR: personal data exporter & eraser.
229        add_filter( 'wp_privacy_personal_data_exporters', array( $this, 'register_personal_data_exporter' ) );
230        add_filter( 'wp_privacy_personal_data_erasers', array( $this, 'register_personal_data_eraser' ) );
231
232        // Export to CSV feature
233        if ( is_admin() ) {
234            add_action( 'wp_ajax_feedback_export', array( $this, 'download_feedback_as_csv' ) );
235            add_action( 'wp_ajax_create_new_form', array( $this, 'create_new_form' ) );
236            add_action( 'wp_ajax_grunion_export_to_gdrive', array( $this, 'export_to_gdrive' ) );
237        }
238        add_action( 'admin_menu', array( $this, 'admin_menu' ) );
239        // Priority 1000: after Dashboard::add_admin_submenu() (999) registers the Forms submenu,
240        // but well before the menu-badges renderer (100000) reads the registry.
241        add_action( 'admin_menu', array( $this, 'unread_count' ), 1000 );
242        add_action( 'current_screen', array( $this, 'redirect_edit_feedback_to_jetpack_forms' ) );
243
244        add_filter( 'use_block_editor_for_post_type', array( $this, 'use_block_editor_for_post_type' ), 10, 2 );
245        add_filter( 'use_block_editor_for_post', array( $this, 'use_block_editor_for_post' ), 10, 2 );
246
247        // Restrict feedback comments to logged-in users only
248        add_filter( 'comments_open', array( $this, 'restrict_feedback_comments_to_logged_in' ), 10, 2 );
249
250        // custom post type we'll use to keep copies of the feedback items
251        register_post_type(
252            'feedback',
253            array(
254                'labels'                 => array(
255                    'name'               => __( 'Form Responses', 'jetpack-forms' ),
256                    'singular_name'      => __( 'Form Responses', 'jetpack-forms' ),
257                    'search_items'       => __( 'Search Responses', 'jetpack-forms' ),
258                    'not_found'          => __( 'No responses found', 'jetpack-forms' ),
259                    'not_found_in_trash' => __( 'No responses found', 'jetpack-forms' ),
260                ),
261                'menu_icon'              => 'dashicons-feedback',
262                // when the legacy menu item is retired, we don't want to show the default post type listing
263                'show_ui'                => false,
264                'show_in_menu'           => false,
265                'show_in_admin_bar'      => false,
266                'public'                 => false,
267                'rewrite'                => false,
268                'query_var'              => false,
269                'capability_type'        => 'page',
270                'show_in_rest'           => true,
271                'rest_controller_class'  => '\Automattic\Jetpack\Forms\ContactForm\Contact_Form_Endpoint',
272                'supports'               => array( 'comments' ),
273                'default_comment_status' => 'open',
274                'capabilities'           => array(
275                    'create_posts'        => 'do_not_allow',
276                    'publish_posts'       => 'publish_pages',
277                    'edit_posts'          => 'edit_pages',
278                    'edit_others_posts'   => 'edit_others_pages',
279                    'delete_posts'        => 'delete_pages',
280                    'delete_others_posts' => 'delete_others_pages',
281                    'read_private_posts'  => 'read_private_pages',
282                    'edit_post'           => 'edit_page',
283                    'delete_post'         => 'delete_page',
284                    'read_post'           => 'read_page',
285                ),
286                'map_meta_cap'           => true,
287            )
288        );
289        add_filter( 'wp_untrash_post_status', array( $this, 'untrash_feedback_status_handler' ), 10, 3 );
290
291        // Add to REST API post type allowed list.
292        add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_feedback_rest_api_type' ) );
293
294        // Don't let related posts hook into feedback post type.
295        add_filter( 'jetpack_related_posts_rest_api_allowed_post_types', array( $this, 'remove_from_related_posts_allowed_post_types' ) );
296
297        // Add "spam" as a post status
298        register_post_status(
299            'spam',
300            array(
301                'label'                  => 'Spam',
302                'public'                 => false,
303                'exclude_from_search'    => true,
304                'show_in_admin_all_list' => false,
305                // translators: The spam count.
306                'label_count'            => _n_noop( 'Spam <span class="count">(%s)</span>', 'Spam <span class="count">(%s)</span>', 'jetpack-forms' ),
307                'protected'              => true,
308                '_builtin'               => false,
309            )
310        );
311
312        // Add "jp-temp-feedback" as a post status for temporary storage when saveResponses is 'no'.
313        // We want these responses skip the inbox but we still need to keep them in the database so that
314        // filters and integrations continue to work.
315        register_post_status(
316            'jp-temp-feedback',
317            array(
318                'label'                  => 'Temporary Feedback Status',
319                'public'                 => false,
320                'internal'               => true,
321                'exclude_from_search'    => true,
322                'show_in_admin_all_list' => false,
323                'protected'              => true,
324                '_builtin'               => false,
325            )
326        );
327
328        // Track when post status changes to feedback posts types.
329        add_action( 'transition_post_status', array( $this, 'track_feedback_status_change' ), 10, 3 );
330
331        // Purge edge cache when a jetpack_form post is published, updated, or unpublished.
332        add_action( 'transition_post_status', array( $this, 'purge_edge_cache_on_form_status_change' ), 10, 3 );
333
334        // POST handler
335        if (
336            isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) )
337            &&
338            isset( $_POST['action'] ) && 'grunion-contact-form' === $_POST['action'] // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verification should happen when hook fires.
339            &&
340            isset( $_POST['contact-form-id'] ) // phpcs:ignore WordPress.Security.NonceVerification.Missing -- no site changes
341        ) {
342            add_action( 'template_redirect', array( $this, 'process_form_submission' ) );
343        }
344
345        /*
346         * Can be dequeued by placing the following in wp-content/themes/yourtheme/functions.php
347         *
348         *  function remove_grunion_style() {
349         *      wp_deregister_style('grunion.css');
350         *  }
351         *  add_action('wp_print_styles', 'remove_grunion_style');
352         */
353        wp_register_style( 'grunion.css', Jetpack_Forms::plugin_url() . '../dist/contact-form/css/grunion.css', array(), \JETPACK__VERSION );
354        wp_style_add_data( 'grunion.css', 'rtl', 'replace' );
355
356        /*
357         * Late enough that the theme and Global Styles have been resolved, early enough
358         * that grunion.css has not been printed yet.
359         */
360        add_action( 'wp_enqueue_scripts', array( __CLASS__, 'add_global_styles_label_css' ), 20 );
361
362        wp_register_style(
363            'jetpack-forms-layout',
364            Jetpack_Forms::plugin_url() . '../dist/contact-form/css/jetpack-forms-layout.css',
365            array(),
366            \JETPACK__VERSION
367        );
368
369        wp_register_style(
370            'jetpack-form-status-notice',
371            Jetpack_Forms::plugin_url() . '../dist/contact-form/css/form-status-notice.css',
372            array(),
373            \JETPACK__VERSION
374        );
375
376        add_filter( 'js_do_concat', array( __CLASS__, 'disable_forms_view_script_concat' ), 10, 3 );
377
378        if ( defined( 'JETPACK__PLUGIN_DIR' ) ) {
379            // Register Unauthenticated file download hooks.
380            require_once JETPACK__PLUGIN_DIR . 'unauth-file-upload.php';
381        }
382
383        self::register_contact_form_blocks();
384
385        // Register MailPoet integration hook after the class is loaded.
386        if ( Jetpack_Forms::is_mailpoet_enabled() ) {
387            add_action(
388                'grunion_after_feedback_post_inserted',
389                array( MailPoet_Integration::class, 'handle_mailpoet_integration' ),
390                15,
391                4
392            );
393        }
394
395        // Register Hostinger Reach integration hook after the class is loaded.
396        if ( Jetpack_Forms::is_hostinger_reach_enabled() ) {
397            add_action(
398                'grunion_after_feedback_post_inserted',
399                array( Hostinger_Reach_Integration::class, 'handle_hostinger_reach_integration' ),
400                16,
401                4
402            );
403        }
404
405        if ( self::has_editor_feature_flag( 'central-form-management' ) ) {
406            Contact_Form::register_post_type();
407            Form_Editor::init();
408            Form_Preview::init();
409        }
410    }
411
412    /**
413     * Return the merged Global Styles for the `label` element, or an empty array.
414     *
415     * Not wp_get_global_styles(): core's resolver drops `label` before WP 7.1, and a missing
416     * path returns the whole styles tree instead of nothing.
417     *
418     * @since 8.4.0
419     *
420     * @return array Style object for the label element, keyed as in theme.json.
421     */
422    private static function get_global_styles_label_object() {
423        $resolver = class_exists( 'WP_Theme_JSON_Resolver_Gutenberg' )
424            ? 'WP_Theme_JSON_Resolver_Gutenberg'
425            : 'WP_Theme_JSON_Resolver';
426
427        if ( ! class_exists( $resolver ) || ! method_exists( $resolver, 'get_merged_data' ) ) {
428            return array();
429        }
430
431        $data = $resolver::get_merged_data()->get_raw_data();
432
433        return isset( $data['styles']['elements']['label'] ) && is_array( $data['styles']['elements']['label'] )
434            ? $data['styles']['elements']['label']
435            : array();
436    }
437
438    /**
439     * Let Global Styles' `label` element reach form labels, and mirror it onto grouped fields.
440     *
441     * Global Styles emits `label { ... }` at (0,0,1), which loses to grunion.css at (0,1,0), so
442     * the contested properties are re-asserted only when the site has set label styles.
443     *
444     * @since 8.4.0
445     *
446     * @return void
447     */
448    public static function add_global_styles_label_css() {
449        $css = self::build_global_styles_label_css( self::get_global_styles_label_object() );
450
451        if ( '' === $css ) {
452            return;
453        }
454
455        wp_add_inline_style( 'grunion.css', $css );
456    }
457
458    /**
459     * Build the label CSS for a Global Styles `label` style object.
460     *
461     * Every rule is (0,1,0) and printed after grunion.css, so source order decides each tie.
462     *
463     * @since 8.4.0
464     *
465     * @param array $label Style object for the label element, keyed as in theme.json.
466     * @return string CSS, or an empty string when there is nothing to emit.
467     */
468    private static function build_global_styles_label_css( $label ) {
469        if ( ! function_exists( 'wp_style_engine_get_styles' ) || empty( $label ) || ! is_array( $label ) ) {
470            return '';
471        }
472
473        // A grouped field's label is a <legend>, which `label { ... }` cannot match.
474        $mirror       = wp_style_engine_get_styles( $label, array( 'selector' => '.contact-form :where(legend.grunion-field-label)' ) );
475        $declarations = $mirror['declarations'] ?? array();
476        if ( empty( $declarations ) ) {
477            return '';
478        }
479
480        /*
481         * Field labels in every style, minus the consent and option labels grunion.scss exempts.
482         * Below-style labels use their own class, so they are listed separately.
483         */
484        $field_labels = 'label.grunion-field-label:not(.consent):not(.checkbox):not(.checkbox-multiple):not(.radio),label.below-label__label,legend.grunion-field-label';
485
486        // What the generic `.contact-form :where(label)` rule in grunion.scss sets; keep in sync.
487        $contested = array( 'font-weight', 'margin', 'margin-bottom' );
488        $reassert  = array();
489        foreach ( $contested as $property ) {
490            // An unresolved `ref` stays an array; drop it as core's own CSS output does.
491            if ( isset( $declarations[ $property ] ) && is_scalar( $declarations[ $property ] ) ) {
492                /*
493                 * `declarations` is unfiltered theme.json, and safecss_filter_attr() keeps HTML, so
494                 * strip tags first or `600</style>` closes the inline style element early.
495                 */
496                $reassert[] = $property . ':' . wp_strip_all_tags( $declarations[ $property ], true );
497            }
498        }
499
500        $css = '';
501        if ( ! empty( $reassert ) ) {
502            $filtered = safecss_filter_attr( implode( ';', $reassert ) );
503            if ( '' !== $filtered ) {
504                $css .= '.contact-form :where(' . $field_labels . '){' . $filtered . '}';
505            }
506        }
507
508        if ( ! empty( $mirror['css'] ) ) {
509            $css .= $mirror['css'];
510        }
511
512        // Outlined and Animated own their label weight (300 and 700 in grunion.scss); restore it.
513        if ( isset( $declarations['font-weight'] ) ) {
514            $css .= '.contact-form :where(.is-style-outlined :is(' . $field_labels . ')){font-weight:300}';
515            $css .= '.contact-form :where(.is-style-animated :is(' . $field_labels . ')){font-weight:700}';
516        }
517
518        return $css;
519    }
520
521    /**
522     * Check if a feature flag is enabled.
523     *
524     * @param string $flag The feature flag to check.
525     * @return bool
526     */
527    public static function has_editor_feature_flag( $flag ) {
528        /** This filter is documented in jetpack/class.jetpack-gutenberg.php. */
529        $feature_flags = apply_filters( 'jetpack_block_editor_feature_flags', array() );
530        return ! empty( $feature_flags[ $flag ] );
531    }
532    /**
533     * Remove feedback post type from the allowed post types for related posts.
534     *
535     * @param array $post_types The allowed post types.
536     * @return array The allowed post types.
537     */
538    public static function remove_from_related_posts_allowed_post_types( $post_types ) {
539        return array_diff( $post_types, array( 'feedback' ) );
540    }
541
542    /**
543     * Prevent 'jp-forms-view' script from being concatenated.
544     *
545     * @param array  $do_concat - the concatenation flag.
546     * @param string $handle - script name.
547     */
548    public static function disable_forms_view_script_concat( $do_concat, $handle ) {
549        if ( 'jp-forms-view' === $handle ) {
550            $do_concat = false;
551        }
552        return $do_concat;
553    }
554
555    /**
556     * Register the contact form block.
557     */
558    private static function register_contact_form_blocks() {
559        Contact_Form_Block::register_block();
560        // Field render methods.
561        Contact_Form_Block::register_child_blocks();
562    }
563
564    /**
565     * Generate block support CSS classes and inline styles for block supports
566     * via the style engine.
567     *
568     * @param string $block_name - the block name.
569     * @param array  $attrs      - the block attributes.
570     * @param array  $options    - the types of support to apply.
571     *
572     * @return array
573     */
574    private static function get_block_support_classes_and_styles( $block_name, $attrs, $options = array() ) {
575        $block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block_name );
576
577        if ( ! $block_type ) {
578            return array();
579        }
580
581        $default_options = array( 'color', 'typography', 'border', 'custom', 'spacing' );
582        $enabled_options = empty( $options ) ? $default_options : $options;
583
584        // Leverage the individual core block support functions to generate classes and styles.
585        $color_styles      = in_array( 'color', $enabled_options, true ) ? \wp_apply_colors_support( $block_type, $attrs ) : array();
586        $typography_styles = in_array( 'typography', $enabled_options, true ) ? \wp_apply_typography_support( $block_type, $attrs ) : array();
587        $border_styles     = in_array( 'border', $enabled_options, true ) ? \wp_apply_border_support( $block_type, $attrs ) : array();
588        $custom_classname  = in_array( 'custom', $enabled_options, true ) ? \wp_apply_custom_classname_support( $block_type, $attrs ) : array();
589        $spacing_styles    = in_array( 'spacing', $enabled_options, true ) ? \wp_apply_spacing_support( $block_type, $attrs ) : array();
590
591        // Merge all the block support classes and styles.
592        $classes = array_filter(
593            array(
594                $color_styles['class'] ?? '',
595                $typography_styles['class'] ?? '',
596                $border_styles['class'] ?? '',
597                $custom_classname['class'] ?? '',
598                $spacing_styles['class'] ?? '',
599            ),
600            'strlen'
601        );
602
603        $styles = array_filter(
604            array(
605                $color_styles['style'] ?? '',
606                $typography_styles['style'] ?? '',
607                $border_styles['style'] ?? '',
608                $spacing_styles['style'] ?? '',
609            ),
610            'strlen'
611        );
612
613        $merged_styles = array();
614
615        if ( ! empty( $classes ) ) {
616            $merged_styles['class'] = implode( ' ', $classes );
617        }
618        if ( ! empty( $styles ) ) {
619            $merged_styles['style'] = implode( ' ', $styles );
620        }
621
622        return $merged_styles;
623    }
624
625    /**
626     * Returns an array containing the field classes (including -wrap classes), the remaining classes without block style classes.
627     * The wrap classes are used for the wrapper div around the field.
628     *
629     * @param string $classname The class name.
630     *
631     * @return array {
632     *     @type string $fieldwrapperclasses         Classes that should be added to the field wrapper.
633     *     @type string $classes_without_block_style The remaining classes without block style classes, intended for internal field controls.
634     * }
635     */
636    private static function get_block_style_classes( $classname = '' ) {
637        if ( ! $classname ) {
638            return array(
639                'fieldwrapperclasses' => '',
640                'classes'             => '',
641            );
642        }
643
644        $field_wrapper_classes       = '';
645        $classes_without_block_style = '';
646
647        preg_match_all( '/is-style-([^\s]+)/i', $classname, $matches );
648
649        $block_style_classes = empty( $matches[0] ) ? '' : implode( ' ', $matches[0] );
650
651        if ( ! empty( $block_style_classes ) ) {
652            $wrap_classes          = ! empty( $matches[0] ) ? ' ' . implode( '-wrap ', array_filter( $matches[0] ) ) . '-wrap' : '';
653            $field_wrapper_classes = " $block_style_classes $wrap_classes";
654        }
655
656        // Remove block style classes from the original classname.
657        $classes_without_block_style = trim( preg_replace( '/is-style-([^\s]+)/i', '', $classname ) );
658
659        return array(
660            'fieldwrapperclasses' => $field_wrapper_classes,
661            'classes'             => $classes_without_block_style,
662        );
663    }
664
665    /**
666     * Turn block attribute to shortcode attributes.
667     *
668     * @param array         $atts  - the block attributes.
669     * @param string        $type  - the type.
670     * @param WP_Block|null $block - the block object.
671     *
672     * @return array
673     */
674    public static function block_attributes_to_shortcode_attributes( $atts, $type, $block = null ) {
675        $atts['type'] = $type;
676        if ( isset( $atts['className'] ) ) {
677            $atts['class'] = $atts['className'];
678            unset( $atts['className'] );
679        }
680
681        if ( isset( $atts['defaultValue'] ) ) {
682            $atts['default'] = $atts['defaultValue'];
683            unset( $atts['defaultValue'] );
684        }
685
686        // Serialize the conditionalLogic object so it survives the shortcode roundtrip.
687        // Only emit when explicitly enabled to keep the shortcode and frontend context lean.
688        //
689        // JSON_HEX_TAG matters as much as JSON_HEX_AMP here: this lands in `post_content` as
690        // shortcode text and is decoded back in Contact_Form_Field, and KSES rewrites a bare
691        // `<` on the way in. A rule comparing against a value containing `<` would come back
692        // as unparseable JSON and silently drop the field's whole condition.
693        if ( isset( $atts['conditionalLogic'] ) ) {
694            $logic = $atts['conditionalLogic'];
695            if ( is_array( $logic ) && ! empty( $logic['enabled'] ) ) {
696                $json = \wp_json_encode( $logic, JSON_UNESCAPED_SLASHES | JSON_HEX_AMP | JSON_HEX_TAG );
697
698                // The rules are a JSON array, so the value contains `[` and `]`. WordPress's
699                // shortcode attribute pattern excludes both, so as shortcode text the value is
700                // cut short and the attribute is dropped entirely -- leaving a field that is
701                // still required but no longer conditional, which blocks submission on a
702                // question the visitor cannot see. Numeric entities survive the pattern and
703                // are turned back by the html_entity_decode() in Contact_Form_Field.
704                $atts['conditionallogic'] = str_replace(
705                    array( '[', ']' ),
706                    array( '&#91;', '&#93;' ),
707                    (string) $json
708                );
709            }
710            unset( $atts['conditionalLogic'] );
711        }
712
713        // Process inner blocks to shortcode attributes.
714        if ( $block && ! empty( $block->parsed_block['innerBlocks'] ) ) {
715            // Only apply the block style classes to the field wrapper if the field is one of the new inner block types.
716            $add_block_style_classes_to_field_wrapper = false;
717
718            foreach ( $block->parsed_block['innerBlocks'] as $inner_block ) {
719                $block_name = $inner_block['blockName'] ?? '';
720
721                if ( 'jetpack/label' === $block_name ) {
722                    $atts['label']                            = $inner_block['attrs']['label'] ?? $inner_block['attrs']['defaultLabel'] ?? '';
723                    $atts['requiredText']                     = $inner_block['attrs']['requiredText'] ?? null;
724                    $label_attrs                              = self::get_block_support_classes_and_styles( $block_name, $inner_block['attrs'] );
725                    $atts['labelclasses']                     = 'wp-block-jetpack-label';
726                    $atts['labelclasses']                    .= isset( $label_attrs['class'] ) ? ' ' . $label_attrs['class'] : '';
727                    $atts['labelstyles']                      = $label_attrs['style'] ?? null;
728                    $add_block_style_classes_to_field_wrapper = true;
729
730                    // Honor blockVisibility support on the label. Full-hide
731                    // (blockVisibility === false) skips the label render; per-viewport
732                    // hide gets the same wp-block-hidden-{mobile,tablet,desktop} classes
733                    // Gutenberg would add â€” the matching media-query CSS is already
734                    // registered by core's render_block visibility filter (the label
735                    // keeps visibility support). See FORMS-694.
736                    $block_visibility                     = $inner_block['attrs']['metadata']['blockVisibility'] ?? null;
737                    $atts['labelhiddenbyblockvisibility'] = false === $block_visibility;
738
739                    if ( is_array( $block_visibility ) && isset( $block_visibility['viewport'] ) && is_array( $block_visibility['viewport'] ) ) {
740                        foreach ( array( 'mobile', 'tablet', 'desktop' ) as $viewport_size ) {
741                            if ( isset( $block_visibility['viewport'][ $viewport_size ] ) && false === $block_visibility['viewport'][ $viewport_size ] ) {
742                                $atts['labelclasses'] .= ' wp-block-hidden-' . $viewport_size;
743                            }
744                        }
745                    }
746
747                    continue;
748                }
749
750                if ( 'jetpack/input' === $block_name ) {
751                    $atts['placeholder']   = $inner_block['attrs']['placeholder'] ?? '';
752                    $atts['min']           = $inner_block['attrs']['min'] ?? '';
753                    $atts['max']           = $inner_block['attrs']['max'] ?? '';
754                    $input_attrs           = self::get_block_support_classes_and_styles( $block_name, $inner_block['attrs'] );
755                    $atts['inputclasses']  = 'wp-block-jetpack-input';
756                    $atts['inputclasses'] .= isset( $input_attrs['class'] ) ? ' ' . $input_attrs['class'] : '';
757                    $atts['inputstyles']   = $input_attrs['style'] ?? null;
758
759                    if ( 'jetpack/field-select' === $block->name ) {
760                        $atts['togglelabel'] = $atts['placeholder'];
761                    }
762
763                    /*
764                        Borders for the outlined notched HTML.
765                    */
766                    $style_variation_data                     = self::get_style_variation_shortcode_attributes( $block_name, $inner_block['attrs'] );
767                    $atts                                     = array_merge( $atts, $style_variation_data );
768                    $add_block_style_classes_to_field_wrapper = true;
769
770                    continue;
771                }
772
773                // This input is exclusively used by the new telephone field.
774                if ( 'jetpack/phone-input' === $block_name ) {
775                    $atts['placeholder'] = $inner_block['attrs']['placeholder'] ?? '';
776
777                    if ( ! isset( $atts['showCountrySelector'] ) || ! $atts['showCountrySelector'] ) {
778                        unset( $atts['default'] );
779                    }
780
781                    $input_attrs           = self::get_block_support_classes_and_styles( $block_name, $inner_block['attrs'] );
782                    $atts['inputclasses']  = 'wp-block-jetpack-input';
783                    $atts['inputclasses'] .= isset( $input_attrs['class'] ) ? ' ' . $input_attrs['class'] : '';
784                    $atts['inputstyles']   = $input_attrs['style'] ?? null;
785
786                    /*
787                        Borders for the outlined notched HTML.
788                    */
789                    $style_variation_data                     = self::get_style_variation_shortcode_attributes( $block_name, $inner_block['attrs'] );
790                    $atts                                     = array_merge( $atts, $style_variation_data );
791                    $add_block_style_classes_to_field_wrapper = true;
792
793                    continue;
794                }
795
796                // The following handles when option blocks are a direct inner block for a field e.g. singular checkbox field.
797                if ( 'jetpack/option' === $block_name ) {
798                    $atts['label']                            = $inner_block['attrs']['label'] ?? $inner_block['attrs']['defaultLabel'] ?? '';
799                    $option_attrs                             = self::get_block_support_classes_and_styles( $block_name, $inner_block['attrs'] );
800                    $atts['optionclasses']                    = 'wp-block-jetpack-option';
801                    $atts['optionclasses']                   .= isset( $option_attrs['class'] ) ? ' ' . $option_attrs['class'] : '';
802                    $atts['optionstyles']                     = $option_attrs['style'] ?? null;
803                    $atts['requiredText']                     = $inner_block['attrs']['requiredText'] ?? ( $atts['requiredText'] ?? null );
804                    $add_block_style_classes_to_field_wrapper = true;
805
806                    continue;
807                }
808
809                // The following handles choice fields such as; Single Choice Field (radio) or Multiple Choice Field (checkbox).
810                if ( 'jetpack/options' === $block_name ) {
811                    $option_blocks           = $inner_block['innerBlocks'] ?? array();
812                    $options                 = array();
813                    $options_data            = array();
814                    $atts['optionsclasses']  = 'wp-block-jetpack-options';
815                    $options_attrs           = self::get_block_support_classes_and_styles( $block_name, $inner_block['attrs'] );
816                    $atts['optionsclasses'] .= isset( $options_attrs['class'] ) ? ' ' . $options_attrs['class'] : '';
817
818                    // Check if the block has left border, then apply a class for indentation.
819                    $global_styles = wp_get_global_styles(
820                        array( 'border' ),
821                        array(
822                            'block_name' => $block_name,
823                            'transforms' => array( 'resolve-variables' ),
824                        )
825                    );
826
827                    if ( isset( $inner_block['attrs']['style']['border']['width'] ) || isset( $inner_block['attrs']['style']['border']['left']['width'] ) || isset( $global_styles['width'] ) || isset( $global_styles['left']['width'] ) ) {
828                        $atts['optionsclasses'] .= ' jetpack-field-multiple__list--has-border';
829                    }
830
831                    $atts['optionsstyles'] = $options_attrs['style'] ?? null;
832
833                    foreach ( $option_blocks as $option ) {
834                        $option_label = trim( $option['attrs']['label'] ?? '' );
835
836                        if ( $option_label ) {
837                            $option_attrs = self::get_block_support_classes_and_styles( 'jetpack/option', $option['attrs'] );
838                            $option_data  = array( 'label' => $option_label );
839
840                            // Preserve isOther attribute from the option block so
841                            // server-side rendering can attach special handlers.
842                            if ( ! empty( $option['attrs']['isOther'] ) ) {
843                                $option_data['isOther'] = true;
844                                $atts['allowother']     = true;
845                            }
846                            if ( ! empty( $option['attrs']['otherPlaceholder'] ) ) {
847                                $option_data['otherPlaceholder'] = $option['attrs']['otherPlaceholder'];
848                            }
849
850                            if ( isset( $option_attrs['class'] ) ) {
851                                $option_data['class'] = $option_attrs['class'] . ' wp-block-jetpack-option';
852                            } else {
853                                $option_data['class'] = 'wp-block-jetpack-option';
854                            }
855
856                            if ( isset( $option_attrs['style'] ) ) {
857                                $option_data['style'] = $option_attrs['style'];
858                            }
859
860                            $options[]      = $option_label; // Legacy shortcode attribute in case filters are using it.
861                            $options_data[] = $option_data;
862                        }
863                    }
864
865                    $atts['options']     = implode( ',', $options );
866                    $atts['optionsdata'] = \wp_json_encode( $options_data, JSON_UNESCAPED_SLASHES | JSON_HEX_AMP );
867
868                    /*
869                        Borders for the outlined notched HTML.
870                    */
871                    $style_variation_atts                     = self::get_style_variation_shortcode_attributes( $block_name, $inner_block['attrs'] );
872                    $atts                                     = array_merge( $atts, $style_variation_atts );
873                    $add_block_style_classes_to_field_wrapper = true;
874
875                    continue;
876                }
877
878                if ( 'jetpack/fieldset-image-options' === $block_name ) {
879                    $option_blocks           = $inner_block['innerBlocks'] ?? array();
880                    $options                 = array();
881                    $options_data            = array();
882                    $atts['optionsclasses']  = 'wp-block-jetpack-fieldset-image-options';
883                    $options_attrs           = self::get_block_support_classes_and_styles( $block_name, $inner_block['attrs'] );
884                    $atts['optionsclasses'] .= isset( $options_attrs['class'] ) ? ' ' . $options_attrs['class'] : '';
885
886                    // Check if the block has left border, then apply a class for indentation.
887                    $global_styles = wp_get_global_styles(
888                        array( 'border' ),
889                        array(
890                            'block_name' => $block_name,
891                            'transforms' => array( 'resolve-variables' ),
892                        )
893                    );
894
895                    if ( isset( $inner_block['attrs']['style']['border']['width'] ) || isset( $inner_block['attrs']['style']['border']['left']['width'] ) || isset( $global_styles['width'] ) || isset( $global_styles['left']['width'] ) ) {
896                        $atts['optionsclasses'] .= ' jetpack-field-image-select__list--has-border';
897                    }
898
899                    $atts['optionsstyles'] = $options_attrs['style'] ?? null;
900
901                    foreach ( $option_blocks as $option_index => $option ) {
902                        $option_label = trim( $option['attrs']['label'] ?? '' );
903
904                        // Generate letter for this option (A, B, C, ..., AA, AB, etc.)
905                        $option_letter = self::get_image_option_letter( $option_index + 1 );
906
907                        $option_attrs       = self::get_block_support_classes_and_styles( 'jetpack/input-image-option', $option['attrs'], array( 'typography', 'border', 'custom', 'spacing' ) );
908                        $option_attrs_color = self::get_block_support_classes_and_styles( 'jetpack/input-image-option', $option['attrs'], array( 'color' ) );
909                        $option_data        = array(
910                            'label'  => $option_label,
911                            'letter' => $option_letter,
912                            'image'  => $option['innerBlocks'][0],
913                        );
914
915                        if ( isset( $option_attrs['class'] ) ) {
916                            $option_data['class'] = $option_attrs['class'] . ' wp-block-jetpack-input-image-option';
917                        } else {
918                            $option_data['class'] = 'wp-block-jetpack-input-image-option';
919                        }
920                        if ( isset( $option_attrs_color['class'] ) ) {
921                            $option_data['classcolor'] = $option_attrs_color['class'];
922                        }
923
924                        if ( isset( $option_attrs['style'] ) ) {
925                            $option_data['style'] = $option_attrs['style'];
926                        }
927                        if ( isset( $option_attrs_color['style'] ) ) {
928                            $option_data['stylecolor'] = $option_attrs_color['style'];
929                        }
930
931                        $options[]      = $option_letter; // Legacy shortcode attribute - use letter for consistent submission
932                        $options_data[] = $option_data;
933                    }
934
935                    $atts['options']     = implode( ',', $options );
936                    $atts['optionsdata'] = \wp_json_encode( $options_data, JSON_UNESCAPED_SLASHES | JSON_HEX_AMP );
937
938                    /*
939                        Borders for the outlined notched HTML.
940                    */
941                    $style_variation_atts                     = self::get_style_variation_shortcode_attributes( $block_name, $inner_block['attrs'] );
942                    $atts                                     = array_merge( $atts, $style_variation_atts );
943                    $add_block_style_classes_to_field_wrapper = true;
944
945                    continue;
946                }
947
948                if ( 'jetpack/input-rating' === $block_name ) {
949                    $input_attrs          = self::get_block_support_classes_and_styles( $block_name, $inner_block['attrs'] );
950                    $atts['inputclasses'] = isset( $input_attrs['class'] ) ? ' ' . $input_attrs['class'] : '';
951                    $atts['inputstyles']  = $input_attrs['style'] ?? null;
952                    $atts['iconStyle']  ??= $inner_block['attrs']['iconStyle'] ?? 'stars';
953                    continue;
954                }
955
956                if ( 'jetpack/input-range' === $block_name ) {
957                    $input_attrs          = self::get_block_support_classes_and_styles( $block_name, $inner_block['attrs'] );
958                    $atts['inputclasses'] = isset( $input_attrs['class'] ) ? ' ' . $input_attrs['class'] : '';
959                    $atts['inputstyles']  = $input_attrs['style'] ?? null;
960                    // Also add classes to the field wrapper so color/typography presets cascade to slider labels on the frontend.
961                    if ( isset( $input_attrs['class'] ) && $input_attrs['class'] ) {
962                        $atts['fieldwrapperclasses'] = trim( ( $atts['fieldwrapperclasses'] ?? '' ) . ' ' . $input_attrs['class'] );
963                    }
964                    $add_block_style_classes_to_field_wrapper = true;
965                    continue;
966                }
967            }
968
969            /*
970             * Add the `wp-block-jetpack-field-*` and `is-style-*` classes to the field wrapper div
971             * for fields that are one of the new inner block types.
972             * This ensures any updates to field block styles in theme.json or global styles are
973             * correctly applied.
974             */
975            if ( $add_block_style_classes_to_field_wrapper ) {
976                $atts['fieldwrapperclasses'] = 'wp-block-jetpack-field-' . $type;
977                if ( ! empty( $atts['class'] ) ) {
978                    $block_style_classes          = self::get_block_style_classes( $atts['class'] );
979                    $atts['fieldwrapperclasses'] .= $block_style_classes['fieldwrapperclasses'];
980                    // Return the rest of the classes without the block style classes.
981                    $atts['class'] = $block_style_classes['classes'];
982                }
983            }
984        }
985
986        return $atts;
987    }
988
989    /**
990     * Generates a letter for image options based on position (A, B, C, ..., AA, AB, etc.)
991     *
992     * @param int $position The 1-based position of the option.
993     * @return string The letter representation.
994     */
995    private static function get_image_option_letter( $position ) {
996        if ( $position < 1 ) {
997            return '';
998        }
999
1000        $result = '';
1001
1002        while ( $position > 0 ) {
1003            --$position;
1004            $result   = chr( 65 + ( $position % 26 ) ) . $result;
1005            $position = floor( $position / 26 );
1006        }
1007
1008        return $result;
1009    }
1010
1011    /**
1012     * Resets the step counter back to 0.
1013     */
1014    public static function reset_step() {
1015        self::$step_count = 0;
1016    }
1017
1018    /**
1019     * Render the number field.
1020     *
1021     * @param array  $atts - the block attributes.
1022     * @param string $content - html content.
1023     *
1024     * @return string HTML for the number field.
1025     */
1026    public static function gutenblock_render_form_step( $atts, $content ) {
1027        self::$step_count = 1 + self::$step_count;
1028
1029        $version = Constants::get_constant( 'JETPACK__VERSION' );
1030        if ( empty( $version ) ) {
1031            $version = '0.1';
1032        }
1033
1034        \wp_enqueue_script_module(
1035            'jetpack-form-step',
1036            plugins_url( '../../dist/modules/form-step/view.js', __FILE__ ),
1037            array( '@wordpress/interactivity' ),
1038            $version
1039        );
1040
1041        // Process content for marker classes and add interactivity
1042        $blocks_content = do_blocks( $content );
1043        $tags           = new \WP_HTML_Tag_Processor( $blocks_content );
1044
1045        // Move to the first token so the bookmark has a valid span, then set the bookmark.
1046        $tags->next_tag();
1047        $tags->set_bookmark( 'start' );
1048
1049        // Process blocks with the "next step" trigger
1050        while ( $tags->next_tag( array( 'class_name' => 'trigger-next-step' ) ) ) {
1051            // No need to set data-wp-interactive since the parent div already has it
1052            $tags->set_attribute( 'data-wp-on--click', 'actions.nextStep' );
1053        }
1054
1055        // Reset and process blocks with the "previous step" trigger
1056        $tags->seek( 'start' );
1057        while ( $tags->next_tag( array( 'class_name' => 'trigger-previous-step' ) ) ) {
1058            $tags->set_attribute( 'data-wp-on--click', 'actions.previousStep' );
1059        }
1060
1061        $processed_content = $tags->get_updated_html();
1062
1063        $processed_content = Contact_Form_Block::apply_background_support( $processed_content, $atts, Contact_Form_Block::STEP_BLOCK_CLASS );
1064
1065        $is_current_step_class = ( self::$step_count === 1 ? 'is-current-step' : '' );
1066        return '<div data-wp-interactive="jetpack/form" class="jetpack-form-step ' . $is_current_step_class . ' " data-wp-class--is-before-current="state.isBeforeCurrent" data-wp-class--is-after-current="state.isAfterCurrent" data-wp-class--is-current-step="state.isCurrentStep" ' . wp_interactivity_data_wp_context( array( 'step' => self::$step_count ) ) . ' >'
1067                . $processed_content
1068            . '</div>';
1069    }
1070
1071    /**
1072     * Render the number field.
1073     *
1074     * @param array  $atts - the block attributes.
1075     * @param string $content - html content.
1076     *
1077     * @return string HTML for the number field.
1078     */
1079    public static function gutenblock_render_form_step_navigation( $atts, $content ) {
1080
1081        $version = Constants::get_constant( 'JETPACK__VERSION' );
1082        if ( empty( $version ) ) {
1083            $version = '0.1';
1084        }
1085        \wp_enqueue_script_module(
1086            'jetpack-form-step-navigation',
1087            plugins_url( '../../dist/modules/form-step-navigation/view.js', __FILE__ ),
1088            array( '@wordpress/interactivity' ),
1089            $version
1090        );
1091
1092        // Enqueue the frontend style for the step navigation.
1093        $style_handle = 'jetpack-form-step-navigation-style';
1094        $style_path   = '../../dist/blocks/form-step-navigation/style.css';
1095        if ( ! wp_style_is( $style_handle, 'enqueued' ) ) {
1096            wp_enqueue_style( $style_handle, plugins_url( $style_path, __FILE__ ), array(), $version );
1097        }
1098
1099        $button_blocks_html = do_blocks( $content );
1100
1101        $processor = new \WP_HTML_Tag_Processor( $button_blocks_html );
1102
1103        $processor->next_tag();
1104        // @phan-suppress-next-line PhanPluginDuplicateAdjacentStatement -- Intentionally bumping cursor to next tag.
1105        $processor->next_tag();
1106
1107        $processor->set_attribute( 'data-wp-interactive', 'jetpack/form' );
1108
1109        $class_names = array();
1110
1111        if ( ! empty( $atts['layout']['type'] ) ) {
1112            $class_names[] = 'is-layout-' . sanitize_title( $atts['layout']['type'] );
1113        }
1114
1115        if ( ! empty( $atts['layout']['orientation'] ) ) {
1116            $class_names[] = 'is-' . sanitize_title( $atts['layout']['orientation'] );
1117        }
1118
1119        if ( ! empty( $atts['layout']['justifyContent'] ) ) {
1120            $class_names[] = 'is-content-justification-' . sanitize_title( $atts['layout']['justifyContent'] );
1121        }
1122
1123        if ( ! empty( $atts['layout']['flexWrap'] ) && 'nowrap' === $atts['layout']['flexWrap'] ) {
1124            $class_names[] = 'is-nowrap';
1125        }
1126
1127        foreach ( $class_names as $class_name ) {
1128            $processor->add_class( $class_name );
1129        }
1130
1131        while ( $processor->next_tag() ) {
1132            // Check for button type - support both legacy (data-id-attr) and new (class-based) identification.
1133            $id              = $processor->get_attribute( 'data-id-attr' );
1134            $is_previous_btn = 'previous-step' === $id || $processor->has_class( 'form-button-previous' );
1135            $is_next_btn     = 'next-step' === $id || $processor->has_class( 'form-button-next' );
1136            $is_submit_btn   = 'submit-step' === $id || $processor->has_class( 'form-button-submit' );
1137
1138            if ( $is_previous_btn ) {
1139                $processor->remove_attribute( 'id' );
1140                $processor->add_class( 'disable-spinner is-previous is-hidden' );
1141                $processor->set_attribute( 'data-wp-on--click', 'actions.previousStep' );
1142                $processor->set_attribute( 'data-wp-class--is-hidden', 'state.isFirstStep' );
1143            }
1144            if ( $is_next_btn ) {
1145                $processor->remove_attribute( 'id' );
1146                $processor->add_class( 'disable-spinner is-next' );
1147                $processor->set_attribute( 'data-wp-on--click', 'actions.nextStep' );
1148                $processor->set_attribute( 'data-wp-class--is-hidden', 'state.isLastStep' );
1149            }
1150            if ( $is_submit_btn ) {
1151                $processor->remove_attribute( 'id' );
1152                if ( $processor->has_class( 'is-submit' ) ) {
1153                    $processor->add_class( 'is-hidden' );
1154                } else {
1155                    $processor->add_class( 'is-submit is-hidden' );
1156                }
1157
1158                $processor->set_attribute( 'data-wp-class--is-hidden', 'state.isNotLastStep' );
1159                if ( 'BUTTON' === $processor->get_tag() ) {
1160                    Contact_Form::add_submit_button_interactivity_attributes( $processor );
1161                } else {
1162                    $processor->set_bookmark( 'pre-button-search' );
1163                    if ( $processor->next_tag( 'button' ) ) {
1164                        Contact_Form::add_submit_button_interactivity_attributes( $processor );
1165                    } else {
1166                        $processor->seek( 'pre-button-search' );
1167                    }
1168                    $processor->release_bookmark( 'pre-button-search' );
1169                }
1170            }
1171        }
1172
1173        return $processor->get_updated_html();
1174    }
1175
1176    /**
1177     * Render the progress indicator.
1178     *
1179     * @param array $attributes - the block attributes.
1180     *
1181     * @return string HTML for the progress indicator.
1182     */
1183    public static function gutenblock_render_form_progress_indicator( $attributes ) {
1184        $version = Constants::get_constant( 'JETPACK__VERSION' );
1185        if ( empty( $version ) ) {
1186            $version = '0.1';
1187        }
1188
1189        // Get step count from Contact_Form_Block
1190        $max_steps = Contact_Form_Block::get_form_step_count();
1191
1192        $style_handle = 'jetpack-form-progress-indicator-style';
1193        if ( ! wp_style_is( $style_handle, 'enqueued' ) ) {
1194            wp_enqueue_style( $style_handle, plugins_url( 'dist/blocks/form-progress-indicator/style.css', dirname( __DIR__ ) ), array(), $version );
1195        }
1196
1197        $script_handle = 'jetpack-form-progress-indicator';
1198        \wp_enqueue_script_module(
1199            $script_handle,
1200            plugins_url( 'dist/modules/form-progress-indicator/view.js', dirname( __DIR__ ) ),
1201            array( '@wordpress/interactivity' ),
1202            $version
1203        );
1204
1205        $variant       = $attributes['variant'] ?? 'line';
1206        $is_dots_style = $variant === 'dots';
1207
1208        // Build custom CSS variables for progress indicator colors
1209        $custom_styles = array();
1210
1211        if ( isset( $attributes['progressColor'] ) ) {
1212            $custom_styles[] = '--jp-progress-active-color: ' . esc_attr( $attributes['progressColor'] );
1213        }
1214
1215        if ( isset( $attributes['progressBackgroundColor'] ) ) {
1216            $custom_styles[] = '--jp-progress-track-color: ' . esc_attr( $attributes['progressBackgroundColor'] );
1217        }
1218
1219        if ( isset( $attributes['textColor'] ) ) {
1220            $custom_styles[] = '--jp-progress-text-color: var(--wp--preset--color--' . esc_attr( $attributes['textColor'] ) . ')';
1221        } elseif ( isset( $attributes['style']['color']['text'] ) ) {
1222            $custom_styles[] = '--jp-progress-text-color: ' . esc_attr( $attributes['style']['color']['text'] );
1223        }
1224
1225        // Use WordPress Style Engine for block supports (dimensions, spacing, background, etc.)
1226        $generated_styles = wp_style_engine_get_styles( $attributes['style'] ?? array() );
1227
1228        $generated_css_parts = ! empty( $generated_styles['css'] ) ? explode( ';', $generated_styles['css'] ) : array();
1229        $all_styles          = array_filter( array_merge( $custom_styles, $generated_css_parts ) );
1230
1231        $extra_attributes = array();
1232        if ( ! empty( $all_styles ) ) {
1233            $extra_attributes['style'] = implode( '; ', $all_styles );
1234        }
1235
1236        // Add generated classnames if any
1237        $classes = array();
1238        if ( ! empty( $generated_styles['classnames'] ) ) {
1239            $classes[] = $generated_styles['classnames'];
1240        }
1241        // Add variant class
1242        $classes[] = 'is-variant-' . $variant;
1243
1244        $extra_attributes['class'] = implode( ' ', $classes );
1245
1246        $wrapper_attributes = get_block_wrapper_attributes( $extra_attributes );
1247
1248        // Build the complete HTML structure using output buffering for better readability
1249        ob_start();
1250        $progress_state = $is_dots_style ? 'state.getDotsProgress' : 'state.getStepProgress';
1251        ?>
1252        <div <?php echo wp_kses_post( $wrapper_attributes ); ?>>
1253            <div class="jetpack-form-progress-indicator-steps">
1254                <?php if ( $is_dots_style ) : ?>
1255                    <?php for ( $i = 0; $i < $max_steps; $i++ ) : ?>
1256                        <?php $step_context = array( 'stepIndex' => $i ); ?>
1257                        <div class="jetpack-form-progress-indicator-step"
1258                            data-wp-class--is-active="state.isStepActive"
1259                            data-wp-class--is-completed="state.isStepCompleted"
1260                            data-wp-context='<?php echo esc_attr( wp_json_encode( $step_context, JSON_HEX_AMP | JSON_UNESCAPED_SLASHES ) ); ?>'>
1261                            <div class="jetpack-form-progress-indicator-line"></div>
1262                            <div class="jetpack-form-progress-indicator-dot">
1263                                <span class="jetpack-form-progress-indicator-step-number">
1264                                    <span class="step-number"><?php echo esc_html( $i + 1 ); ?></span>
1265                                    <span class="step-checkmark" role="img" aria-label="<?php echo esc_attr__( 'Completed', 'jetpack-forms' ); ?>">
1266                                        <svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
1267                                            <path d="M16.7 7.1l-6.3 8.5-3.3-2.5-.9 1.2 4.5 3.4L17.9 8z" fill="currentColor"/>
1268                                        </svg>
1269                                    </span>
1270                                </span>
1271                            </div>
1272                        </div>
1273                    <?php endfor; ?>
1274                <?php endif; ?>
1275                <div class="jetpack-form-progress-indicator-progress"
1276                    data-wp-style--width="<?php echo esc_attr( $progress_state ); ?>"></div>
1277            </div>
1278        </div>
1279        <?php
1280        return ob_get_clean();
1281    }
1282
1283    /**
1284     * Returns the form "Outlined" style classes and styles.
1285     * Important: The "Outlined" style is somewhat different as it uses custom HTML to create a border around the field's label.
1286     * When applying styles to the control, background and border styles are applied to the custom HTML, not the input itself.
1287     *
1288     * @param string $block_name - the block name.
1289     * @param array  $attrs - the block attributes.
1290     *
1291     * @return array
1292     */
1293    protected static function get_style_variation_shortcode_attributes( $block_name, $attrs ) {
1294        $picked_attributes = array();
1295
1296        // For style variations like the outlined style, we only care about porting specific attributes like background color and border
1297        // to the custom label HTML, so we pick those attributes and ignore the rest.
1298        if ( isset( $attrs['backgroundColor'] ) ) {
1299            $picked_attributes['backgroundColor'] = $attrs['backgroundColor'];
1300        }
1301
1302        if ( isset( $attrs['borderColor'] ) ) {
1303            $picked_attributes['borderColor'] = $attrs['borderColor'];
1304        }
1305
1306        if ( isset( $attrs['style']['border'] ) ) {
1307            $picked_attributes['style']['border'] = $attrs['style']['border'];
1308        }
1309
1310        if ( isset( $attrs['borderColor'] ) ) {
1311            $picked_attributes['borderColor'] = $attrs['borderColor'];
1312        }
1313
1314        if ( isset( $attrs['style']['color']['background'] ) ) {
1315            $picked_attributes['style']['color']['background'] = $attrs['style']['color']['background'];
1316        }
1317
1318        $block_support_styles = self::get_block_support_classes_and_styles( $block_name, $picked_attributes );
1319        return array(
1320            'stylevariationattributes' => isset( $picked_attributes['style'] ) ? \wp_json_encode( $picked_attributes['style'], JSON_UNESCAPED_SLASHES | JSON_HEX_AMP ) : '',
1321            'stylevariationclasses'    => isset( $block_support_styles['class'] ) ? ' ' . $block_support_styles['class'] : '',
1322            'stylevariationstyles'     => $block_support_styles['style'] ?? '',
1323        );
1324    }
1325
1326    /**
1327     * Render the text field.
1328     *
1329     * @param array    $atts - the block attributes.
1330     * @param string   $content - html content.
1331     * @param WP_Block $block - the block instance object.
1332     *
1333     * @return string HTML for the contact form field.
1334     */
1335    public static function gutenblock_render_field_text( $atts, $content, $block ) {
1336        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'text', $block );
1337        return Contact_Form::parse_contact_field( $atts, $content, $block );
1338    }
1339
1340    /**
1341     * Render the name field.
1342     *
1343     * @param array    $atts - the block attributes.
1344     * @param string   $content - html content.
1345     * @param WP_Block $block - the block instance object.
1346     *
1347     * @return string HTML for the contact form field.
1348     */
1349    public static function gutenblock_render_field_name( $atts, $content, $block ) {
1350        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'name', $block );
1351        return Contact_Form::parse_contact_field( $atts, $content, $block );
1352    }
1353
1354    /**
1355     * Render the email field.
1356     *
1357     * @param array    $atts - the block attributes.
1358     * @param string   $content - html content.
1359     * @param WP_Block $block - the block instance object.
1360     *
1361     * @return string HTML for the contact form field.
1362     */
1363    public static function gutenblock_render_field_email( $atts, $content, $block ) {
1364        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'email', $block );
1365        return Contact_Form::parse_contact_field( $atts, $content, $block );
1366    }
1367
1368    /**
1369     * Render the url field.
1370     *
1371     * @param array    $atts - the block attributes.
1372     * @param string   $content - html content.
1373     * @param WP_Block $block - the block instance object.
1374     *
1375     * @return string HTML for the contact form field.
1376     */
1377    public static function gutenblock_render_field_url( $atts, $content, $block ) {
1378        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'url', $block );
1379        return Contact_Form::parse_contact_field( $atts, $content, $block );
1380    }
1381
1382    /**
1383     * Render the date field.
1384     *
1385     * @param array    $atts - the block attributes.
1386     * @param string   $content - html content.
1387     * @param WP_Block $block - the block instance object.
1388     *
1389     * @return string HTML for the contact form field.
1390     */
1391    public static function gutenblock_render_field_date( $atts, $content, $block ) {
1392        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'date', $block );
1393        return Contact_Form::parse_contact_field( $atts, $content, $block );
1394    }
1395
1396    /**
1397     * Render the telephone field.
1398     *
1399     * @param array    $atts - the block attributes.
1400     * @param string   $content - html content.
1401     * @param WP_Block $block - the block instance object.
1402     *
1403     * @return string HTML for the contact form field.
1404     */
1405    public static function gutenblock_render_field_telephone( $atts, $content, $block ) {
1406        // conversion telephone to phone
1407        $type = empty( $atts['showCountrySelector'] ) ? 'telephone' : 'phone';
1408        $atts = self::block_attributes_to_shortcode_attributes( $atts, $type, $block );
1409        return Contact_Form::parse_contact_field( $atts, $content, $block );
1410    }
1411
1412    /**
1413     * Render the text area field.
1414     *
1415     * @param array    $atts - the block attributes.
1416     * @param string   $content - html content.
1417     * @param WP_Block $block - the block instance object.
1418     *
1419     * @return string HTML for the contact form field.
1420     */
1421    public static function gutenblock_render_field_textarea( $atts, $content, $block ) {
1422        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'textarea', $block );
1423        return Contact_Form::parse_contact_field( $atts, $content, $block );
1424    }
1425
1426    /**
1427     * Render the checkbox field.
1428     *
1429     * @param array    $atts - the block attributes.
1430     * @param string   $content - html content.
1431     * @param WP_Block $block - the block instance object.
1432     *
1433     * @return string HTML for the contact form field.
1434     */
1435    public static function gutenblock_render_field_checkbox( $atts, $content, $block ) {
1436        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'checkbox', $block );
1437        return Contact_Form::parse_contact_field( $atts, $content, $block );
1438    }
1439
1440    /**
1441     * Render the multiple checkbox field.
1442     *
1443     * @param array    $atts - the block attributes.
1444     * @param string   $content - html content.
1445     * @param WP_Block $block - the block instance object.
1446     *
1447     * @return string HTML for the contact form field.
1448     */
1449    public static function gutenblock_render_field_checkbox_multiple( $atts, $content, $block ) {
1450        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'checkbox-multiple', $block );
1451        return Contact_Form::parse_contact_field( $atts, $content, $block );
1452    }
1453
1454    /**
1455     * Render the multiple choice field option.
1456     *
1457     * @param array  $atts - the block attributes.
1458     * @param string $content - html content.
1459     *
1460     * @return string HTML for the contact form field.
1461     */
1462    public static function gutenblock_render_field_option( $atts, $content ) {
1463        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'field-option' );
1464        return Contact_Form::parse_contact_field( $atts, $content );
1465    }
1466
1467    /**
1468     * Render the radio button field.
1469     *
1470     * @param array    $atts - the block attributes.
1471     * @param string   $content - html content.
1472     * @param WP_Block $block - the block instance object.
1473     *
1474     * @return string HTML for the contact form field.
1475     */
1476    public static function gutenblock_render_field_radio( $atts, $content, $block ) {
1477        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'radio', $block );
1478        return Contact_Form::parse_contact_field( $atts, $content, $block );
1479    }
1480
1481    /**
1482     * Render the select field.
1483     *
1484     * @param array    $atts - the block attributes.
1485     * @param string   $content - html content.
1486     * @param WP_Block $block - the block instance object.
1487     *
1488     * @return string HTML for the contact form field.
1489     */
1490    public static function gutenblock_render_field_select( $atts, $content, $block ) {
1491        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'select', $block );
1492        return Contact_Form::parse_contact_field( $atts, $content, $block );
1493    }
1494
1495    /**
1496     * Render the consent field.
1497     *
1498     * @param array    $atts - the block attributes.
1499     * @param string   $content - html content.
1500     * @param WP_Block $block - the block instance object.
1501     */
1502    public static function gutenblock_render_field_consent( $atts, $content, $block ) {
1503        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'consent', $block );
1504
1505        if ( ! isset( $atts['implicitConsentMessage'] ) ) {
1506            $atts['implicitConsentMessage'] = __( "By submitting your information, you're giving us permission to email you. You may unsubscribe at any time.", 'jetpack-forms' );
1507        }
1508
1509        if ( ! isset( $atts['explicitConsentMessage'] ) ) {
1510            $atts['explicitConsentMessage'] = __( 'Can we send you an email from time to time?', 'jetpack-forms' );
1511        }
1512
1513        return Contact_Form::parse_contact_field( $atts, $content );
1514    }
1515
1516    /**
1517     * Render the file upload field.
1518     *
1519     * @param array    $atts - the block attributes.
1520     * @param string   $content - html content.
1521     * @param WP_Block $block - the block instance object.
1522     *
1523     * @return string HTML for the file upload field.
1524     */
1525    public static function gutenblock_render_field_file( $atts, $content, $block ) {
1526        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'file', $block );
1527        return Contact_Form::parse_contact_field( $atts, $content );
1528    }
1529    /**
1530     * Render the dropzone field.
1531     *
1532     * @param array  $atts - the block attributes.
1533     * @param string $content - html content.
1534     *
1535     * @return string HTML for the dropzone field.
1536     */
1537    public static function gutenblock_render_dropzone( $atts, $content ) {
1538
1539        if ( class_exists( 'WP_HTML_Tag_Processor' ) ) {
1540            $processor = \WP_HTML_Processor::create_fragment( $content );
1541            while ( $processor->next_tag() ) {
1542                if ( $processor->has_class( 'wp-block-jetpack-dropzone' ) ) {
1543                    if ( isset( $atts['layout']['justifyContent'] ) ) {
1544                        $processor->add_class( 'is-content-justification-' . $atts['layout']['justifyContent'] );
1545                    }
1546                }
1547                if ( 'A' === $processor->get_tag() || 'BUTTON' === $processor->get_tag() ) {
1548                    $processor->set_attribute( 'tabindex', '-1' );
1549                }
1550            }
1551            $content = $processor->get_updated_html();
1552        }
1553
1554        return $content;
1555    }
1556    /**
1557     * Render the hidden field.
1558     *
1559     * @param array  $atts - the block attributes.
1560     * @param string $content - html content.
1561     *
1562     * @return string HTML for the hidden field.
1563     */
1564    public static function gutenblock_render_field_hidden( $atts, $content ) {
1565        // Convert block attributes to shortcode attributes.
1566        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'hidden' );
1567        // Parse the contact field.
1568        return Contact_Form::parse_contact_field( $atts, $content );
1569    }
1570
1571    /**
1572     * Render the number field.
1573     *
1574     * @param array    $atts - the block attributes.
1575     * @param string   $content - html content.
1576     * @param WP_Block $block - the block instance object.
1577     *
1578     * @return string HTML for the number field.
1579     */
1580    public static function gutenblock_render_field_number( $atts, $content, $block ) {
1581        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'number', $block );
1582        return Contact_Form::parse_contact_field( $atts, $content, $block );
1583    }
1584
1585    /**
1586     * Render the time field.
1587     *
1588     * @param array    $atts - the block attributes.
1589     * @param string   $content - html content.
1590     * @param WP_Block $block - the block instance object.
1591     *
1592     * @return string HTML for the time field.
1593     */
1594    public static function gutenblock_render_field_time( $atts, $content, $block ) {
1595        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'time', $block );
1596        return Contact_Form::parse_contact_field( $atts, $content, $block );
1597    }
1598
1599    /**
1600     * Render the image select field.
1601     *
1602     * @param array    $atts - the block attributes.
1603     * @param string   $content - html content.
1604     * @param WP_Block $block - the block instance object.
1605     *
1606     * @return string HTML for the image select form field.
1607     */
1608    public static function gutenblock_render_field_image_select( $atts, $content, $block ) {
1609        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'image-select', $block );
1610
1611        // Ensure showLabels is always present in the shortcode attributes, as it defaults to true.
1612        if ( ! array_key_exists( 'showLabels', $atts ) ) {
1613            $atts['showLabels'] = true;
1614        }
1615
1616        return Contact_Form::parse_contact_field( $atts, $content, $block );
1617    }
1618
1619    /**
1620     * Add the 'Form Responses' menu item as a submenu of Feedback.
1621     */
1622    public function admin_menu() {
1623        $slug = 'feedback';
1624
1625        // Do we still need to create the Feedback menu item for polldaddy?
1626        // WPCOM already handles this. Self hosted will depend on us until we produce a new release for polldaddy.
1627        if ( is_plugin_active( 'polldaddy/polldaddy.php' ) || ! Jetpack_Forms::is_legacy_menu_item_retired() ) {
1628            add_menu_page(
1629                __( 'Feedback', 'jetpack-forms' ),
1630                __( 'Feedback', 'jetpack-forms' ),
1631                'edit_pages',
1632                $slug,
1633                null,
1634                'dashicons-feedback',
1635                45
1636            );
1637        }
1638
1639        add_submenu_page(
1640            $slug,
1641            __( 'Form Responses', 'jetpack-forms' ),
1642            __( 'Form Responses', 'jetpack-forms' ),
1643            'edit_pages',
1644            'edit.php?post_type=feedback',
1645            null,
1646            0
1647        );
1648
1649        remove_submenu_page(
1650            $slug,
1651            $slug
1652        );
1653
1654        // remove the first default submenu item
1655        remove_submenu_page(
1656            $slug,
1657            'edit.php?post_type=feedback'
1658        );
1659    }
1660
1661    /**
1662     * Add to REST API post type allowed list.
1663     *
1664     * @param array $post_types - the post types.
1665     */
1666    public function allow_feedback_rest_api_type( $post_types ) {
1667        $post_types[] = 'feedback';
1668        return $post_types;
1669    }
1670
1671    /**
1672     * Report the count of new feedback entries received to the central menu-badges
1673     * registry. It's reset when the user visits the Feedback screen.
1674     *
1675     * @since 4.1.0
1676     */
1677    public function unread_count() {
1678        if ( ! current_user_can( 'edit_pages' ) ) {
1679            return;
1680        }
1681        \Automattic\Jetpack\Menu_Badges\Menu_Badges::init(); // idempotent; wires the renderer.
1682        \Automattic\Jetpack\Menu_Badges\Notification_Counts::register(
1683            'jetpack-forms',
1684            array(
1685                'menu_slug' => Dashboard::FORMS_WPBUILD_ADMIN_SLUG,
1686                'count'     => self::get_unread_count(),
1687                'type'      => 'count',
1688            )
1689        );
1690    }
1691
1692    /**
1693     * Get the count of unread feedback entries.
1694     *
1695     * @since 6.10.0
1696     *
1697     * @return int The count of unread feedback entries.
1698     */
1699    public static function get_unread_count() {
1700        return (int) get_option( 'jetpack_feedback_unread_count', 0 ); // previously defaulted named "feedback_unread_count".
1701    }
1702
1703    /**
1704     * Recalculate the count of unread feedback entries.
1705     *
1706     * @since 6.10.0
1707     *
1708     * @return int The count of unread feedback entries.
1709     */
1710    public static function recalculate_unread_count() {
1711        $count = Feedback::get_unread_count();
1712        update_option( 'jetpack_feedback_unread_count', $count );
1713        return $count;
1714    }
1715
1716    /**
1717     * Handles all contact-form POST submissions
1718     *
1719     * Conditionally attached to `template_redirect`
1720     */
1721    public function process_form_submission() {
1722        // Add a filter to replace tokens in the subject field with sanitized field values.
1723        add_filter( 'contact_form_subject', array( $this, 'replace_tokens_with_input' ), 10, 2 );
1724
1725        $id   = isset( $_POST['contact-form-id'] ) ? sanitize_text_field( wp_unslash( $_POST['contact-form-id'] ) ) : null;
1726        $hash = isset( $_POST['contact-form-hash'] ) ? sanitize_text_field( wp_unslash( $_POST['contact-form-hash'] ) ) : null;
1727        $hash = is_string( $hash ) ? preg_replace( '/[^\da-f]/i', '', $hash ) : $hash;
1728
1729        if ( ! is_string( $id ) || ! is_string( $hash ) ) {
1730            return Form_Submission_Error::system_error( 'invalid_form_id_or_hash', __( 'Invalid form ID or hash.', 'jetpack-forms' ) );
1731        }
1732
1733        if ( is_user_logged_in() ) {
1734            check_admin_referer( "contact-form_{$id}" );
1735        }
1736
1737        $is_widget              = str_starts_with( $id, 'widget-' );
1738        $is_block_template      = str_starts_with( $id, 'block-template-' );
1739        $is_block_template_part = str_starts_with( $id, 'block-template-part-' );
1740
1741        if ( isset( $_POST['jetpack_contact_form_jwt'] ) ) {
1742            $jwt = sanitize_text_field( wp_unslash( $_POST['jetpack_contact_form_jwt'] ) );
1743
1744            try {
1745                $form = Contact_Form::get_instance_from_jwt( $jwt, true );
1746            } catch ( \Exception $e ) {
1747                // Fail early if the JWT is invalid with detailed error information.
1748                return Form_Submission_Error::system_error(
1749                    'invalid_jwt',
1750                    $e->getMessage()
1751                );
1752            }
1753
1754            // Validate that the parent post/page where the form lives still exists and is not trashed/deleted
1755            $validation_error = $this->validate_parent_post( $form );
1756            if ( $validation_error ) {
1757                return $validation_error;
1758            }
1759
1760            // Bind the posted `contact-form-id` to the form the JWT was signed for. The JWT
1761            // authenticates the form's source, but the posted id is a separate, unsigned field;
1762            // without this a submission could present one form's signed token while claiming a
1763            // different id, leaving the two out of sync for anything downstream that reads the
1764            // raw id. For a single-post form the posted id is the source post id (optionally
1765            // suffixed for multiple forms on a page, e.g. `5-2`), so compare on the integer id.
1766            //
1767            // Only apply this when the source is an actual post: a form rendered with no post in
1768            // scope has source id 0 (and a non-numeric posted id like `jp-form`), which is not a
1769            // mismatch to reject. This mirrors validate_parent_post()'s `is_numeric && > 0` guard.
1770            $source    = $form->get_source();
1771            $source_id = $source->get_id();
1772
1773            if ( 'single' === $source->get_source_type() && is_numeric( $source_id ) && (int) $source_id > 0 ) {
1774                if ( (int) $id !== (int) $source_id ) {
1775                    return Form_Submission_Error::system_error( 'form_id_mismatch_post', __( 'Form ID mismatch.', 'jetpack-forms' ) );
1776                }
1777            }
1778
1779            $form->validate();
1780
1781            if ( $form->has_errors() ) {
1782                return $form->errors;
1783            }
1784
1785            if ( ! empty( $form->attributes['salesforceData'] ) ) {
1786                Post_To_Url::init();
1787            }
1788
1789            // Outbound destinations declared in the form content are only honored when the
1790            // source post author is allowed to configure them. Filter-supplied webhooks
1791            // (applied below) are exempt, so this runs before the filter.
1792            $this->reconcile_content_destinations( $form );
1793
1794            /**
1795             * Filters the list of extra webhooks to be called when a form is submitted.
1796             *
1797             * This filter allows developers to programmatically add webhook configurations that will
1798             * receive form submission data. The webhooks added through this filter are merged
1799             * with any webhooks already configured in the form's attributes.
1800             *
1801             * Each webhook configuration array supports the following keys:
1802             * - `webhook_id` (string, required): Unique identifier for the webhook.
1803             * - `url` (string, required): The webhook URL to POST data to.
1804             * - `method` (string, optional): HTTP method. Default 'POST'.
1805             * - `verified` (bool, optional): Whether the webhook is verified. Default false.
1806             * - `format` (string, optional): Data format ('json'). Default 'json'.
1807             * - `enabled` (bool, optional): Whether the webhook is enabled. Default false.
1808             *
1809             * Example usage:
1810             * ```
1811             * add_filter( 'jetpack_forms_extra_webhooks', function( $webhooks, $form ) {
1812             *     if ( $form->get_attribute( 'id' ) === '123' ) {
1813             *         $webhooks[] = array(
1814             *            'webhook_id' => 'test-webhook-1',
1815             *            'url'        => '[your webhook URL]',
1816             *            'method'     => 'POST',
1817             *            'verified'   => false,
1818             *            'format'     => 'json',
1819             *            'enabled'    => true,
1820             *         );
1821             *     }
1822             *     return $webhooks;
1823             * }, 10, 2 );
1824             * ```
1825             *
1826             * @since 7.0.0
1827             *
1828             * @param array        $extra_webhooks Array of webhook configuration arrays. Default empty array.
1829             * @param Contact_Form $form           The form instance being processed.
1830             * @return array                       The modified array of webhook configurations.
1831             */
1832            $extra_webhooks = apply_filters( 'jetpack_forms_extra_webhooks', array(), $form );
1833            if ( ! empty( $extra_webhooks ) ) {
1834                $form->attributes['webhooks'] = array_merge(
1835                    $form->attributes['webhooks'] ?? array(),
1836                    $extra_webhooks
1837                );
1838            }
1839
1840            if ( Jetpack_Forms::is_webhooks_enabled() && ! empty( $form->attributes['webhooks'] ) ) {
1841                Form_Webhooks::init();
1842            }
1843
1844            // The decoded JWT carries a serialized Feedback_Source; when the
1845            // form was rendered in preview mode that source has is_test=true.
1846            // Flag the submission accordingly so the response is stored as a
1847            // test response. JWTs issued before this feature shipped simply
1848            // omit the flag and behave as regular submissions.
1849            $form->set_is_preview_submission( $form->get_source()->is_test() );
1850
1851            // Process the form
1852            return $form->process_submission();
1853        }
1854        /** This action is documented already in this file. */
1855        do_action( 'jetpack_forms_log', 'submission_missing_jwt' );
1856
1857        if ( $is_widget ) {
1858            // It's a form embedded in a text widget
1859            $this->current_widget_id = substr( $id, 7 ); // remove "widget-"
1860            $widget_type             = implode( '-', array_slice( explode( '-', $this->current_widget_id ), 0, -1 ) ); // Remove trailing -#
1861
1862            // Is the widget active?
1863            $sidebar = is_active_widget( false, $this->current_widget_id, $widget_type );
1864
1865            // This is lame - no core API for getting a widget by ID
1866            $widget = $GLOBALS['wp_registered_widgets'][ $this->current_widget_id ] ?? false;
1867
1868            if ( $sidebar && $widget && isset( $widget['callback'] ) ) {
1869                // prevent PHP notices by populating widget args
1870                $widget_args = array(
1871                    'before_widget' => '',
1872                    'after_widget'  => '',
1873                    'before_title'  => '',
1874                    'after_title'   => '',
1875                );
1876                // This is lamer - no API for outputting a given widget by ID
1877                ob_start();
1878                // Process the widget to populate Contact_Form::$last
1879                call_user_func( $widget['callback'], $widget_args, $widget['params'][0] );
1880                ob_end_clean();
1881            }
1882        } elseif ( $is_block_template ) {
1883            /*
1884             * Recreate the logic in wp-includes/template-loader.php
1885             * that happens *after* 'template_redirect'.
1886             *
1887             * This logic populates the $_wp_current_template_content
1888             * global, which we need in order to render the contact
1889             * form for this block template.
1890             */
1891            // start of copy-pasta from wp-includes/template-loader.php.
1892            $tag_templates = array(
1893                'is_embed'             => 'get_embed_template',
1894                'is_404'               => 'get_404_template',
1895                'is_search'            => 'get_search_template',
1896                'is_front_page'        => 'get_front_page_template',
1897                'is_home'              => 'get_home_template',
1898                'is_privacy_policy'    => 'get_privacy_policy_template',
1899                'is_post_type_archive' => 'get_post_type_archive_template',
1900                'is_tax'               => 'get_taxonomy_template',
1901                'is_attachment'        => 'get_attachment_template',
1902                'is_single'            => 'get_single_template',
1903                'is_page'              => 'get_page_template',
1904                'is_singular'          => 'get_singular_template',
1905                'is_category'          => 'get_category_template',
1906                'is_tag'               => 'get_tag_template',
1907                'is_author'            => 'get_author_template',
1908                'is_date'              => 'get_date_template',
1909                'is_archive'           => 'get_archive_template',
1910            );
1911            $template      = false;
1912            // Loop through each of the template conditionals, and find the appropriate template file.
1913            // This is what calls locate_block_template() to hydrate $_wp_current_template_content.
1914            foreach ( $tag_templates as $tag => $template_getter ) {
1915                if ( call_user_func( $tag ) ) {
1916                    $template = call_user_func( $template_getter );
1917                }
1918                if ( $template ) {
1919                    if ( 'is_attachment' === $tag ) {
1920                        remove_filter( 'the_content', 'prepend_attachment' );
1921                    }
1922                    break;
1923                }
1924            }
1925            if ( ! $template ) {
1926                $template = get_index_template();
1927            }
1928            // end of copy-pasta from wp-includes/template-loader.php.
1929
1930            // Ensure 'block_template' attribute is added to any shortcodes in the template.
1931            $template = Util::grunion_contact_form_set_block_template_attribute( $template );
1932
1933            // Process the block template to populate Contact_Form::$last
1934            get_the_block_template_html();
1935        } elseif ( $is_block_template_part ) {
1936            $block_template_part_id   = str_replace( 'block-template-part-', '', $id );
1937            $bits                     = explode( '//', $block_template_part_id );
1938            $block_template_part_slug = array_pop( $bits );
1939            // Process the block part template to populate Contact_Form::$last
1940            $attributes = array(
1941                'theme'   => wp_get_theme()->get_stylesheet(),
1942                'slug'    => $block_template_part_slug,
1943                'tagName' => 'div',
1944            );
1945            do_blocks( '<!-- wp:template-part ' . wp_json_encode( $attributes, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ) . ' /-->' );
1946        } else {
1947            // It's a form embedded in a post
1948
1949            if ( ! is_post_publicly_viewable( $id ) && ! current_user_can( 'read_post', $id ) ) {
1950                // The user can't see the post.
1951                return Form_Submission_Error::system_error( 'post_not_viewable', __( 'You do not have permission to view this form.', 'jetpack-forms' ) );
1952            }
1953
1954            if ( post_password_required( $id ) ) {
1955                // The post is password-protected and the password is not provided.
1956                return Form_Submission_Error::system_error( 'post_password_required', __( 'This form requires a password.', 'jetpack-forms' ) );
1957            }
1958
1959            $post = get_post( $id );
1960
1961            // Process the content to populate Contact_Form::$last
1962            if ( $post ) {
1963                if ( str_contains( $post->post_content, '<!--nextpage-->' ) ) {
1964                    $postdata = generate_postdata( $post );
1965                    $page     = isset( $_POST['page'] ) ? absint( wp_unslash( $_POST['page'] ) ) : null; // phpcs:Ignore WordPress.Security.NonceVerification.Missing
1966                    $paged    = $page ?? 1;
1967                    $content  = $postdata['pages'][ $paged - 1 ] ?? $post->post_content;
1968                } else {
1969                    $content = $post->post_content;
1970                }
1971                /** This filter is already documented in core. wp-includes/post-template.php */
1972                apply_filters( 'the_content', $content );
1973            }
1974        }
1975
1976        // In future version we will be able to skip this step.
1977        $form = Contact_Form::$forms[ $hash ] ?? null;
1978
1979        // No form may mean user is using apply_shortcodes, grab the form using the stored post meta
1980        if ( ! $form && is_numeric( $id ) && $hash ) {
1981
1982            // Get shortcode from post meta
1983            $shortcode = get_post_meta( $id, "_g_feedback_shortcode_{$hash}", true );
1984
1985            // Format it
1986            if ( $shortcode !== '' && $shortcode !== false ) {
1987
1988                // Get attributes from post meta.
1989                $parameters = '';
1990                $attributes = get_post_meta( $id, "_g_feedback_shortcode_atts_{$hash}", true );
1991                if ( ! empty( $attributes ) && is_array( $attributes ) ) {
1992                    foreach ( array_filter( $attributes ) as $param => $value ) {
1993                        if ( is_scalar( $value ) ) {
1994                            $parameters .= " $param=\"$value\"";
1995                        }
1996                    }
1997                }
1998
1999                $shortcode = '[contact-form' . $parameters . ']' . $shortcode . '[/contact-form]';
2000                apply_shortcodes( $shortcode );
2001
2002                // Recreate form
2003                $form = Contact_Form::$last;
2004            }
2005        }
2006
2007        if ( ! $form ) {
2008            return Form_Submission_Error::system_error( 'form_not_found', __( 'Form not found.', 'jetpack-forms' ) );
2009        }
2010
2011        // Conditional fields cannot be validated while the form is still being parsed: a rule's
2012        // subject may not exist yet, so `parse_contact_field()` defers them. Something has to
2013        // validate them once the whole form is known, and on this path nothing did -- the JWT
2014        // branch calls `validate()` above, but this one went straight to `has_errors()`. A
2015        // required conditional field left empty, an invalid email or an out-of-allow-list choice
2016        // would all be stored unchecked.
2017        //
2018        // Fields that were validated at parse time early-return once `is_error()` is set, so
2019        // this is idempotent for everything else.
2020        $form->validate();
2021
2022        if ( $form->has_errors() ) {
2023            return $form->errors;
2024        }
2025
2026        // Validate that the parent post/page where the form lives still exists and is not trashed/deleted (legacy submission path where we don't have a JWT)
2027        $validation_error = $this->validate_parent_post( $form );
2028        if ( $validation_error ) {
2029            return $validation_error;
2030        }
2031
2032        if ( ! empty( $form->attributes['salesforceData'] ) ) {
2033            Post_To_Url::init();
2034        }
2035
2036        // Outbound destinations declared in the form content are only honored when the
2037        // source post author is allowed to configure them.
2038        $this->reconcile_content_destinations( $form );
2039
2040        if ( Jetpack_Forms::is_webhooks_enabled() && ! empty( $form->attributes['webhooks'] ) ) {
2041            Form_Webhooks::init();
2042        }
2043
2044        // Process the form
2045        return $form->process_submission();
2046    }
2047
2048    /**
2049     * Handle the ajax request.
2050     *
2051     * @return never
2052     */
2053    public function ajax_request() {
2054        $submission_result = self::process_form_submission();
2055        $accepts_json      = isset( $_SERVER['HTTP_ACCEPT'] ) && false !== strpos( strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_ACCEPT'] ) ) ), 'application/json' );
2056        $is_system_error   = Form_Submission_Error::is_system_error( $submission_result );
2057
2058        if ( ! $submission_result || $is_system_error ) {
2059            $error_code    = $is_system_error ? $submission_result->get_error_code() : 'unknown';
2060            $error_details = $is_system_error ? $submission_result->get_error_message() : null;
2061
2062            /**
2063             * Action when we want to log a jetpack_forms event.
2064             *
2065             * @since 6.3.0
2066             *
2067             * @param string $log_message The log message.
2068             * @param string $error_code The error code (optional).
2069             * @param string $error_details The error details (optional).
2070             */
2071            do_action( 'jetpack_forms_log', 'submission_failed', $error_code, $error_details );
2072
2073            // Use a specific error message for invalid JWT tokens
2074            $error_message = ( 'invalid_jwt' === $error_code )
2075                ? __( 'An error occurred. Please reload the page and try again â€” data entered may be lost.', 'jetpack-forms' )
2076                : __( 'An error occurred. Please try again later.', 'jetpack-forms' );
2077
2078            $accepts_json && wp_send_json_error(
2079                array(
2080                    'error' => $error_message,
2081                    'code'  => $error_code,
2082                ),
2083                500,
2084                JSON_UNESCAPED_SLASHES
2085            );
2086
2087            // Non-JSON request, output the error message directly.
2088            header( 'HTTP/1.1 500 Server Error', true, 500 );
2089            echo '<div class="form-error"><ul class="form-errors"><li class="form-error-message">';
2090            echo esc_html( $error_message );
2091            echo '</li></ul></div>';
2092
2093            die();
2094        } elseif ( is_wp_error( $submission_result ) ) {
2095            do_action( 'jetpack_forms_log', $submission_result->get_error_message() );
2096
2097            $accepts_json && wp_send_json_error(
2098                array(
2099                    'error' => $submission_result->get_error_message(),
2100                ),
2101                400,
2102                JSON_UNESCAPED_SLASHES
2103            );
2104
2105            // Non-JSON request, output the error message directly.
2106            header( 'HTTP/1.1 400 Bad Request', true, 403 );
2107            echo '<div class="form-error"><ul class="form-errors"><li class="form-error-message">';
2108            echo esc_html( $submission_result->get_error_message() );
2109            echo '</li></ul></div>';
2110
2111            die();
2112        }
2113
2114        // Success case.
2115        echo '<h4>' . esc_html__( 'Your message has been sent', 'jetpack-forms' ) . '</h4>' . wp_kses(
2116            $submission_result,
2117            array(
2118                'br'         => array(),
2119                'blockquote' => array( 'class' => array() ),
2120                'p'          => array(),
2121            )
2122        );
2123        die();
2124    }
2125
2126    /**
2127     * Enforcement point for outbound-destination authorization on a submitted form.
2128     *
2129     * Destinations declared in the form content â€” webhooks, the legacy postToUrl attribute and
2130     * the Salesforce integration â€” are kept only when whoever placed the form had an
2131     * administrator-level capability (an admin author for post/page forms, or the
2132     * `edit_theme_options` required to author block templates, template parts and widgets);
2133     * otherwise they are removed from the form attributes in place, before the submission
2134     * is processed and the Form_Webhooks / Post_To_Url services read those attributes. The
2135     * mutation is safe because nothing re-reads the original attribute values within the request
2136     * and the form attributes are not persisted after this point.
2137     *
2138     * Webhooks supplied via the jetpack_forms_extra_webhooks filter (JWT submissions only) are
2139     * applied by the caller afterwards and are never affected here.
2140     *
2141     * @param Contact_Form $form The form whose attributes may be modified in place.
2142     */
2143    private function reconcile_content_destinations( Contact_Form $form ) {
2144        if ( empty( $form->attributes['webhooks'] )
2145            && empty( $form->attributes['postToUrl'] )
2146            && empty( $form->attributes['salesforceData'] ) ) {
2147            return;
2148        }
2149
2150        $source = $form->get_source();
2151        if ( ! Jetpack_Forms::should_honor_content_destinations( $source->get_id(), $source->get_source_type() ) ) {
2152            // Drop every content-configured destination before the services read them.
2153            // postToUrl and salesforceData are read directly by Post_To_Url.
2154            $form->attributes['webhooks']       = array();
2155            $form->attributes['postToUrl']      = array();
2156            $form->attributes['salesforceData'] = null;
2157
2158            /** This action is documented already in this file. */
2159            do_action( 'jetpack_forms_log', 'content_destinations_dropped', 'author_unauthorized' );
2160            return;
2161        }
2162
2163        // Deprecate postToUrl, migrate to webhooks in case someone put it to work.
2164        if ( ! empty( $form->attributes['postToUrl'] ) ) {
2165            // webhooks should be a collection.
2166            // Turn postToUrl into a collection and merge with existing webhooks.
2167            $form->attributes['webhooks'] = array_merge(
2168                $form->attributes['webhooks'] ?? array(),
2169                array( $form->attributes['postToUrl'] )
2170            );
2171        }
2172    }
2173
2174    /**
2175     * Validates that the parent post/page where the form lives still exists and is not trashed/deleted.
2176     *
2177     * @param Contact_Form $form The contact form instance.
2178     * @return Form_Submission_Error|null Returns a Form_Submission_Error if validation fails, null otherwise.
2179     */
2180    private function validate_parent_post( Contact_Form $form ) {
2181        $source    = $form->get_source();
2182        $source_id = $source->get_id();
2183
2184        // Only check for regular posts/pages (numeric IDs), not widgets or templates
2185        if ( is_numeric( $source_id ) && $source_id > 0 ) {
2186            $parent_post = get_post( (int) $source_id );
2187
2188            // If the parent post doesn't exist or is not trashed/deleted, reject the submission
2189            if ( ! $parent_post || in_array( $parent_post->post_status, array( 'trash', 'auto-draft' ), true ) ) {
2190                /** This action is documented already in this file. */
2191                do_action( 'jetpack_forms_log', 'submission_rejected_parent_trashed_or_deleted' );
2192
2193                return Form_Submission_Error::system_error(
2194                    'form_unavailable',
2195                    __( 'This form is no longer available.', 'jetpack-forms' )
2196                );
2197            }
2198        }
2199
2200        return null;
2201    }
2202
2203    /**
2204     * Ensure the post author is always zero for contact-form feedbacks
2205     * Attached to `wp_insert_post_data`
2206     *
2207     * @see Contact_Form::process_submission()
2208     *
2209     * @param array $data the data to insert.
2210     * @param array $postarr the data sent to wp_insert_post().
2211     * @return array The filtered $data to insert.
2212     */
2213    public function insert_feedback_filter( $data, $postarr ) {
2214        if ( $data['post_type'] === 'feedback' && $postarr['post_type'] === 'feedback' ) {
2215            $data['post_author'] = 0;
2216        }
2217
2218        return $data;
2219    }
2220
2221    /**
2222     * Adds our contact-form shortcode
2223     * The "child" contact-field shortcode is enabled as needed by the contact-form shortcode handler
2224     */
2225    public function add_shortcode() {
2226        add_shortcode( 'contact-form', array( '\Automattic\Jetpack\Forms\ContactForm\Contact_Form', 'parse' ) );
2227        add_shortcode( 'contact-field', array( '\Automattic\Jetpack\Forms\ContactForm\Contact_Form', 'parse_contact_field' ) );
2228
2229        // We need 'contact-field-option' to be registered, so it's included to the get_shortcode_regex() method
2230        // But we don't need a callback because we're handling contact-field-option manually
2231        add_shortcode( 'contact-field-option', '__return_null' );
2232    }
2233
2234    /**
2235     * Tokenize the label.
2236     *
2237     * @param string $label - the label.
2238     *
2239     * @return string
2240     */
2241    public static function tokenize_label( $label ) {
2242        return '{' . trim( wp_strip_all_tags( preg_replace( '#^\d+_#', '', $label ) ) ) . '}';
2243    }
2244
2245    /**
2246     * Sanitizes the value of a field.
2247     *
2248     * @param string|array|null $value The value to sanitize.
2249     * @return string The sanitized value.
2250     */
2251    public static function sanitize_value( $value ) {
2252        if ( null === $value ) {
2253            return '';
2254        }
2255
2256        // If value is an array, convert it to a comma-separated string
2257        if ( is_array( $value ) ) {
2258            return implode( ', ', array_map( array( __CLASS__, 'sanitize_value' ), $value ) );
2259        }
2260
2261        return preg_replace( '=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i', '', $value );
2262    }
2263
2264    /**
2265     * Sanitizes and formats values for display, ensuring arrays are properly converted to strings.
2266     *
2267     * @param mixed $value The value to format.
2268     * @return string|array The formatted value ready for display or file array for upload fields.
2269     */
2270    public static function format_value_for_display( $value ) {
2271        if ( is_array( $value ) ) {
2272            // Check if this is a file upload field
2273            if ( Contact_Form::is_file_upload_field( $value ) ) {
2274                // This is a file upload field, return as is to be handled by the proper renderer
2275                return $value;
2276            }
2277
2278            // Process each array element recursively and join with commas
2279            $formatted_values = array();
2280            foreach ( $value as $key => $item ) {
2281                $formatted_values[] = is_numeric( $key ) ? self::format_value_for_display( $item ) : "$key: " . self::format_value_for_display( $item );
2282            }
2283            return implode( ', ', $formatted_values );
2284        }
2285
2286        // Simple value, just convert to string
2287        return (string) $value;
2288    }
2289
2290    /**
2291     * Replaces tokens like {city} or {City} (case insensitive) with the value
2292     * of an input field of that name
2293     *
2294     * @param string $subject - the subject.
2295     * @param array  $field_values Array with field label => field value associations.
2296     *
2297     * @return string The filtered $subject with the tokens replaced.
2298     */
2299    public function replace_tokens_with_input( $subject, $field_values ) {
2300        // Wrap labels into tokens (inside {})
2301        $wrapped_labels = array_map( array( '\Automattic\Jetpack\Forms\ContactForm\Contact_Form_Plugin', 'tokenize_label' ), array_keys( $field_values ) );
2302        // Sanitize all values
2303        $sanitized_values = array_map( array( '\Automattic\Jetpack\Forms\ContactForm\Contact_Form_Plugin', 'sanitize_value' ), array_values( $field_values ) );
2304
2305        foreach ( $sanitized_values as $k => $sanitized_value ) {
2306            if ( is_array( $sanitized_value ) ) {
2307                $sanitized_values[ $k ] = implode( ', ', $sanitized_value );
2308            }
2309        }
2310
2311        // Search for all valid tokens (based on existing fields) and replace with the field's value
2312        $subject = str_ireplace( $wrapped_labels, $sanitized_values, $subject );
2313        return $subject;
2314    }
2315
2316    /**
2317     * Tracks the widget currently being processed.
2318     * Attached to `dynamic_sidebar`
2319     *
2320     * @see $current_widget_id - the current widget ID.
2321     *
2322     * @param array $widget The widget data.
2323     */
2324    public function track_current_widget( $widget ) {
2325        $this->current_widget_id = $widget['id'] ?? '';
2326    }
2327
2328    /**
2329     * Tracks the sidebar currently being processed.
2330     * Attached to `dynamic_sidebar_before`
2331     *
2332     * @see $current_sidebar_id - the current sidebar ID.
2333     *
2334     * @param string $index The sidebar index.
2335     */
2336    public function track_current_widget_before( $index ) {
2337        $this->current_sidebar_id = $index;
2338    }
2339
2340    /**
2341     * Clear the current widget context.
2342     */
2343    public function track_current_widget_after() {
2344        $this->current_sidebar_id = '';
2345        $this->current_widget_id  = '';
2346    }
2347
2348    /**
2349     * Gets the current widget context.
2350     *
2351     * @return string The current widget context or false if not set.
2352     */
2353    public function get_current_widget_context() {
2354        // If we don't have a current widget ID or sidebar ID, we
2355        if ( empty( $this->current_widget_id ) || empty( $this->current_sidebar_id ) ) {
2356            return '';
2357        }
2358        return $this->current_widget_id . '-' . $this->current_sidebar_id;
2359    }
2360
2361    /**
2362     * Adds a "widget" attribute to every contact-form embedded in a text widget.
2363     * Used to tell the difference between post-embedded contact-forms and widget-embedded contact-forms
2364     * Attached to `widget_text`
2365     *
2366     * @param string $text The widget text.
2367     *
2368     * @return string The filtered widget text.
2369     */
2370    public function widget_atts( $text ) {
2371        Contact_Form::style( true );
2372
2373        return preg_replace( '/\[contact-form([^a-zA-Z_-])/', '[contact-form widget="' . $this->current_widget_id . '"\\1', $text );
2374    }
2375
2376    /**
2377     * For sites where text widgets are not processed for shortcodes, we add this hack to process just our shortcode
2378     * Attached to `widget_text`
2379     *
2380     * @param string $text The widget text.
2381     *
2382     * @return string The contact-form filtered widget text
2383     *
2384     * @deprecated 8.3.4 Core processes shortcodes in text widgets since WordPress 4.9.
2385     */
2386    public function widget_shortcode_hack( $text ) {
2387        _deprecated_function( __METHOD__, 'package-8.3.4' );
2388
2389        if ( ! preg_match( '/\[contact-form([^a-zA-Z_-])/', $text ) ) {
2390            return $text;
2391        }
2392
2393        $old = $GLOBALS['shortcode_tags'];
2394        remove_all_shortcodes();
2395        self::$using_contact_form_field = true;
2396        $this->add_shortcode();
2397
2398        $text = apply_shortcodes( $text );
2399
2400        self::$using_contact_form_field = false;
2401        $GLOBALS['shortcode_tags']      = $old; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
2402
2403        return $text;
2404    }
2405
2406    /**
2407     * Check if a submission matches the Comment Blocklist.
2408     * The Comment Blocklist is a means to moderate discussion, and contact
2409     * forms are 1:1 discussion forums, ripe for abuse by users who are being
2410     * removed from the public discussion.
2411     * Attached to `jetpack_contact_form_is_spam`
2412     *
2413     * @param bool  $is_spam - if the submission is spam.
2414     * @param array $form - the form data.
2415     * @return bool TRUE => spam, FALSE => not spam
2416     */
2417    public function is_spam_blocklist( $is_spam, $form = array() ) {
2418        if ( $is_spam ) {
2419            return $is_spam;
2420        }
2421
2422        return $this->is_in_disallowed_list( false, $form );
2423    }
2424
2425    /**
2426     * Check if a submission matches the comment disallowed list.
2427     * Attached to `jetpack_contact_form_in_comment_disallowed_list`.
2428     *
2429     * @param boolean $in_disallowed_list Whether the feedback is in the disallowed list.
2430     * @param array   $form The form array.
2431     * @return bool Returns true if the form submission matches the disallowed list and false if it doesn't.
2432     */
2433    public function is_in_disallowed_list( $in_disallowed_list, $form = array() ) {
2434        if ( $in_disallowed_list ) {
2435            return $in_disallowed_list;
2436        }
2437
2438        if (
2439            wp_check_comment_disallowed_list(
2440                $form['comment_author'],
2441                $form['comment_author_email'],
2442                $form['comment_author_url'],
2443                $form['comment_content'],
2444                $form['user_ip'],
2445                $form['user_agent']
2446            )
2447        ) {
2448            return true;
2449        }
2450
2451        return false;
2452    }
2453
2454    /**
2455     * Populate an array with all values necessary to submit a NEW contact-form feedback to Akismet.
2456     * Note that this includes the current user_ip etc, so this should only be called when accepting a new item via $_POST
2457     *
2458     * @param array $form - contact form feedback array.
2459     *
2460     * @return array feedback array with additional data ready for submission to Akismet.
2461     */
2462    public function prepare_for_akismet( $form ) {
2463        $form['comment_type']     = 'contact_form';
2464        $form['user_ip']          = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
2465        $form['user_agent']       = isset( $_SERVER['HTTP_USER_AGENT'] ) ? filter_var( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
2466        $form['referrer']         = isset( $_SERVER['HTTP_REFERER'] ) ? esc_url_raw( wp_unslash( $_SERVER['HTTP_REFERER'] ) ) : '';
2467        $form['blog']             = get_option( 'home' );
2468        $form['blog_lang']        = get_bloginfo( 'language' );
2469        $form['comment_date_gmt'] = gmdate( DATE_ATOM, time() ); // ISO 8601. See https://www.php.net/manual/en/class.datetimeinterface.php#datetimeinterface.constants.types
2470
2471        foreach ( $_SERVER as $key => $value ) {
2472            if ( ! is_string( $value ) ) {
2473                continue;
2474            }
2475            if ( in_array( $key, array( 'HTTP_COOKIE', 'HTTP_COOKIE2', 'HTTP_USER_AGENT', 'HTTP_REFERER' ), true ) ) {
2476                // We don't care about cookies, and the UA and Referrer were caught above.
2477                continue;
2478            } elseif ( in_array( $key, array( 'REMOTE_ADDR', 'REQUEST_URI', 'DOCUMENT_URI' ), true ) ) {
2479                // All three of these are relevant indicators and should be passed along.
2480                $form[ $key ] = $value;
2481            } elseif ( str_starts_with( $key, 'HTTP_' ) ) {
2482                // Any other HTTP header indicators.
2483                $form[ $key ] = $value;
2484            }
2485        }
2486
2487        /**
2488         * Filter the values that are sent to Akismet for the spam check.
2489         *
2490         * @module contact-form
2491         *
2492         * @since 10.2.0
2493         *
2494         * @param array $form The form values being sent to Akismet.
2495         */
2496        return apply_filters( 'jetpack_contact_form_akismet_values', $form );
2497    }
2498
2499    /**
2500     * Submit contact-form data to Akismet to check for spam.
2501     * If you're accepting a new item via $_POST, run it Contact_Form_Plugin::prepare_for_akismet() first
2502     * Attached to `jetpack_contact_form_is_spam`
2503     *
2504     * @param bool  $is_spam - if the submission is spam.
2505     * @param array $form - the form data.
2506     * @return bool|WP_Error TRUE => spam, FALSE => not spam, WP_Error => stop processing entirely
2507     */
2508    public function is_spam_akismet( $is_spam, $form = array() ) {
2509        global $akismet_api_host, $akismet_api_port;
2510
2511        // The signature of this function changed from accepting just $form.
2512        // If something only sends an array, assume it's still using the old
2513        // signature and work around it.
2514        if ( empty( $form ) && is_array( $is_spam ) ) {
2515            $form    = $is_spam;
2516            $is_spam = false;
2517        }
2518
2519        // If a previous filter has alrady marked this as spam, trust that and move on.
2520        if ( $is_spam ) {
2521            return $is_spam;
2522        }
2523
2524        if ( ! function_exists( 'akismet_http_post' ) && ! defined( 'AKISMET_VERSION' ) ) {
2525            return false;
2526        }
2527
2528        $query_string = http_build_query( $form );
2529
2530        if ( method_exists( 'Akismet', 'http_post' ) ) {
2531            $response = \Akismet::http_post( $query_string, 'comment-check' );
2532        } else {
2533            $response = akismet_http_post( $query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port );
2534        }
2535
2536        $result = false;
2537
2538        if ( isset( $response[0]['x-akismet-pro-tip'] ) && 'discard' === trim( $response[0]['x-akismet-pro-tip'] ) && get_option( 'akismet_strictness' ) === '1' ) {
2539            $result = new WP_Error( 'feedback-discarded', __( 'Feedback discarded.', 'jetpack-forms' ) );
2540        } elseif ( isset( $response[1] ) && 'true' === trim( $response[1] ) ) { // 'true' is spam
2541            $result = true;
2542        }
2543
2544        /**
2545         * Filter the results returned by Akismet for each submitted contact form.
2546         *
2547         * @module contact-form
2548         *
2549         * @since 1.3.1
2550         *
2551         * @param WP_Error|bool $result Is the submitted feedback spam.
2552         * @param array|bool $form Submitted feedback.
2553         */
2554        return apply_filters( 'contact_form_is_spam_akismet', $result, $form );
2555    }
2556
2557    /**
2558     * Submit a feedback as either spam or ham
2559     *
2560     * @param string $as - Either 'spam' or 'ham'.
2561     * @param array  $form - the contact-form data.
2562     *
2563     * @return bool|string
2564     */
2565    public function akismet_submit( $as, $form ) {
2566        global $akismet_api_host, $akismet_api_port;
2567
2568        if ( ! in_array( $as, array( 'ham', 'spam' ), true ) ) {
2569            return false;
2570        }
2571
2572        $query_string = '';
2573        if ( is_array( $form ) ) {
2574            $query_string = http_build_query( $form );
2575        }
2576        if ( method_exists( 'Akismet', 'http_post' ) ) {
2577            $response = \Akismet::http_post( $query_string, "submit-{$as}" );
2578        } else {
2579            $response = akismet_http_post( $query_string, $akismet_api_host, "/1.1/submit-{$as}", $akismet_api_port );
2580        }
2581
2582        return trim( $response[1] );
2583    }
2584
2585    /**
2586     * Prints a dropdown of posts with forms.
2587     *
2588     * @param int $selected_id Currently selected post ID.
2589     * @return void
2590     */
2591    public static function form_posts_dropdown( $selected_id ) {
2592        ?>
2593        <select name="jetpack_form_parent_id">
2594            <option value="all"><?php esc_html_e( 'All sources', 'jetpack-forms' ); ?></option>
2595            <?php echo self::get_feedbacks_as_options( $selected_id ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML is escaped in the function. ?>
2596        </select>
2597        <?php
2598    }
2599
2600    /**
2601     * Fetch post content for a post and extract just the comment.
2602     *
2603     * @param int $post_id The post id to fetch the content for.
2604     *
2605     * @return string Trimmed post comment.
2606     *
2607     * @codeCoverageIgnore
2608     */
2609    public function get_post_content_for_csv_export( $post_id ) {
2610        $post_content = get_post_field( 'post_content', $post_id );
2611        $content      = explode( '<!--more-->', $post_content );
2612
2613        return trim( $content[0] );
2614    }
2615
2616    /**
2617     * Get `_feedback_extra_fields` field from post meta data.
2618     *
2619     * @param int  $post_id Id of the post to fetch meta data for.
2620     * @param bool $has_json_data Whether the post has JSON data or not, defaults to false for backwards compatibility.
2621     *
2622     * @return mixed
2623     */
2624    public function get_post_meta_for_csv_export( $post_id, $has_json_data = false ) {
2625        $content_fields = self::parse_fields_from_content( $post_id );
2626        $all_fields     = $content_fields['_feedback_all_fields'] ?? array();
2627        $md             = $has_json_data
2628            ? array_diff_key( $all_fields, array_flip( array_keys( self::NON_PRINTABLE_FIELDS ) ) )
2629            : (array) get_post_meta( $post_id, '_feedback_extra_fields', true );
2630
2631        $md['-3_response_date'] = get_the_date( 'Y-m-d H:i:s', $post_id );
2632        $md['93_ip_address']    = $content_fields['_feedback_ip'] ?? 0;
2633
2634        // add the email_marketing_consent to the post meta.
2635        $md['90_consent'] = 0;
2636        if ( ! empty( $all_fields ) ) {
2637            // check if the email_marketing_consent field exists.
2638            if ( isset( $all_fields['email_marketing_consent'] ) ) {
2639                $md['90_consent'] = $all_fields['email_marketing_consent'];
2640            }
2641
2642            // check if the feedback entry has a title.
2643            if ( isset( $all_fields['entry_title'] ) ) {
2644                $md['-9_title'] = $all_fields['entry_title'];
2645            }
2646
2647            // check if the feedback entry has a permalink we can use.
2648            if ( ! empty( $all_fields['entry_permalink'] ) ) {
2649                $parsed          = wp_parse_url( $all_fields['entry_permalink'] );
2650                $md['-6_source'] = '';
2651                if ( $parsed && ! empty( $parsed['path'] ) && strpos( $parsed['path'], '/' ) === 0 ) {
2652                    $md['-6_source'] .= $parsed['path'];
2653                }
2654                if ( $parsed && ! empty( $parsed['query'] ) ) {
2655                    $md['-6_source'] .= '?' . $parsed['query'];
2656                }
2657            }
2658        }
2659
2660        // flatten and decode all values.
2661        $result = array();
2662        foreach ( $md as $key => $value ) {
2663            if ( is_array( $value ) ) {
2664                if ( Contact_Form::is_file_upload_field( $value ) ) {
2665                    $file_names = array();
2666                    foreach ( $value['files'] as $file ) {
2667                        $file_names[] = $file['name'];
2668                    }
2669                    $value = implode( ', ', $file_names );
2670                } else {
2671                    $value = implode( ', ', $value );
2672                }
2673            }
2674            $result[ $key ] = html_entity_decode( $value, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 );
2675        }
2676
2677        return $result;
2678    }
2679
2680    /**
2681     * Get parsed feedback post fields.
2682     *
2683     * @param int $post_id Id of the post to fetch parsed contents for.
2684     *
2685     * @return array
2686     *
2687     * @codeCoverageIgnore - No need to be covered.
2688     */
2689    public function get_parsed_field_contents_of_post( $post_id ) {
2690        return self::parse_fields_from_content( $post_id );
2691    }
2692
2693    /**
2694     * Properly maps fields that are missing from the post meta data
2695     * to names, that are similar to those of the post meta.
2696     *
2697     * @param array $parsed_post_content Parsed post content.
2698     * @param bool  $use_main_comment Whether to use the main comment from the post_content or not.
2699     *                                Defaults to true for backwards compatibility. New JSON format
2700     *                                does not have a main comment and instead has all fields in the parsed content.
2701     *
2702     * @see parse_fields_from_content for how the input data is generated.
2703     *
2704     * @return array Mapped fields.
2705     */
2706    public function map_parsed_field_contents_of_post_to_field_names( $parsed_post_content, $use_main_comment = true ) {
2707
2708        $mapped_fields = array();
2709
2710        $field_mapping = array(
2711            // TODO: Commented out since we'll be re-introducing this after some other changes
2712            // '_feedback_subject'      => __( 'Contact Form', 'jetpack-forms' ),
2713            '_feedback_author'       => '1_Name',
2714            '_feedback_author_email' => '2_Email',
2715            '_feedback_author_url'   => '3_Website',
2716            '_feedback_ip'           => '93_ip_address',
2717        );
2718
2719        if ( $use_main_comment ) {
2720            $field_mapping['_feedback_main_comment'] = '4_Comment';
2721        }
2722
2723        foreach ( $field_mapping as $parsed_field_name => $field_name ) {
2724            if (
2725                isset( $parsed_post_content[ $parsed_field_name ] )
2726                && ! empty( $parsed_post_content[ $parsed_field_name ] )
2727            ) {
2728                $mapped_fields[ $field_name ] = $parsed_post_content[ $parsed_field_name ];
2729            }
2730        }
2731
2732        return $mapped_fields;
2733    }
2734
2735    /**
2736     * Registers the personal data exporter.
2737     *
2738     * @since 6.1.1
2739     *
2740     * @param  array $exporters An array of personal data exporters.
2741     *
2742     * @return array $exporters An array of personal data exporters.
2743     */
2744    public function register_personal_data_exporter( $exporters ) {
2745        $exporters['jetpack-feedback'] = array(
2746            'exporter_friendly_name' => __( 'Feedback', 'jetpack-forms' ),
2747            'callback'               => array( $this, 'personal_data_exporter' ),
2748        );
2749
2750        return $exporters;
2751    }
2752
2753    /**
2754     * Registers the personal data eraser.
2755     *
2756     * @since 6.1.1
2757     *
2758     * @param  array $erasers An array of personal data erasers.
2759     *
2760     * @return array $erasers An array of personal data erasers.
2761     */
2762    public function register_personal_data_eraser( $erasers ) {
2763        $erasers['jetpack-feedback'] = array(
2764            'eraser_friendly_name' => __( 'Feedback', 'jetpack-forms' ),
2765            'callback'             => array( $this, 'personal_data_eraser' ),
2766        );
2767
2768        return $erasers;
2769    }
2770
2771    /**
2772     * Exports personal data.
2773     *
2774     * @since 6.1.1
2775     *
2776     * @param  string $email  Email address.
2777     * @param  int    $page   Page to export.
2778     *
2779     * @return array  $return Associative array with keys expected by core.
2780     */
2781    public function personal_data_exporter( $email, $page = 1 ) {
2782        return $this->internal_personal_data_exporter( $email, $page );
2783    }
2784
2785    /**
2786     * Internal method for exporting personal data.
2787     *
2788     * Allows us to have a different signature than core expects
2789     * while protecting against future core API changes.
2790     *
2791     * @internal
2792     * @since 6.5
2793     *
2794     * @param  string $email    Email address.
2795     * @param  int    $page     Page to export.
2796     * @param  int    $per_page Number of feedbacks to process per page. Internal use only (testing).
2797     *
2798     * @return array            Associative array with keys expected by core.
2799     */
2800    public function internal_personal_data_exporter( $email, $page = 1, $per_page = 250 ) {
2801        $post_ids = $this->personal_data_post_ids_by_email( $email, $per_page, $page );
2802
2803        return array(
2804            'data' => $this->internal_personal_data_formater( $post_ids ),
2805            'done' => count( $post_ids ) < $per_page,
2806        );
2807    }
2808
2809    /**
2810     * Formats personal data for export.
2811     *
2812     * @param  array $post_ids Array of post IDs to format.
2813     *
2814     * @return array $export_data Formatted personal data for export.
2815     */
2816    public function internal_personal_data_formater( $post_ids ) {
2817        $export_data = array();
2818        foreach ( $post_ids as $post_id ) {
2819            $post_export_data = array();
2820            $feedback         = Feedback::get( $post_id );
2821            if ( ! $feedback ) {
2822                continue;
2823            }
2824            $fields             = $feedback->get_compiled_fields( 'personal_export', 'all' );
2825            $post_export_data[] = array(
2826                'name'  => __( 'Date', 'jetpack-forms' ),
2827                'value' => $feedback->get_time(),
2828            );
2829
2830            $post_export_data[] = array(
2831                'name'  => __( 'Source Title', 'jetpack-forms' ),
2832                'value' => $feedback->get_entry_title(),
2833            );
2834
2835            $post_export_data[] = array(
2836                'name'  => __( 'Source URL:', 'jetpack-forms' ),
2837                'value' => $feedback->get_entry_permalink(),
2838            );
2839
2840            foreach ( $fields as $field ) {
2841                $post_export_data[] = array(
2842                    'name'  => $field['label'],
2843                    'value' => $field['value'],
2844                );
2845            }
2846
2847            $post_export_data[] = array(
2848                'name'  => __( 'Consent', 'jetpack-forms' ),
2849                'value' => $feedback->has_consent() ? __( 'Yes', 'jetpack-forms' ) : __( 'No', 'jetpack-forms' ),
2850            );
2851
2852            $post_export_data[] = array(
2853                'name'  => __( 'IP Address', 'jetpack-forms' ),
2854                'value' => $feedback->get_ip_address() ?? '',
2855            );
2856
2857            $post_export_data[] = array(
2858                'name'  => __( 'Country code', 'jetpack-forms' ),
2859                'value' => $feedback->get_country_code() ?? '',
2860            );
2861
2862            $export_data[] = array(
2863                'group_id'    => 'feedback',
2864                'group_label' => __( 'Feedback', 'jetpack-forms' ),
2865                'item_id'     => 'feedback-' . $post_id,
2866                'data'        => $post_export_data,
2867            );
2868        }
2869
2870        return $export_data;
2871    }
2872
2873    /**
2874     * Erases personal data.
2875     *
2876     * @since 6.1.1
2877     *
2878     * @param  string $email Email address.
2879     * @param  int    $page  Page to erase.
2880     *
2881     * @return array         Associative array with keys expected by core.
2882     */
2883    public function personal_data_eraser( $email, $page = 1 ) {
2884        return $this->_internal_personal_data_eraser( $email, $page );
2885    }
2886
2887    /**
2888     * Internal method for erasing personal data.
2889     *
2890     * Allows us to have a different signature than core expects
2891     * while protecting against future core API changes.
2892     *
2893     * @internal
2894     * @since 6.5
2895     *
2896     * @param  string $email    Email address.
2897     * @param  int    $page     Page to erase.
2898     * @param  int    $per_page Number of feedbacks to process per page. Internal use only (testing).
2899     *
2900     * @return array            Associative array with keys expected by core.
2901     */
2902    public function _internal_personal_data_eraser( $email, $page = 1, $per_page = 250 ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore -- this is called in other files.
2903        $removed      = false;
2904        $retained     = false;
2905        $messages     = array();
2906        $option_name  = sprintf( '_jetpack_pde_feedback_%s', md5( $email ) );
2907        $last_post_id = 1 === $page ? 0 : get_option( $option_name, 0 );
2908        $post_ids     = $this->personal_data_post_ids_by_email( $email, $per_page, $page, $last_post_id );
2909
2910        foreach ( $post_ids as $post_id ) {
2911            $last_post_id = $post_id;
2912
2913            /**
2914             * Filters whether to erase a particular Feedback post.
2915             *
2916             * @since 6.3.0
2917             *
2918             * @param bool|string $prevention_message Whether to apply erase the Feedback post (bool).
2919             *                                        Custom prevention message (string). Default true.
2920             * @param int         $post_id            Feedback post ID.
2921             */
2922            $prevention_message = apply_filters( 'grunion_contact_form_delete_feedback_post', true, $post_id );
2923
2924            if ( true !== $prevention_message ) {
2925                if ( $prevention_message && is_string( $prevention_message ) ) {
2926                    $messages[] = esc_html( $prevention_message );
2927                } else {
2928                    $messages[] = sprintf(
2929                    // translators: %d: Post ID.
2930                        __( 'Feedback ID %d could not be removed at this time.', 'jetpack-forms' ),
2931                        $post_id
2932                    );
2933                }
2934
2935                $retained = true;
2936
2937                continue;
2938            }
2939
2940            if ( wp_delete_post( $post_id, true ) ) {
2941                $removed = true;
2942            } else {
2943                $retained   = true;
2944                $messages[] = sprintf(
2945                // translators: %d: Post ID.
2946                    __( 'Feedback ID %d could not be removed at this time.', 'jetpack-forms' ),
2947                    $post_id
2948                );
2949            }
2950        }
2951
2952        $done = count( $post_ids ) < $per_page;
2953
2954        if ( $done ) {
2955            delete_option( $option_name );
2956        } else {
2957            update_option( $option_name, (int) $last_post_id );
2958        }
2959
2960        return array(
2961            'items_removed'  => $removed,
2962            'items_retained' => $retained,
2963            'messages'       => $messages,
2964            'done'           => $done,
2965        );
2966    }
2967
2968    /**
2969     * Queries personal data by email address.
2970     *
2971     * @since 6.1.1
2972     *
2973     * @param  string $email        Email address.
2974     * @param  int    $per_page     Post IDs per page. Default is `250`.
2975     * @param  int    $page         Page to query. Default is `1`.
2976     * @param  int    $last_post_id Page to query. Default is `0`. If non-zero, used instead of $page.
2977     *
2978     * @return array An array of post IDs.
2979     */
2980    public function personal_data_post_ids_by_email( $email, $per_page = 250, $page = 1, $last_post_id = 0 ) {
2981        add_filter( 'posts_search', array( $this, 'personal_data_search_filter' ) );
2982
2983        $this->pde_last_post_id_erased = $last_post_id;
2984        $this->set_pde_email_address( $email );
2985
2986        $post_ids = get_posts(
2987            array(
2988                'post_type'        => 'feedback',
2989                'post_status'      => 'publish',
2990                // This search parameter gets overwritten in ->personal_data_search_filter()
2991                's'                => '..PDE..AUTHOR EMAIL:..PDE..',
2992                'sentence'         => true,
2993                'order'            => 'ASC',
2994                'orderby'          => 'ID',
2995                'fields'           => 'ids',
2996                'posts_per_page'   => $per_page,
2997                'paged'            => $last_post_id ? 1 : $page,
2998                'suppress_filters' => false,
2999            )
3000        );
3001
3002        $this->pde_last_post_id_erased = 0;
3003        $this->pde_email_address       = '';
3004
3005        remove_filter( 'posts_search', array( $this, 'personal_data_search_filter' ) );
3006
3007        return $post_ids;
3008    }
3009
3010    /**
3011     * Sets the email address to filter searches by.
3012     * Helper for tests.
3013     *
3014     * @since 6.1.1
3015     *
3016     * @param  string $email Email address.
3017     */
3018    public function set_pde_email_address( $email ) {
3019        $this->pde_email_address = $email;
3020    }
3021
3022    /**
3023     * Filters searches by email address.
3024     *
3025     * @since 6.1.1
3026     *
3027     * @param  string $search SQL where clause.
3028     *
3029     * @return string         Filtered SQL where clause.
3030     */
3031    public function personal_data_search_filter( $search ) {
3032        global $wpdb;
3033
3034        /*
3035         * Searches for email addresses in feedback post_content across all storage formats:
3036         * - Legacy format: AUTHOR EMAIL on its own line
3037         * - V2/V3 format: JSON with email in field values
3038         */
3039        if ( $this->pde_email_address && str_contains( $search, '..PDE..AUTHOR EMAIL:..PDE..' ) ) {
3040            // Build search patterns for all formats
3041            $patterns = array(
3042                // Pattern 1 & 2: Legacy format - AUTHOR EMAIL on its own line
3043                // `chr( 10 )` = `\n`, `chr( 13 )` = `\r`
3044                '%' . $wpdb->esc_like( chr( 10 ) . 'AUTHOR EMAIL: ' . $this->pde_email_address . chr( 10 ) ) . '%',
3045                '%' . $wpdb->esc_like( chr( 13 ) . 'AUTHOR EMAIL: ' . $this->pde_email_address . chr( 13 ) ) . '%',
3046
3047                // Pattern 3 & 4: V2/V3 format - JSON field value with escaped quotes
3048                // Handles both storage variants:
3049                // - Pattern 3: double-escaped quotes (e.g. stored as \"value\":\" in JSON-encoded content).
3050                // - Pattern 4: single-escaped quotes (e.g. stored as "value":" after one level of unescaping).
3051                // The closing quote stops foo@example.com from matching foo@example.com.au.
3052                '%\\"value\\":\\"' . $wpdb->esc_like( $this->pde_email_address ) . '\\"%',
3053                '%\"value\":\"' . $wpdb->esc_like( $this->pde_email_address ) . '\"%',
3054            );
3055
3056            // V2 has a bug where emojis become malformed: ðŸŽ‰ becomes ud83cudf89 instead of \ud83c\udf89.
3057            // Here we deliberately reproduce that corruption so we can still match feedback saved by V2:
3058            // - wp_json_encode( '🎉' ) produces the JSON string "\"\ud83c\udf89\"" (note the backslashes).
3059            // - trim( ..., '"' ) removes the surrounding JSON quotes, giving "\ud83c\udf89".
3060            // - stripslashes() then removes the backslashes from the escape sequence, yielding "ud83cudf89",
3061            // which is exactly how V2 stored the corrupted value in post_content.
3062            // If the email contains unicode, also search for the V2 corrupted version generated this way.
3063            $v2_corrupted_email = stripslashes( trim( wp_json_encode( $this->pde_email_address, JSON_UNESCAPED_SLASHES ), '"' ) );
3064            if ( $v2_corrupted_email !== $this->pde_email_address ) {
3065                // Email contains unicode - add pattern for V2's corrupted format.
3066                $patterns[] = '%\"value\":\"' . $wpdb->esc_like( $v2_corrupted_email ) . '\"%';
3067            }
3068
3069            // Build SQL with all patterns
3070            $placeholders = implode( ' OR ', array_fill( 0, count( $patterns ), "{$wpdb->posts}.post_content LIKE %s" ) );
3071
3072            // Validate that the number of placeholders matches the number of pattern values
3073            $placeholder_count = substr_count( $placeholders, '%s' );
3074            if ( $placeholder_count !== count( $patterns ) ) {
3075                return $search;
3076            }
3077
3078            $search = (string) $wpdb->prepare(
3079                ' AND ( ' . $placeholders . ' )', // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
3080                ...$patterns
3081            );
3082
3083            if ( $this->pde_last_post_id_erased ) {
3084                $search .= $wpdb->prepare( " AND {$wpdb->posts}.ID > %d", $this->pde_last_post_id_erased );
3085            }
3086        }
3087
3088        return $search;
3089    }
3090
3091    /**
3092     * Returns an array of feedback data for export.
3093     *
3094     * @param array $feedback_ids           Array of feedback IDs to fetch the data for.
3095     * @param bool  $include_test_responses Whether to include feedback that was submitted
3096     *                                      from form preview. Defaults to false, meaning
3097     *                                      preview/test responses are excluded from the export.
3098     *
3099     * @return array
3100     */
3101    public function get_export_feedback_data( $feedback_ids, $include_test_responses = false ) {
3102        $results = array();
3103        $header  = null;
3104        foreach ( $this->get_export_rows( $feedback_ids, $include_test_responses ) as $row ) {
3105            if ( null === $header ) {
3106                $header = $row;
3107                continue;
3108            }
3109            foreach ( $row as $index => $value ) {
3110                $results[ $header[ $index ] ][] = $value;
3111            }
3112        }
3113        return $results;
3114    }
3115
3116    /**
3117     * Yields the export header row, then one row per response.
3118     *
3119     * @since 8.4.0
3120     *
3121     * @param int[] $feedback_ids           Feedback IDs to export.
3122     * @param bool  $include_test_responses Whether to include responses submitted from form preview.
3123     *
3124     * @return \Generator<array> Yields nothing when no response qualifies.
3125     */
3126    public function get_export_rows( $feedback_ids, $include_test_responses = false ) {
3127        yield from $this->get_prepared_export_rows( $this->prepare_export( $feedback_ids, $include_test_responses ) );
3128    }
3129
3130    /**
3131     * Runs the export's first pass: which responses qualify, and every field column the header needs.
3132     *
3133     * @param int[] $feedback_ids           Feedback IDs to export.
3134     * @param bool  $include_test_responses Whether to include responses submitted from form preview.
3135     *
3136     * @return array{ids: int[], field_names: string[]}
3137     */
3138    private function prepare_export( $feedback_ids, $include_test_responses ) {
3139        $field_names = array();
3140        $export_ids  = array();
3141        foreach ( $this->get_export_feedback_batches( $feedback_ids, $include_test_responses ) as $feedback_id => $feedback ) {
3142            $export_ids[] = $feedback_id;
3143            // The label-value shape already de-duplicates labels, e.g. "Name (2)".
3144            foreach ( array_keys( $feedback->get_compiled_fields( 'csv', 'label-value' ) ) as $field_name ) {
3145                $field_names[ trim( $field_name ) ] = true;
3146            }
3147        }
3148
3149        return array(
3150            'ids'         => $export_ids,
3151            'field_names' => array_map( 'strval', array_keys( $field_names ) ),
3152        );
3153    }
3154
3155    /**
3156     * Yields the header row, then one row per response, for a prepare_export() result.
3157     *
3158     * @param array $export Result of prepare_export().
3159     *
3160     * @return \Generator<array> Yields nothing when no response qualifies.
3161     */
3162    private function get_prepared_export_rows( $export ) {
3163        $is_first_row = true;
3164        foreach ( $this->get_export_feedback_batches( $export['ids'], true ) as $feedback_id => $feedback ) {
3165            $row = $this->get_export_row( $feedback_id, $feedback, $export['field_names'] );
3166            if ( $is_first_row ) {
3167                $is_first_row = false;
3168                yield array_keys( $row );
3169            }
3170            yield array_values( $row );
3171        }
3172    }
3173
3174    /**
3175     * Yields Feedback objects keyed by ID, dropping each batch from memory before loading the next.
3176     *
3177     * @param int[] $feedback_ids           Feedback IDs to load.
3178     * @param bool  $include_test_responses Whether to include responses submitted from form preview.
3179     *
3180     * @return \Generator<int, Feedback>
3181     */
3182    private function get_export_feedback_batches( $feedback_ids, $include_test_responses ) {
3183        foreach ( array_chunk( $feedback_ids, self::EXPORT_BATCH_SIZE ) as $batch ) {
3184            _prime_post_caches( $batch, false, true );
3185
3186            foreach ( $batch as $feedback_id ) {
3187                $feedback = Feedback::get( $feedback_id );
3188                if ( ! $feedback instanceof Feedback ) {
3189                    continue;
3190                }
3191                if ( ! $include_test_responses && $feedback->is_test() ) {
3192                    continue;
3193                }
3194                yield $feedback_id => $feedback;
3195            }
3196
3197            Feedback::clear_cache();
3198            if ( function_exists( 'wp_cache_supports' ) && wp_cache_supports( 'flush_runtime' ) ) {
3199                wp_cache_flush_runtime();
3200            }
3201        }
3202    }
3203
3204    /**
3205     * Returns one response's export row, keyed by column name.
3206     *
3207     * @param int      $feedback_id Feedback ID.
3208     * @param Feedback $feedback    The response.
3209     * @param string[] $field_names Form field columns, in order; missing fields export as an empty string.
3210     *
3211     * @return array
3212     */
3213    private function get_export_row( $feedback_id, $feedback, $field_names ) {
3214        $compiled_fields    = $feedback->get_compiled_fields( 'csv', 'label-value' );
3215        $prefix_meta_fields = ' '; // Prefix all meta fields with a space to ensure that they don't clash with form field names.
3216
3217        $row = array(
3218            $prefix_meta_fields . __( 'ID', 'jetpack-forms' )     => $feedback_id,
3219            $prefix_meta_fields . __( 'Date', 'jetpack-forms' )   => $feedback->get_time(),
3220            $prefix_meta_fields . __( 'Title', 'jetpack-forms' )  => $feedback->get_entry_title(),
3221            $prefix_meta_fields . __( 'Source', 'jetpack-forms' ) => $feedback->get_entry_short_permalink(),
3222        );
3223
3224        foreach ( $field_names as $field_name ) {
3225            $row[ $field_name ] = $compiled_fields[ $field_name ] ?? '';
3226        }
3227
3228        $row[ $prefix_meta_fields . __( 'Consent', 'jetpack-forms' ) ] = $feedback->has_consent() ? __( 'Yes', 'jetpack-forms' ) : __( 'No', 'jetpack-forms' );
3229
3230        // Convert null values to empty strings for proper CSV/export formatting.
3231        $row[ $prefix_meta_fields . __( 'IP Address', 'jetpack-forms' ) ]   = $feedback->get_ip_address() ?? '';
3232        $row[ $prefix_meta_fields . __( 'Country code', 'jetpack-forms' ) ] = $feedback->get_country_code() ?? '';
3233        $row[ $prefix_meta_fields . __( 'Browser', 'jetpack-forms' ) ]      = $feedback->get_browser() ?? '';
3234
3235        return $row;
3236    }
3237
3238    /**
3239     * Prepares feedback post data for CSV export.
3240     *
3241     * @deprecated since 5.1.0
3242     *
3243     * @see get_export_feedback_data()
3244     * @param array $post_ids Post IDs to fetch the data for. These need to be Feedback posts.
3245     *
3246     * @return array
3247     */
3248    public function get_export_data_for_posts( $post_ids ) {
3249        _deprecated_function( __METHOD__, 'package-5.1.0', 'Contact_Form_Plugin::get_export_feedback_data()' );
3250        return $this->get_export_feedback_data( $post_ids );
3251    }
3252
3253    /**
3254     * Returns an array of [prefixed column name] => [translated column name], used on export.
3255     * Prefix indicates the position in which the column will be rendered:
3256     * - Negative numbers render BEFORE any form field/value column: -5, -3, -1...
3257     * - Positive values render AFTER any form field/value column: 1, 30, 93...
3258     *   Mind using high numbering on these ones as the prefix is used on regular inputs: 1_Name, 2_Email, etc
3259     *
3260     * @deprecated since 5.1.0
3261     *
3262     * @return array
3263     */
3264    public function get_well_known_column_names() {
3265        _deprecated_function( __METHOD__, 'package-5.1.0', 'Contact_Form_Plugin::get_export_column_names()' );
3266        return array(
3267            '-9_title'         => __( 'Title', 'jetpack-forms' ),
3268            '-6_source'        => __( 'Source', 'jetpack-forms' ),
3269            '-3_response_date' => __( 'Response Date', 'jetpack-forms' ),
3270            '90_consent'       => _x( 'Consent', 'noun', 'jetpack-forms' ),
3271            '93_ip_address'    => __( 'IP Address', 'jetpack-forms' ),
3272            '94_country_code'  => __( 'Country code', 'jetpack-forms' ),
3273            '95_browser'       => __( 'Browser', 'jetpack-forms' ),
3274        );
3275    }
3276
3277    /**
3278     * Extracts feedback entries based on POST data.
3279     *
3280     * @return array|null Column name => values, or null when the request is not a permitted export.
3281     */
3282    public function get_feedback_entries_from_post() {
3283        $export = $this->get_export_feedback_ids_from_post();
3284        if ( null === $export ) {
3285            return null;
3286        }
3287        return $this->get_export_feedback_data( $export['ids'], $export['include_test_responses'] );
3288    }
3289
3290    /**
3291     * Returns the export rows requested by POST data, header row first.
3292     *
3293     * @return \Generator<array>|null Null when the request is not a permitted export.
3294     */
3295    private function get_export_rows_from_post() {
3296        $export = $this->get_export_feedback_ids_from_post();
3297        if ( null === $export ) {
3298            return null;
3299        }
3300        return $this->get_export_rows( $export['ids'], $export['include_test_responses'] );
3301    }
3302
3303    /**
3304     * Verifies an export request and returns the IDs of the responses it covers.
3305     *
3306     * @return array|null With 'ids' and 'include_test_responses' keys, or null when the request is not a permitted export.
3307     */
3308    private function get_export_feedback_ids_from_post() {
3309        if ( empty( $_POST['feedback_export_nonce_csv'] ) && empty( $_POST['feedback_export_nonce_gdrive'] ) ) {
3310            return null;
3311        } elseif ( ! empty( $_POST['feedback_export_nonce_csv'] ) ) {
3312            check_admin_referer( 'feedback_export', 'feedback_export_nonce_csv' );
3313        } elseif ( ! empty( $_POST['feedback_export_nonce_gdrive'] ) ) {
3314            check_admin_referer( 'feedback_export', 'feedback_export_nonce_gdrive' );
3315        }
3316
3317        if ( ! current_user_can( 'export' ) ) {
3318            return null;
3319        }
3320
3321        $filters = array(
3322            'status' => ! empty( $_POST['status'] ) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : '',
3323            'search' => ! empty( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : '',
3324            'source' => ! empty( $_POST['source'] ) ? absint( $_POST['source'] ) : 0,
3325        );
3326
3327        // Check if we want to download all the feedbacks or just a certain contact form
3328        if ( ! empty( $_POST['post'] ) && $_POST['post'] !== 'all' ) {
3329            $filters['form'] = (int) $_POST['post'];
3330        }
3331
3332        // The dashboard applies a date range only when both ends are set and in order.
3333        if ( ! empty( $_POST['after'] ) && ! empty( $_POST['before'] ) ) {
3334            $before      = sanitize_text_field( wp_unslash( $_POST['before'] ) );
3335            $after       = sanitize_text_field( wp_unslash( $_POST['after'] ) );
3336            $after_time  = strtotime( $after );
3337            $before_time = strtotime( $before );
3338            if ( $after_time && $before_time && $after_time < $before_time ) {
3339                $filters['after']  = $after;
3340                $filters['before'] = $before;
3341            }
3342        }
3343
3344        $has_explicit_selection = ! empty( $_POST['selected'] ) && is_array( $_POST['selected'] );
3345        if ( $has_explicit_selection ) {
3346            $filters['selected'] = array_map(
3347                'intval',
3348                $_POST['selected'] // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
3349            );
3350        }
3351
3352        // Bulk exports skip form-preview test responses; an explicit dashboard selection keeps them.
3353        return array(
3354            'ids'                    => $this->get_export_feedback_ids( $filters ),
3355            'include_test_responses' => $has_explicit_selection,
3356        );
3357    }
3358
3359    /**
3360     * Returns the IDs of the responses an export covers, oldest first.
3361     *
3362     * Does no permission checks; callers must.
3363     *
3364     * @since 8.4.0
3365     *
3366     * @param array $filters {
3367     *     Optional. Filters to narrow the export.
3368     *
3369     *     @type int    $form     Only responses to the form on this post ID.
3370     *     @type string $status   'spam' or 'trash'; anything else exports the inbox.
3371     *     @type string $search   Search term.
3372     *     @type string $after    Only responses after this date; any format strtotime() accepts.
3373     *     @type string $before   Only responses before this date; any format strtotime() accepts.
3374     *     @type int[]  $selected Only these response IDs.
3375     *     @type int    $source   Only responses from this source post ID.
3376     * }
3377     *
3378     * @return int[]
3379     */
3380    public function get_export_feedback_ids( $filters = array() ) {
3381        $args = array(
3382            'posts_per_page'   => -1,
3383            'post_type'        => Feedback::POST_TYPE,
3384            'post_status'      => array( 'publish', 'draft' ),
3385            'order'            => 'ASC',
3386            'fields'           => 'ids',
3387            'suppress_filters' => false,
3388            'date_query'       => array(),
3389        );
3390
3391        if ( ! empty( $filters['form'] ) ) {
3392            $args['post_parent'] = (int) $filters['form'];
3393        }
3394
3395        if ( ! empty( $filters['status'] ) && in_array( $filters['status'], array( 'spam', 'trash' ), true ) ) {
3396            $args['post_status'] = $filters['status'];
3397        }
3398
3399        if ( ! empty( $filters['search'] ) ) {
3400            $args['s'] = $filters['search'];
3401        }
3402
3403        // date_query expects date strings/arrays, not timestamps.
3404        foreach ( array( 'after', 'before' ) as $bound ) {
3405            $time = ! empty( $filters[ $bound ] ) ? strtotime( $filters[ $bound ] ) : false;
3406            if ( $time ) {
3407                $args['date_query'][ $bound ] = gmdate( 'Y-m-d H:i:s', $time );
3408            }
3409        }
3410
3411        if ( ! empty( $filters['selected'] ) ) {
3412            $args['include'] = array_filter( array_map( 'intval', (array) $filters['selected'] ) );
3413        }
3414
3415        $source_id = ! empty( $filters['source'] ) ? absint( $filters['source'] ) : 0;
3416        $join_cb   = null;
3417        $where_cb  = null;
3418        $feedbacks = array();
3419
3420        if ( $source_id > 0 ) {
3421            $source_sql = Feedback::get_source_filter_sql( $source_id );
3422
3423            $join_cb  = function ( $join, $query ) use ( $source_sql ) {
3424                if ( Feedback::POST_TYPE !== $query->get( 'post_type' ) ) {
3425                    return $join;
3426                }
3427                return $join . $source_sql['join'];
3428            };
3429            $where_cb = function ( $where, $query ) use ( $source_sql ) {
3430                if ( Feedback::POST_TYPE !== $query->get( 'post_type' ) ) {
3431                    return $where;
3432                }
3433                return $where . ' AND ' . $source_sql['where'];
3434            };
3435
3436            add_filter( 'posts_join', $join_cb, 10, 2 );
3437            add_filter( 'posts_where', $where_cb, 10, 2 );
3438        }
3439
3440        try {
3441            $feedbacks = get_posts( $args );
3442        } finally {
3443            if ( is_callable( $join_cb ) ) {
3444                remove_filter( 'posts_join', $join_cb, 10 );
3445            }
3446            if ( is_callable( $where_cb ) ) {
3447                remove_filter( 'posts_where', $where_cb, 10 );
3448            }
3449        }
3450
3451        return array_map( 'intval', $feedbacks );
3452    }
3453
3454    /**
3455     * Download exported data as CSV
3456     */
3457    public function download_feedback_as_csv() {
3458        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verification is done on get_export_feedback_ids_from_post function
3459        $post_data = wp_unslash( $_POST );
3460        $request   = $this->get_export_feedback_ids_from_post();
3461        if ( null === $request ) {
3462            return;
3463        }
3464
3465        $export = $this->prepare_export( $request['ids'], $request['include_test_responses'] );
3466        $rows   = $this->get_prepared_export_rows( $export );
3467        if ( ! $rows->valid() ) {
3468            return;
3469        }
3470
3471        // Check if we want to download all the feedbacks or just a certain contact form
3472        if ( ! empty( $post_data['post'] ) && $post_data['post'] !== 'all' ) {
3473            $filename = sprintf(
3474                '%s - %s.csv',
3475                Util::get_export_filename( get_the_title( (int) $post_data['post'] ) ),
3476                gmdate( 'Y-m-d H:i' )
3477            );
3478        } else {
3479            $filename = sprintf(
3480                '%s - %s.csv',
3481                Util::get_export_filename(),
3482                gmdate( 'Y-m-d H:i' )
3483            );
3484        }
3485
3486        // Forces the download of the CSV instead of echoing
3487        header( 'Content-Disposition: attachment; filename=' . $filename );
3488        header( 'Pragma: no-cache' );
3489        header( 'Expires: 0' );
3490        header( 'Content-Type: text/csv; charset=utf-8' );
3491        // Lets the dashboard show a percentage, since a streamed file has no Content-Length.
3492        header( 'X-Jetpack-Forms-Export-Count: ' . count( $export['ids'] ) );
3493
3494        $output = fopen( 'php://output', 'w' );
3495        $this->write_export_csv( $output, $rows );
3496        fclose( $output ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
3497
3498        $this->record_tracks_event( 'forms_export_responses', array( 'format' => 'csv' ) );
3499        exit( 0 );
3500    }
3501
3502    /**
3503     * Create a new page with a Form block
3504     */
3505    public function create_new_form() {
3506        if ( ! isset( $_POST['newFormNonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['newFormNonce'] ) ), 'create_new_form' ) ) {
3507            wp_send_json_error(
3508                __( 'Invalid nonce', 'jetpack-forms' ),
3509                403,
3510                JSON_UNESCAPED_SLASHES
3511            );
3512        }
3513
3514        if ( ! current_user_can( 'edit_pages' ) ) {
3515            wp_send_json_error(
3516                __( 'You do not have permission to create pages', 'jetpack-forms' ),
3517                403,
3518                JSON_UNESCAPED_SLASHES
3519            );
3520        }
3521
3522        $pattern_name = isset( $_POST['pattern'] ) ? sanitize_text_field( wp_unslash( $_POST['pattern'] ) ) : null;
3523
3524        if ( $pattern_name && WP_Block_Patterns_Registry::get_instance()->is_registered( $pattern_name ) ) {
3525            $pattern         = WP_Block_Patterns_Registry::get_instance()->get_registered( $pattern_name );
3526            $pattern_content = $pattern['content'] ?? '';
3527        }
3528
3529        // If no pattern found or specified, use a default form block
3530        if ( empty( $pattern_content ) ) {
3531            $pattern_content = '<!-- wp:jetpack/contact-form -->
3532                                                        <div class="wp-block-jetpack-contact-form"></div>
3533                                                    <!-- /wp:jetpack/contact-form -->';
3534        }
3535
3536        $form_title = isset( $_POST['formTitle'] ) ? sanitize_text_field( wp_unslash( $_POST['formTitle'] ) ) : '';
3537
3538        $post_id = wp_insert_post(
3539            array(
3540                'post_type'    => 'page',
3541                'post_title'   => $form_title,
3542                'post_content' => $pattern_content,
3543            )
3544        );
3545
3546        if ( is_wp_error( $post_id ) ) {
3547            wp_send_json_error(
3548                $post_id->get_error_message(),
3549                500,
3550                JSON_UNESCAPED_SLASHES
3551            );
3552        } else {
3553            wp_send_json(
3554                array(
3555                    'post_url' => admin_url( 'post.php?post=' . intval( $post_id ) . '&action=edit' ),
3556                ),
3557                null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
3558                JSON_UNESCAPED_SLASHES
3559            );
3560        }
3561    }
3562
3563    /**
3564     * Send an event to Tracks
3565     *
3566     * @param string $event_name - the name of the event.
3567     * @param array  $event_props - event properties to send.
3568     *
3569     * @return null|void
3570     */
3571    public function record_tracks_event( $event_name, $event_props ) {
3572        /*
3573         * Event details.
3574         */
3575        $event_user = wp_get_current_user();
3576
3577        /*
3578         * Record event.
3579         * We use different libs on wpcom and Jetpack.
3580         */
3581        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
3582            $event_name             = 'wpcom_' . $event_name;
3583            $event_props['blog_id'] = get_current_blog_id();
3584            // logged out visitor, record event with blog owner.
3585            if ( empty( $event_user->ID ) ) {
3586                $event_user_id = wpcom_get_blog_owner( $event_props['blog_id'] );
3587                $event_user    = get_userdata( $event_user_id );
3588            }
3589
3590            require_lib( 'tracks/client' );
3591            tracks_record_event( $event_user, $event_name, $event_props );
3592        } else {
3593            $user_connected = ( new \Automattic\Jetpack\Connection\Manager( 'jetpack-forms' ) )->is_user_connected( get_current_user_id() );
3594            if ( ! $user_connected ) {
3595                return;
3596            }
3597            // logged out visitor, record event with Jetpack master user.
3598            if ( empty( $event_user->ID ) ) {
3599                $master_user_id = Jetpack_Options::get_option( 'master_user' );
3600                if ( ! empty( $master_user_id ) ) {
3601                    $event_user = get_userdata( $master_user_id );
3602                }
3603            }
3604
3605            $tracking = new Tracking();
3606            $tracking->record_user_event( $event_name, $event_props, $event_user );
3607        }
3608    }
3609
3610    /**
3611     * Writes export rows as CSV: the header row as-is, then every response row through esc_csv().
3612     *
3613     * @since 8.4.0
3614     *
3615     * @param resource   $output Writable stream.
3616     * @param \Generator $rows   Rows from get_export_rows(), header first.
3617     *
3618     * @return int Number of response rows written.
3619     */
3620    public function write_export_csv( $output, $rows ) {
3621        $count     = 0;
3622        $is_header = true;
3623        foreach ( $rows as $row ) {
3624            if ( $is_header ) {
3625                $is_header = false;
3626            } else {
3627                $row = array_map( array( $this, 'esc_csv' ), $row );
3628                ++$count;
3629            }
3630            fputcsv( $output, $row, ',', '"', '' );
3631        }
3632        return $count;
3633    }
3634
3635    /**
3636     * Escape a string to be used in a CSV context
3637     *
3638     * Malicious input can inject formulas into CSV files, opening up the possibility for phishing attacks and
3639     * disclosure of sensitive information.
3640     *
3641     * Additionally, Excel exposes the ability to launch arbitrary commands through the DDE protocol.
3642     *
3643     * @see https://www.contextis.com/en/blog/comma-separated-vulnerabilities
3644     *
3645     * @param string $field - the CSV field.
3646     *
3647     * @return string
3648     */
3649    public function esc_csv( $field ) {
3650        $active_content_triggers = array( '=', '+', '-', '@' );
3651
3652        if ( $field && in_array( mb_substr( $field, 0, 1 ), $active_content_triggers, true ) ) {
3653            $field = "'" . $field;
3654        }
3655
3656        return $field;
3657    }
3658
3659    /**
3660     * Returns an array of parent post IDs for the user.
3661     * The parent posts are those posts where forms have been published.
3662     *
3663     * @param array $query_args A WP_Query compatible array of query args.
3664     *
3665     * @return array The array of post IDs
3666     */
3667    public static function get_all_parent_post_ids( $query_args = array() ) {
3668        $default_query_args = array(
3669            'fields'           => 'id=>parent',
3670            'posts_per_page'   => 100000, // phpcs:ignore WordPress.WP.PostsPerPage.posts_per_page_posts_per_page
3671            'post_type'        => 'feedback',
3672            'post_status'      => 'publish',
3673            'suppress_filters' => false,
3674        );
3675        $args               = array_merge( $default_query_args, $query_args );
3676        // Get the feedbacks' parents' post IDs
3677        $feedbacks = get_posts( $args );
3678        return array_values( array_unique( array_values( $feedbacks ) ) );
3679    }
3680
3681    /**
3682     * Returns a string of HTML <option> items from an array of posts
3683     *
3684     * @param int $selected_id Currently selected post ID.
3685     * @return string a string of HTML <option> items
3686     */
3687    protected static function get_feedbacks_as_options( $selected_id = 0 ) {
3688        $options    = '';
3689        $parent_ids = self::get_all_parent_post_ids();
3690
3691        // creates the string of <option> elements
3692        foreach ( $parent_ids as $parent_id ) {
3693            $parent_url = get_permalink( $parent_id );
3694            $parsed_url = wp_parse_url( $parent_url );
3695
3696            $options .= sprintf(
3697                '<option value="%s" %s>/%s</option>',
3698                esc_attr( $parent_id ),
3699                $selected_id === $parent_id ? 'selected' : '',
3700                esc_html( basename( $parsed_url['path'] ) )
3701            );
3702        }
3703
3704        return $options;
3705    }
3706
3707    /**
3708     * Get the names of all the form's fields
3709     *
3710     * @param array|int $posts the post we want the fields of.
3711     *
3712     * @return array     the array of fields
3713     *
3714     * @deprecated As this is no longer necessary as of the CSV export rewrite. - 2015-12-29
3715     */
3716    protected function get_field_names( $posts ) {
3717        $posts      = (array) $posts;
3718        $all_fields = array();
3719
3720        foreach ( $posts as $post ) {
3721            $fields = self::parse_fields_from_content( $post );
3722
3723            if ( isset( $fields['_feedback_all_fields'] ) ) {
3724                $extra_fields = array_keys( $fields['_feedback_all_fields'] );
3725                $all_fields   = array_merge( $all_fields, $extra_fields );
3726            }
3727        }
3728
3729        $all_fields = array_unique( $all_fields );
3730
3731        return $all_fields;
3732    }
3733
3734    /**
3735     * Returns if the feedback post has JSON data
3736     *
3737     * @param int $post_id The feedback post ID to check.
3738     * @return bool
3739     */
3740    public function has_json_data( $post_id ) {
3741        $post_content = get_post_field( 'post_content', $post_id );
3742        $content      = explode( "\nJSON_DATA", $post_content );
3743        if ( empty( $content[1] ) ) {
3744            return false;
3745        }
3746        $json_data = json_decode( $content[1], true );
3747        return is_array( $json_data ) && ! empty( $json_data );
3748    }
3749
3750    /**
3751     * Helper function to parse the post content.
3752     *
3753     * @param string $post_content The post content to parse.
3754     * @return array Parsed fields.
3755     *
3756     * @codeCoverageIgnore - No need to be covered.
3757     * @deprecated since 5.3.0
3758     */
3759    public static function parse_feedback_content( $post_content ) {
3760        $all_values = array();
3761
3762        $content = explode( '<!--more-->', $post_content );
3763        $lines   = array();
3764
3765        if ( count( $content ) > 1 ) {
3766            $content = str_ireplace( array( '<br />', ')</p>' ), '', $content[1] );
3767            if ( str_contains( $content, 'JSON_DATA' ) ) {
3768                $chunks     = explode( "\nJSON_DATA", $content );
3769                $all_values = json_decode( $chunks[1], true );
3770                if ( $all_values === null ) {
3771                    // If JSON decoding fails, try to decode the second try with stripslashes and trim.
3772                    // This is a workaround for some cases where the JSON data is not properly formatted.
3773                    $all_values = json_decode( stripslashes( trim( $chunks[1] ) ), true );
3774                }
3775                $lines = array_filter( explode( "\n", $chunks[0] ) );
3776            } else {
3777                $fields_array = preg_replace( '/.*Array\s\( (.*)\)/msx', '$1', $content );
3778
3779                // This line of code is used to parse a string containing key-value pairs formatted as [Key] => Value and extract the keys and values into an array.
3780                // The regular expression ensures that each key-value pair is correctly identified and captured.
3781                // Given an input string
3782                // [Key1] => Value1
3783                // [Key2] => Value2
3784                // it  $matches[1]: The keys (e.g., Key1, Key2 ).
3785                // and $matches[2]: The values (e.g., Value1, Value2 ).
3786                preg_match_all( '/^\s*\[([^\]]+)\] =\&gt\; (.*)(?=^\s*(\[[^\]]+\] =\&gt\;)|\z)/msU', $fields_array, $matches );
3787
3788                if ( count( $matches ) > 1 ) {
3789                    $all_values = array_combine( array_map( 'trim', $matches[1] ), array_map( 'trim', $matches[2] ) );
3790                }
3791
3792                $lines = array_filter( explode( "\n", $content ) );
3793            }
3794        }
3795
3796        $var_map = array(
3797            'AUTHOR'       => '_feedback_author',
3798            'AUTHOR EMAIL' => '_feedback_author_email',
3799            'AUTHOR URL'   => '_feedback_author_url',
3800            'SUBJECT'      => '_feedback_subject',
3801            'IP'           => '_feedback_ip',
3802        );
3803
3804        $fields = array();
3805
3806        foreach ( $lines as $line ) {
3807            $vars = explode( ': ', $line, 2 );
3808            if ( ! empty( $vars ) ) {
3809                if ( isset( $var_map[ $vars[0] ] ) ) {
3810                    $fields[ $var_map[ $vars[0] ] ] = self::strip_tags( trim( $vars[1] ) );
3811                }
3812            }
3813        }
3814        // All fields should always be an array, even if empty.
3815        if ( ! is_array( $all_values ) ) {
3816            $all_values = array();
3817        }
3818        $fields['_feedback_all_fields'] = array();
3819        foreach ( $all_values as $key => $value ) {
3820            $fields['_feedback_all_fields'][ wp_strip_all_tags( $key ) ] = $value;
3821        }
3822
3823        return $fields;
3824    }
3825
3826    /**
3827     * Parse the contact form fields.
3828     *
3829     * @param int $post_id - the post ID.
3830     * @return array Fields.
3831     */
3832    public static function parse_fields_from_content( $post_id ) {
3833        $response = Feedback::get( $post_id );
3834
3835        if ( $response instanceof Feedback ) {
3836            return $response->get_all_legacy_values();
3837        }
3838
3839        return array();
3840    }
3841
3842    /**
3843     * Creates a valid csv row from a post id
3844     *
3845     * @param int   $post_id The id of the post.
3846     * @param array $fields  An array containing the names of all the fields of the csv.
3847     *
3848     * @return String The csv row
3849     *
3850     * @deprecated This is no longer needed, as of the CSV export rewrite.
3851     */
3852    protected static function make_csv_row_from_feedback( $post_id, $fields ) {
3853        $content_fields = self::parse_fields_from_content( $post_id );
3854        $all_fields     = array();
3855
3856        if ( isset( $content_fields['_feedback_all_fields'] ) ) {
3857            $all_fields = $content_fields['_feedback_all_fields'];
3858        }
3859
3860        // Overwrite the parsed content with the content we stored in post_meta in a better format.
3861        $extra_fields = get_post_meta( $post_id, '_feedback_extra_fields', true );
3862        foreach ( $extra_fields as $extra_field => $extra_value ) {
3863            $all_fields[ $extra_field ] = $extra_value;
3864        }
3865
3866        // The first element in all of the exports will be the subject
3867        $row_items   = array();
3868        $row_items[] = $content_fields['_feedback_subject'];
3869
3870        // Loop the fields array in order to fill the $row_items array correctly
3871        foreach ( $fields as $field ) {
3872            if ( $field === __( 'Contact Form', 'jetpack-forms' ) ) { // the first field will ever be the contact form, so we can continue
3873                continue;
3874            } elseif ( array_key_exists( $field, $all_fields ) ) {
3875                $row_items[] = $all_fields[ $field ];
3876            } else {
3877                $row_items[] = '';
3878            }
3879        }
3880
3881        return $row_items;
3882    }
3883
3884    /**
3885     * Get the IP address.
3886     *
3887     * @return string|null IP address.
3888     */
3889    public static function get_ip_address() {
3890        return isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : null;
3891    }
3892
3893    /**
3894     * Control Block Editor usage for form-related post types.
3895     *
3896     * Disables the Block Editor for feedback (form responses) and
3897     * forces it on for jetpack_form (form definitions), even if the
3898     * Classic Editor plugin is active.
3899     *
3900     * @param bool   $can_edit Whether the post type can be edited or not.
3901     * @param string $post_type The post type being checked.
3902     * @return bool
3903     */
3904    public function use_block_editor_for_post_type( $can_edit, $post_type ) {
3905        if ( 'feedback' === $post_type ) {
3906            return false;
3907        }
3908
3909        if ( Contact_Form::POST_TYPE === $post_type ) {
3910            return true;
3911        }
3912
3913        return $can_edit;
3914    }
3915
3916    /**
3917     * Force the Block Editor for jetpack_form posts, even if the
3918     * Classic Editor plugin is active.
3919     *
3920     * @param bool    $can_edit Whether the post can be edited or not.
3921     * @param WP_Post $post    The post being checked.
3922     * @return bool
3923     */
3924    public function use_block_editor_for_post( $can_edit, $post ) {
3925        if ( Contact_Form::POST_TYPE === get_post_type( $post ) ) {
3926            return true;
3927        }
3928
3929        return $can_edit;
3930    }
3931
3932    /**
3933     * Restrict comments on feedback posts to logged-in users only.
3934     * Hooks into comment permissions to enforce authentication requirement.
3935     *
3936     * For feedback posts, we override the comment_status field (which we use
3937     * for read/unread tracking) and always allow comments for logged-in users.
3938     *
3939     * @param bool $open    Whether comments are open.
3940     * @param int  $post_id Post ID.
3941     * @return bool Whether comments are open for this post.
3942     */
3943    public function restrict_feedback_comments_to_logged_in( $open, $post_id ) {
3944        $post = get_post( $post_id );
3945
3946        if ( ! $post || 'feedback' !== $post->post_type ) {
3947            return $open;
3948        }
3949
3950        // For feedback posts, comments are always open for users that can read pages.
3951        // regardless of comment_status (which we use for read/unread tracking).
3952        return current_user_can( 'edit_pages' );
3953    }
3954
3955    /**
3956     * Kludge method: reverses the output of a standard print_r( $array ).
3957     * Sort of what unserialize does to a serialized object.
3958     * This is here while we work on a better data storage inside the posts. See:
3959     * - p1675781140892129-slack-C01CSBEN0QZ
3960     * - https://www.php.net/manual/en/function.print-r.php#93529
3961     *
3962     * @param string $print_r_output The array string to be reverted. Needs to being with 'Array'.
3963     * @param bool   $parse_html Whether to run html_entity_decode on each line.
3964     *                           As strings are stored right now, they are all escaped, so '=>' are '&gt;'.
3965     * @return array|string Array when successfully reconstructed, string otherwise. Output will always be esc_html'd.
3966     */
3967    public static function reverse_that_print( $print_r_output, $parse_html = false ) {
3968        $lines = explode( "\n", trim( $print_r_output ) );
3969        if ( $parse_html ) {
3970            $lines = array_map( 'html_entity_decode', $lines );
3971        }
3972
3973        if ( trim( $lines[0] ) !== 'Array' ) {
3974            // bottomed out to something that isn't an array, escape it and be done
3975            return esc_html( $print_r_output );
3976        } else {
3977            // this is an array, lets parse it
3978            if ( preg_match( '/(\s{5,})\(/', $lines[1], $match ) ) {
3979                // this is a tested array/recursive call to this function
3980                // take a set of spaces off the beginning
3981                $spaces        = $match[1];
3982                $spaces_length = strlen( $spaces );
3983                $lines_total   = count( $lines );
3984
3985                for ( $i = 0; $i < $lines_total; $i++ ) {
3986                    if ( substr( $lines[ $i ], 0, $spaces_length ) === $spaces ) {
3987                        $lines[ $i ] = substr( $lines[ $i ], $spaces_length );
3988                    }
3989                }
3990            }
3991
3992            array_splice( $lines, 0, 2 ); // Remove first two items: 'Array' and '('.
3993            array_pop( $lines ); // Remove last item: ')'.
3994            $print_r_output = implode( "\n", $lines );
3995
3996            // make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one
3997            preg_match_all( '/^\s{4}\[(.+?)\] \=\> /m', $print_r_output, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER );
3998
3999            $pos          = array();
4000            $previous_key = '';
4001            $in_length    = strlen( $print_r_output );
4002
4003            // store the following in $pos:
4004            // array with key = key of the parsed array's item
4005            // value = array(start position in $print_r_output, $end position in $print_r_output)
4006            foreach ( $matches as $match ) {
4007                $key         = $match[1][0];
4008                $start       = $match[0][1] + strlen( $match[0][0] );
4009                $pos[ $key ] = array( $start, $in_length );
4010
4011                if ( $previous_key !== '' ) {
4012                    $pos[ $previous_key ][1] = $match[0][1] - 1;
4013                }
4014
4015                $previous_key = $key;
4016            }
4017
4018            $ret = array();
4019
4020            foreach ( $pos as $key => $where ) {
4021                // recursively see if the parsed out value is an array too
4022                $ret[ $key ] = self::reverse_that_print( substr( $print_r_output, $where[0], $where[1] - $where[0] ), $parse_html );
4023            }
4024
4025            return $ret;
4026        }
4027    }
4028
4029    /**
4030     * Method untrash_feedback_status_handler
4031     * wp_untrash_post filter handler.
4032     *
4033     * @param string $current_status   The status to be set.
4034     * @param int    $post_id          The post ID.
4035     * @param string $previous_status  The previous status.
4036     */
4037    public function untrash_feedback_status_handler( $current_status, $post_id, $previous_status ) {
4038        $post = get_post( $post_id );
4039        if ( 'feedback' === $post->post_type ) {
4040            if ( in_array( $previous_status, array( 'spam', 'publish' ), true ) ) {
4041                return $previous_status;
4042            }
4043            return 'publish';
4044        }
4045        return $current_status;
4046    }
4047
4048    /**
4049     * Tracks when a feedback post status changes to 'spam' and stores the timestamp.
4050     * This allows us to accurately determine when spam was marked, independent of other post updates.
4051     *
4052     * @param string       $new_status The new post status.
4053     * @param string       $old_status The old post status.
4054     * @param WP_Post|null $post       The post object, when available.
4055     *
4056     * @deprecated since 7.5.0
4057     */
4058    public function track_spam_status_change( $new_status, $old_status, ?WP_Post $post = null ) {
4059        _deprecated_function( __METHOD__, 'package-jetpack-forms-7.5.0' );
4060
4061        if ( ! $post instanceof WP_Post ) {
4062            // Some callers fire the action without a populated post object (e.g. failed get_post lookups).
4063            return;
4064        }
4065
4066        // Only track for feedback posts
4067        if ( 'feedback' !== $post->post_type ) {
4068            return;
4069        }
4070
4071        $this->track_spam_status( $new_status, $old_status, $post->ID );
4072    }
4073
4074    /**
4075     * Tracks when a feedback post status changes and triggers related handlers.
4076     * Used to handle spam meta tracking and unread count recalculation for feedback posts.
4077     *
4078     * @param string       $new_status The new post status.
4079     * @param string       $old_status The old post status.
4080     * @param WP_Post|null $post       The post object, when available.
4081     */
4082    public function track_feedback_status_change( $new_status, $old_status, ?WP_Post $post = null ) {
4083        if ( ! $post instanceof WP_Post ) {
4084            // Some callers fire the action without a populated post object (e.g. failed get_post lookups).
4085            return;
4086        }
4087
4088        // Only track for feedback posts
4089        if ( 'feedback' !== $post->post_type ) {
4090            return;
4091        }
4092        $this->track_spam_status( $new_status, $old_status, $post->ID );
4093        $this->track_recount_unread( $new_status, $old_status, $post );
4094    }
4095
4096    /**
4097     * Purges the edge cache when a jetpack_form post is published, updated while published, or unpublished.
4098     *
4099     * @param string       $new_status The new post status.
4100     * @param string       $old_status The old post status.
4101     * @param WP_Post|null $post       The post object, when available.
4102     */
4103    public function purge_edge_cache_on_form_status_change( $new_status, $old_status, ?WP_Post $post = null ) {
4104        if ( ! $post instanceof WP_Post ) {
4105            return;
4106        }
4107
4108        if ( Contact_Form::POST_TYPE !== $post->post_type ) {
4109            return;
4110        }
4111
4112        if ( 'publish' === $new_status || 'publish' === $old_status ) {
4113            /**
4114             * Fires when the edge cache for the entire domain should be purged.
4115             *
4116             * This action is handled by the WordPress.com hosting platform
4117             * and has no effect in self-hosted WordPress environments.
4118             */
4119            do_action( 'edge_cache_purge_domain' );
4120        }
4121    }
4122
4123    /**
4124     * Tracks when a feedback post status changes to 'spam' and stores the timestamp.
4125     * This allows us to accurately determine when spam was marked, independent of other post updates.
4126     *
4127     * @param string $new_status The new post status.
4128     * @param string $old_status The old post status.
4129     * @param int    $post_id    The post ID.
4130     */
4131    private function track_spam_status( $new_status, $old_status, $post_id ) {
4132        // Only track when status changes TO spam (not from spam to something else)
4133        if ( 'spam' === $new_status && 'spam' !== $old_status ) {
4134            // Store the current GMT timestamp when status changes to spam
4135            update_post_meta( $post_id, '_spam_status_changed_gmt', current_time( 'mysql', 1 ) );
4136        } elseif ( 'spam' === $old_status && 'spam' !== $new_status ) {
4137            // Remove the meta when post is no longer spam
4138            delete_post_meta( $post_id, '_spam_status_changed_gmt' );
4139        }
4140    }
4141
4142    /**
4143     * Tracks when a feedback post status changes to or from 'publish' and triggers unread count recalculation.
4144     *
4145     * @param string  $new_status The new post status.
4146     * @param string  $old_status The old post status.
4147     * @param WP_Post $post       The post object.
4148     */
4149    private function track_recount_unread( $new_status, $old_status, WP_Post $post ) {
4150        // If the feedback is already marked as read, it doesn't matter if its status changes.
4151        if ( $post->comment_status === Feedback::STATUS_READ ) {
4152            return;
4153        }
4154
4155        // If the status changed to or from 'publish', we need to recount unread feedbacks.
4156        if ( ( 'publish' === $new_status && 'publish' !== $old_status ) ||
4157            ( 'publish' === $old_status && 'publish' !== $new_status ) ) {
4158            add_action( 'shutdown', array( __CLASS__, 'recalculate_unread_count' ) );
4159        }
4160    }
4161
4162    /**
4163     * Returns whether we are in condition to track and use
4164     * analytics functionality like Tracks.
4165     *
4166     * @return bool Returns true if we can track analytics, else false.
4167     */
4168    public static function can_use_analytics() {
4169        $is_wpcom               = defined( 'IS_WPCOM' ) && IS_WPCOM;
4170        $status                 = new Status();
4171        $connection             = new Connection_Manager();
4172        $tracking               = new Tracking( 'jetpack', $connection );
4173        $should_enable_tracking = $tracking->should_enable_tracking( new Terms_Of_Service(), $status );
4174
4175        return $is_wpcom || $should_enable_tracking;
4176    }
4177
4178    /**
4179     * Render the rating field.
4180     *
4181     * @param array    $atts - the block attributes.
4182     * @param string   $content - html content.
4183     * @param WP_Block $block - the block instance object.
4184     *
4185     * @return string HTML for the contact form field.
4186     */
4187    public static function gutenblock_render_field_rating( $atts, $content, $block ) {
4188        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'rating', $block );
4189        return Contact_Form::parse_contact_field( $atts, $content, $block );
4190    }
4191
4192    /**
4193     * Render the slider field.
4194     *
4195     * @param array    $atts - the block attributes.
4196     * @param string   $content - html content.
4197     * @param WP_Block $block - the block instance object.
4198     *
4199     * @return string HTML for the contact form field.
4200     */
4201    public static function gutenblock_render_field_slider( $atts, $content, $block ) {
4202        // Get min, max, and default from the parent block's attributes.
4203        $parent_attrs     = $block->parsed_block['attrs'] ?? array();
4204        $atts['min']      = $parent_attrs['min'] ?? 0;
4205        $atts['max']      = $parent_attrs['max'] ?? 100;
4206        $atts['default']  = $parent_attrs['default'] ?? 0;
4207        $atts['step']     = $parent_attrs['step'] ?? 1;
4208        $atts['minLabel'] = $parent_attrs['minLabel'] ?? '';
4209        $atts['maxLabel'] = $parent_attrs['maxLabel'] ?? '';
4210
4211        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'slider', $block );
4212        return Contact_Form::parse_contact_field( $atts, $content, $block );
4213    }
4214
4215    /**
4216     * Redirect users from the edit-feedback and edit-jetpack_form screens to the Jetpack Forms admin page.
4217     *
4218     * This method is hooked to 'current_screen' and redirects:
4219     * - edit-jetpack_form: to &p=/forms
4220     * - edit-feedback: to &p=/responses/inbox
4221     *
4222     * @since 6.0.0
4223     */
4224    public function redirect_edit_feedback_to_jetpack_forms() {
4225        if ( ! function_exists( 'get_current_screen' ) ) {
4226            return;
4227        }
4228
4229        $screen = get_current_screen();
4230
4231        if ( ! $screen || ! isset( $screen->id ) ) {
4232            return;
4233        }
4234
4235        // Don't redirect if we're already on the Forms admin page (prevents redirect loop).
4236        if ( Dashboard::is_jetpack_forms_admin_page() ) {
4237            return;
4238        }
4239
4240        $redirect = null;
4241
4242        if ( 'edit-jetpack_form' === $screen->id ) {
4243            $redirect = Dashboard::get_forms_admin_url( 'forms' );
4244        } elseif ( 'edit-feedback' === $screen->id ) {
4245            $redirect = Dashboard::get_forms_admin_url( 'inbox' );
4246        }
4247
4248        if ( $redirect ) {
4249            wp_safe_redirect( $redirect );
4250            exit;
4251        }
4252    }
4253
4254    /**
4255     * Validates the export to Google Drive request.
4256     *
4257     * @param array $post_data The POST data to validate.
4258     * @return bool True if the request is valid, false otherwise.
4259     */
4260    public function validate_export_to_gdrive_request( $post_data ) {
4261        if ( ! current_user_can( 'export' ) ) {
4262            return false;
4263        }
4264
4265        if ( empty( $post_data[ $this->export_nonce_field_gdrive ] ) ) {
4266            return false;
4267        }
4268
4269        $nonce = sanitize_text_field( $post_data[ $this->export_nonce_field_gdrive ] );
4270        if ( ! wp_verify_nonce( $nonce, 'feedback_export' ) ) {
4271            return false;
4272        }
4273
4274        return true;
4275    }
4276
4277    /**
4278     * Ajax handler for wp_ajax_grunion_export_to_gdrive.
4279     * Exports data to Google Drive, based on POST data.
4280     *
4281     * @see Contact_Form_Plugin::get_feedback_entries_from_post
4282     * @return never
4283     */
4284    public function export_to_gdrive() {
4285        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verification is done on validate_export_to_gdrive_request function
4286        $post_data = wp_unslash( $_POST );
4287
4288        if ( ! $this->validate_export_to_gdrive_request( $post_data ) ) {
4289            wp_send_json_error(
4290                __( 'You aren\'t authorized to do that.', 'jetpack-forms' ),
4291                403,
4292                JSON_UNESCAPED_SLASHES
4293            );
4294        }
4295
4296        $grunion = self::init();
4297        $rows    = $grunion->get_export_rows_from_post();
4298
4299        // Google Sheets rejects the whole export if any cell is over 50,000 characters.
4300        $esc_cell = function ( $value ) {
4301            $value = $this->esc_csv( $value );
4302            return is_string( $value ) && mb_strlen( $value ) > 50000 ? mb_substr( $value, 0, 50000 ) : $value;
4303        };
4304
4305        // WordPress.com refuses Sheets requests of about 20 MB, so stop before building one.
4306        $max_bytes  = 15 * MB_IN_BYTES;
4307        $bytes      = 0;
4308        $sheet_data = array();
4309        foreach ( $rows ?? array() as $row ) {
4310            $row    = empty( $sheet_data ) ? $row : array_map( $esc_cell, $row );
4311            $bytes += strlen( (string) wp_json_encode( $row, JSON_UNESCAPED_SLASHES ) );
4312            if ( $bytes > $max_bytes ) {
4313                wp_send_json_error(
4314                    array(
4315                        'code'    => 'export_too_large',
4316                        'message' => __( 'This export is too large for Google Sheets. Export fewer responses, or download a CSV file instead.', 'jetpack-forms' ),
4317                    ),
4318                    413,
4319                    JSON_UNESCAPED_SLASHES
4320                );
4321            }
4322            $sheet_data[] = $row;
4323        }
4324        if ( empty( $sheet_data ) ) {
4325            $sheet_data[] = array();
4326        }
4327
4328        $user_id = (int) get_current_user_id();
4329
4330        if ( ! empty( $post_data['post'] ) && $post_data['post'] !== 'all' ) {
4331            $spreadsheet_title = sprintf(
4332                '%1$s - %2$s',
4333                Util::get_export_filename( get_the_title( (int) $post_data['post'] ) ),
4334                gmdate( 'Y-m-d H:i' )
4335            );
4336        } else {
4337            $spreadsheet_title = sprintf( '%s - %s', Util::get_export_filename(), gmdate( 'Y-m-d H:i' ) );
4338        }
4339
4340        $sheet = Google_Drive::create_sheet( $user_id, $spreadsheet_title, $sheet_data );
4341
4342        $grunion->record_tracks_event( 'forms_export_responses', array( 'format' => 'gsheets' ) );
4343
4344        wp_send_json(
4345            array(
4346                'success' => ! is_wp_error( $sheet ),
4347                'data'    => $sheet,
4348            ),
4349            is_wp_error( $sheet ) ? 500 : 200,
4350            JSON_UNESCAPED_SLASHES
4351        );
4352    }
4353}