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