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