Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
45.20% covered (danger)
45.20%
688 / 1522
29.70% covered (danger)
29.70%
30 / 101
CRAP
0.00% covered (danger)
0.00%
0 / 1
Contact_Form_Plugin
45.26% covered (danger)
45.26%
688 / 1520
29.70% covered (danger)
29.70%
30 / 101
45727.02
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%
16 / 16
100.00% covered (success)
100.00%
1 / 1
6
 validate_parent_post
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
5
 insert_feedback_filter
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 add_shortcode
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 tokenize_label
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 sanitize_value
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 format_value_for_display
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 replace_tokens_with_input
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
3.03
 track_current_widget
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 track_current_widget_before
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 track_current_widget_after
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 get_current_widget_context
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 widget_atts
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 widget_shortcode_hack
n/a
0 / 0
n/a
0 / 0
2
 is_spam_blocklist
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 is_in_disallowed_list
83.33% covered (warning)
83.33%
10 / 12
0.00% covered (danger)
0.00%
0 / 1
3.04
 prepare_for_akismet
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
9
 is_spam_akismet
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
156
 akismet_submit
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 form_posts_dropdown
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 get_post_content_for_csv_export
n/a
0 / 0
n/a
0 / 0
1
 get_post_meta_for_csv_export
0.00% covered (danger)
0.00%
0 / 31
0.00% covered (danger)
0.00%
0 / 1
240
 get_parsed_field_contents_of_post
n/a
0 / 0
n/a
0 / 0
1
 map_parsed_field_contents_of_post_to_field_names
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
30
 register_personal_data_exporter
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 register_personal_data_eraser
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 personal_data_exporter
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 internal_personal_data_exporter
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 internal_personal_data_formater
97.67% covered (success)
97.67%
42 / 43
0.00% covered (danger)
0.00%
0 / 1
5
 personal_data_eraser
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 _internal_personal_data_eraser
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
72
 personal_data_post_ids_by_email
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
6
 set_pde_email_address
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 personal_data_search_filter
90.48% covered (success)
90.48%
19 / 21
0.00% covered (danger)
0.00%
0 / 1
6.03
 get_export_feedback_data
100.00% covered (success)
100.00%
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 and
2008     * the Salesforce integration â€” are kept only when whoever placed the form had an
2009     * administrator-level capability (an admin author for post/page forms, or the
2010     * `edit_theme_options` required to author block templates, template parts and widgets);
2011     * otherwise they are removed from the form attributes in place, before the submission
2012     * is processed and the Form_Webhooks / Post_To_Url services read those attributes. The
2013     * mutation is safe because nothing re-reads the original attribute values within the request
2014     * and the form attributes are not persisted after this point.
2015     *
2016     * Webhooks supplied via the jetpack_forms_extra_webhooks filter (JWT submissions only) are
2017     * applied by the caller afterwards and are never affected here.
2018     *
2019     * @param Contact_Form $form The form whose attributes may be modified in place.
2020     */
2021    private function reconcile_content_destinations( Contact_Form $form ) {
2022        if ( empty( $form->attributes['webhooks'] )
2023            && empty( $form->attributes['postToUrl'] )
2024            && empty( $form->attributes['salesforceData'] ) ) {
2025            return;
2026        }
2027
2028        $source = $form->get_source();
2029        if ( ! Jetpack_Forms::should_honor_content_destinations( $source->get_id(), $source->get_source_type() ) ) {
2030            // Drop every content-configured destination before the services read them.
2031            // postToUrl and salesforceData are read directly by Post_To_Url.
2032            $form->attributes['webhooks']       = array();
2033            $form->attributes['postToUrl']      = array();
2034            $form->attributes['salesforceData'] = null;
2035
2036            /** This action is documented already in this file. */
2037            do_action( 'jetpack_forms_log', 'content_destinations_dropped', 'author_unauthorized' );
2038            return;
2039        }
2040
2041        // Deprecate postToUrl, migrate to webhooks in case someone put it to work.
2042        if ( ! empty( $form->attributes['postToUrl'] ) ) {
2043            // webhooks should be a collection.
2044            // Turn postToUrl into a collection and merge with existing webhooks.
2045            $form->attributes['webhooks'] = array_merge(
2046                $form->attributes['webhooks'] ?? array(),
2047                array( $form->attributes['postToUrl'] )
2048            );
2049        }
2050    }
2051
2052    /**
2053     * Validates that the parent post/page where the form lives still exists and is not trashed/deleted.
2054     *
2055     * @param Contact_Form $form The contact form instance.
2056     * @return Form_Submission_Error|null Returns a Form_Submission_Error if validation fails, null otherwise.
2057     */
2058    private function validate_parent_post( Contact_Form $form ) {
2059        $source    = $form->get_source();
2060        $source_id = $source->get_id();
2061
2062        // Only check for regular posts/pages (numeric IDs), not widgets or templates
2063        if ( is_numeric( $source_id ) && $source_id > 0 ) {
2064            $parent_post = get_post( (int) $source_id );
2065
2066            // If the parent post doesn't exist or is not trashed/deleted, reject the submission
2067            if ( ! $parent_post || in_array( $parent_post->post_status, array( 'trash', 'auto-draft' ), true ) ) {
2068                /** This action is documented already in this file. */
2069                do_action( 'jetpack_forms_log', 'submission_rejected_parent_trashed_or_deleted' );
2070
2071                return Form_Submission_Error::system_error(
2072                    'form_unavailable',
2073                    __( 'This form is no longer available.', 'jetpack-forms' )
2074                );
2075            }
2076        }
2077
2078        return null;
2079    }
2080
2081    /**
2082     * Ensure the post author is always zero for contact-form feedbacks
2083     * Attached to `wp_insert_post_data`
2084     *
2085     * @see Contact_Form::process_submission()
2086     *
2087     * @param array $data the data to insert.
2088     * @param array $postarr the data sent to wp_insert_post().
2089     * @return array The filtered $data to insert.
2090     */
2091    public function insert_feedback_filter( $data, $postarr ) {
2092        if ( $data['post_type'] === 'feedback' && $postarr['post_type'] === 'feedback' ) {
2093            $data['post_author'] = 0;
2094        }
2095
2096        return $data;
2097    }
2098
2099    /**
2100     * Adds our contact-form shortcode
2101     * The "child" contact-field shortcode is enabled as needed by the contact-form shortcode handler
2102     */
2103    public function add_shortcode() {
2104        add_shortcode( 'contact-form', array( '\Automattic\Jetpack\Forms\ContactForm\Contact_Form', 'parse' ) );
2105        add_shortcode( 'contact-field', array( '\Automattic\Jetpack\Forms\ContactForm\Contact_Form', 'parse_contact_field' ) );
2106
2107        // We need 'contact-field-option' to be registered, so it's included to the get_shortcode_regex() method
2108        // But we don't need a callback because we're handling contact-field-option manually
2109        add_shortcode( 'contact-field-option', '__return_null' );
2110    }
2111
2112    /**
2113     * Tokenize the label.
2114     *
2115     * @param string $label - the label.
2116     *
2117     * @return string
2118     */
2119    public static function tokenize_label( $label ) {
2120        return '{' . trim( wp_strip_all_tags( preg_replace( '#^\d+_#', '', $label ) ) ) . '}';
2121    }
2122
2123    /**
2124     * Sanitizes the value of a field.
2125     *
2126     * @param string|array|null $value The value to sanitize.
2127     * @return string The sanitized value.
2128     */
2129    public static function sanitize_value( $value ) {
2130        if ( null === $value ) {
2131            return '';
2132        }
2133
2134        // If value is an array, convert it to a comma-separated string
2135        if ( is_array( $value ) ) {
2136            return implode( ', ', array_map( array( __CLASS__, 'sanitize_value' ), $value ) );
2137        }
2138
2139        return preg_replace( '=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i', '', $value );
2140    }
2141
2142    /**
2143     * Sanitizes and formats values for display, ensuring arrays are properly converted to strings.
2144     *
2145     * @param mixed $value The value to format.
2146     * @return string|array The formatted value ready for display or file array for upload fields.
2147     */
2148    public static function format_value_for_display( $value ) {
2149        if ( is_array( $value ) ) {
2150            // Check if this is a file upload field
2151            if ( Contact_Form::is_file_upload_field( $value ) ) {
2152                // This is a file upload field, return as is to be handled by the proper renderer
2153                return $value;
2154            }
2155
2156            // Process each array element recursively and join with commas
2157            $formatted_values = array();
2158            foreach ( $value as $key => $item ) {
2159                $formatted_values[] = is_numeric( $key ) ? self::format_value_for_display( $item ) : "$key: " . self::format_value_for_display( $item );
2160            }
2161            return implode( ', ', $formatted_values );
2162        }
2163
2164        // Simple value, just convert to string
2165        return (string) $value;
2166    }
2167
2168    /**
2169     * Replaces tokens like {city} or {City} (case insensitive) with the value
2170     * of an input field of that name
2171     *
2172     * @param string $subject - the subject.
2173     * @param array  $field_values Array with field label => field value associations.
2174     *
2175     * @return string The filtered $subject with the tokens replaced.
2176     */
2177    public function replace_tokens_with_input( $subject, $field_values ) {
2178        // Wrap labels into tokens (inside {})
2179        $wrapped_labels = array_map( array( '\Automattic\Jetpack\Forms\ContactForm\Contact_Form_Plugin', 'tokenize_label' ), array_keys( $field_values ) );
2180        // Sanitize all values
2181        $sanitized_values = array_map( array( '\Automattic\Jetpack\Forms\ContactForm\Contact_Form_Plugin', 'sanitize_value' ), array_values( $field_values ) );
2182
2183        foreach ( $sanitized_values as $k => $sanitized_value ) {
2184            if ( is_array( $sanitized_value ) ) {
2185                $sanitized_values[ $k ] = implode( ', ', $sanitized_value );
2186            }
2187        }
2188
2189        // Search for all valid tokens (based on existing fields) and replace with the field's value
2190        $subject = str_ireplace( $wrapped_labels, $sanitized_values, $subject );
2191        return $subject;
2192    }
2193
2194    /**
2195     * Tracks the widget currently being processed.
2196     * Attached to `dynamic_sidebar`
2197     *
2198     * @see $current_widget_id - the current widget ID.
2199     *
2200     * @param array $widget The widget data.
2201     */
2202    public function track_current_widget( $widget ) {
2203        $this->current_widget_id = $widget['id'] ?? '';
2204    }
2205
2206    /**
2207     * Tracks the sidebar currently being processed.
2208     * Attached to `dynamic_sidebar_before`
2209     *
2210     * @see $current_sidebar_id - the current sidebar ID.
2211     *
2212     * @param string $index The sidebar index.
2213     */
2214    public function track_current_widget_before( $index ) {
2215        $this->current_sidebar_id = $index;
2216    }
2217
2218    /**
2219     * Clear the current widget context.
2220     */
2221    public function track_current_widget_after() {
2222        $this->current_sidebar_id = '';
2223        $this->current_widget_id  = '';
2224    }
2225
2226    /**
2227     * Gets the current widget context.
2228     *
2229     * @return string The current widget context or false if not set.
2230     */
2231    public function get_current_widget_context() {
2232        // If we don't have a current widget ID or sidebar ID, we
2233        if ( empty( $this->current_widget_id ) || empty( $this->current_sidebar_id ) ) {
2234            return '';
2235        }
2236        return $this->current_widget_id . '-' . $this->current_sidebar_id;
2237    }
2238
2239    /**
2240     * Adds a "widget" attribute to every contact-form embedded in a text widget.
2241     * Used to tell the difference between post-embedded contact-forms and widget-embedded contact-forms
2242     * Attached to `widget_text`
2243     *
2244     * @param string $text The widget text.
2245     *
2246     * @return string The filtered widget text.
2247     */
2248    public function widget_atts( $text ) {
2249        Contact_Form::style( true );
2250
2251        return preg_replace( '/\[contact-form([^a-zA-Z_-])/', '[contact-form widget="' . $this->current_widget_id . '"\\1', $text );
2252    }
2253
2254    /**
2255     * For sites where text widgets are not processed for shortcodes, we add this hack to process just our shortcode
2256     * Attached to `widget_text`
2257     *
2258     * @param string $text The widget text.
2259     *
2260     * @return string The contact-form filtered widget text
2261     *
2262     * @deprecated $$next-version$$ Core processes shortcodes in text widgets since WordPress 4.9.
2263     */
2264    public function widget_shortcode_hack( $text ) {
2265        _deprecated_function( __METHOD__, 'package-$$next-version$$' );
2266
2267        if ( ! preg_match( '/\[contact-form([^a-zA-Z_-])/', $text ) ) {
2268            return $text;
2269        }
2270
2271        $old = $GLOBALS['shortcode_tags'];
2272        remove_all_shortcodes();
2273        self::$using_contact_form_field = true;
2274        $this->add_shortcode();
2275
2276        $text = apply_shortcodes( $text );
2277
2278        self::$using_contact_form_field = false;
2279        $GLOBALS['shortcode_tags']      = $old; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
2280
2281        return $text;
2282    }
2283
2284    /**
2285     * Check if a submission matches the Comment Blocklist.
2286     * The Comment Blocklist is a means to moderate discussion, and contact
2287     * forms are 1:1 discussion forums, ripe for abuse by users who are being
2288     * removed from the public discussion.
2289     * Attached to `jetpack_contact_form_is_spam`
2290     *
2291     * @param bool  $is_spam - if the submission is spam.
2292     * @param array $form - the form data.
2293     * @return bool TRUE => spam, FALSE => not spam
2294     */
2295    public function is_spam_blocklist( $is_spam, $form = array() ) {
2296        if ( $is_spam ) {
2297            return $is_spam;
2298        }
2299
2300        return $this->is_in_disallowed_list( false, $form );
2301    }
2302
2303    /**
2304     * Check if a submission matches the comment disallowed list.
2305     * Attached to `jetpack_contact_form_in_comment_disallowed_list`.
2306     *
2307     * @param boolean $in_disallowed_list Whether the feedback is in the disallowed list.
2308     * @param array   $form The form array.
2309     * @return bool Returns true if the form submission matches the disallowed list and false if it doesn't.
2310     */
2311    public function is_in_disallowed_list( $in_disallowed_list, $form = array() ) {
2312        if ( $in_disallowed_list ) {
2313            return $in_disallowed_list;
2314        }
2315
2316        if (
2317            wp_check_comment_disallowed_list(
2318                $form['comment_author'],
2319                $form['comment_author_email'],
2320                $form['comment_author_url'],
2321                $form['comment_content'],
2322                $form['user_ip'],
2323                $form['user_agent']
2324            )
2325        ) {
2326            return true;
2327        }
2328
2329        return false;
2330    }
2331
2332    /**
2333     * Populate an array with all values necessary to submit a NEW contact-form feedback to Akismet.
2334     * Note that this includes the current user_ip etc, so this should only be called when accepting a new item via $_POST
2335     *
2336     * @param array $form - contact form feedback array.
2337     *
2338     * @return array feedback array with additional data ready for submission to Akismet.
2339     */
2340    public function prepare_for_akismet( $form ) {
2341        $form['comment_type']     = 'contact_form';
2342        $form['user_ip']          = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
2343        $form['user_agent']       = isset( $_SERVER['HTTP_USER_AGENT'] ) ? filter_var( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
2344        $form['referrer']         = isset( $_SERVER['HTTP_REFERER'] ) ? esc_url_raw( wp_unslash( $_SERVER['HTTP_REFERER'] ) ) : '';
2345        $form['blog']             = get_option( 'home' );
2346        $form['blog_lang']        = get_bloginfo( 'language' );
2347        $form['comment_date_gmt'] = gmdate( DATE_ATOM, time() ); // ISO 8601. See https://www.php.net/manual/en/class.datetimeinterface.php#datetimeinterface.constants.types
2348
2349        foreach ( $_SERVER as $key => $value ) {
2350            if ( ! is_string( $value ) ) {
2351                continue;
2352            }
2353            if ( in_array( $key, array( 'HTTP_COOKIE', 'HTTP_COOKIE2', 'HTTP_USER_AGENT', 'HTTP_REFERER' ), true ) ) {
2354                // We don't care about cookies, and the UA and Referrer were caught above.
2355                continue;
2356            } elseif ( in_array( $key, array( 'REMOTE_ADDR', 'REQUEST_URI', 'DOCUMENT_URI' ), true ) ) {
2357                // All three of these are relevant indicators and should be passed along.
2358                $form[ $key ] = $value;
2359            } elseif ( str_starts_with( $key, 'HTTP_' ) ) {
2360                // Any other HTTP header indicators.
2361                $form[ $key ] = $value;
2362            }
2363        }
2364
2365        /**
2366         * Filter the values that are sent to Akismet for the spam check.
2367         *
2368         * @module contact-form
2369         *
2370         * @since 10.2.0
2371         *
2372         * @param array $form The form values being sent to Akismet.
2373         */
2374        return apply_filters( 'jetpack_contact_form_akismet_values', $form );
2375    }
2376
2377    /**
2378     * Submit contact-form data to Akismet to check for spam.
2379     * If you're accepting a new item via $_POST, run it Contact_Form_Plugin::prepare_for_akismet() first
2380     * Attached to `jetpack_contact_form_is_spam`
2381     *
2382     * @param bool  $is_spam - if the submission is spam.
2383     * @param array $form - the form data.
2384     * @return bool|WP_Error TRUE => spam, FALSE => not spam, WP_Error => stop processing entirely
2385     */
2386    public function is_spam_akismet( $is_spam, $form = array() ) {
2387        global $akismet_api_host, $akismet_api_port;
2388
2389        // The signature of this function changed from accepting just $form.
2390        // If something only sends an array, assume it's still using the old
2391        // signature and work around it.
2392        if ( empty( $form ) && is_array( $is_spam ) ) {
2393            $form    = $is_spam;
2394            $is_spam = false;
2395        }
2396
2397        // If a previous filter has alrady marked this as spam, trust that and move on.
2398        if ( $is_spam ) {
2399            return $is_spam;
2400        }
2401
2402        if ( ! function_exists( 'akismet_http_post' ) && ! defined( 'AKISMET_VERSION' ) ) {
2403            return false;
2404        }
2405
2406        $query_string = http_build_query( $form );
2407
2408        if ( method_exists( 'Akismet', 'http_post' ) ) {
2409            $response = \Akismet::http_post( $query_string, 'comment-check' );
2410        } else {
2411            $response = akismet_http_post( $query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port );
2412        }
2413
2414        $result = false;
2415
2416        if ( isset( $response[0]['x-akismet-pro-tip'] ) && 'discard' === trim( $response[0]['x-akismet-pro-tip'] ) && get_option( 'akismet_strictness' ) === '1' ) {
2417            $result = new WP_Error( 'feedback-discarded', __( 'Feedback discarded.', 'jetpack-forms' ) );
2418        } elseif ( isset( $response[1] ) && 'true' === trim( $response[1] ) ) { // 'true' is spam
2419            $result = true;
2420        }
2421
2422        /**
2423         * Filter the results returned by Akismet for each submitted contact form.
2424         *
2425         * @module contact-form
2426         *
2427         * @since 1.3.1
2428         *
2429         * @param WP_Error|bool $result Is the submitted feedback spam.
2430         * @param array|bool $form Submitted feedback.
2431         */
2432        return apply_filters( 'contact_form_is_spam_akismet', $result, $form );
2433    }
2434
2435    /**
2436     * Submit a feedback as either spam or ham
2437     *
2438     * @param string $as - Either 'spam' or 'ham'.
2439     * @param array  $form - the contact-form data.
2440     *
2441     * @return bool|string
2442     */
2443    public function akismet_submit( $as, $form ) {
2444        global $akismet_api_host, $akismet_api_port;
2445
2446        if ( ! in_array( $as, array( 'ham', 'spam' ), true ) ) {
2447            return false;
2448        }
2449
2450        $query_string = '';
2451        if ( is_array( $form ) ) {
2452            $query_string = http_build_query( $form );
2453        }
2454        if ( method_exists( 'Akismet', 'http_post' ) ) {
2455            $response = \Akismet::http_post( $query_string, "submit-{$as}" );
2456        } else {
2457            $response = akismet_http_post( $query_string, $akismet_api_host, "/1.1/submit-{$as}", $akismet_api_port );
2458        }
2459
2460        return trim( $response[1] );
2461    }
2462
2463    /**
2464     * Prints a dropdown of posts with forms.
2465     *
2466     * @param int $selected_id Currently selected post ID.
2467     * @return void
2468     */
2469    public static function form_posts_dropdown( $selected_id ) {
2470        ?>
2471        <select name="jetpack_form_parent_id">
2472            <option value="all"><?php esc_html_e( 'All sources', 'jetpack-forms' ); ?></option>
2473            <?php echo self::get_feedbacks_as_options( $selected_id ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML is escaped in the function. ?>
2474        </select>
2475        <?php
2476    }
2477
2478    /**
2479     * Fetch post content for a post and extract just the comment.
2480     *
2481     * @param int $post_id The post id to fetch the content for.
2482     *
2483     * @return string Trimmed post comment.
2484     *
2485     * @codeCoverageIgnore
2486     */
2487    public function get_post_content_for_csv_export( $post_id ) {
2488        $post_content = get_post_field( 'post_content', $post_id );
2489        $content      = explode( '<!--more-->', $post_content );
2490
2491        return trim( $content[0] );
2492    }
2493
2494    /**
2495     * Get `_feedback_extra_fields` field from post meta data.
2496     *
2497     * @param int  $post_id Id of the post to fetch meta data for.
2498     * @param bool $has_json_data Whether the post has JSON data or not, defaults to false for backwards compatibility.
2499     *
2500     * @return mixed
2501     */
2502    public function get_post_meta_for_csv_export( $post_id, $has_json_data = false ) {
2503        $content_fields = self::parse_fields_from_content( $post_id );
2504        $all_fields     = $content_fields['_feedback_all_fields'] ?? array();
2505        $md             = $has_json_data
2506            ? array_diff_key( $all_fields, array_flip( array_keys( self::NON_PRINTABLE_FIELDS ) ) )
2507            : (array) get_post_meta( $post_id, '_feedback_extra_fields', true );
2508
2509        $md['-3_response_date'] = get_the_date( 'Y-m-d H:i:s', $post_id );
2510        $md['93_ip_address']    = $content_fields['_feedback_ip'] ?? 0;
2511
2512        // add the email_marketing_consent to the post meta.
2513        $md['90_consent'] = 0;
2514        if ( ! empty( $all_fields ) ) {
2515            // check if the email_marketing_consent field exists.
2516            if ( isset( $all_fields['email_marketing_consent'] ) ) {
2517                $md['90_consent'] = $all_fields['email_marketing_consent'];
2518            }
2519
2520            // check if the feedback entry has a title.
2521            if ( isset( $all_fields['entry_title'] ) ) {
2522                $md['-9_title'] = $all_fields['entry_title'];
2523            }
2524
2525            // check if the feedback entry has a permalink we can use.
2526            if ( ! empty( $all_fields['entry_permalink'] ) ) {
2527                $parsed          = wp_parse_url( $all_fields['entry_permalink'] );
2528                $md['-6_source'] = '';
2529                if ( $parsed && ! empty( $parsed['path'] ) && strpos( $parsed['path'], '/' ) === 0 ) {
2530                    $md['-6_source'] .= $parsed['path'];
2531                }
2532                if ( $parsed && ! empty( $parsed['query'] ) ) {
2533                    $md['-6_source'] .= '?' . $parsed['query'];
2534                }
2535            }
2536        }
2537
2538        // flatten and decode all values.
2539        $result = array();
2540        foreach ( $md as $key => $value ) {
2541            if ( is_array( $value ) ) {
2542                if ( Contact_Form::is_file_upload_field( $value ) ) {
2543                    $file_names = array();
2544                    foreach ( $value['files'] as $file ) {
2545                        $file_names[] = $file['name'];
2546                    }
2547                    $value = implode( ', ', $file_names );
2548                } else {
2549                    $value = implode( ', ', $value );
2550                }
2551            }
2552            $result[ $key ] = html_entity_decode( $value, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 );
2553        }
2554
2555        return $result;
2556    }
2557
2558    /**
2559     * Get parsed feedback post fields.
2560     *
2561     * @param int $post_id Id of the post to fetch parsed contents for.
2562     *
2563     * @return array
2564     *
2565     * @codeCoverageIgnore - No need to be covered.
2566     */
2567    public function get_parsed_field_contents_of_post( $post_id ) {
2568        return self::parse_fields_from_content( $post_id );
2569    }
2570
2571    /**
2572     * Properly maps fields that are missing from the post meta data
2573     * to names, that are similar to those of the post meta.
2574     *
2575     * @param array $parsed_post_content Parsed post content.
2576     * @param bool  $use_main_comment Whether to use the main comment from the post_content or not.
2577     *                                Defaults to true for backwards compatibility. New JSON format
2578     *                                does not have a main comment and instead has all fields in the parsed content.
2579     *
2580     * @see parse_fields_from_content for how the input data is generated.
2581     *
2582     * @return array Mapped fields.
2583     */
2584    public function map_parsed_field_contents_of_post_to_field_names( $parsed_post_content, $use_main_comment = true ) {
2585
2586        $mapped_fields = array();
2587
2588        $field_mapping = array(
2589            // TODO: Commented out since we'll be re-introducing this after some other changes
2590            // '_feedback_subject'      => __( 'Contact Form', 'jetpack-forms' ),
2591            '_feedback_author'       => '1_Name',
2592            '_feedback_author_email' => '2_Email',
2593            '_feedback_author_url'   => '3_Website',
2594            '_feedback_ip'           => '93_ip_address',
2595        );
2596
2597        if ( $use_main_comment ) {
2598            $field_mapping['_feedback_main_comment'] = '4_Comment';
2599        }
2600
2601        foreach ( $field_mapping as $parsed_field_name => $field_name ) {
2602            if (
2603                isset( $parsed_post_content[ $parsed_field_name ] )
2604                && ! empty( $parsed_post_content[ $parsed_field_name ] )
2605            ) {
2606                $mapped_fields[ $field_name ] = $parsed_post_content[ $parsed_field_name ];
2607            }
2608        }
2609
2610        return $mapped_fields;
2611    }
2612
2613    /**
2614     * Registers the personal data exporter.
2615     *
2616     * @since 6.1.1
2617     *
2618     * @param  array $exporters An array of personal data exporters.
2619     *
2620     * @return array $exporters An array of personal data exporters.
2621     */
2622    public function register_personal_data_exporter( $exporters ) {
2623        $exporters['jetpack-feedback'] = array(
2624            'exporter_friendly_name' => __( 'Feedback', 'jetpack-forms' ),
2625            'callback'               => array( $this, 'personal_data_exporter' ),
2626        );
2627
2628        return $exporters;
2629    }
2630
2631    /**
2632     * Registers the personal data eraser.
2633     *
2634     * @since 6.1.1
2635     *
2636     * @param  array $erasers An array of personal data erasers.
2637     *
2638     * @return array $erasers An array of personal data erasers.
2639     */
2640    public function register_personal_data_eraser( $erasers ) {
2641        $erasers['jetpack-feedback'] = array(
2642            'eraser_friendly_name' => __( 'Feedback', 'jetpack-forms' ),
2643            'callback'             => array( $this, 'personal_data_eraser' ),
2644        );
2645
2646        return $erasers;
2647    }
2648
2649    /**
2650     * Exports personal data.
2651     *
2652     * @since 6.1.1
2653     *
2654     * @param  string $email  Email address.
2655     * @param  int    $page   Page to export.
2656     *
2657     * @return array  $return Associative array with keys expected by core.
2658     */
2659    public function personal_data_exporter( $email, $page = 1 ) {
2660        return $this->internal_personal_data_exporter( $email, $page );
2661    }
2662
2663    /**
2664     * Internal method for exporting personal data.
2665     *
2666     * Allows us to have a different signature than core expects
2667     * while protecting against future core API changes.
2668     *
2669     * @internal
2670     * @since 6.5
2671     *
2672     * @param  string $email    Email address.
2673     * @param  int    $page     Page to export.
2674     * @param  int    $per_page Number of feedbacks to process per page. Internal use only (testing).
2675     *
2676     * @return array            Associative array with keys expected by core.
2677     */
2678    public function internal_personal_data_exporter( $email, $page = 1, $per_page = 250 ) {
2679        $post_ids = $this->personal_data_post_ids_by_email( $email, $per_page, $page );
2680
2681        return array(
2682            'data' => $this->internal_personal_data_formater( $post_ids ),
2683            'done' => count( $post_ids ) < $per_page,
2684        );
2685    }
2686
2687    /**
2688     * Formats personal data for export.
2689     *
2690     * @param  array $post_ids Array of post IDs to format.
2691     *
2692     * @return array $export_data Formatted personal data for export.
2693     */
2694    public function internal_personal_data_formater( $post_ids ) {
2695        $export_data = array();
2696        foreach ( $post_ids as $post_id ) {
2697            $post_export_data = array();
2698            $feedback         = Feedback::get( $post_id );
2699            if ( ! $feedback ) {
2700                continue;
2701            }
2702            $fields             = $feedback->get_compiled_fields( 'personal_export', 'all' );
2703            $post_export_data[] = array(
2704                'name'  => __( 'Date', 'jetpack-forms' ),
2705                'value' => $feedback->get_time(),
2706            );
2707
2708            $post_export_data[] = array(
2709                'name'  => __( 'Source Title', 'jetpack-forms' ),
2710                'value' => $feedback->get_entry_title(),
2711            );
2712
2713            $post_export_data[] = array(
2714                'name'  => __( 'Source URL:', 'jetpack-forms' ),
2715                'value' => $feedback->get_entry_permalink(),
2716            );
2717
2718            foreach ( $fields as $field ) {
2719                $post_export_data[] = array(
2720                    'name'  => $field['label'],
2721                    'value' => $field['value'],
2722                );
2723            }
2724
2725            $post_export_data[] = array(
2726                'name'  => __( 'Consent', 'jetpack-forms' ),
2727                'value' => $feedback->has_consent() ? __( 'Yes', 'jetpack-forms' ) : __( 'No', 'jetpack-forms' ),
2728            );
2729
2730            $post_export_data[] = array(
2731                'name'  => __( 'IP Address', 'jetpack-forms' ),
2732                'value' => $feedback->get_ip_address() ?? '',
2733            );
2734
2735            $post_export_data[] = array(
2736                'name'  => __( 'Country code', 'jetpack-forms' ),
2737                'value' => $feedback->get_country_code() ?? '',
2738            );
2739
2740            $export_data[] = array(
2741                'group_id'    => 'feedback',
2742                'group_label' => __( 'Feedback', 'jetpack-forms' ),
2743                'item_id'     => 'feedback-' . $post_id,
2744                'data'        => $post_export_data,
2745            );
2746        }
2747
2748        return $export_data;
2749    }
2750
2751    /**
2752     * Erases personal data.
2753     *
2754     * @since 6.1.1
2755     *
2756     * @param  string $email Email address.
2757     * @param  int    $page  Page to erase.
2758     *
2759     * @return array         Associative array with keys expected by core.
2760     */
2761    public function personal_data_eraser( $email, $page = 1 ) {
2762        return $this->_internal_personal_data_eraser( $email, $page );
2763    }
2764
2765    /**
2766     * Internal method for erasing personal data.
2767     *
2768     * Allows us to have a different signature than core expects
2769     * while protecting against future core API changes.
2770     *
2771     * @internal
2772     * @since 6.5
2773     *
2774     * @param  string $email    Email address.
2775     * @param  int    $page     Page to erase.
2776     * @param  int    $per_page Number of feedbacks to process per page. Internal use only (testing).
2777     *
2778     * @return array            Associative array with keys expected by core.
2779     */
2780    public function _internal_personal_data_eraser( $email, $page = 1, $per_page = 250 ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore -- this is called in other files.
2781        $removed      = false;
2782        $retained     = false;
2783        $messages     = array();
2784        $option_name  = sprintf( '_jetpack_pde_feedback_%s', md5( $email ) );
2785        $last_post_id = 1 === $page ? 0 : get_option( $option_name, 0 );
2786        $post_ids     = $this->personal_data_post_ids_by_email( $email, $per_page, $page, $last_post_id );
2787
2788        foreach ( $post_ids as $post_id ) {
2789            $last_post_id = $post_id;
2790
2791            /**
2792             * Filters whether to erase a particular Feedback post.
2793             *
2794             * @since 6.3.0
2795             *
2796             * @param bool|string $prevention_message Whether to apply erase the Feedback post (bool).
2797             *                                        Custom prevention message (string). Default true.
2798             * @param int         $post_id            Feedback post ID.
2799             */
2800            $prevention_message = apply_filters( 'grunion_contact_form_delete_feedback_post', true, $post_id );
2801
2802            if ( true !== $prevention_message ) {
2803                if ( $prevention_message && is_string( $prevention_message ) ) {
2804                    $messages[] = esc_html( $prevention_message );
2805                } else {
2806                    $messages[] = sprintf(
2807                    // translators: %d: Post ID.
2808                        __( 'Feedback ID %d could not be removed at this time.', 'jetpack-forms' ),
2809                        $post_id
2810                    );
2811                }
2812
2813                $retained = true;
2814
2815                continue;
2816            }
2817
2818            if ( wp_delete_post( $post_id, true ) ) {
2819                $removed = true;
2820            } else {
2821                $retained   = true;
2822                $messages[] = sprintf(
2823                // translators: %d: Post ID.
2824                    __( 'Feedback ID %d could not be removed at this time.', 'jetpack-forms' ),
2825                    $post_id
2826                );
2827            }
2828        }
2829
2830        $done = count( $post_ids ) < $per_page;
2831
2832        if ( $done ) {
2833            delete_option( $option_name );
2834        } else {
2835            update_option( $option_name, (int) $last_post_id );
2836        }
2837
2838        return array(
2839            'items_removed'  => $removed,
2840            'items_retained' => $retained,
2841            'messages'       => $messages,
2842            'done'           => $done,
2843        );
2844    }
2845
2846    /**
2847     * Queries personal data by email address.
2848     *
2849     * @since 6.1.1
2850     *
2851     * @param  string $email        Email address.
2852     * @param  int    $per_page     Post IDs per page. Default is `250`.
2853     * @param  int    $page         Page to query. Default is `1`.
2854     * @param  int    $last_post_id Page to query. Default is `0`. If non-zero, used instead of $page.
2855     *
2856     * @return array An array of post IDs.
2857     */
2858    public function personal_data_post_ids_by_email( $email, $per_page = 250, $page = 1, $last_post_id = 0 ) {
2859        add_filter( 'posts_search', array( $this, 'personal_data_search_filter' ) );
2860
2861        $this->pde_last_post_id_erased = $last_post_id;
2862        $this->set_pde_email_address( $email );
2863
2864        $post_ids = get_posts(
2865            array(
2866                'post_type'        => 'feedback',
2867                'post_status'      => 'publish',
2868                // This search parameter gets overwritten in ->personal_data_search_filter()
2869                's'                => '..PDE..AUTHOR EMAIL:..PDE..',
2870                'sentence'         => true,
2871                'order'            => 'ASC',
2872                'orderby'          => 'ID',
2873                'fields'           => 'ids',
2874                'posts_per_page'   => $per_page,
2875                'paged'            => $last_post_id ? 1 : $page,
2876                'suppress_filters' => false,
2877            )
2878        );
2879
2880        $this->pde_last_post_id_erased = 0;
2881        $this->pde_email_address       = '';
2882
2883        remove_filter( 'posts_search', array( $this, 'personal_data_search_filter' ) );
2884
2885        return $post_ids;
2886    }
2887
2888    /**
2889     * Sets the email address to filter searches by.
2890     * Helper for tests.
2891     *
2892     * @since 6.1.1
2893     *
2894     * @param  string $email Email address.
2895     */
2896    public function set_pde_email_address( $email ) {
2897        $this->pde_email_address = $email;
2898    }
2899
2900    /**
2901     * Filters searches by email address.
2902     *
2903     * @since 6.1.1
2904     *
2905     * @param  string $search SQL where clause.
2906     *
2907     * @return string         Filtered SQL where clause.
2908     */
2909    public function personal_data_search_filter( $search ) {
2910        global $wpdb;
2911
2912        /*
2913         * Searches for email addresses in feedback post_content across all storage formats:
2914         * - Legacy format: AUTHOR EMAIL on its own line
2915         * - V2/V3 format: JSON with email in field values
2916         */
2917        if ( $this->pde_email_address && str_contains( $search, '..PDE..AUTHOR EMAIL:..PDE..' ) ) {
2918            // Build search patterns for all formats
2919            $patterns = array(
2920                // Pattern 1 & 2: Legacy format - AUTHOR EMAIL on its own line
2921                // `chr( 10 )` = `\n`, `chr( 13 )` = `\r`
2922                '%' . $wpdb->esc_like( chr( 10 ) . 'AUTHOR EMAIL: ' . $this->pde_email_address . chr( 10 ) ) . '%',
2923                '%' . $wpdb->esc_like( chr( 13 ) . 'AUTHOR EMAIL: ' . $this->pde_email_address . chr( 13 ) ) . '%',
2924
2925                // Pattern 3 & 4: V2/V3 format - JSON field value with escaped quotes
2926                // Handles both storage variants:
2927                // - Pattern 3: double-escaped quotes (e.g. stored as \"value\":\" in JSON-encoded content).
2928                // - Pattern 4: single-escaped quotes (e.g. stored as "value":" after one level of unescaping).
2929                '%\\"value\\":\\"' . $wpdb->esc_like( $this->pde_email_address ) . '%',
2930                '%\"value\":\"' . $wpdb->esc_like( $this->pde_email_address ) . '%',
2931            );
2932
2933            // V2 has a bug where emojis become malformed: ðŸŽ‰ becomes ud83cudf89 instead of \ud83c\udf89.
2934            // Here we deliberately reproduce that corruption so we can still match feedback saved by V2:
2935            // - wp_json_encode( '🎉' ) produces the JSON string "\"\ud83c\udf89\"" (note the backslashes).
2936            // - trim( ..., '"' ) removes the surrounding JSON quotes, giving "\ud83c\udf89".
2937            // - stripslashes() then removes the backslashes from the escape sequence, yielding "ud83cudf89",
2938            // which is exactly how V2 stored the corrupted value in post_content.
2939            // If the email contains unicode, also search for the V2 corrupted version generated this way.
2940            $v2_corrupted_email = stripslashes( trim( wp_json_encode( $this->pde_email_address, JSON_UNESCAPED_SLASHES ), '"' ) );
2941            if ( $v2_corrupted_email !== $this->pde_email_address ) {
2942                // Email contains unicode - add pattern for V2's corrupted format.
2943                $patterns[] = '%\"value\":\"' . $wpdb->esc_like( $v2_corrupted_email ) . '%';
2944            }
2945
2946            // Build SQL with all patterns
2947            $placeholders = implode( ' OR ', array_fill( 0, count( $patterns ), "{$wpdb->posts}.post_content LIKE %s" ) );
2948
2949            // Validate that the number of placeholders matches the number of pattern values
2950            $placeholder_count = substr_count( $placeholders, '%s' );
2951            if ( $placeholder_count !== count( $patterns ) ) {
2952                return $search;
2953            }
2954
2955            $search = (string) $wpdb->prepare(
2956                ' AND ( ' . $placeholders . ' )', // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
2957                ...$patterns
2958            );
2959
2960            if ( $this->pde_last_post_id_erased ) {
2961                $search .= $wpdb->prepare( " AND {$wpdb->posts}.ID > %d", $this->pde_last_post_id_erased );
2962            }
2963        }
2964
2965        return $search;
2966    }
2967
2968    /**
2969     * Returns an array of feedback data for export.
2970     *
2971     * @param array $feedback_ids           Array of feedback IDs to fetch the data for.
2972     * @param bool  $include_test_responses Whether to include feedback that was submitted
2973     *                                      from form preview. Defaults to false, meaning
2974     *                                      preview/test responses are excluded from the export.
2975     *
2976     * @return array
2977     */
2978    public function get_export_feedback_data( $feedback_ids, $include_test_responses = false ) {
2979        $feedback_data   = array();
2980        $all_field_names = array();
2981
2982        // Collect all feedback responses and their compiled fields
2983        foreach ( $feedback_ids as $feedback_id ) {
2984            $response = Feedback::get( $feedback_id );
2985            if ( ! $response instanceof Feedback ) {
2986                continue; // Skip if the feedback is not an instance of Feedback.
2987            }
2988
2989            // Skip test responses from form preview unless explicitly requested.
2990            if ( ! $include_test_responses && $response->is_test() ) {
2991                continue;
2992            }
2993
2994            // Get fields with automatic duplicate handling (label-value shape includes counts)
2995            $compiled_fields = $response->get_compiled_fields( 'csv', 'label-value' );
2996
2997            $feedback_data[ $feedback_id ] = array(
2998                'response' => $response,
2999                'fields'   => $compiled_fields,
3000            );
3001
3002            // Collect all unique field names across all responses
3003            $all_field_names = array_merge( $all_field_names, array_keys( $compiled_fields ) );
3004        }
3005
3006        // Get unique field names (this preserves the incremented labels like "Name (2)")
3007        $all_field_names = array_unique( $all_field_names );
3008
3009        return $this->format_feedback_data_for_csv( $feedback_data, $all_field_names );
3010    }
3011
3012    /**
3013     * Returns an array of feedback data for CSV export.
3014     *
3015     * @param array $feedback_data Array of feedback data with 'response' and 'fields' keys.
3016     * @param array $field_names   Array of field names to include in the results.
3017     *
3018     * @return array
3019     */
3020    private function format_feedback_data_for_csv( $feedback_data, $field_names ) {
3021        $results            = array();
3022        $prefix_meta_fields = ' '; // Prefix all meta fields with a space to ensure that they don't clash with form field names.
3023        foreach ( $feedback_data as $feedback_id => $data ) {
3024
3025            $feedback        = $data['response'];
3026            $compiled_fields = $data['fields'];
3027
3028            if ( ! $feedback instanceof Feedback ) {
3029                continue; // Skip if the feedback is not an instance of Feedback.
3030            }
3031
3032            $results[ $prefix_meta_fields . __( 'ID', 'jetpack-forms' ) ][]     = $feedback_id;
3033            $results[ $prefix_meta_fields . __( 'Date', 'jetpack-forms' ) ][]   = $feedback->get_time();
3034            $results[ $prefix_meta_fields . __( 'Title', 'jetpack-forms' ) ][]  = $feedback->get_entry_title();
3035            $results[ $prefix_meta_fields . __( 'Source', 'jetpack-forms' ) ][] = $feedback->get_entry_short_permalink();
3036            /**
3037             * Go through all the possible fields and check if the field is available
3038             * in the current feedback.
3039             *
3040             * If it is - add the data as a value.
3041             * If it is not - add an empty string, which is just a placeholder in the CSV.
3042             */
3043            foreach ( $field_names as $single_field_name ) {
3044                $trimmed_field_name = trim( $single_field_name );
3045                if ( ! isset( $results[ $trimmed_field_name ] ) ) {
3046                    $results[ $trimmed_field_name ] = array();
3047                }
3048                // Use the compiled fields directly (which already have incremented labels)
3049                $results[ $trimmed_field_name ][] = $compiled_fields[ $trimmed_field_name ] ?? '';
3050            }
3051
3052            $results[ $prefix_meta_fields . __( 'Consent', 'jetpack-forms' ) ][] = $feedback->has_consent() ? __( 'Yes', 'jetpack-forms' ) : __( 'No', 'jetpack-forms' );
3053
3054            // Convert null values to empty strings for proper CSV/export formatting.
3055            $results[ $prefix_meta_fields . __( 'IP Address', 'jetpack-forms' ) ][]   = $feedback->get_ip_address() ?? '';
3056            $results[ $prefix_meta_fields . __( 'Country code', 'jetpack-forms' ) ][] = $feedback->get_country_code() ?? '';
3057            $results[ $prefix_meta_fields . __( 'Browser', 'jetpack-forms' ) ][]      = $feedback->get_browser() ?? '';
3058
3059        }
3060        return $results;
3061    }
3062
3063    /**
3064     * Prepares feedback post data for CSV export.
3065     *
3066     * @deprecated since 5.1.0
3067     *
3068     * @see get_export_feedback_data()
3069     * @param array $post_ids Post IDs to fetch the data for. These need to be Feedback posts.
3070     *
3071     * @return array
3072     */
3073    public function get_export_data_for_posts( $post_ids ) {
3074        _deprecated_function( __METHOD__, 'package-5.1.0', 'Contact_Form_Plugin::get_export_feedback_data()' );
3075        return $this->get_export_feedback_data( $post_ids );
3076    }
3077
3078    /**
3079     * Returns an array of [prefixed column name] => [translated column name], used on export.
3080     * Prefix indicates the position in which the column will be rendered:
3081     * - Negative numbers render BEFORE any form field/value column: -5, -3, -1...
3082     * - Positive values render AFTER any form field/value column: 1, 30, 93...
3083     *   Mind using high numbering on these ones as the prefix is used on regular inputs: 1_Name, 2_Email, etc
3084     *
3085     * @deprecated since 5.1.0
3086     *
3087     * @return array
3088     */
3089    public function get_well_known_column_names() {
3090        _deprecated_function( __METHOD__, 'package-5.1.0', 'Contact_Form_Plugin::get_export_column_names()' );
3091        return array(
3092            '-9_title'         => __( 'Title', 'jetpack-forms' ),
3093            '-6_source'        => __( 'Source', 'jetpack-forms' ),
3094            '-3_response_date' => __( 'Response Date', 'jetpack-forms' ),
3095            '90_consent'       => _x( 'Consent', 'noun', 'jetpack-forms' ),
3096            '93_ip_address'    => __( 'IP Address', 'jetpack-forms' ),
3097            '94_country_code'  => __( 'Country code', 'jetpack-forms' ),
3098            '95_browser'       => __( 'Browser', 'jetpack-forms' ),
3099        );
3100    }
3101
3102    /**
3103     * Extracts feedback entries based on POST data.
3104     */
3105    public function get_feedback_entries_from_post() {
3106        if ( empty( $_POST['feedback_export_nonce_csv'] ) && empty( $_POST['feedback_export_nonce_gdrive'] ) ) {
3107            return;
3108        } elseif ( ! empty( $_POST['feedback_export_nonce_csv'] ) ) {
3109            check_admin_referer( 'feedback_export', 'feedback_export_nonce_csv' );
3110        } elseif ( ! empty( $_POST['feedback_export_nonce_gdrive'] ) ) {
3111            check_admin_referer( 'feedback_export', 'feedback_export_nonce_gdrive' );
3112        }
3113
3114        if ( ! current_user_can( 'export' ) ) {
3115            return;
3116        }
3117
3118        $args = array(
3119            'posts_per_page'   => -1,
3120            'post_type'        => Feedback::POST_TYPE,
3121            'post_status'      => array( 'publish', 'draft' ),
3122            'order'            => 'ASC',
3123            'fields'           => 'ids',
3124            'suppress_filters' => false,
3125            'date_query'       => array(),
3126        );
3127
3128        // Check if we want to download all the feedbacks or just a certain contact form
3129        if ( ! empty( $_POST['post'] ) && $_POST['post'] !== 'all' ) {
3130            $args['post_parent'] = (int) $_POST['post'];
3131        }
3132
3133        if ( ! empty( $_POST['status'] ) && in_array( $_POST['status'], array( 'spam', 'trash' ), true ) ) {
3134            $args['post_status'] = sanitize_text_field( wp_unslash( $_POST['status'] ) );
3135        }
3136
3137        if ( ! empty( $_POST['search'] ) ) {
3138            $args['s'] = sanitize_text_field( wp_unslash( $_POST['search'] ) );
3139        }
3140
3141        if ( ! empty( $_POST['after'] ) && ! empty( $_POST['before'] ) ) {
3142            $before = strtotime( sanitize_text_field( wp_unslash( $_POST['before'] ) ) );
3143            $after  = strtotime( sanitize_text_field( wp_unslash( $_POST['after'] ) ) );
3144            if ( $before && $after && $after < $before ) {
3145                // date_query expects date strings/arrays, not timestamps.
3146                $args['date_query']['after']  = gmdate( 'Y-m-d H:i:s', $after );
3147                $args['date_query']['before'] = gmdate( 'Y-m-d H:i:s', $before );
3148            }
3149        }
3150
3151        $has_explicit_selection = ! empty( $_POST['selected'] ) && is_array( $_POST['selected'] );
3152        if ( $has_explicit_selection ) {
3153            $args['include'] = array_filter(
3154                array_map(
3155                    function ( $selected ) {
3156                        return intval( $selected );
3157                    },
3158                    $_POST['selected'] // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
3159                )
3160            );
3161        }
3162
3163        $source_id = ! empty( $_POST['source'] ) ? absint( $_POST['source'] ) : 0;
3164        $join_cb   = null;
3165        $where_cb  = null;
3166        $feedbacks = array();
3167
3168        if ( $source_id > 0 ) {
3169            $source_sql = Feedback::get_source_filter_sql( $source_id );
3170
3171            $join_cb  = function ( $join, $query ) use ( $source_sql ) {
3172                if ( Feedback::POST_TYPE !== $query->get( 'post_type' ) ) {
3173                    return $join;
3174                }
3175                return $join . $source_sql['join'];
3176            };
3177            $where_cb = function ( $where, $query ) use ( $source_sql ) {
3178                if ( Feedback::POST_TYPE !== $query->get( 'post_type' ) ) {
3179                    return $where;
3180                }
3181                return $where . ' AND ' . $source_sql['where'];
3182            };
3183
3184            add_filter( 'posts_join', $join_cb, 10, 2 );
3185            add_filter( 'posts_where', $where_cb, 10, 2 );
3186        }
3187
3188        try {
3189            $feedbacks = get_posts( $args );
3190        } finally {
3191            if ( is_callable( $join_cb ) ) {
3192                remove_filter( 'posts_join', $join_cb, 10 );
3193            }
3194            if ( is_callable( $where_cb ) ) {
3195                remove_filter( 'posts_where', $where_cb, 10 );
3196            }
3197        }
3198
3199        // Test responses from form preview are excluded from bulk exports by
3200        // default. When the user has explicitly picked specific rows (via the
3201        // dashboard selection UI), we trust their selection and include any
3202        // test responses that landed in it.
3203        return $this->get_export_feedback_data( $feedbacks, $has_explicit_selection );
3204    }
3205
3206    /**
3207     * Download exported data as CSV
3208     */
3209    public function download_feedback_as_csv() {
3210        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verification is done on get_feedback_entries_from_post function
3211        $post_data = wp_unslash( $_POST );
3212        $data      = $this->get_feedback_entries_from_post();
3213
3214        if ( empty( $data ) ) {
3215            return;
3216        }
3217
3218        // Check if we want to download all the feedbacks or just a certain contact form
3219        if ( ! empty( $post_data['post'] ) && $post_data['post'] !== 'all' ) {
3220            $filename = sprintf(
3221                '%s - %s.csv',
3222                Util::get_export_filename( get_the_title( (int) $post_data['post'] ) ),
3223                gmdate( 'Y-m-d H:i' )
3224            );
3225        } else {
3226            $filename = sprintf(
3227                '%s - %s.csv',
3228                Util::get_export_filename(),
3229                gmdate( 'Y-m-d H:i' )
3230            );
3231        }
3232
3233        /**
3234         * Extract field names from `$data` for later use.
3235         */
3236        $fields = array_keys( $data );
3237
3238        /**
3239         * Count how many rows will be exported.
3240         */
3241        $row_count = count( reset( $data ) );
3242
3243        // Forces the download of the CSV instead of echoing
3244        header( 'Content-Disposition: attachment; filename=' . $filename );
3245        header( 'Pragma: no-cache' );
3246        header( 'Expires: 0' );
3247        header( 'Content-Type: text/csv; charset=utf-8' );
3248
3249        $output = fopen( 'php://output', 'w' );
3250
3251        /**
3252         * Print CSV headers
3253         */
3254        fputcsv( $output, $fields, ',', '"', '' );
3255
3256        /**
3257         * Print rows to the output.
3258         */
3259        for ( $i = 0; $i < $row_count; $i++ ) {
3260
3261            $current_row = array();
3262
3263            /**
3264             * Put all the fields in `$current_row` array.
3265             */
3266            foreach ( $fields as $single_field_name ) {
3267                $current_row[] = $this->esc_csv( $data[ $single_field_name ][ $i ] );
3268            }
3269
3270            /**
3271             * Output the complete CSV row
3272             */
3273            fputcsv( $output, $current_row, ',', '"', '' );
3274        }
3275
3276        fclose( $output ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
3277
3278        $this->record_tracks_event( 'forms_export_responses', array( 'format' => 'csv' ) );
3279        exit( 0 );
3280    }
3281
3282    /**
3283     * Create a new page with a Form block
3284     */
3285    public function create_new_form() {
3286        if ( ! isset( $_POST['newFormNonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['newFormNonce'] ) ), 'create_new_form' ) ) {
3287            wp_send_json_error(
3288                __( 'Invalid nonce', 'jetpack-forms' ),
3289                403,
3290                JSON_UNESCAPED_SLASHES
3291            );
3292        }
3293
3294        if ( ! current_user_can( 'edit_pages' ) ) {
3295            wp_send_json_error(
3296                __( 'You do not have permission to create pages', 'jetpack-forms' ),
3297                403,
3298                JSON_UNESCAPED_SLASHES
3299            );
3300        }
3301
3302        $pattern_name = isset( $_POST['pattern'] ) ? sanitize_text_field( wp_unslash( $_POST['pattern'] ) ) : null;
3303
3304        if ( $pattern_name && WP_Block_Patterns_Registry::get_instance()->is_registered( $pattern_name ) ) {
3305            $pattern         = WP_Block_Patterns_Registry::get_instance()->get_registered( $pattern_name );
3306            $pattern_content = $pattern['content'] ?? '';
3307        }
3308
3309        // If no pattern found or specified, use a default form block
3310        if ( empty( $pattern_content ) ) {
3311            $pattern_content = '<!-- wp:jetpack/contact-form -->
3312                                                        <div class="wp-block-jetpack-contact-form"></div>
3313                                                    <!-- /wp:jetpack/contact-form -->';
3314        }
3315
3316        $form_title = isset( $_POST['formTitle'] ) ? sanitize_text_field( wp_unslash( $_POST['formTitle'] ) ) : '';
3317
3318        $post_id = wp_insert_post(
3319            array(
3320                'post_type'    => 'page',
3321                'post_title'   => $form_title,
3322                'post_content' => $pattern_content,
3323            )
3324        );
3325
3326        if ( is_wp_error( $post_id ) ) {
3327            wp_send_json_error(
3328                $post_id->get_error_message(),
3329                500,
3330                JSON_UNESCAPED_SLASHES
3331            );
3332        } else {
3333            wp_send_json(
3334                array(
3335                    'post_url' => admin_url( 'post.php?post=' . intval( $post_id ) . '&action=edit' ),
3336                ),
3337                null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
3338                JSON_UNESCAPED_SLASHES
3339            );
3340        }
3341    }
3342
3343    /**
3344     * Send an event to Tracks
3345     *
3346     * @param string $event_name - the name of the event.
3347     * @param array  $event_props - event properties to send.
3348     *
3349     * @return null|void
3350     */
3351    public function record_tracks_event( $event_name, $event_props ) {
3352        /*
3353         * Event details.
3354         */
3355        $event_user = wp_get_current_user();
3356
3357        /*
3358         * Record event.
3359         * We use different libs on wpcom and Jetpack.
3360         */
3361        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
3362            $event_name             = 'wpcom_' . $event_name;
3363            $event_props['blog_id'] = get_current_blog_id();
3364            // logged out visitor, record event with blog owner.
3365            if ( empty( $event_user->ID ) ) {
3366                $event_user_id = wpcom_get_blog_owner( $event_props['blog_id'] );
3367                $event_user    = get_userdata( $event_user_id );
3368            }
3369
3370            require_lib( 'tracks/client' );
3371            tracks_record_event( $event_user, $event_name, $event_props );
3372        } else {
3373            $user_connected = ( new \Automattic\Jetpack\Connection\Manager( 'jetpack-forms' ) )->is_user_connected( get_current_user_id() );
3374            if ( ! $user_connected ) {
3375                return;
3376            }
3377            // logged out visitor, record event with Jetpack master user.
3378            if ( empty( $event_user->ID ) ) {
3379                $master_user_id = Jetpack_Options::get_option( 'master_user' );
3380                if ( ! empty( $master_user_id ) ) {
3381                    $event_user = get_userdata( $master_user_id );
3382                }
3383            }
3384
3385            $tracking = new Tracking();
3386            $tracking->record_user_event( $event_name, $event_props, $event_user );
3387        }
3388    }
3389
3390    /**
3391     * Escape a string to be used in a CSV context
3392     *
3393     * Malicious input can inject formulas into CSV files, opening up the possibility for phishing attacks and
3394     * disclosure of sensitive information.
3395     *
3396     * Additionally, Excel exposes the ability to launch arbitrary commands through the DDE protocol.
3397     *
3398     * @see https://www.contextis.com/en/blog/comma-separated-vulnerabilities
3399     *
3400     * @param string $field - the CSV field.
3401     *
3402     * @return string
3403     */
3404    public function esc_csv( $field ) {
3405        $active_content_triggers = array( '=', '+', '-', '@' );
3406
3407        if ( $field && in_array( mb_substr( $field, 0, 1 ), $active_content_triggers, true ) ) {
3408            $field = "'" . $field;
3409        }
3410
3411        return $field;
3412    }
3413
3414    /**
3415     * Returns an array of parent post IDs for the user.
3416     * The parent posts are those posts where forms have been published.
3417     *
3418     * @param array $query_args A WP_Query compatible array of query args.
3419     *
3420     * @return array The array of post IDs
3421     */
3422    public static function get_all_parent_post_ids( $query_args = array() ) {
3423        $default_query_args = array(
3424            'fields'           => 'id=>parent',
3425            'posts_per_page'   => 100000, // phpcs:ignore WordPress.WP.PostsPerPage.posts_per_page_posts_per_page
3426            'post_type'        => 'feedback',
3427            'post_status'      => 'publish',
3428            'suppress_filters' => false,
3429        );
3430        $args               = array_merge( $default_query_args, $query_args );
3431        // Get the feedbacks' parents' post IDs
3432        $feedbacks = get_posts( $args );
3433        return array_values( array_unique( array_values( $feedbacks ) ) );
3434    }
3435
3436    /**
3437     * Returns a string of HTML <option> items from an array of posts
3438     *
3439     * @param int $selected_id Currently selected post ID.
3440     * @return string a string of HTML <option> items
3441     */
3442    protected static function get_feedbacks_as_options( $selected_id = 0 ) {
3443        $options    = '';
3444        $parent_ids = self::get_all_parent_post_ids();
3445
3446        // creates the string of <option> elements
3447        foreach ( $parent_ids as $parent_id ) {
3448            $parent_url = get_permalink( $parent_id );
3449            $parsed_url = wp_parse_url( $parent_url );
3450
3451            $options .= sprintf(
3452                '<option value="%s" %s>/%s</option>',
3453                esc_attr( $parent_id ),
3454                $selected_id === $parent_id ? 'selected' : '',
3455                esc_html( basename( $parsed_url['path'] ) )
3456            );
3457        }
3458
3459        return $options;
3460    }
3461
3462    /**
3463     * Get the names of all the form's fields
3464     *
3465     * @param array|int $posts the post we want the fields of.
3466     *
3467     * @return array     the array of fields
3468     *
3469     * @deprecated As this is no longer necessary as of the CSV export rewrite. - 2015-12-29
3470     */
3471    protected function get_field_names( $posts ) {
3472        $posts      = (array) $posts;
3473        $all_fields = array();
3474
3475        foreach ( $posts as $post ) {
3476            $fields = self::parse_fields_from_content( $post );
3477
3478            if ( isset( $fields['_feedback_all_fields'] ) ) {
3479                $extra_fields = array_keys( $fields['_feedback_all_fields'] );
3480                $all_fields   = array_merge( $all_fields, $extra_fields );
3481            }
3482        }
3483
3484        $all_fields = array_unique( $all_fields );
3485
3486        return $all_fields;
3487    }
3488
3489    /**
3490     * Returns if the feedback post has JSON data
3491     *
3492     * @param int $post_id The feedback post ID to check.
3493     * @return bool
3494     */
3495    public function has_json_data( $post_id ) {
3496        $post_content = get_post_field( 'post_content', $post_id );
3497        $content      = explode( "\nJSON_DATA", $post_content );
3498        if ( empty( $content[1] ) ) {
3499            return false;
3500        }
3501        $json_data = json_decode( $content[1], true );
3502        return is_array( $json_data ) && ! empty( $json_data );
3503    }
3504
3505    /**
3506     * Helper function to parse the post content.
3507     *
3508     * @param string $post_content The post content to parse.
3509     * @return array Parsed fields.
3510     *
3511     * @codeCoverageIgnore - No need to be covered.
3512     * @deprecated since 5.3.0
3513     */
3514    public static function parse_feedback_content( $post_content ) {
3515        $all_values = array();
3516
3517        $content = explode( '<!--more-->', $post_content );
3518        $lines   = array();
3519
3520        if ( count( $content ) > 1 ) {
3521            $content = str_ireplace( array( '<br />', ')</p>' ), '', $content[1] );
3522            if ( str_contains( $content, 'JSON_DATA' ) ) {
3523                $chunks     = explode( "\nJSON_DATA", $content );
3524                $all_values = json_decode( $chunks[1], true );
3525                if ( $all_values === null ) {
3526                    // If JSON decoding fails, try to decode the second try with stripslashes and trim.
3527                    // This is a workaround for some cases where the JSON data is not properly formatted.
3528                    $all_values = json_decode( stripslashes( trim( $chunks[1] ) ), true );
3529                }
3530                $lines = array_filter( explode( "\n", $chunks[0] ) );
3531            } else {
3532                $fields_array = preg_replace( '/.*Array\s\( (.*)\)/msx', '$1', $content );
3533
3534                // 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.
3535                // The regular expression ensures that each key-value pair is correctly identified and captured.
3536                // Given an input string
3537                // [Key1] => Value1
3538                // [Key2] => Value2
3539                // it  $matches[1]: The keys (e.g., Key1, Key2 ).
3540                // and $matches[2]: The values (e.g., Value1, Value2 ).
3541                preg_match_all( '/^\s*\[([^\]]+)\] =\&gt\; (.*)(?=^\s*(\[[^\]]+\] =\&gt\;)|\z)/msU', $fields_array, $matches );
3542
3543                if ( count( $matches ) > 1 ) {
3544                    $all_values = array_combine( array_map( 'trim', $matches[1] ), array_map( 'trim', $matches[2] ) );
3545                }
3546
3547                $lines = array_filter( explode( "\n", $content ) );
3548            }
3549        }
3550
3551        $var_map = array(
3552            'AUTHOR'       => '_feedback_author',
3553            'AUTHOR EMAIL' => '_feedback_author_email',
3554            'AUTHOR URL'   => '_feedback_author_url',
3555            'SUBJECT'      => '_feedback_subject',
3556            'IP'           => '_feedback_ip',
3557        );
3558
3559        $fields = array();
3560
3561        foreach ( $lines as $line ) {
3562            $vars = explode( ': ', $line, 2 );
3563            if ( ! empty( $vars ) ) {
3564                if ( isset( $var_map[ $vars[0] ] ) ) {
3565                    $fields[ $var_map[ $vars[0] ] ] = self::strip_tags( trim( $vars[1] ) );
3566                }
3567            }
3568        }
3569        // All fields should always be an array, even if empty.
3570        if ( ! is_array( $all_values ) ) {
3571            $all_values = array();
3572        }
3573        $fields['_feedback_all_fields'] = array();
3574        foreach ( $all_values as $key => $value ) {
3575            $fields['_feedback_all_fields'][ wp_strip_all_tags( $key ) ] = $value;
3576        }
3577
3578        return $fields;
3579    }
3580
3581    /**
3582     * Parse the contact form fields.
3583     *
3584     * @param int $post_id - the post ID.
3585     * @return array Fields.
3586     */
3587    public static function parse_fields_from_content( $post_id ) {
3588        $response = Feedback::get( $post_id );
3589
3590        if ( $response instanceof Feedback ) {
3591            return $response->get_all_legacy_values();
3592        }
3593
3594        return array();
3595    }
3596
3597    /**
3598     * Creates a valid csv row from a post id
3599     *
3600     * @param int   $post_id The id of the post.
3601     * @param array $fields  An array containing the names of all the fields of the csv.
3602     *
3603     * @return String The csv row
3604     *
3605     * @deprecated This is no longer needed, as of the CSV export rewrite.
3606     */
3607    protected static function make_csv_row_from_feedback( $post_id, $fields ) {
3608        $content_fields = self::parse_fields_from_content( $post_id );
3609        $all_fields     = array();
3610
3611        if ( isset( $content_fields['_feedback_all_fields'] ) ) {
3612            $all_fields = $content_fields['_feedback_all_fields'];
3613        }
3614
3615        // Overwrite the parsed content with the content we stored in post_meta in a better format.
3616        $extra_fields = get_post_meta( $post_id, '_feedback_extra_fields', true );
3617        foreach ( $extra_fields as $extra_field => $extra_value ) {
3618            $all_fields[ $extra_field ] = $extra_value;
3619        }
3620
3621        // The first element in all of the exports will be the subject
3622        $row_items   = array();
3623        $row_items[] = $content_fields['_feedback_subject'];
3624
3625        // Loop the fields array in order to fill the $row_items array correctly
3626        foreach ( $fields as $field ) {
3627            if ( $field === __( 'Contact Form', 'jetpack-forms' ) ) { // the first field will ever be the contact form, so we can continue
3628                continue;
3629            } elseif ( array_key_exists( $field, $all_fields ) ) {
3630                $row_items[] = $all_fields[ $field ];
3631            } else {
3632                $row_items[] = '';
3633            }
3634        }
3635
3636        return $row_items;
3637    }
3638
3639    /**
3640     * Get the IP address.
3641     *
3642     * @return string|null IP address.
3643     */
3644    public static function get_ip_address() {
3645        return isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : null;
3646    }
3647
3648    /**
3649     * Control Block Editor usage for form-related post types.
3650     *
3651     * Disables the Block Editor for feedback (form responses) and
3652     * forces it on for jetpack_form (form definitions), even if the
3653     * Classic Editor plugin is active.
3654     *
3655     * @param bool   $can_edit Whether the post type can be edited or not.
3656     * @param string $post_type The post type being checked.
3657     * @return bool
3658     */
3659    public function use_block_editor_for_post_type( $can_edit, $post_type ) {
3660        if ( 'feedback' === $post_type ) {
3661            return false;
3662        }
3663
3664        if ( Contact_Form::POST_TYPE === $post_type ) {
3665            return true;
3666        }
3667
3668        return $can_edit;
3669    }
3670
3671    /**
3672     * Force the Block Editor for jetpack_form posts, even if the
3673     * Classic Editor plugin is active.
3674     *
3675     * @param bool    $can_edit Whether the post can be edited or not.
3676     * @param WP_Post $post    The post being checked.
3677     * @return bool
3678     */
3679    public function use_block_editor_for_post( $can_edit, $post ) {
3680        if ( Contact_Form::POST_TYPE === get_post_type( $post ) ) {
3681            return true;
3682        }
3683
3684        return $can_edit;
3685    }
3686
3687    /**
3688     * Restrict comments on feedback posts to logged-in users only.
3689     * Hooks into comment permissions to enforce authentication requirement.
3690     *
3691     * For feedback posts, we override the comment_status field (which we use
3692     * for read/unread tracking) and always allow comments for logged-in users.
3693     *
3694     * @param bool $open    Whether comments are open.
3695     * @param int  $post_id Post ID.
3696     * @return bool Whether comments are open for this post.
3697     */
3698    public function restrict_feedback_comments_to_logged_in( $open, $post_id ) {
3699        $post = get_post( $post_id );
3700
3701        if ( ! $post || 'feedback' !== $post->post_type ) {
3702            return $open;
3703        }
3704
3705        // For feedback posts, comments are always open for users that can read pages.
3706        // regardless of comment_status (which we use for read/unread tracking).
3707        return current_user_can( 'edit_pages' );
3708    }
3709
3710    /**
3711     * Kludge method: reverses the output of a standard print_r( $array ).
3712     * Sort of what unserialize does to a serialized object.
3713     * This is here while we work on a better data storage inside the posts. See:
3714     * - p1675781140892129-slack-C01CSBEN0QZ
3715     * - https://www.php.net/manual/en/function.print-r.php#93529
3716     *
3717     * @param string $print_r_output The array string to be reverted. Needs to being with 'Array'.
3718     * @param bool   $parse_html Whether to run html_entity_decode on each line.
3719     *                           As strings are stored right now, they are all escaped, so '=>' are '&gt;'.
3720     * @return array|string Array when successfully reconstructed, string otherwise. Output will always be esc_html'd.
3721     */
3722    public static function reverse_that_print( $print_r_output, $parse_html = false ) {
3723        $lines = explode( "\n", trim( $print_r_output ) );
3724        if ( $parse_html ) {
3725            $lines = array_map( 'html_entity_decode', $lines );
3726        }
3727
3728        if ( trim( $lines[0] ) !== 'Array' ) {
3729            // bottomed out to something that isn't an array, escape it and be done
3730            return esc_html( $print_r_output );
3731        } else {
3732            // this is an array, lets parse it
3733            if ( preg_match( '/(\s{5,})\(/', $lines[1], $match ) ) {
3734                // this is a tested array/recursive call to this function
3735                // take a set of spaces off the beginning
3736                $spaces        = $match[1];
3737                $spaces_length = strlen( $spaces );
3738                $lines_total   = count( $lines );
3739
3740                for ( $i = 0; $i < $lines_total; $i++ ) {
3741                    if ( substr( $lines[ $i ], 0, $spaces_length ) === $spaces ) {
3742                        $lines[ $i ] = substr( $lines[ $i ], $spaces_length );
3743                    }
3744                }
3745            }
3746
3747            array_splice( $lines, 0, 2 ); // Remove first two items: 'Array' and '('.
3748            array_pop( $lines ); // Remove last item: ')'.
3749            $print_r_output = implode( "\n", $lines );
3750
3751            // make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one
3752            preg_match_all( '/^\s{4}\[(.+?)\] \=\> /m', $print_r_output, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER );
3753
3754            $pos          = array();
3755            $previous_key = '';
3756            $in_length    = strlen( $print_r_output );
3757
3758            // store the following in $pos:
3759            // array with key = key of the parsed array's item
3760            // value = array(start position in $print_r_output, $end position in $print_r_output)
3761            foreach ( $matches as $match ) {
3762                $key         = $match[1][0];
3763                $start       = $match[0][1] + strlen( $match[0][0] );
3764                $pos[ $key ] = array( $start, $in_length );
3765
3766                if ( $previous_key !== '' ) {
3767                    $pos[ $previous_key ][1] = $match[0][1] - 1;
3768                }
3769
3770                $previous_key = $key;
3771            }
3772
3773            $ret = array();
3774
3775            foreach ( $pos as $key => $where ) {
3776                // recursively see if the parsed out value is an array too
3777                $ret[ $key ] = self::reverse_that_print( substr( $print_r_output, $where[0], $where[1] - $where[0] ), $parse_html );
3778            }
3779
3780            return $ret;
3781        }
3782    }
3783
3784    /**
3785     * Method untrash_feedback_status_handler
3786     * wp_untrash_post filter handler.
3787     *
3788     * @param string $current_status   The status to be set.
3789     * @param int    $post_id          The post ID.
3790     * @param string $previous_status  The previous status.
3791     */
3792    public function untrash_feedback_status_handler( $current_status, $post_id, $previous_status ) {
3793        $post = get_post( $post_id );
3794        if ( 'feedback' === $post->post_type ) {
3795            if ( in_array( $previous_status, array( 'spam', 'publish' ), true ) ) {
3796                return $previous_status;
3797            }
3798            return 'publish';
3799        }
3800        return $current_status;
3801    }
3802
3803    /**
3804     * Tracks when a feedback post status changes to 'spam' and stores the timestamp.
3805     * This allows us to accurately determine when spam was marked, independent of other post updates.
3806     *
3807     * @param string       $new_status The new post status.
3808     * @param string       $old_status The old post status.
3809     * @param WP_Post|null $post       The post object, when available.
3810     *
3811     * @deprecated since 7.5.0
3812     */
3813    public function track_spam_status_change( $new_status, $old_status, ?WP_Post $post = null ) {
3814        _deprecated_function( __METHOD__, 'package-jetpack-forms-7.5.0' );
3815
3816        if ( ! $post instanceof WP_Post ) {
3817            // Some callers fire the action without a populated post object (e.g. failed get_post lookups).
3818            return;
3819        }
3820
3821        // Only track for feedback posts
3822        if ( 'feedback' !== $post->post_type ) {
3823            return;
3824        }
3825
3826        $this->track_spam_status( $new_status, $old_status, $post->ID );
3827    }
3828
3829    /**
3830     * Tracks when a feedback post status changes and triggers related handlers.
3831     * Used to handle spam meta tracking and unread count recalculation for feedback posts.
3832     *
3833     * @param string       $new_status The new post status.
3834     * @param string       $old_status The old post status.
3835     * @param WP_Post|null $post       The post object, when available.
3836     */
3837    public function track_feedback_status_change( $new_status, $old_status, ?WP_Post $post = null ) {
3838        if ( ! $post instanceof WP_Post ) {
3839            // Some callers fire the action without a populated post object (e.g. failed get_post lookups).
3840            return;
3841        }
3842
3843        // Only track for feedback posts
3844        if ( 'feedback' !== $post->post_type ) {
3845            return;
3846        }
3847        $this->track_spam_status( $new_status, $old_status, $post->ID );
3848        $this->track_recount_unread( $new_status, $old_status, $post );
3849    }
3850
3851    /**
3852     * Purges the edge cache when a jetpack_form post is published, updated while published, or unpublished.
3853     *
3854     * @param string       $new_status The new post status.
3855     * @param string       $old_status The old post status.
3856     * @param WP_Post|null $post       The post object, when available.
3857     */
3858    public function purge_edge_cache_on_form_status_change( $new_status, $old_status, ?WP_Post $post = null ) {
3859        if ( ! $post instanceof WP_Post ) {
3860            return;
3861        }
3862
3863        if ( Contact_Form::POST_TYPE !== $post->post_type ) {
3864            return;
3865        }
3866
3867        if ( 'publish' === $new_status || 'publish' === $old_status ) {
3868            /**
3869             * Fires when the edge cache for the entire domain should be purged.
3870             *
3871             * This action is handled by the WordPress.com hosting platform
3872             * and has no effect in self-hosted WordPress environments.
3873             */
3874            do_action( 'edge_cache_purge_domain' );
3875        }
3876    }
3877
3878    /**
3879     * Tracks when a feedback post status changes to 'spam' and stores the timestamp.
3880     * This allows us to accurately determine when spam was marked, independent of other post updates.
3881     *
3882     * @param string $new_status The new post status.
3883     * @param string $old_status The old post status.
3884     * @param int    $post_id    The post ID.
3885     */
3886    private function track_spam_status( $new_status, $old_status, $post_id ) {
3887        // Only track when status changes TO spam (not from spam to something else)
3888        if ( 'spam' === $new_status && 'spam' !== $old_status ) {
3889            // Store the current GMT timestamp when status changes to spam
3890            update_post_meta( $post_id, '_spam_status_changed_gmt', current_time( 'mysql', 1 ) );
3891        } elseif ( 'spam' === $old_status && 'spam' !== $new_status ) {
3892            // Remove the meta when post is no longer spam
3893            delete_post_meta( $post_id, '_spam_status_changed_gmt' );
3894        }
3895    }
3896
3897    /**
3898     * Tracks when a feedback post status changes to or from 'publish' and triggers unread count recalculation.
3899     *
3900     * @param string  $new_status The new post status.
3901     * @param string  $old_status The old post status.
3902     * @param WP_Post $post       The post object.
3903     */
3904    private function track_recount_unread( $new_status, $old_status, WP_Post $post ) {
3905        // If the feedback is already marked as read, it doesn't matter if its status changes.
3906        if ( $post->comment_status === Feedback::STATUS_READ ) {
3907            return;
3908        }
3909
3910        // If the status changed to or from 'publish', we need to recount unread feedbacks.
3911        if ( ( 'publish' === $new_status && 'publish' !== $old_status ) ||
3912            ( 'publish' === $old_status && 'publish' !== $new_status ) ) {
3913            add_action( 'shutdown', array( __CLASS__, 'recalculate_unread_count' ) );
3914        }
3915    }
3916
3917    /**
3918     * Returns whether we are in condition to track and use
3919     * analytics functionality like Tracks.
3920     *
3921     * @return bool Returns true if we can track analytics, else false.
3922     */
3923    public static function can_use_analytics() {
3924        $is_wpcom               = defined( 'IS_WPCOM' ) && IS_WPCOM;
3925        $status                 = new Status();
3926        $connection             = new Connection_Manager();
3927        $tracking               = new Tracking( 'jetpack', $connection );
3928        $should_enable_tracking = $tracking->should_enable_tracking( new Terms_Of_Service(), $status );
3929
3930        return $is_wpcom || $should_enable_tracking;
3931    }
3932
3933    /**
3934     * Render the rating field.
3935     *
3936     * @param array    $atts - the block attributes.
3937     * @param string   $content - html content.
3938     * @param WP_Block $block - the block instance object.
3939     *
3940     * @return string HTML for the contact form field.
3941     */
3942    public static function gutenblock_render_field_rating( $atts, $content, $block ) {
3943        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'rating', $block );
3944        return Contact_Form::parse_contact_field( $atts, $content, $block );
3945    }
3946
3947    /**
3948     * Render the slider field.
3949     *
3950     * @param array    $atts - the block attributes.
3951     * @param string   $content - html content.
3952     * @param WP_Block $block - the block instance object.
3953     *
3954     * @return string HTML for the contact form field.
3955     */
3956    public static function gutenblock_render_field_slider( $atts, $content, $block ) {
3957        // Get min, max, and default from the parent block's attributes.
3958        $parent_attrs     = $block->parsed_block['attrs'] ?? array();
3959        $atts['min']      = $parent_attrs['min'] ?? 0;
3960        $atts['max']      = $parent_attrs['max'] ?? 100;
3961        $atts['default']  = $parent_attrs['default'] ?? 0;
3962        $atts['step']     = $parent_attrs['step'] ?? 1;
3963        $atts['minLabel'] = $parent_attrs['minLabel'] ?? '';
3964        $atts['maxLabel'] = $parent_attrs['maxLabel'] ?? '';
3965
3966        $atts = self::block_attributes_to_shortcode_attributes( $atts, 'slider', $block );
3967        return Contact_Form::parse_contact_field( $atts, $content, $block );
3968    }
3969
3970    /**
3971     * Redirect users from the edit-feedback and edit-jetpack_form screens to the Jetpack Forms admin page.
3972     *
3973     * This method is hooked to 'current_screen' and redirects:
3974     * - edit-jetpack_form: to &p=/forms
3975     * - edit-feedback: to &p=/responses/inbox
3976     *
3977     * @since 6.0.0
3978     */
3979    public function redirect_edit_feedback_to_jetpack_forms() {
3980        if ( ! function_exists( 'get_current_screen' ) ) {
3981            return;
3982        }
3983
3984        $screen = get_current_screen();
3985
3986        if ( ! $screen || ! isset( $screen->id ) ) {
3987            return;
3988        }
3989
3990        // Don't redirect if we're already on the Forms admin page (prevents redirect loop).
3991        if ( Dashboard::is_jetpack_forms_admin_page() ) {
3992            return;
3993        }
3994
3995        $redirect = null;
3996
3997        if ( 'edit-jetpack_form' === $screen->id ) {
3998            $redirect = Dashboard::get_forms_admin_url( 'forms' );
3999        } elseif ( 'edit-feedback' === $screen->id ) {
4000            $redirect = Dashboard::get_forms_admin_url( 'inbox' );
4001        }
4002
4003        if ( $redirect ) {
4004            wp_safe_redirect( $redirect );
4005            exit;
4006        }
4007    }
4008
4009    /**
4010     * Validates the export to Google Drive request.
4011     *
4012     * @param array $post_data The POST data to validate.
4013     * @return bool True if the request is valid, false otherwise.
4014     */
4015    public function validate_export_to_gdrive_request( $post_data ) {
4016        if ( ! current_user_can( 'export' ) ) {
4017            return false;
4018        }
4019
4020        if ( empty( $post_data[ $this->export_nonce_field_gdrive ] ) ) {
4021            return false;
4022        }
4023
4024        $nonce = sanitize_text_field( $post_data[ $this->export_nonce_field_gdrive ] );
4025        if ( ! wp_verify_nonce( $nonce, 'feedback_export' ) ) {
4026            return false;
4027        }
4028
4029        return true;
4030    }
4031
4032    /**
4033     * Ajax handler for wp_ajax_grunion_export_to_gdrive.
4034     * Exports data to Google Drive, based on POST data.
4035     *
4036     * @see Contact_Form_Plugin::get_feedback_entries_from_post
4037     * @return never
4038     */
4039    public function export_to_gdrive() {
4040        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verification is done on validate_export_to_gdrive_request function
4041        $post_data = wp_unslash( $_POST );
4042
4043        if ( ! $this->validate_export_to_gdrive_request( $post_data ) ) {
4044            wp_send_json_error(
4045                __( 'You aren\'t authorized to do that.', 'jetpack-forms' ),
4046                403,
4047                JSON_UNESCAPED_SLASHES
4048            );
4049        }
4050
4051        $grunion     = self::init();
4052        $export_data = $grunion->get_feedback_entries_from_post();
4053
4054        $fields    = is_array( $export_data ) ? array_keys( $export_data ) : array();
4055        $row_count = ! is_array( $export_data ) || empty( $export_data ) ? 0 : count( reset( $export_data ) );
4056
4057        $sheet_data = array( $fields );
4058
4059        for ( $i = 0; $i < $row_count; $i++ ) {
4060
4061            $current_row = array();
4062
4063            /**
4064             * Put all the fields in `$current_row` array.
4065             */
4066            foreach ( $fields as $single_field_name ) {
4067                if ( isset( $export_data[ $single_field_name ][ $i ] ) ) {
4068                    $current_row[] = $this->esc_csv( $export_data[ $single_field_name ][ $i ] );
4069                } else {
4070                    $current_row[] = '';
4071                }
4072            }
4073
4074            $sheet_data[] = $current_row;
4075        }
4076
4077        $user_id = (int) get_current_user_id();
4078
4079        if ( ! empty( $post_data['post'] ) && $post_data['post'] !== 'all' ) {
4080            $spreadsheet_title = sprintf(
4081                '%1$s - %2$s',
4082                Util::get_export_filename( get_the_title( (int) $post_data['post'] ) ),
4083                gmdate( 'Y-m-d H:i' )
4084            );
4085        } else {
4086            $spreadsheet_title = sprintf( '%s - %s', Util::get_export_filename(), gmdate( 'Y-m-d H:i' ) );
4087        }
4088
4089        $sheet = Google_Drive::create_sheet( $user_id, $spreadsheet_title, $sheet_data );
4090
4091        $grunion->record_tracks_event( 'forms_export_responses', array( 'format' => 'gsheets' ) );
4092
4093        wp_send_json(
4094            array(
4095                'success' => ! is_wp_error( $sheet ),
4096                'data'    => $sheet,
4097            ),
4098            is_wp_error( $sheet ) ? 500 : 200,
4099            JSON_UNESCAPED_SLASHES
4100        );
4101    }
4102}