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