Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
72.07% covered (warning)
72.07%
1690 / 2345
24.32% covered (danger)
24.32%
18 / 74
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Core_Json_Api_Endpoints
72.25% covered (warning)
72.25%
1690 / 2339
24.32% covered (danger)
24.32%
18 / 74
2686.61
0.00% covered (danger)
0.00%
0 / 1
 register_endpoints
100.00% covered (success)
100.00%
498 / 498
100.00% covered (success)
100.00%
1 / 1
2
 get_openai_jwt
n/a
0 / 0
n/a
0 / 0
2
 set_subscriber_cookie_and_redirect
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 get_purchase_token
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 delete_purchase_token
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_plans
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
6
 get_products
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
6
 submit_survey
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
6
 is_site_verified_and_token
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
342
 verify_site
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
12
 dismiss_notice
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
72
 disconnect_site_permission_callback
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 connect_url_permission_callback
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 unlink_user_permission_callback
n/a
0 / 0
n/a
0 / 0
1
 manage_modules_permission_check
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 configure_modules_permission_check
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 view_admin_page_permission_check
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 view_scan_state_permission_check
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 update_settings_permission_check
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 activate_plugins_permission_check
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 edit_others_posts_check
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 purchase_token_permission_check
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
3.01
 rewind_data
57.14% covered (warning)
57.14%
8 / 14
0.00% covered (danger)
0.00%
0 / 1
6.97
 get_rewind_data
22.22% covered (danger)
22.22%
4 / 18
0.00% covered (danger)
0.00%
0 / 1
11.53
 scan_state
68.75% covered (warning)
68.75%
11 / 16
0.00% covered (danger)
0.00%
0 / 1
5.76
 increase_timeout_30
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_scan_state
61.11% covered (warning)
61.11%
11 / 18
0.00% covered (danger)
0.00%
0 / 1
4.94
 disconnect_site
n/a
0 / 0
n/a
0 / 0
4
 build_connect_url
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
2.02
 get_user_connection_data
n/a
0 / 0
n/a
0 / 0
2
 unlink_user
n/a
0 / 0
n/a
0 / 0
1
 get_user_tracking_settings
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
12
 update_user_tracking_settings
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
12
 site_data
n/a
0 / 0
n/a
0 / 0
1
 get_site_data
n/a
0 / 0
n/a
0 / 0
1
 get_site_activity
0.00% covered (danger)
0.00%
0 / 39
0.00% covered (danger)
0.00%
0 / 1
20
 reset_jetpack_options
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
90
 get_updateable_parameters
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 get_updateable_data_list
100.00% covered (success)
100.00%
868 / 868
100.00% covered (success)
100.00%
1 / 1
10
 validate_onboarding
n/a
0 / 0
n/a
0 / 0
1
 validate_boolean
22.22% covered (danger)
22.22%
2 / 9
0.00% covered (danger)
0.00%
0 / 1
11.53
 validate_posint
22.22% covered (danger)
22.22%
2 / 9
0.00% covered (danger)
0.00%
0 / 1
7.23
 validate_non_neg_int
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 validate_list_item
36.00% covered (danger)
36.00%
9 / 25
0.00% covered (danger)
0.00%
0 / 1
15.44
 validate_module_list
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
12
 validate_alphanum
22.22% covered (danger)
22.22%
2 / 9
0.00% covered (danger)
0.00%
0 / 1
11.53
 validate_verification_service
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
 validate_stats_roles
95.65% covered (success)
95.65%
22 / 23
0.00% covered (danger)
0.00%
0 / 1
6
 validate_sharing_show
57.89% covered (warning)
57.89%
11 / 19
0.00% covered (danger)
0.00%
0 / 1
3.67
 validate_subscriptions_reply_to
30.00% covered (danger)
30.00%
3 / 10
0.00% covered (danger)
0.00%
0 / 1
6.09
 validate_subscriptions_reply_to_name
22.22% covered (danger)
22.22%
2 / 9
0.00% covered (danger)
0.00%
0 / 1
7.23
 validate_services
32.00% covered (danger)
32.00%
8 / 25
0.00% covered (danger)
0.00%
0 / 1
57.28
 validate_custom_service
13.04% covered (danger)
13.04%
3 / 23
0.00% covered (danger)
0.00%
0 / 1
184.32
 validate_custom_service_id
28.57% covered (danger)
28.57%
6 / 21
0.00% covered (danger)
0.00%
0 / 1
31.32
 validate_twitter_username
22.22% covered (danger)
22.22%
2 / 9
0.00% covered (danger)
0.00%
0 / 1
11.53
 validate_waf_ip_block_list
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
 validate_string
22.22% covered (danger)
22.22%
2 / 9
0.00% covered (danger)
0.00%
0 / 1
3.88
 validate_array_of_strings
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 validate_subscription_options
26.67% covered (danger)
26.67%
4 / 15
0.00% covered (danger)
0.00%
0 / 1
10.31
 validate_array
22.22% covered (danger)
22.22%
2 / 9
0.00% covered (danger)
0.00%
0 / 1
3.88
 sanitize_stats_allowed_roles
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_module_requested
33.33% covered (danger)
33.33%
2 / 6
0.00% covered (danger)
0.00%
0 / 1
8.74
 prepare_modules_for_response
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
42
 filter_options_for_response
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
3
 prepare_options_for_response
86.54% covered (warning)
86.54%
45 / 52
0.00% covered (danger)
0.00%
0 / 1
22.08
 split_options
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 cast_value
80.95% covered (warning)
80.95%
17 / 21
0.00% covered (danger)
0.00%
0 / 1
11.84
 get_remote_value
91.67% covered (success)
91.67%
22 / 24
0.00% covered (danger)
0.00%
0 / 1
12.08
 get_plugin_update_count
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
20
 get_plugins
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 install_plugin
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
72
 activate_plugin
0.00% covered (danger)
0.00%
0 / 49
0.00% covered (danger)
0.00%
0 / 1
90
 validate_activate_plugin
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_plugin
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
12
 get_jetpack_crm_data
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 activate_crm_jetpack_forms_extension
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 jetpack_crm_data_permission_check
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 activate_crm_extensions_permission_check
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 set_has_seen_wc_connection_modal
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_features_available
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 get_features_enabled
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 get_features_permission_check
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
2.01
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * Register WP REST API endpoints for Jetpack.
4 *
5 * @package automattic/jetpack
6 */
7
8use Automattic\Jetpack\Connection\Client;
9use Automattic\Jetpack\Connection\Manager as Connection_Manager;
10use Automattic\Jetpack\Connection\Rest_Authentication;
11use Automattic\Jetpack\Connection\REST_Connector;
12use Automattic\Jetpack\Connection\REST_Jetpack_AI_JWT;
13use Automattic\Jetpack\Connection\SSO;
14use Automattic\Jetpack\Jetpack_CRM_Data;
15use Automattic\Jetpack\Plugins_Installer;
16use Automattic\Jetpack\Protect\Sections\Firewall as Protect_Firewall;
17use Automattic\Jetpack\Stats\Options as Stats_Options;
18use Automattic\Jetpack\Status\Visitor;
19use Automattic\Jetpack\Waf\Brute_Force_Protection\Brute_Force_Protection_Shared_Functions;
20use Automattic\Jetpack\Waf\Waf_Compatibility;
21
22// Disable direct access.
23if ( ! defined( 'ABSPATH' ) ) {
24    exit( 0 );
25}
26
27// Load WP_Error for error messages.
28require_once ABSPATH . '/wp-includes/class-wp-error.php';
29
30// Register endpoints when WP REST API is initialized.
31add_action( 'rest_api_init', array( 'Jetpack_Core_Json_Api_Endpoints', 'register_endpoints' ) );
32// Load API endpoints that are synced with WP.com
33// Each of these is a class that will register its own routes on 'rest_api_init'.
34require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/load-wpcom-endpoints.php';
35
36require_once JETPACK__PLUGIN_DIR . 'modules/subscriptions/class-settings.php';
37
38/**
39 * Class Jetpack_Core_Json_Api_Endpoints
40 *
41 * @since 4.3.0
42 */
43class Jetpack_Core_Json_Api_Endpoints {
44    /**
45     * Roles that can access Stats once they're granted access.
46     *
47     * @var array
48     */
49    public static $stats_roles;
50
51    /**
52     * Declare the Jetpack REST API endpoints.
53     *
54     * @since 4.3.0
55     */
56    public static function register_endpoints() {
57
58        // Load API endpoint base classes.
59        require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-xmlrpc-consumer-endpoint.php';
60
61        // Load API endpoints.
62        require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-module-endpoints.php';
63        require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-site-endpoints.php';
64        require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-widgets-endpoints.php';
65
66        self::$stats_roles = array( 'administrator', 'editor', 'author', 'contributor', 'subscriber' );
67
68        $ixr_client             = new Jetpack_IXR_Client( array( 'user_id' => get_current_user_id() ) );
69        $core_api_endpoint      = new Jetpack_Core_API_Data( $ixr_client );
70        $module_list_endpoint   = new Jetpack_Core_API_Module_List_Endpoint();
71        $module_data_endpoint   = new Jetpack_Core_API_Module_Data_Endpoint();
72        $module_toggle_endpoint = new Jetpack_Core_API_Module_Toggle_Endpoint( new Jetpack_IXR_Client() );
73        $site_endpoint          = new Jetpack_Core_API_Site_Endpoint();
74        $widget_endpoint        = new Jetpack_Core_API_Widget_Endpoint();
75
76        // My Jetpack and Agents Manager register the same controller; its guard keeps the route registered once.
77        ( new REST_Jetpack_AI_JWT() )->register_rest_route();
78
79        register_rest_route(
80            'jetpack/v4',
81            'plans',
82            array(
83                'methods'             => WP_REST_Server::READABLE,
84                'callback'            => __CLASS__ . '::get_plans',
85                'permission_callback' => __CLASS__ . '::connect_url_permission_callback',
86            )
87        );
88
89        register_rest_route(
90            'jetpack/v4',
91            'products',
92            array(
93                'methods'             => WP_REST_Server::READABLE,
94                'callback'            => __CLASS__ . '::get_products',
95                'permission_callback' => __CLASS__ . '::connect_url_permission_callback',
96            )
97        );
98
99        register_rest_route(
100            'jetpack/v4',
101            'marketing/survey',
102            array(
103                'methods'             => WP_REST_Server::CREATABLE,
104                'callback'            => __CLASS__ . '::submit_survey',
105                'permission_callback' => __CLASS__ . '::disconnect_site_permission_callback',
106            )
107        );
108
109        register_rest_route(
110            'jetpack/v4',
111            '/rewind',
112            array(
113                'methods'             => WP_REST_Server::READABLE,
114                'callback'            => __CLASS__ . '::get_rewind_data',
115                'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
116            )
117        );
118
119        register_rest_route(
120            'jetpack/v4',
121            '/scan',
122            array(
123                'methods'             => WP_REST_Server::READABLE,
124                'callback'            => __CLASS__ . '::get_scan_state',
125                'permission_callback' => __CLASS__ . '::view_scan_state_permission_check',
126            )
127        );
128
129        // Fetches a fresh connect URL.
130        register_rest_route(
131            'jetpack/v4',
132            '/connection/url',
133            array(
134                'methods'             => WP_REST_Server::READABLE,
135                'callback'            => __CLASS__ . '::build_connect_url',
136                'permission_callback' => __CLASS__ . '::connect_url_permission_callback',
137                'args'                => array(
138                    'from'     => array( 'type' => 'string' ),
139                    'redirect' => array( 'type' => 'string' ),
140                ),
141            )
142        );
143
144        // Current user: get or set tracking settings.
145        register_rest_route(
146            'jetpack/v4',
147            '/tracking/settings',
148            array(
149                array(
150                    'methods'             => WP_REST_Server::READABLE,
151                    'callback'            => __CLASS__ . '::get_user_tracking_settings',
152                    'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
153                ),
154                array(
155                    'methods'             => WP_REST_Server::EDITABLE,
156                    'callback'            => __CLASS__ . '::update_user_tracking_settings',
157                    'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
158                    'args'                => array(
159                        'tracks_opt_out' => array( 'type' => 'boolean' ),
160                    ),
161                ),
162            )
163        );
164
165        // Get current site features.
166        register_rest_route(
167            'jetpack/v4',
168            '/site/features',
169            array(
170                'methods'             => WP_REST_Server::READABLE,
171                'callback'            => array( $site_endpoint, 'get_features' ),
172                'permission_callback' => array( $site_endpoint, 'can_request' ),
173            )
174        );
175
176        register_rest_route(
177            'jetpack/v4',
178            '/site/products',
179            array(
180                'methods'             => WP_REST_Server::READABLE,
181                'callback'            => array( $site_endpoint, 'get_products' ),
182                'permission_callback' => array( $site_endpoint, 'can_request' ),
183            )
184        );
185
186        // Get current site purchases.
187        register_rest_route(
188            'jetpack/v4',
189            '/site/purchases',
190            array(
191                'methods'             => WP_REST_Server::READABLE,
192                'callback'            => array( $site_endpoint, 'get_purchases' ),
193                'permission_callback' => array( $site_endpoint, 'can_request' ),
194            )
195        );
196
197        // Get current site benefits.
198        register_rest_route(
199            'jetpack/v4',
200            '/site/benefits',
201            array(
202                'methods'             => WP_REST_Server::READABLE,
203                'callback'            => array( $site_endpoint, 'get_benefits' ),
204                'permission_callback' => array( $site_endpoint, 'can_request' ),
205            )
206        );
207
208        // Get Activity Log data for this site.
209        register_rest_route(
210            'jetpack/v4',
211            '/site/activity',
212            array(
213                'methods'             => WP_REST_Server::READABLE,
214                'callback'            => __CLASS__ . '::get_site_activity',
215                'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
216            )
217        );
218
219        // Return all modules.
220        register_rest_route(
221            'jetpack/v4',
222            '/module/all',
223            array(
224                'methods'             => WP_REST_Server::READABLE,
225                'callback'            => array( $module_list_endpoint, 'process' ),
226                'permission_callback' => array( $module_list_endpoint, 'can_request' ),
227            )
228        );
229
230        // Activate many modules.
231        register_rest_route(
232            'jetpack/v4',
233            '/module/all/active',
234            array(
235                'methods'             => WP_REST_Server::EDITABLE,
236                'callback'            => array( $module_list_endpoint, 'process' ),
237                'permission_callback' => array( $module_list_endpoint, 'can_request' ),
238                'args'                => array(
239                    'modules' => array(
240                        'default'           => '',
241                        'type'              => 'array',
242                        'items'             => array(
243                            'type' => 'string',
244                        ),
245                        'required'          => true,
246                        'validate_callback' => __CLASS__ . '::validate_module_list',
247                    ),
248                    'active'  => array(
249                        'default'           => true,
250                        'type'              => 'boolean',
251                        'required'          => false,
252                        'validate_callback' => __CLASS__ . '::validate_boolean',
253                    ),
254                ),
255            )
256        );
257
258        // Return a single module and update it when needed.
259        register_rest_route(
260            'jetpack/v4',
261            '/module/(?P<slug>[a-z\-]+)',
262            array(
263                'methods'             => WP_REST_Server::READABLE,
264                'callback'            => array( $core_api_endpoint, 'process' ),
265                'permission_callback' => array( $core_api_endpoint, 'can_request' ),
266            )
267        );
268
269        // Activate and deactivate a module.
270        register_rest_route(
271            'jetpack/v4',
272            '/module/(?P<slug>[a-z\-]+)/active',
273            array(
274                'methods'             => WP_REST_Server::EDITABLE,
275                'callback'            => array( $module_toggle_endpoint, 'process' ),
276                'permission_callback' => array( $module_toggle_endpoint, 'can_request' ),
277                'args'                => array(
278                    'active' => array(
279                        'default'           => true,
280                        'type'              => 'boolean',
281                        'required'          => true,
282                        'validate_callback' => __CLASS__ . '::validate_boolean',
283                    ),
284                ),
285            )
286        );
287
288        // Update a module.
289        register_rest_route(
290            'jetpack/v4',
291            '/module/(?P<slug>[a-z\-]+)',
292            array(
293                'methods'             => WP_REST_Server::EDITABLE,
294                'callback'            => array( $core_api_endpoint, 'process' ),
295                'permission_callback' => array( $core_api_endpoint, 'can_request' ),
296                'args'                => self::get_updateable_parameters( 'any' ),
297            )
298        );
299
300        // Get data for a specific module, i.e. Protect block count, WPCOM stats,
301        // Akismet spam count, etc.
302        register_rest_route(
303            'jetpack/v4',
304            '/module/(?P<slug>[a-z\-]+)/data',
305            array(
306                'methods'             => WP_REST_Server::READABLE,
307                'callback'            => array( $module_data_endpoint, 'process' ),
308                'permission_callback' => array( $module_data_endpoint, 'can_request' ),
309                'args'                => array(
310                    'range' => array(
311                        'default'           => 'day',
312                        'type'              => 'string',
313                        'required'          => false,
314                        'validate_callback' => __CLASS__ . '::validate_string',
315                    ),
316                ),
317            )
318        );
319
320        // Check if the API key for a specific service is valid or not.
321        register_rest_route(
322            'jetpack/v4',
323            '/module/(?P<service>[a-z\-]+)/key/check',
324            array(
325                'methods'             => WP_REST_Server::READABLE,
326                'callback'            => array( $module_data_endpoint, 'key_check' ),
327                'permission_callback' => __CLASS__ . '::update_settings_permission_check',
328                'sanitize_callback'   => 'sanitize_text_field',
329            )
330        );
331
332        register_rest_route(
333            'jetpack/v4',
334            '/module/(?P<service>[a-z\-]+)/key/check',
335            array(
336                'methods'             => WP_REST_Server::EDITABLE,
337                'callback'            => array( $module_data_endpoint, 'key_check' ),
338                'permission_callback' => __CLASS__ . '::update_settings_permission_check',
339                'sanitize_callback'   => 'sanitize_text_field',
340                'args'                => array(
341                    'api_key' => array(
342                        'default'           => '',
343                        'type'              => 'string',
344                        'validate_callback' => __CLASS__ . '::validate_alphanum',
345                    ),
346                ),
347            )
348        );
349
350        // Update any Jetpack module option or setting.
351        register_rest_route(
352            'jetpack/v4',
353            '/settings',
354            array(
355                'methods'             => WP_REST_Server::EDITABLE,
356                'callback'            => array( $core_api_endpoint, 'process' ),
357                'permission_callback' => array( $core_api_endpoint, 'can_request' ),
358                'args'                => self::get_updateable_parameters( 'any' ),
359            )
360        );
361
362        // Update a module.
363        register_rest_route(
364            'jetpack/v4',
365            '/settings/(?P<slug>[a-z\-]+)',
366            array(
367                'methods'             => WP_REST_Server::EDITABLE,
368                'callback'            => array( $core_api_endpoint, 'process' ),
369                'permission_callback' => array( $core_api_endpoint, 'can_request' ),
370                'args'                => self::get_updateable_parameters(),
371            )
372        );
373
374        // Return all module settings.
375        register_rest_route(
376            'jetpack/v4',
377            '/settings/',
378            array(
379                'methods'             => WP_REST_Server::READABLE,
380                'callback'            => array( $core_api_endpoint, 'process' ),
381                'permission_callback' => array( $core_api_endpoint, 'can_request' ),
382            )
383        );
384
385        // Reset all Jetpack options.
386        register_rest_route(
387            'jetpack/v4',
388            '/options/(?P<options>[a-z\-]+)',
389            array(
390                'methods'             => WP_REST_Server::EDITABLE,
391                'callback'            => __CLASS__ . '::reset_jetpack_options',
392                'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
393            )
394        );
395
396        // Updates: get number of plugin updates available.
397        register_rest_route(
398            'jetpack/v4',
399            '/updates/plugins',
400            array(
401                'methods'             => WP_REST_Server::READABLE,
402                'callback'            => __CLASS__ . '::get_plugin_update_count',
403                'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
404            )
405        );
406
407        // Dismiss Jetpack Notices.
408        register_rest_route(
409            'jetpack/v4',
410            '/notice/(?P<notice>[a-z\-_]+)',
411            array(
412                'methods'             => WP_REST_Server::EDITABLE,
413                'callback'            => __CLASS__ . '::dismiss_notice',
414                'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
415            )
416        );
417
418        /*
419         * Plugins: manage plugins on your site.
420         *
421         * @since 8.9.0
422         *
423         * @to-do: deprecate and switch to /wp/v2/plugins when WordPress 5.5 is the minimum required version.
424         * Noting that the `source` parameter is Jetpack-specific (not implemented in Core).
425         */
426        register_rest_route(
427            'jetpack/v4',
428            '/plugins',
429            array(
430                array(
431                    'methods'             => WP_REST_Server::READABLE,
432                    'callback'            => __CLASS__ . '::get_plugins',
433                    'permission_callback' => __CLASS__ . '::activate_plugins_permission_check',
434                ),
435                array(
436                    'methods'             => WP_REST_Server::CREATABLE,
437                    'callback'            => __CLASS__ . '::install_plugin',
438                    'permission_callback' => __CLASS__ . '::activate_plugins_permission_check',
439                    'args'                => array(
440                        'slug'   => array(
441                            'type'        => 'string',
442                            'required'    => true,
443                            'description' => __( 'WordPress.org plugin directory slug.', 'jetpack' ),
444                            'pattern'     => '[\w\-]+',
445                        ),
446                        'status' => array(
447                            'description' => __( 'The plugin activation status.', 'jetpack' ),
448                            'type'        => 'string',
449                            'enum'        => is_multisite() ? array( 'inactive', 'active', 'network-active' ) : array( 'inactive', 'active' ),
450                            'default'     => 'inactive',
451                        ),
452                        'source' => array(
453                            'required'          => false,
454                            'type'              => 'string',
455                            'validate_callback' => __CLASS__ . '::validate_string',
456                        ),
457                    ),
458                ),
459            )
460        );
461
462        /*
463         * Plugins: activate a specific plugin.
464         *
465         * @since 8.9.0
466         *
467         * @to-do: deprecate and switch to /wp/v2/plugins when WordPress 5.5 is the minimum required version.
468         * Noting that the `source` parameter is Jetpack-specific (not implemented in Core).
469         */
470        register_rest_route(
471            'jetpack/v4',
472            '/plugins/(?P<plugin>[^.\/]+(?:\/[^.\/]+)?)',
473            array(
474                'methods'             => WP_REST_Server::EDITABLE,
475                'callback'            => __CLASS__ . '::activate_plugin',
476                'permission_callback' => __CLASS__ . '::activate_plugins_permission_check',
477                'args'                => array(
478                    'status' => array(
479                        'required'          => true,
480                        'type'              => 'string',
481                        'validate_callback' => __CLASS__ . '::validate_activate_plugin',
482                    ),
483                    'source' => array(
484                        'required'          => false,
485                        'type'              => 'string',
486                        'validate_callback' => __CLASS__ . '::validate_string',
487                    ),
488                ),
489            )
490        );
491
492        // Plugins: check if the plugin is active.
493        register_rest_route(
494            'jetpack/v4',
495            '/plugin/(?P<plugin>[a-z\/\.\-_]+)',
496            array(
497                'methods'             => WP_REST_Server::READABLE,
498                'callback'            => __CLASS__ . '::get_plugin',
499                'permission_callback' => __CLASS__ . '::activate_plugins_permission_check',
500            )
501        );
502
503        // Widgets: get information about a widget that supports it.
504        register_rest_route(
505            'jetpack/v4',
506            '/widgets/(?P<id>[0-9a-z\-_]+)',
507            array(
508                'methods'             => WP_REST_Server::READABLE,
509                'callback'            => array( $widget_endpoint, 'process' ),
510                'permission_callback' => array( $widget_endpoint, 'can_request' ),
511            )
512        );
513
514        // Site Verify: check if the site is verified, and a get verification token if not.
515        register_rest_route(
516            'jetpack/v4',
517            '/verify-site/(?P<service>[a-z\-_]+)',
518            array(
519                'methods'             => WP_REST_Server::READABLE,
520                'callback'            => __CLASS__ . '::is_site_verified_and_token',
521                'permission_callback' => __CLASS__ . '::update_settings_permission_check',
522            )
523        );
524
525        register_rest_route(
526            'jetpack/v4',
527            '/verify-site/(?P<service>[a-z\-_]+)/(?<keyring_id>[0-9]+)',
528            array(
529                'methods'             => WP_REST_Server::READABLE,
530                'callback'            => __CLASS__ . '::is_site_verified_and_token',
531                'permission_callback' => __CLASS__ . '::update_settings_permission_check',
532            )
533        );
534
535        // Site Verify: tell a service to verify the site.
536        register_rest_route(
537            'jetpack/v4',
538            '/verify-site/(?P<service>[a-z\-_]+)',
539            array(
540                'methods'             => WP_REST_Server::EDITABLE,
541                'callback'            => __CLASS__ . '::verify_site',
542                'permission_callback' => __CLASS__ . '::update_settings_permission_check',
543                'args'                => array(
544                    'keyring_id' => array(
545                        'required'          => true,
546                        'type'              => 'integer',
547                        'validate_callback' => __CLASS__ . '::validate_posint',
548                    ),
549                ),
550            )
551        );
552
553        /*
554         * Manage the Jetpack CRM plugin's integration with Jetpack contact forms.
555         */
556        register_rest_route(
557            'jetpack/v4',
558            'jetpack_crm',
559            array(
560                array(
561                    'methods'             => WP_REST_Server::READABLE,
562                    'callback'            => __CLASS__ . '::get_jetpack_crm_data',
563                    'permission_callback' => __CLASS__ . '::jetpack_crm_data_permission_check',
564                ),
565                array(
566                    'methods'             => WP_REST_Server::EDITABLE,
567                    'callback'            => __CLASS__ . '::activate_crm_jetpack_forms_extension',
568                    'permission_callback' => __CLASS__ . '::activate_crm_extensions_permission_check',
569                    'args'                => array(
570                        'extension' => array(
571                            'required' => true,
572                            'type'     => 'text',
573                        ),
574                    ),
575                ),
576            )
577        );
578
579        register_rest_route(
580            'jetpack/v4',
581            'purchase-token',
582            array(
583                array(
584                    'methods'             => WP_REST_Server::READABLE,
585                    'callback'            => __CLASS__ . '::get_purchase_token',
586                    'permission_callback' => __CLASS__ . '::purchase_token_permission_check',
587                ),
588                array(
589                    'methods'             => WP_REST_Server::CREATABLE,
590                    'callback'            => __CLASS__ . '::delete_purchase_token',
591                    'permission_callback' => __CLASS__ . '::purchase_token_permission_check',
592                ),
593            )
594        );
595
596        /*
597         * Set the Jetpack Option `has_see_wc_connection_modal` to true
598         */
599        register_rest_route(
600            'jetpack/v4',
601            'seen-wc-connection-modal',
602            array(
603                'methods'             => WP_REST_Server::EDITABLE,
604                'callback'            => __CLASS__ . '::set_has_seen_wc_connection_modal',
605                'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
606            )
607        );
608
609        // Save subscriber token and redirect
610        register_rest_route(
611            'jetpack/v4',
612            '/subscribers/auth',
613            array(
614                'methods'             => WP_REST_Server::READABLE,
615                'callback'            => __CLASS__ . '::set_subscriber_cookie_and_redirect',
616                'permission_callback' => '__return_true',
617                'args'                => array(
618                    'redirect_url' => array(
619                        'required'          => true,
620                        'description'       => __( 'The URL to redirect to.', 'jetpack' ),
621                        'validate_callback' => 'wp_http_validate_url',
622                        'sanitize_callback' => 'sanitize_url',
623                        'type'              => 'string',
624                        'format'            => 'uri',
625                    ),
626                ),
627            )
628        );
629
630        /**
631         * Get the list of available Jetpack features.
632         *
633         * @since 13.9
634         */
635        register_rest_route(
636            'jetpack/v4',
637            '/features/available',
638            array(
639                'methods'             => WP_REST_Server::READABLE,
640                'callback'            => array( static::class, 'get_features_available' ),
641                'permission_callback' => array( static::class, 'get_features_permission_check' ),
642            )
643        );
644
645        /**
646         * Get the list of enabled Jetpack features.
647         *
648         * @since 13.9
649         */
650        register_rest_route(
651            'jetpack/v4',
652            '/features/enabled',
653            array(
654                'methods'             => WP_REST_Server::READABLE,
655                'callback'            => array( static::class, 'get_features_enabled' ),
656                'permission_callback' => array( static::class, 'get_features_permission_check' ),
657            )
658        );
659    }
660
661    /**
662     * Ask WPCOM for a JWT token to use for OpenAI conversations.
663     *
664     * @deprecated since 16.2
665     * @see Automattic\Jetpack\Connection\REST_Jetpack_AI_JWT::get_jwt()
666     *
667     * @return array|WP_Error The token and blog ID, or the error from WPCOM.
668     */
669    public static function get_openai_jwt() {
670        _deprecated_function( __METHOD__, 'jetpack-16.2', '\Automattic\Jetpack\Connection\REST_Jetpack_AI_JWT::get_jwt' );
671
672        $response = ( new REST_Jetpack_AI_JWT() )->get_jwt();
673
674        if ( is_wp_error( $response ) ) {
675            return $response;
676        }
677
678        // Pre-deprecation callers expect the raw array, not a WP_REST_Response.
679        return $response->get_data();
680    }
681
682    /**
683     * Set subscriber cookie and redirect
684     *
685     * @param \WP_Rest_Request $request The URL to redirect to.
686     *
687     * @return WP_Error|WP_REST_Response
688     */
689    public static function set_subscriber_cookie_and_redirect( $request ) {
690        require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/premium-content/_inc/subscription-service/include.php';
691        $subscription_service = \Automattic\Jetpack\Extensions\Premium_Content\subscription_service();
692        // Note: get_and_set_token_from_request() sets the subscriber cookie as a side effect.
693        // The cookie is set regardless of the redirect target below; only the redirect is gated.
694        $token          = $subscription_service->get_and_set_token_from_request();
695        $payload        = $subscription_service->decode_token( $token );
696        $is_valid_token = ! empty( $payload );
697        if ( ! $is_valid_token ) {
698            return new WP_Error( 'invalid-token', 'Invalid Token', array( 'status' => 403 ) );
699        }
700
701        // Only redirect to the current site, not to an arbitrary host.
702        $redirect_url = wp_validate_redirect( $request['redirect_url'], '' );
703        if ( ! $redirect_url ) {
704            return new WP_Error( 'invalid-redirect', 'Invalid Redirect URL', array( 'status' => 400 ) );
705        }
706
707        return new WP_REST_Response( null, 302, array( 'location' => $redirect_url ) );
708    }
709
710    /**
711     * Return a purchase token used for site-connected (non user-authenticated) checkout.
712     *
713     * @return string|WP_Error The current purchase token or WP_Error with error details.
714     */
715    public static function get_purchase_token() {
716        $blog_id = Jetpack_Options::get_option( 'id' );
717        if ( ! $blog_id ) {
718            return new WP_Error( 'site_not_registered', esc_html__( 'Site not registered.', 'jetpack' ) );
719        }
720
721        return Jetpack_Options::get_option( 'purchase_token', '' );
722    }
723
724    /**
725     * Delete the current purchase token.
726     *
727     * @return boolean|WP_Error Whether the token was deleted or WP_Error with error details.
728     */
729    public static function delete_purchase_token() {
730        $blog_id = Jetpack_Options::get_option( 'id' );
731        if ( ! $blog_id ) {
732            return new WP_Error( 'site_not_registered', esc_html__( 'Site not registered.', 'jetpack' ) );
733        }
734
735        return Jetpack_Options::delete_option( 'purchase_token' );
736    }
737
738    /**
739     * Get list of Jetpack Plans.
740     *
741     * @param WP_REST_Request $request The request.
742     */
743    public static function get_plans( $request ) {
744        $request = Client::wpcom_json_api_request_as_user(
745            '/plans?_locale=' . get_user_locale(),
746            '2',
747            array(
748                'method'  => 'GET',
749                'headers' => array(
750                    'X-Forwarded-For' => ( new Visitor() )->get_ip( true ),
751                ),
752            )
753        );
754
755        $body = json_decode( wp_remote_retrieve_body( $request ) );
756        if ( 200 === wp_remote_retrieve_response_code( $request ) ) {
757            $data = $body;
758        } else {
759            // something went wrong so we'll just return the response without caching.
760            return $body;
761        }
762
763        return $data;
764    }
765
766    /**
767     * Gets the WP.com products that are in use on wpcom.
768     * Similar to the WP.com plans that we currently in user on WPCOM.
769     *
770     * @param WP_REST_Request $request The request.
771     *
772     * @return string|WP_Error A JSON object of wpcom products if the request was successful, or a WP_Error otherwise.
773     */
774    public static function get_products( $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
775        $wpcom_request = Client::wpcom_json_api_request_as_user(
776            '/products?_locale=' . get_user_locale() . '&type=jetpack',
777            '2',
778            array(
779                'method'  => 'GET',
780                'headers' => array(
781                    'X-Forwarded-For' => ( new Visitor() )->get_ip( true ),
782                ),
783            )
784        );
785
786        $response_code = wp_remote_retrieve_response_code( $wpcom_request );
787        if ( 200 === $response_code ) {
788            return json_decode( wp_remote_retrieve_body( $wpcom_request ) );
789        } else {
790            // Something went wrong so we'll just return the response without caching.
791            return new WP_Error(
792                'failed_to_fetch_data',
793                esc_html__( 'Unable to fetch the requested data.', 'jetpack' ),
794                array( 'status' => $response_code )
795            );
796        }
797    }
798
799    /**
800     * Send Survey details to WordPress.com.
801     *
802     * @param WP_REST_Request $request The request.
803     */
804    public static function submit_survey( $request ) {
805        $wpcom_request = Client::wpcom_json_api_request_as_user(
806            '/marketing/survey',
807            'v2',
808            array(
809                'method'  => 'POST',
810                'headers' => array(
811                    'Content-Type'    => 'application/json',
812                    'X-Forwarded-For' => ( new Visitor() )->get_ip( true ),
813                ),
814            ),
815            $request->get_json_params()
816        );
817
818        $wpcom_request_body = json_decode( wp_remote_retrieve_body( $wpcom_request ) );
819        if ( 200 === wp_remote_retrieve_response_code( $wpcom_request ) ) {
820            $data = $wpcom_request_body;
821        } else {
822            // something went wrong so we'll just return the response without caching.
823            return $wpcom_request_body;
824        }
825
826        return $data;
827    }
828
829    /**
830     * Checks if this site has been verified using a service - only 'google' supported at present - and a specfic
831     *  keyring to use to get the token if it is not
832     *
833     * Returns 'verified' = true/false, and a token if 'verified' is false and site is ready for verification
834     *
835     * @since 6.6.0
836     *
837     * @param WP_REST_Request $request The request sent to the WP REST API.
838     *
839     * @return array|WP_Error
840     */
841    public static function is_site_verified_and_token( $request ) {
842        /**
843         * Return an error if the site uses a Maintenance / Coming Soon plugin
844         * and if the plugin is configured to make the site private.
845         *
846         * We currently handle the following plugins:
847         * - https://github.com/mojoness/mojo-marketplace-wp-plugin (used by bluehost)
848         * - https://wordpress.org/plugins/mojo-under-construction
849         * - https://wordpress.org/plugins/under-construction-page
850         * - https://wordpress.org/plugins/ultimate-under-construction
851         * - https://wordpress.org/plugins/coming-soon
852         *
853         * You can handle this in your own plugin thanks to the `jetpack_is_under_construction_plugin` filter.
854         * If the filter returns true, we will consider the site as under construction.
855         */
856        $mm_coming_soon                       = get_option( 'mm_coming_soon', null );
857        $under_construction_activation_status = get_option( 'underConstructionActivationStatus', null );
858        $ucp_options                          = get_option( 'ucp_options', array() );
859        $uuc_settings                         = get_option( 'uuc_settings', array() );
860        $csp4                                 = get_option( 'seed_csp4_settings_content', array() );
861        if (
862            ( Jetpack::is_plugin_active( 'mojo-marketplace-wp-plugin/mojo-marketplace.php' ) && 'true' === $mm_coming_soon )
863            || Jetpack::is_plugin_active( 'mojo-under-construction/mojo-contruction.php' ) && 1 == $under_construction_activation_status // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
864            || ( Jetpack::is_plugin_active( 'under-construction-page/under-construction.php' ) && isset( $ucp_options['status'] ) && 1 == $ucp_options['status'] ) // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
865            || ( Jetpack::is_plugin_active( 'ultimate-under-construction/ultimate-under-construction.php' ) && isset( $uuc_settings['enable'] ) && 1 == $uuc_settings['enable'] ) // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
866            || ( Jetpack::is_plugin_active( 'coming-soon/coming-soon.php' ) && isset( $csp4['status'] ) && ( 1 == $csp4['status'] || 2 == $csp4['status'] ) ) // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
867            ||
868            /**
869             * Allow plugins to mark a site as "under construction".
870             *
871             * @since 6.7.0
872             *
873             * @param false bool Is the site under construction? Default to false.
874             */
875            true === apply_filters( 'jetpack_is_under_construction_plugin', false )
876        ) {
877            return new WP_Error( 'forbidden', __( 'Site is under construction and cannot be verified', 'jetpack' ) );
878        }
879
880        $xml = new Jetpack_IXR_Client(
881            array(
882                'user_id' => get_current_user_id(),
883            )
884        );
885
886        $args = array(
887            'user_id' => get_current_user_id(),
888            'service' => $request['service'],
889        );
890
891        if ( isset( $request['keyring_id'] ) ) {
892            $args['keyring_id'] = $request['keyring_id'];
893        }
894
895        $xml->query( 'jetpack.isSiteVerified', $args );
896
897        if ( $xml->isError() ) {
898            return new WP_Error( 'error_checking_if_site_verified_google', sprintf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() ) );
899        } else {
900            return $xml->getResponse();
901        }
902    }
903
904    /**
905     * Verify site with external service.
906     *
907     * @param WP_REST_Request $request The request.
908     */
909    public static function verify_site( $request ) {
910        $xml = new Jetpack_IXR_Client(
911            array(
912                'user_id' => get_current_user_id(),
913            )
914        );
915
916        $params = $request->get_json_params();
917
918        $xml->query(
919            'jetpack.verifySite',
920            array(
921                'user_id'    => get_current_user_id(),
922                'service'    => $request['service'],
923                'keyring_id' => $params['keyring_id'],
924            )
925        );
926
927        if ( $xml->isError() ) {
928            return new WP_Error( 'error_verifying_site_google', sprintf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() ) );
929        } else {
930            $response = $xml->getResponse();
931
932            if ( ! empty( $response['errors'] ) ) {
933                $error         = new WP_Error();
934                $error->errors = $response['errors'];
935                return $error;
936            }
937
938            return $response;
939        }
940    }
941
942    /**
943     * Handles dismissing of Jetpack Notices
944     *
945     * @since 4.3.0
946     *
947     * @param WP_REST_Request $request The request sent to the WP REST API.
948     *
949     * @return array|WP_Error
950     */
951    public static function dismiss_notice( $request ) {
952        $notice = $request['notice'];
953
954        if ( ! isset( $request['dismissed'] ) || true !== $request['dismissed'] ) {
955            return new WP_Error( 'invalid_param', esc_html__( 'Invalid parameter "dismissed".', 'jetpack' ), array( 'status' => 404 ) );
956        }
957
958        if ( isset( $notice ) && ! empty( $notice ) ) {
959            switch ( $notice ) {
960                case 'feedback_dash_request':
961                case 'welcome':
962                    $notices            = get_option( 'jetpack_dismissed_notices', array() );
963                    $notices[ $notice ] = true;
964                    update_option( 'jetpack_dismissed_notices', $notices );
965                    return rest_ensure_response( get_option( 'jetpack_dismissed_notices', array() ) );
966
967                default:
968                    return new WP_Error( 'invalid_param', esc_html__( 'Invalid parameter "notice".', 'jetpack' ), array( 'status' => 404 ) );
969            }
970        }
971
972        return new WP_Error( 'required_param', esc_html__( 'Missing parameter "notice".', 'jetpack' ), array( 'status' => 404 ) );
973    }
974
975    /**
976     * Verify that the user can disconnect the site.
977     *
978     * @since 4.3.0
979     *
980     * @return bool|WP_Error True if user is able to disconnect the site.
981     */
982    public static function disconnect_site_permission_callback() {
983        if ( current_user_can( 'jetpack_disconnect' ) ) {
984            return true;
985        }
986
987        return new WP_Error(
988            'invalid_user_permission_jetpack_disconnect',
989            REST_Connector::get_user_permissions_error_msg(),
990            array( 'status' => rest_authorization_required_code() )
991        );
992    }
993
994    /**
995     * Verify that the user can get a connect/link URL
996     *
997     * @since 4.3.0
998     *
999     * @return bool|WP_Error True if user is able to disconnect the site.
1000     */
1001    public static function connect_url_permission_callback() {
1002        if ( current_user_can( 'jetpack_connect_user' ) ) {
1003            return true;
1004        }
1005
1006        return new WP_Error(
1007            'invalid_user_permission_jetpack_connect',
1008            REST_Connector::get_user_permissions_error_msg(),
1009            array( 'status' => rest_authorization_required_code() )
1010        );
1011    }
1012
1013    /**
1014     * Verify that a user can use the /connection/user endpoint. Has to be a registered user and be currently linked.
1015     *
1016     * @uses Automattic\Jetpack\Connection\Manager::is_user_connected();)
1017     *
1018     * @deprecated since Jetpack 14.4.0
1019     * @see Automattic\Jetpack\Connection\REST_Connector::unlink_user_permission_callback()
1020     *
1021     * @since 4.3.0
1022     *
1023     * @return bool|WP_Error True if user is able to unlink.
1024     */
1025    public static function unlink_user_permission_callback() {
1026        _deprecated_function( __METHOD__, 'jetpack-14.4.0', 'Automattic\Jetpack\Connection\REST_Connector::unlink_user_permission_callback()' );
1027        return REST_Connector::unlink_user_permission_callback();
1028    }
1029
1030    /**
1031     * Verify that user can manage Jetpack modules.
1032     *
1033     * @since 4.3.0
1034     *
1035     * @return bool Whether user has the capability 'jetpack_manage_modules'.
1036     */
1037    public static function manage_modules_permission_check() {
1038        if ( current_user_can( 'jetpack_manage_modules' ) ) {
1039            return true;
1040        }
1041
1042        return new WP_Error(
1043            'invalid_user_permission_manage_modules',
1044            REST_Connector::get_user_permissions_error_msg(),
1045            array( 'status' => rest_authorization_required_code() )
1046        );
1047    }
1048
1049    /**
1050     * Verify that user can update Jetpack modules.
1051     *
1052     * @since 4.3.0
1053     *
1054     * @return bool Whether user has the capability 'jetpack_configure_modules'.
1055     */
1056    public static function configure_modules_permission_check() {
1057        if ( current_user_can( 'jetpack_configure_modules' ) ) {
1058            return true;
1059        }
1060
1061        return new WP_Error(
1062            'invalid_user_permission_configure_modules',
1063            REST_Connector::get_user_permissions_error_msg(),
1064            array( 'status' => rest_authorization_required_code() )
1065        );
1066    }
1067
1068    /**
1069     * Verify that user can view Jetpack admin page.
1070     *
1071     * @since 4.3.0
1072     *
1073     * @return bool Whether user has the capability 'jetpack_admin_page'.
1074     */
1075    public static function view_admin_page_permission_check() {
1076        if ( current_user_can( 'jetpack_admin_page' ) ) {
1077            return true;
1078        }
1079
1080        return new WP_Error(
1081            'invalid_user_permission_view_admin',
1082            REST_Connector::get_user_permissions_error_msg(),
1083            array( 'status' => rest_authorization_required_code() )
1084        );
1085    }
1086
1087    /**
1088     * Verify that user can view the Scan state, the same users who see the Protect menu and the admin bar notice.
1089     *
1090     * @since $$next-version$$
1091     *
1092     * @return bool|WP_Error Whether user has the capability 'manage_options'.
1093     */
1094    public static function view_scan_state_permission_check() {
1095        if ( current_user_can( 'manage_options' ) ) {
1096            return true;
1097        }
1098
1099        return new WP_Error(
1100            'invalid_user_permission_view_scan_state',
1101            REST_Connector::get_user_permissions_error_msg(),
1102            array( 'status' => rest_authorization_required_code() )
1103        );
1104    }
1105
1106    /**
1107     * Verify that user can update Jetpack general settings.
1108     *
1109     * @since 4.3.0
1110     *
1111     * @return bool Whether user has the capability 'update_settings_permission_check'.
1112     */
1113    public static function update_settings_permission_check() {
1114        if ( current_user_can( 'jetpack_configure_modules' ) ) {
1115            return true;
1116        }
1117
1118        return new WP_Error(
1119            'invalid_user_permission_manage_settings',
1120            REST_Connector::get_user_permissions_error_msg(),
1121            array( 'status' => rest_authorization_required_code() )
1122        );
1123    }
1124
1125    /**
1126     * Verify that user can view Jetpack admin page and can activate plugins.
1127     *
1128     * @since 4.3.0
1129     *
1130     * @return bool Whether user has the capability 'jetpack_admin_page' and 'activate_plugins'.
1131     */
1132    public static function activate_plugins_permission_check() {
1133        if ( current_user_can( 'jetpack_admin_page' ) && current_user_can( 'activate_plugins' ) ) {
1134            return true;
1135        }
1136
1137        return new WP_Error(
1138            'invalid_user_permission_activate_plugins',
1139            REST_Connector::get_user_permissions_error_msg(),
1140            array( 'status' => rest_authorization_required_code() )
1141        );
1142    }
1143
1144    /**
1145     * Verify that user can edit other's posts (Editors and Administrators).
1146     *
1147     * @return bool Whether user has the capability 'edit_others_posts'.
1148     */
1149    public static function edit_others_posts_check() {
1150        if ( current_user_can( 'edit_others_posts' ) ) {
1151            return true;
1152        }
1153
1154        return new WP_Error(
1155            'invalid_user_permission_edit_others_posts',
1156            REST_Connector::get_user_permissions_error_msg(),
1157            array( 'status' => rest_authorization_required_code() )
1158        );
1159    }
1160
1161    /**
1162     * Verify that site can view and delete the site's purchase token.
1163     *
1164     * @return bool Whether site has level-site auth or user has the capability 'manage_options'.
1165     */
1166    public static function purchase_token_permission_check() {
1167        if ( Rest_Authentication::is_signed_with_blog_token() ) {
1168            return true;
1169        }
1170
1171        if ( current_user_can( 'manage_options' ) ) {
1172            return true;
1173        }
1174
1175        return new WP_Error(
1176            'invalid_permission_manage_purchase_token',
1177            REST_Connector::get_user_permissions_error_msg(),
1178            array( 'status' => rest_authorization_required_code() )
1179        );
1180    }
1181
1182    /**
1183     * Fetch information about the Rewind status of the site.
1184     */
1185    public static function rewind_data() {
1186        $site_id = Jetpack_Options::get_option( 'id' );
1187
1188        if ( ! $site_id ) {
1189            return new WP_Error( 'site_id_missing' );
1190        }
1191
1192        if ( ! isset( $_GET['_cacheBuster'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1193            $rewind_state = get_transient( 'jetpack_rewind_state' );
1194            if ( $rewind_state ) {
1195                return $rewind_state;
1196            }
1197        }
1198
1199        $response = Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d/rewind', $site_id ) . '?force=wpcom', '2', array(), null, 'wpcom' );
1200
1201        if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
1202            return new WP_Error( 'rewind_data_fetch_failed' );
1203        }
1204
1205        $body   = wp_remote_retrieve_body( $response );
1206        $result = json_decode( $body );
1207        set_transient( 'jetpack_rewind_state', $result, 30 * MINUTE_IN_SECONDS );
1208
1209        return $result;
1210    }
1211
1212    /**
1213     * Get rewind data
1214     *
1215     * @since 5.7.0
1216     *
1217     * @return array Array of rewind properties.
1218     */
1219    public static function get_rewind_data() {
1220        $rewind_data = self::rewind_data();
1221
1222        if ( ! is_wp_error( $rewind_data ) ) {
1223            return rest_ensure_response(
1224                array(
1225                    'code'    => 'success',
1226                    'message' => esc_html__( 'Backup & Scan data correctly received.', 'jetpack' ),
1227                    'data'    => wp_json_encode( $rewind_data, JSON_UNESCAPED_SLASHES ),
1228                )
1229            );
1230        }
1231
1232        if ( $rewind_data->get_error_code() === 'rewind_data_fetch_failed' ) {
1233            return new WP_Error( 'rewind_data_fetch_failed', esc_html__( 'Failed fetching rewind data. Try again later.', 'jetpack' ), array( 'status' => 400 ) );
1234        }
1235
1236        if ( $rewind_data->get_error_code() === 'site_id_missing' ) {
1237            return new WP_Error( 'site_id_missing', esc_html__( 'The ID of this site does not exist.', 'jetpack' ), array( 'status' => 404 ) );
1238        }
1239
1240        return new WP_Error(
1241            'error_get_rewind_data',
1242            esc_html__( 'Could not retrieve Backup & Scan data.', 'jetpack' ),
1243            array( 'status' => 500 )
1244        );
1245    }
1246
1247    /**
1248     * Gets Scan state data.
1249     *
1250     * @since 8.5.0
1251     *
1252     * @return array|WP_Error Result from WPCOM API or error.
1253     */
1254    public static function scan_state() {
1255
1256        if ( ! isset( $_GET['_cacheBuster'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1257            $scan_state = get_transient( 'jetpack_scan_state' );
1258            if ( ! empty( $scan_state ) ) {
1259                return $scan_state;
1260            }
1261        }
1262        $site_id = Jetpack_Options::get_option( 'id' );
1263
1264        if ( ! $site_id ) {
1265            return new WP_Error( 'site_id_missing' );
1266        }
1267        // The default timeout was too short in come cases.
1268        add_filter( 'http_request_timeout', array( __CLASS__, 'increase_timeout_30' ), PHP_INT_MAX - 1 );
1269        $response = Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d/scan', $site_id ) . '?force=wpcom', '2', array(), null, 'wpcom' );
1270        remove_filter( 'http_request_timeout', array( __CLASS__, 'increase_timeout_30' ), PHP_INT_MAX - 1 );
1271
1272        if ( wp_remote_retrieve_response_code( $response ) !== 200 ) {
1273            return new WP_Error( 'scan_state_fetch_failed' );
1274        }
1275
1276        $body   = wp_remote_retrieve_body( $response );
1277        $result = json_decode( $body );
1278        set_transient( 'jetpack_scan_state', $result, 30 * MINUTE_IN_SECONDS );
1279
1280        return $result;
1281    }
1282
1283    /**
1284     * Increases the request timeout value to 30 seconds.
1285     *
1286     * @return int Always returns 30.
1287     */
1288    public static function increase_timeout_30() {
1289        return 30; // 30 Seconds
1290    }
1291
1292    /**
1293     * Get Scan state for API.
1294     *
1295     * @since 8.5.0
1296     *
1297     * @return WP_REST_Response|WP_Error REST response or error state.
1298     */
1299    public static function get_scan_state() {
1300        $scan_state = self::scan_state();
1301
1302        if ( ! is_wp_error( $scan_state ) ) {
1303            return rest_ensure_response(
1304                array(
1305                    'code'    => 'success',
1306                    'message' => esc_html__( 'Scan state correctly received.', 'jetpack' ),
1307                    'data'    => wp_json_encode( $scan_state, JSON_UNESCAPED_SLASHES ),
1308                )
1309            );
1310        }
1311
1312        if ( $scan_state->get_error_code() === 'scan_state_fetch_failed' ) {
1313            return new WP_Error( 'scan_state_fetch_failed', esc_html__( 'Failed fetching rewind data. Try again later.', 'jetpack' ), array( 'status' => 400 ) );
1314        }
1315
1316        if ( $scan_state->get_error_code() === 'site_id_missing' ) {
1317            return new WP_Error( 'site_id_missing', esc_html__( 'The ID of this site does not exist.', 'jetpack' ), array( 'status' => 404 ) );
1318        }
1319
1320        return new WP_Error(
1321            'error_get_rewind_data',
1322            esc_html__( 'Could not retrieve Scan state.', 'jetpack' ),
1323            array( 'status' => 500 )
1324        );
1325    }
1326
1327    /**
1328     * Disconnects Jetpack from the WordPress.com Servers
1329     *
1330     * @deprecated since Jetpack 10.0.0
1331     * @see Automattic\Jetpack\Connection\REST_Connector::disconnect_site()
1332     *
1333     * @uses Jetpack::disconnect();
1334     * @since 4.3.0
1335     *
1336     * @param WP_REST_Request $request The request sent to the WP REST API.
1337     *
1338     * @return bool|WP_Error True if Jetpack successfully disconnected.
1339     */
1340    public static function disconnect_site( $request ) {
1341        _deprecated_function( __METHOD__, 'jetpack-10.0.0', '\Automattic\Jetpack\Connection\REST_Connector::disconnect_site' );
1342
1343        if ( ! isset( $request['isActive'] ) || false !== $request['isActive'] ) {
1344            return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
1345        }
1346
1347        if ( Jetpack::is_connection_ready() ) {
1348            Jetpack::disconnect();
1349            return rest_ensure_response( array( 'code' => 'success' ) );
1350        }
1351
1352        return new WP_Error( 'disconnect_failed', esc_html__( 'Was not able to disconnect the site. Please try again.', 'jetpack' ), array( 'status' => 400 ) );
1353    }
1354
1355    /**
1356     * Gets a new connect raw URL with fresh nonce.
1357     *
1358     * @uses Jetpack::disconnect();
1359     * @since 4.3.0
1360     *
1361     * @param WP_REST_Request $request The request sent to the WP REST API.
1362     *
1363     * @return string|WP_Error A raw URL if the connection URL could be built; error message otherwise.
1364     */
1365    public static function build_connect_url( $request = array() ) {
1366        $from     = $request['from'] ?? false;
1367        $redirect = $request['redirect'] ?? false;
1368
1369        $url = Jetpack::init()->build_connect_url( true, $redirect, $from );
1370        if ( $url ) {
1371            return rest_ensure_response( $url );
1372        }
1373
1374        return new WP_Error( 'build_connect_url_failed', esc_html__( 'Unable to build the connect URL. Please reload the page and try again.', 'jetpack' ), array( 'status' => 400 ) );
1375    }
1376
1377    /**
1378     * Get miscellaneous user data related to the connection. Similar data available in old "My Jetpack".
1379     * Information about the master/primary user.
1380     * Information about the current user.
1381     *
1382     * @deprecated since Jetpack 10.0.0
1383     * @see Automattic\Jetpack\Connection\REST_Connector::get_user_connection_data()
1384     *
1385     * @since 4.3.0
1386     *
1387     * @return object
1388     */
1389    public static function get_user_connection_data() {
1390        _deprecated_function( __METHOD__, 'jetpack-10.0.0', '\Automattic\Jetpack\Connection\REST_Connector::get_user_connection_data' );
1391
1392        require_once JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class-jetpack-redux-state-helper.php';
1393
1394        $connection_owner   = ( new Connection_Manager() )->get_connection_owner();
1395        $owner_display_name = false === $connection_owner ? null : $connection_owner->data->display_name;
1396
1397        $response = array(
1398            'currentUser'     => jetpack_current_user_data(),
1399            'connectionOwner' => $owner_display_name,
1400        );
1401        return rest_ensure_response( $response );
1402    }
1403
1404    /**
1405     * Unlinks current user from the WordPress.com Servers.
1406     *
1407     * @param WP_REST_Request $request The request sent to the WP REST API.
1408     * @uses  Automattic\Jetpack\Connection\Manager->disconnect_user
1409     *
1410     * @deprecated since Jetpack 14.4.0
1411     * @see Automattic\Jetpack\Connection\REST_Connector::unlink_user()
1412     *
1413     * @since 4.3.0
1414     *
1415     * @return bool|WP_Error True if user successfully unlinked.
1416     */
1417    public static function unlink_user( $request ) {
1418        _deprecated_function( __METHOD__, 'jetpack-14.4.0', 'Automattic\Jetpack\Connection\REST_Connector::unlink_user()' );
1419        return REST_Connector::unlink_user( $request );
1420    }
1421
1422    /**
1423     * Gets current user's tracking settings.
1424     *
1425     * @since 6.0.0
1426     *
1427     * @param  WP_REST_Request $request The request sent to the WP REST API.
1428     *
1429     * @return WP_REST_Response|WP_Error Response, else error.
1430     */
1431    public static function get_user_tracking_settings( $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1432        if ( ! ( new Connection_Manager( 'jetpack' ) )->is_user_connected() ) {
1433            $response = array(
1434                'tracks_opt_out' => true, // Default to opt-out if not connected to wp.com.
1435            );
1436        } else {
1437            $response = Client::wpcom_json_api_request_as_user(
1438                '/jetpack-user-tracking',
1439                'v2',
1440                array(
1441                    'method'  => 'GET',
1442                    'headers' => array(
1443                        'X-Forwarded-For' => ( new Visitor() )->get_ip( true ),
1444                    ),
1445                )
1446            );
1447            if ( ! is_wp_error( $response ) ) {
1448                $response = json_decode( wp_remote_retrieve_body( $response ), true );
1449            }
1450        }
1451
1452        return rest_ensure_response( $response );
1453    }
1454
1455    /**
1456     * Updates current user's tracking settings.
1457     *
1458     * @since 6.0.0
1459     *
1460     * @param  WP_REST_Request $request The request sent to the WP REST API.
1461     *
1462     * @return WP_REST_Response|WP_Error Response, else error.
1463     */
1464    public static function update_user_tracking_settings( $request ) {
1465        if ( ! ( new Connection_Manager( 'jetpack' ) )->is_user_connected() ) {
1466            $response = array(
1467                'tracks_opt_out' => true, // Default to opt-out if not connected to wp.com.
1468            );
1469        } else {
1470            $response = Client::wpcom_json_api_request_as_user(
1471                '/jetpack-user-tracking',
1472                'v2',
1473                array(
1474                    'method'  => 'PUT',
1475                    'headers' => array(
1476                        'Content-Type'    => 'application/json',
1477                        'X-Forwarded-For' => ( new Visitor() )->get_ip( true ),
1478                    ),
1479                ),
1480                wp_json_encode( $request->get_params(), JSON_UNESCAPED_SLASHES )
1481            );
1482            if ( ! is_wp_error( $response ) ) {
1483                $response = json_decode( wp_remote_retrieve_body( $response ), true );
1484            }
1485        }
1486
1487        return rest_ensure_response( $response );
1488    }
1489
1490    /**
1491     * Fetch site data from .com including the site's current plan and the site's products.
1492     *
1493     * @since 5.5.0
1494     * @deprecated 16.2 Use Automattic\Jetpack\Connection\Manager::get_connected_site_data().
1495     *
1496     * @return stdClass|WP_Error
1497     */
1498    public static function site_data() {
1499        _deprecated_function( __METHOD__, 'jetpack-16.2', 'Automattic\Jetpack\Connection\Manager::get_connected_site_data' );
1500
1501        return ( new Connection_Manager() )->get_connected_site_data();
1502    }
1503
1504    /**
1505     * Get site data, including for example, the site's current plan.
1506     *
1507     * @since 4.3.0
1508     * @deprecated 16.2 Use Automattic\Jetpack\Connection\REST_Connector::site_data_response().
1509     *
1510     * @return WP_Error|WP_HTTP_Response|WP_REST_Response
1511     */
1512    public static function get_site_data() {
1513        _deprecated_function( __METHOD__, 'jetpack-16.2', 'Automattic\Jetpack\Connection\REST_Connector::site_data_response' );
1514
1515        return REST_Connector::site_data_response();
1516    }
1517
1518    /**
1519     * Fetch AL data for this site and return it.
1520     *
1521     * @since 7.4
1522     *
1523     * @return array|WP_Error
1524     */
1525    public static function get_site_activity() {
1526        $site_id = Jetpack_Options::get_option( 'id' );
1527
1528        if ( ! $site_id ) {
1529            return new WP_Error(
1530                'site_id_missing',
1531                esc_html__( 'Site ID is missing.', 'jetpack' ),
1532                array( 'status' => 400 )
1533            );
1534        }
1535
1536        $response      = Client::wpcom_json_api_request_as_user(
1537            "/sites/$site_id/activity",
1538            '2',
1539            array(
1540                'method'  => 'GET',
1541                'headers' => array(
1542                    'X-Forwarded-For' => ( new Visitor() )->get_ip( true ),
1543                ),
1544            ),
1545            null,
1546            'wpcom'
1547        );
1548        $response_code = wp_remote_retrieve_response_code( $response );
1549
1550        if ( 200 !== $response_code ) {
1551            return new WP_Error(
1552                'activity_fetch_failed',
1553                esc_html__( 'Could not retrieve site activity.', 'jetpack' ),
1554                array( 'status' => $response_code )
1555            );
1556        }
1557
1558        $data = json_decode( wp_remote_retrieve_body( $response ) );
1559
1560        if ( ! isset( $data->current->orderedItems ) ) {
1561            return new WP_Error(
1562                'activity_not_found',
1563                esc_html__( 'No activity found', 'jetpack' ),
1564                array( 'status' => 204 ) // no content.
1565            );
1566        }
1567
1568        return rest_ensure_response(
1569            array(
1570                'code' => 'success',
1571                'data' => $data->current->orderedItems,
1572            )
1573        );
1574    }
1575
1576    /**
1577     * Reset Jetpack options
1578     *
1579     * @since 4.3.0
1580     *
1581     * @param WP_REST_Request $request {
1582     *     Array of parameters received by request.
1583     *
1584     *     @type string $options Available options to reset are options|modules
1585     * }
1586     *
1587     * @return bool|WP_Error True if options were reset. Otherwise, a WP_Error instance with the corresponding error.
1588     */
1589    public static function reset_jetpack_options( $request ) {
1590
1591        if ( ! isset( $request['reset'] ) || true !== $request['reset'] ) {
1592            return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
1593        }
1594
1595        if ( isset( $request['options'] ) ) {
1596            $data    = $request['options'];
1597            $message = '';
1598
1599            switch ( $data ) {
1600                case ( 'options' ):
1601                    $options_to_reset = Jetpack::get_jetpack_options_for_reset();
1602
1603                    // Reset the Jetpack options.
1604                    foreach ( $options_to_reset['jp_options'] as $option_to_reset ) {
1605                        Jetpack_Options::delete_option( $option_to_reset );
1606                    }
1607
1608                    foreach ( $options_to_reset['wp_options'] as $option_to_reset ) {
1609                        delete_option( $option_to_reset );
1610                    }
1611
1612                    // Reset to default modules.
1613                    $default_modules = Jetpack::get_default_modules();
1614                    Jetpack::update_active_modules( $default_modules );
1615                    $message = esc_html__( 'Jetpack options reset.', 'jetpack' );
1616
1617                    break;
1618                case 'modules':
1619                    $default_modules = Jetpack::get_default_modules();
1620                    Jetpack::update_active_modules( $default_modules );
1621                    $message = esc_html__( 'Modules reset to default.', 'jetpack' );
1622
1623                    break;
1624                default:
1625                    return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
1626            }
1627
1628            return rest_ensure_response(
1629                array(
1630                    'code'    => 'success',
1631                    'message' => $message,
1632                )
1633            );
1634        }
1635
1636        return new WP_Error( 'required_param', esc_html__( 'Missing parameter "type".', 'jetpack' ), array( 'status' => 404 ) );
1637    }
1638
1639    /**
1640     * Get the query parameters to update module options or general settings.
1641     *
1642     * @since 4.3.0
1643     * @since 4.4.0 Accepts a $selector parameter.
1644     *
1645     * @param string $selector Selects a set of options to update, Can be empty, a module slug or 'any'.
1646     *
1647     * @return array
1648     */
1649    public static function get_updateable_parameters( $selector = '' ) {
1650        $parameters = array(
1651            'context' => array(
1652                'default' => 'edit',
1653            ),
1654        );
1655
1656        return array_merge( $parameters, self::get_updateable_data_list( $selector ) );
1657    }
1658
1659    /**
1660     * Returns a list of module options or general settings that can be updated.
1661     *
1662     * @since 4.3.0
1663     * @since 4.4.0 Accepts 'any' as a parameter which will make it return the entire list.
1664     *
1665     * @param string|array $selector Module slug, 'any', or an array of parameters.
1666     *                               If empty, it's assumed we're updating a module and we'll try to get its slug.
1667     *                               If 'any' the full list is returned.
1668     *                               If it's an array of parameters, includes the elements by matching keys.
1669     *
1670     * @return array
1671     */
1672    public static function get_updateable_data_list( $selector = '' ) {
1673
1674        $options = array(
1675            // Blocks.
1676            'jetpack_blocks_disabled'                   => array(
1677                'description'       => esc_html__( 'Jetpack Blocks disabled.', 'jetpack' ),
1678                'type'              => 'boolean',
1679                'default'           => false,
1680                'validate_callback' => __CLASS__ . '::validate_boolean',
1681                'jp_group'          => 'settings',
1682            ),
1683
1684            // Carousel
1685            'carousel_background_color'                 => array(
1686                'description'       => esc_html__( 'Color scheme.', 'jetpack' ),
1687                'type'              => 'string',
1688                'default'           => 'black',
1689                'enum'              => array(
1690                    'black',
1691                    'white',
1692                ),
1693                'enum_labels'       => array(
1694                    'black' => esc_html__( 'Black', 'jetpack' ),
1695                    'white' => esc_html__( 'White', 'jetpack' ),
1696                ),
1697                'validate_callback' => __CLASS__ . '::validate_list_item',
1698                'jp_group'          => 'carousel',
1699            ),
1700            'carousel_display_exif'                     => array(
1701                'description'       => wp_kses(
1702                    sprintf( __( 'Show photo metadata (<a href="https://en.wikipedia.org/wiki/Exchangeable_image_file_format" target="_blank">Exif</a>) in carousel, when available.', 'jetpack' ) ),
1703                    array(
1704                        'a' => array(
1705                            'href'   => true,
1706                            'target' => true,
1707                        ),
1708                    )
1709                ),
1710                'type'              => 'boolean',
1711                'default'           => 0,
1712                'validate_callback' => __CLASS__ . '::validate_boolean',
1713                'jp_group'          => 'carousel',
1714            ),
1715            'carousel_display_comments'                 => array(
1716                'description'       => esc_html__( 'Show comments area in carousel', 'jetpack' ),
1717                'type'              => 'boolean',
1718                'default'           => 1,
1719                'validate_callback' => __CLASS__ . '::validate_boolean',
1720                'jp_group'          => 'carousel',
1721            ),
1722
1723            // Comments.
1724            'highlander_comment_form_prompt'            => array(
1725                'description'       => esc_html__( 'Greeting Text', 'jetpack' ),
1726                'type'              => 'string',
1727                'default'           => esc_html__( 'Leave a Reply', 'jetpack' ),
1728                'sanitize_callback' => 'sanitize_text_field',
1729                'jp_group'          => 'comments',
1730            ),
1731            'jetpack_comment_form_color_scheme'         => array(
1732                'description'       => esc_html__( 'Color scheme', 'jetpack' ),
1733                'type'              => 'string',
1734                'default'           => 'light',
1735                'enum'              => array(
1736                    'light',
1737                    'dark',
1738                    'transparent',
1739                ),
1740                'enum_labels'       => array(
1741                    'light'       => esc_html__( 'Light', 'jetpack' ),
1742                    'dark'        => esc_html__( 'Dark', 'jetpack' ),
1743                    'transparent' => esc_html__( 'Transparent', 'jetpack' ),
1744                ),
1745                'validate_callback' => __CLASS__ . '::validate_list_item',
1746                'jp_group'          => 'comments',
1747            ),
1748            'enable_blocks_comments'                    => array(
1749                'description'       => esc_html__( 'Enable blocks in comments', 'jetpack' ),
1750                'type'              => 'boolean',
1751                'default'           => 1,
1752                'validate_callback' => __CLASS__ . '::validate_boolean',
1753                'jp_group'          => 'comments',
1754            ),
1755
1756            // Custom Content Types.
1757            'jetpack_portfolio'                         => array(
1758                'description'       => esc_html__( 'Enable or disable Jetpack portfolio post type.', 'jetpack' ),
1759                'type'              => 'boolean',
1760                'default'           => 0,
1761                'validate_callback' => __CLASS__ . '::validate_boolean',
1762                'jp_group'          => 'settings',
1763            ),
1764            'jetpack_portfolio_posts_per_page'          => array(
1765                'description'       => esc_html__( 'Number of entries to show at most in Portfolio pages.', 'jetpack' ),
1766                'type'              => 'integer',
1767                'default'           => 10,
1768                'validate_callback' => __CLASS__ . '::validate_posint',
1769                'jp_group'          => 'settings',
1770            ),
1771            'jetpack_testimonial'                       => array(
1772                'description'       => esc_html__( 'Enable or disable Jetpack testimonial post type.', 'jetpack' ),
1773                'type'              => 'boolean',
1774                'default'           => 0,
1775                'validate_callback' => __CLASS__ . '::validate_boolean',
1776                'jp_group'          => 'settings',
1777            ),
1778            'jetpack_testimonial_posts_per_page'        => array(
1779                'description'       => esc_html__( 'Number of entries to show at most in Testimonial pages.', 'jetpack' ),
1780                'type'              => 'integer',
1781                'default'           => 10,
1782                'validate_callback' => __CLASS__ . '::validate_posint',
1783                'jp_group'          => 'settings',
1784            ),
1785            // WAF.
1786            'jetpack_waf_automatic_rules'               => array(
1787                'description'       => esc_html__( 'Enable automatic rules - Protect your site against untrusted traffic sources with automatic security rules.', 'jetpack' ),
1788                'type'              => 'boolean',
1789                'default'           => Waf_Compatibility::get_default_automatic_rules_option(),
1790                'validate_callback' => __CLASS__ . '::validate_boolean',
1791                'jp_group'          => 'waf',
1792            ),
1793            'jetpack_waf_ip_block_list_enabled'         => array(
1794                'description'       => esc_html__( 'Block list - Block a specific request IP.', 'jetpack' ),
1795                'type'              => 'boolean',
1796                'default'           => 0,
1797                'validate_callback' => __CLASS__ . '::validate_boolean',
1798                'jp_group'          => 'waf',
1799            ),
1800            'jetpack_waf_ip_block_list'                 => array(
1801                'description'       => esc_html__( 'Blocked IP addresses', 'jetpack' ),
1802                'type'              => 'string',
1803                'default'           => '',
1804                'validate_callback' => __CLASS__ . '::validate_waf_ip_block_list',
1805                'sanitize_callback' => 'esc_textarea',
1806                'jp_group'          => 'waf',
1807            ),
1808            'jetpack_waf_ip_allow_list_enabled'         => array(
1809                'description'       => esc_html__( 'Allow list - Allow a specific request IP.', 'jetpack' ),
1810                'type'              => 'boolean',
1811                'default'           => 0,
1812                'validate_callback' => __CLASS__ . '::validate_boolean',
1813                'jp_group'          => 'settings',
1814            ),
1815            'jetpack_waf_ip_allow_list'                 => array(
1816                'description'       => esc_html__( 'Always allowed IP addresses', 'jetpack' ),
1817                'type'              => 'string',
1818                'default'           => '',
1819                'validate_callback' => __CLASS__ . '::validate_string',
1820                'sanitize_callback' => 'esc_textarea',
1821                'jp_group'          => 'settings',
1822            ),
1823            'jetpack_waf_share_data'                    => array(
1824                'description'       => esc_html__( 'Share basic data with Jetpack.', 'jetpack' ),
1825                'type'              => 'boolean',
1826                'default'           => 0,
1827                'validate_callback' => __CLASS__ . '::validate_boolean',
1828                'jp_group'          => 'waf',
1829            ),
1830            'jetpack_waf_share_debug_data'              => array(
1831                'description'       => esc_html__( 'Share detailed data with Jetpack.', 'jetpack' ),
1832                'type'              => 'boolean',
1833                'default'           => 0,
1834                'validate_callback' => __CLASS__ . '::validate_boolean',
1835                'jp_group'          => 'waf',
1836            ),
1837            // Galleries.
1838            'tiled_galleries'                           => array(
1839                'description'       => esc_html__( 'Display all your gallery pictures in a cool mosaic.', 'jetpack' ),
1840                'type'              => 'boolean',
1841                'default'           => 0,
1842                'validate_callback' => __CLASS__ . '::validate_boolean',
1843                'jp_group'          => 'tiled-gallery',
1844            ),
1845
1846            'gravatar_disable_hovercards'               => array(
1847                'description'       => esc_html__( "View people's profiles when you mouse over their Gravatars", 'jetpack' ),
1848                'type'              => 'string',
1849                'default'           => 'enabled',
1850                // Not visible. This is used as the checkbox value.
1851                'enum'              => array(
1852                    'enabled',
1853                    'disabled',
1854                ),
1855                'enum_labels'       => array(
1856                    'enabled'  => esc_html__( 'Enabled', 'jetpack' ),
1857                    'disabled' => esc_html__( 'Disabled', 'jetpack' ),
1858                ),
1859                'validate_callback' => __CLASS__ . '::validate_list_item',
1860                'jp_group'          => 'gravatar-hovercards',
1861            ),
1862
1863            // Infinite Scroll.
1864            'infinite_scroll'                           => array(
1865                'description'       => esc_html__( 'To infinity and beyond', 'jetpack' ),
1866                'type'              => 'boolean',
1867                'default'           => 1,
1868                'validate_callback' => __CLASS__ . '::validate_boolean',
1869                'jp_group'          => 'infinite-scroll',
1870            ),
1871            'infinite_scroll_google_analytics'          => array(
1872                'description'       => esc_html__( 'Use Google Analytics with Infinite Scroll', 'jetpack' ),
1873                'type'              => 'boolean',
1874                'default'           => 0,
1875                'validate_callback' => __CLASS__ . '::validate_boolean',
1876                'jp_group'          => 'infinite-scroll',
1877            ),
1878
1879            // Likes.
1880            'wpl_default'                               => array(
1881                'description'       => esc_html__( 'WordPress.com Likes are', 'jetpack' ),
1882                'type'              => 'string',
1883                'default'           => 'on',
1884                'enum'              => array(
1885                    'on',
1886                    'off',
1887                ),
1888                'enum_labels'       => array(
1889                    'on'  => esc_html__( 'On for all posts', 'jetpack' ),
1890                    'off' => esc_html__( 'Turned on per post', 'jetpack' ),
1891                ),
1892                'validate_callback' => __CLASS__ . '::validate_list_item',
1893                'jp_group'          => 'likes',
1894            ),
1895            'social_notifications_like'                 => array(
1896                'description'       => esc_html__( 'Send email notification when someone likes a post', 'jetpack' ),
1897                'type'              => 'boolean',
1898                'default'           => 1,
1899                'validate_callback' => __CLASS__ . '::validate_boolean',
1900                'jp_group'          => 'likes',
1901            ),
1902
1903            // Markdown.
1904            'wpcom_publish_comments_with_markdown'      => array(
1905                'description'       => esc_html__( 'Use Markdown for comments.', 'jetpack' ),
1906                'type'              => 'boolean',
1907                'default'           => 0,
1908                'validate_callback' => __CLASS__ . '::validate_boolean',
1909                'jp_group'          => 'markdown',
1910            ),
1911            'wpcom_publish_posts_with_markdown'         => array(
1912                'description'       => esc_html__( 'Use Markdown for posts.', 'jetpack' ),
1913                'type'              => 'boolean',
1914                'default'           => 0,
1915                'validate_callback' => __CLASS__ . '::validate_boolean',
1916                'jp_group'          => 'markdown',
1917            ),
1918
1919            // Monitor.
1920            'monitor_receive_notifications'             => array(
1921                'description'       => esc_html__( 'Receive Monitor Email Notifications.', 'jetpack' ),
1922                'type'              => 'boolean',
1923                'default'           => 0,
1924                'validate_callback' => __CLASS__ . '::validate_boolean',
1925                'jp_group'          => 'monitor',
1926            ),
1927
1928            // Post by Email.
1929            'post_by_email_address'                     => array(
1930                'description'       => esc_html__( 'Email Address', 'jetpack' ),
1931                'type'              => 'string',
1932                'default'           => 'noop',
1933                'enum'              => array(
1934                    'noop',
1935                    'create',
1936                    'regenerate',
1937                    'delete',
1938                ),
1939                'enum_labels'       => array(
1940                    'noop'       => '',
1941                    'create'     => esc_html__( 'Create Post by Email address', 'jetpack' ),
1942                    'regenerate' => esc_html__( 'Regenerate Post by Email address', 'jetpack' ),
1943                    'delete'     => esc_html__( 'Delete Post by Email address', 'jetpack' ),
1944                ),
1945                'validate_callback' => __CLASS__ . '::validate_list_item',
1946                'jp_group'          => 'post-by-email',
1947            ),
1948
1949            // Protect.
1950            'jetpack_protect_key'                       => array(
1951                'description'       => esc_html__( 'Protect API key', 'jetpack' ),
1952                'type'              => 'string',
1953                'default'           => '',
1954                'validate_callback' => __CLASS__ . '::validate_alphanum',
1955                'jp_group'          => 'protect',
1956            ),
1957            'jetpack_protect_global_whitelist'          => array(
1958                'description'       => esc_html__( 'Protect global IP allow list', 'jetpack' ),
1959                'type'              => 'string',
1960                'default'           => '',
1961                'validate_callback' => __CLASS__ . '::validate_string',
1962                'sanitize_callback' => 'esc_textarea',
1963                'jp_group'          => 'protect',
1964            ),
1965
1966            // Sharing.
1967            'sharing_services'                          => array(
1968                'description'       => esc_html__( 'Enabled Services and those hidden behind a button', 'jetpack' ),
1969                'type'              => 'object',
1970                'default'           => array(
1971                    'visible' => array( 'facebook', 'x' ),
1972                    'hidden'  => array(),
1973                ),
1974                'validate_callback' => __CLASS__ . '::validate_services',
1975                'jp_group'          => 'sharedaddy',
1976            ),
1977            'button_style'                              => array(
1978                'description'       => esc_html__( 'Button Style', 'jetpack' ),
1979                'type'              => 'string',
1980                'default'           => 'icon',
1981                'enum'              => array(
1982                    'icon-text',
1983                    'icon',
1984                    'text',
1985                    'official',
1986                ),
1987                'enum_labels'       => array(
1988                    'icon-text' => esc_html__( 'Icon + text', 'jetpack' ),
1989                    'icon'      => esc_html__( 'Icon only', 'jetpack' ),
1990                    'text'      => esc_html__( 'Text only', 'jetpack' ),
1991                    'official'  => esc_html__( 'Official buttons', 'jetpack' ),
1992                ),
1993                'validate_callback' => __CLASS__ . '::validate_list_item',
1994                'jp_group'          => 'sharedaddy',
1995            ),
1996            'sharing_label'                             => array(
1997                'description'       => esc_html__( 'Sharing Label', 'jetpack' ),
1998                'type'              => 'string',
1999                'default'           => '',
2000                'validate_callback' => __CLASS__ . '::validate_string',
2001                'sanitize_callback' => 'esc_html',
2002                'jp_group'          => 'sharedaddy',
2003            ),
2004            'show'                                      => array(
2005                'description'       => esc_html__( 'Views where buttons are shown', 'jetpack' ),
2006                'type'              => 'array',
2007                'items'             => array(
2008                    'type' => 'string',
2009                ),
2010                'default'           => array( 'post' ),
2011                'validate_callback' => __CLASS__ . '::validate_sharing_show',
2012                'jp_group'          => 'sharedaddy',
2013            ),
2014            'jetpack-twitter-cards-site-tag'            => array(
2015                'description'       => esc_html__( "The Twitter username of the owner of this site's domain.", 'jetpack' ),
2016                'type'              => 'string',
2017                'default'           => '',
2018                'validate_callback' => __CLASS__ . '::validate_twitter_username',
2019                'sanitize_callback' => 'esc_html',
2020                'jp_group'          => 'sharedaddy',
2021            ),
2022            'sharedaddy_disable_resources'              => array(
2023                'description'       => esc_html__( 'Disable CSS and JS', 'jetpack' ),
2024                'type'              => 'boolean',
2025                'default'           => 0,
2026                'validate_callback' => __CLASS__ . '::validate_boolean',
2027                'jp_group'          => 'sharedaddy',
2028            ),
2029            'custom'                                    => array(
2030                'description'       => esc_html__( 'Custom sharing services added by user.', 'jetpack' ),
2031                'type'              => 'object',
2032                'default'           => array(
2033                    'sharing_name' => '',
2034                    'sharing_url'  => '',
2035                    'sharing_icon' => '',
2036                ),
2037                'validate_callback' => __CLASS__ . '::validate_custom_service',
2038                'jp_group'          => 'sharedaddy',
2039            ),
2040            // Not an option, but an action that can be performed on the list of custom services passing the service ID.
2041            'sharing_delete_service'                    => array(
2042                'description'       => esc_html__( 'Delete custom sharing service.', 'jetpack' ),
2043                'type'              => 'string',
2044                'default'           => '',
2045                'validate_callback' => __CLASS__ . '::validate_custom_service_id',
2046                'jp_group'          => 'sharedaddy',
2047            ),
2048
2049            // SSO.
2050            'jetpack_sso_require_two_step'              => array(
2051                'description'       => esc_html__( 'Require Two-Step Authentication', 'jetpack' ),
2052                'type'              => 'boolean',
2053                'default'           => SSO\Helpers::is_require_two_step_checkbox_disabled(),
2054                'validate_callback' => __CLASS__ . '::validate_boolean',
2055                'jp_group'          => 'sso',
2056            ),
2057            'jetpack_sso_match_by_email'                => array(
2058                'description'       => esc_html__( 'Match by Email', 'jetpack' ),
2059                'type'              => 'boolean',
2060                'default'           => 1,
2061                'validate_callback' => __CLASS__ . '::validate_boolean',
2062                'jp_group'          => 'sso',
2063            ),
2064
2065            // Subscriptions.
2066            'stb_enabled'                               => array(
2067                'description'       => esc_html__( "Show a <em>'follow blog'</em> option in the comment form", 'jetpack' ),
2068                'type'              => 'boolean',
2069                'default'           => 1,
2070                'validate_callback' => __CLASS__ . '::validate_boolean',
2071                'jp_group'          => 'subscriptions',
2072            ),
2073            'stc_enabled'                               => array(
2074                'description'       => esc_html__( "Show a <em>'follow comments'</em> option in the comment form", 'jetpack' ),
2075                'type'              => 'boolean',
2076                'default'           => 1,
2077                'validate_callback' => __CLASS__ . '::validate_boolean',
2078                'jp_group'          => 'subscriptions',
2079            ),
2080            'wpcom_newsletter_categories'               => array(
2081                'description'       => esc_html__( 'Array of post category ids that are marked as newsletter categories', 'jetpack' ),
2082                'type'              => 'array',
2083                'default'           => array(),
2084                'validate_callback' => __CLASS__ . '::validate_array',
2085                'jp_group'          => 'subscriptions',
2086            ),
2087            'wpcom_newsletter_categories_enabled'       => array(
2088                'description'       => esc_html__( 'Whether the newsletter categories are enabled or not', 'jetpack' ),
2089                'type'              => 'boolean',
2090                'default'           => 0,
2091                'validate_callback' => __CLASS__ . '::validate_boolean',
2092                'jp_group'          => 'subscriptions',
2093            ),
2094            'wpcom_newsletter_send_default'             => array(
2095                'description'       => esc_html__( 'Whether to send newsletter emails by default when publishing a post', 'jetpack' ),
2096                'type'              => 'boolean',
2097                'default'           => 1,
2098                'validate_callback' => __CLASS__ . '::validate_boolean',
2099                'jp_group'          => 'subscriptions',
2100            ),
2101            'wpcom_featured_image_in_email'             => array(
2102                'description'       => esc_html__( 'Whether to include the featured image in the email or not', 'jetpack' ),
2103                'type'              => 'boolean',
2104                'default'           => 0,
2105                'validate_callback' => __CLASS__ . '::validate_boolean',
2106                'jp_group'          => 'subscriptions',
2107            ),
2108            'jetpack_gravatar_in_email'                 => array(
2109                'description'       => esc_html__( 'Whether to show author avatar in the email byline', 'jetpack' ),
2110                'type'              => 'boolean',
2111                'default'           => 1,
2112                'validate_callback' => __CLASS__ . '::validate_boolean',
2113                'jp_group'          => 'subscriptions',
2114            ),
2115            'jetpack_author_in_email'                   => array(
2116                'description'       => esc_html__( 'Whether to show author display name in the email byline', 'jetpack' ),
2117                'type'              => 'boolean',
2118                'default'           => 1,
2119                'validate_callback' => __CLASS__ . '::validate_boolean',
2120                'jp_group'          => 'subscriptions',
2121            ),
2122            'jetpack_post_date_in_email'                => array(
2123                'description'       => esc_html__( 'Whether to show date in the email byline', 'jetpack' ),
2124                'type'              => 'boolean',
2125                'default'           => 1,
2126                'validate_callback' => __CLASS__ . '::validate_boolean',
2127                'jp_group'          => 'subscriptions',
2128            ),
2129            'wpcom_subscription_emails_use_excerpt'     => array(
2130                'description'       => esc_html__( 'Whether to use the excerpt in the email or not', 'jetpack' ),
2131                'type'              => 'boolean',
2132                'default'           => 0,
2133                'validate_callback' => __CLASS__ . '::validate_boolean',
2134                'jp_group'          => 'subscriptions',
2135            ),
2136            'jetpack_subscriptions_reply_to'            => array(
2137                'description'       => esc_html__( 'Reply to email behaviour for newsletters emails', 'jetpack' ),
2138                'type'              => 'string',
2139                'default'           => Automattic\Jetpack\Modules\Subscriptions\Settings::$default_reply_to,
2140                'validate_callback' => __CLASS__ . '::validate_subscriptions_reply_to',
2141                'jp_group'          => 'subscriptions',
2142            ),
2143            'jetpack_subscriptions_from_name'           => array(
2144                'description'       => esc_html__( 'From name for newsletters emails', 'jetpack' ),
2145                'type'              => 'string',
2146                'default'           => '',
2147                'validate_callback' => __CLASS__ . '::validate_subscriptions_reply_to_name',
2148                'jp_group'          => 'subscriptions',
2149            ),
2150            'sm_enabled'                                => array(
2151                'description'       => esc_html__( 'Show popup Subscribe modal to readers.', 'jetpack' ),
2152                'type'              => 'boolean',
2153                'default'           => 0,
2154                'validate_callback' => __CLASS__ . '::validate_boolean',
2155                'jp_group'          => 'subscriptions',
2156            ),
2157            'jetpack_subscribe_overlay_enabled'         => array(
2158                'description'       => esc_html__( 'Show subscribe overlay on homepage.', 'jetpack' ),
2159                'type'              => 'boolean',
2160                'default'           => 0,
2161                'validate_callback' => __CLASS__ . '::validate_boolean',
2162                'jp_group'          => 'subscriptions',
2163            ),
2164            'jetpack_subscribe_floating_button_enabled' => array(
2165                'description'       => esc_html__( 'Show a floating subscribe button.', 'jetpack' ),
2166                'type'              => 'boolean',
2167                'default'           => 0,
2168                'validate_callback' => __CLASS__ . '::validate_boolean',
2169                'jp_group'          => 'subscriptions',
2170            ),
2171            'jetpack_subscriptions_subscribe_post_end_enabled' => array(
2172                'description'       => esc_html__( 'Add Subscribe block at the end of each post.', 'jetpack' ),
2173                'type'              => 'boolean',
2174                'default'           => 0,
2175                'validate_callback' => __CLASS__ . '::validate_boolean',
2176                'jp_group'          => 'subscriptions',
2177            ),
2178            'jetpack_subscriptions_login_navigation_enabled' => array(
2179                'description'       => esc_html__( 'Add Subscriber Login block to the navigation.', 'jetpack' ),
2180                'type'              => 'boolean',
2181                'default'           => 0,
2182                'validate_callback' => __CLASS__ . '::validate_boolean',
2183                'jp_group'          => 'subscriptions',
2184            ),
2185            'jetpack_subscriptions_subscribe_navigation_enabled' => array(
2186                'description'       => esc_html__( 'Add Subscribe block to the navigation.', 'jetpack' ),
2187                'type'              => 'boolean',
2188                'default'           => 0,
2189                'validate_callback' => __CLASS__ . '::validate_boolean',
2190                'jp_group'          => 'subscriptions',
2191            ),
2192            'social_notifications_subscribe'            => array(
2193                'description'       => esc_html__( 'Send email notification when someone subscribes to my blog', 'jetpack' ),
2194                'type'              => 'boolean',
2195                'default'           => 0,
2196                'validate_callback' => __CLASS__ . '::validate_boolean',
2197                'jp_group'          => 'subscriptions',
2198            ),
2199            'subscription_options'                      => array(
2200                'description'       => esc_html__( 'Options used in subscription email templates and the Subscribe block: \'invitation\', \'welcome\', \'comment_follow\', \'subscribe_modal_heading\', \'free_tier_description\' and \'hide_free_tier\'.', 'jetpack' ),
2201                'type'              => 'object',
2202                'default'           => array(
2203                    'invitation'              => '',
2204                    'welcome'                 => '',
2205                    'comment_follow'          => '',
2206                    'subscribe_modal_heading' => '',
2207                    'free_tier_description'   => '',
2208                    'hide_free_tier'          => false,
2209                ),
2210                'validate_callback' => __CLASS__ . '::validate_subscription_options',
2211                'jp_group'          => 'subscriptions',
2212            ),
2213
2214            // Related Posts.
2215            'show_headline'                             => array(
2216                'description'       => esc_html__( 'Highlight related content with a heading', 'jetpack' ),
2217                'type'              => 'boolean',
2218                'default'           => 1,
2219                'validate_callback' => __CLASS__ . '::validate_boolean',
2220                'jp_group'          => 'related-posts',
2221            ),
2222            'show_thumbnails'                           => array(
2223                'description'       => esc_html__( 'Show a thumbnail image where available', 'jetpack' ),
2224                'type'              => 'boolean',
2225                'default'           => 0,
2226                'validate_callback' => __CLASS__ . '::validate_boolean',
2227                'jp_group'          => 'related-posts',
2228            ),
2229
2230            // Search.
2231            'instant_search_enabled'                    => array(
2232                'description'       => esc_html__( 'Enable Instant Search', 'jetpack' ),
2233                'type'              => 'boolean',
2234                'default'           => 0,
2235                'validate_callback' => __CLASS__ . '::validate_boolean',
2236                'jp_group'          => 'search',
2237            ),
2238
2239            'has_jetpack_search_product'                => array(
2240                'description'       => esc_html__( 'Has an active Jetpack Search product purchase', 'jetpack' ),
2241                'type'              => 'boolean',
2242                'default'           => 0,
2243                'validate_callback' => __CLASS__ . '::validate_boolean',
2244                'jp_group'          => 'settings',
2245            ),
2246
2247            'search_auto_config'                        => array(
2248                'description'       => esc_html__( 'Trigger an auto config of instant search', 'jetpack' ),
2249                'type'              => 'boolean',
2250                'default'           => 0,
2251                'validate_callback' => __CLASS__ . '::validate_boolean',
2252                'jp_group'          => 'search',
2253            ),
2254
2255            // Verification Tools.
2256            'google'                                    => array(
2257                'description'       => esc_html__( 'Google Search Console', 'jetpack' ),
2258                'type'              => 'string',
2259                'default'           => '',
2260                'validate_callback' => __CLASS__ . '::validate_verification_service',
2261                'jp_group'          => 'verification-tools',
2262            ),
2263            'bing'                                      => array(
2264                'description'       => esc_html__( 'Bing Webmaster Center', 'jetpack' ),
2265                'type'              => 'string',
2266                'default'           => '',
2267                'validate_callback' => __CLASS__ . '::validate_verification_service',
2268                'jp_group'          => 'verification-tools',
2269            ),
2270            'pinterest'                                 => array(
2271                'description'       => esc_html__( 'Pinterest Site Verification', 'jetpack' ),
2272                'type'              => 'string',
2273                'default'           => '',
2274                'validate_callback' => __CLASS__ . '::validate_verification_service',
2275                'jp_group'          => 'verification-tools',
2276            ),
2277            'yandex'                                    => array(
2278                'description'       => esc_html__( 'Yandex Site Verification', 'jetpack' ),
2279                'type'              => 'string',
2280                'default'           => '',
2281                'validate_callback' => __CLASS__ . '::validate_verification_service',
2282                'jp_group'          => 'verification-tools',
2283            ),
2284            'facebook'                                  => array(
2285                'description'       => esc_html__( 'Facebook Domain Verification', 'jetpack' ),
2286                'type'              => 'string',
2287                'default'           => '',
2288                'validate_callback' => __CLASS__ . '::validate_verification_service',
2289                'jp_group'          => 'verification-tools',
2290            ),
2291
2292            // WordAds.
2293            'enable_header_ad'                          => array(
2294                'description'       => esc_html__( 'Display an ad unit at the top of each page.', 'jetpack' ),
2295                'type'              => 'boolean',
2296                'default'           => 1,
2297                'validate_callback' => __CLASS__ . '::validate_boolean',
2298                'jp_group'          => 'wordads',
2299            ),
2300            'wordads_approved'                          => array(
2301                'description'       => esc_html__( 'Is site approved for WordAds?', 'jetpack' ),
2302                'type'              => 'boolean',
2303                'default'           => 0,
2304                'validate_callback' => __CLASS__ . '::validate_boolean',
2305                'jp_group'          => 'wordads',
2306            ),
2307            'wordads_second_belowpost'                  => array(
2308                'description'       => esc_html__( 'Display second ad below post?', 'jetpack' ),
2309                'type'              => 'boolean',
2310                'default'           => 1,
2311                'validate_callback' => __CLASS__ . '::validate_boolean',
2312                'jp_group'          => 'wordads',
2313            ),
2314            'wordads_inline_enabled'                    => array(
2315                'description'       => esc_html__( 'Display inline ad within post content?', 'jetpack' ),
2316                'type'              => 'boolean',
2317                'default'           => 1,
2318                'validate_callback' => __CLASS__ . '::validate_boolean',
2319                'jp_group'          => 'wordads',
2320            ),
2321            'wordads_display_front_page'                => array(
2322                'description'       => esc_html__( 'Display ads on the front page?', 'jetpack' ),
2323                'type'              => 'boolean',
2324                'default'           => 1,
2325                'validate_callback' => __CLASS__ . '::validate_boolean',
2326                'jp_group'          => 'wordads',
2327            ),
2328            'wordads_display_post'                      => array(
2329                'description'       => esc_html__( 'Display ads on posts?', 'jetpack' ),
2330                'type'              => 'boolean',
2331                'default'           => 1,
2332                'validate_callback' => __CLASS__ . '::validate_boolean',
2333                'jp_group'          => 'wordads',
2334            ),
2335            'wordads_display_page'                      => array(
2336                'description'       => esc_html__( 'Display ads on pages?', 'jetpack' ),
2337                'type'              => 'boolean',
2338                'default'           => 1,
2339                'validate_callback' => __CLASS__ . '::validate_boolean',
2340                'jp_group'          => 'wordads',
2341            ),
2342            'wordads_display_archive'                   => array(
2343                'description'       => esc_html__( 'Display ads on archive pages?', 'jetpack' ),
2344                'type'              => 'boolean',
2345                'default'           => 1,
2346                'validate_callback' => __CLASS__ . '::validate_boolean',
2347                'jp_group'          => 'wordads',
2348            ),
2349            'wordads_custom_adstxt_enabled'             => array(
2350                'description'       => esc_html__( 'Custom ads.txt', 'jetpack' ),
2351                'type'              => 'boolean',
2352                'default'           => 0,
2353                'validate_callback' => __CLASS__ . '::validate_boolean',
2354                'jp_group'          => 'wordads',
2355            ),
2356            'wordads_custom_adstxt'                     => array(
2357                'description'       => esc_html__( 'Custom ads.txt entries', 'jetpack' ),
2358                'type'              => 'string',
2359                'default'           => '',
2360                'validate_callback' => __CLASS__ . '::validate_string',
2361                'sanitize_callback' => 'sanitize_textarea_field',
2362                'jp_group'          => 'wordads',
2363            ),
2364            'wordads_ccpa_enabled'                      => array(
2365                'description'       => esc_html__( 'Enable support for California Consumer Privacy Act', 'jetpack' ),
2366                'type'              => 'boolean',
2367                'default'           => 0,
2368                'validate_callback' => __CLASS__ . '::validate_boolean',
2369                'jp_group'          => 'wordads',
2370            ),
2371            'wordads_ccpa_privacy_policy_url'           => array(
2372                'description'       => esc_html__( 'Privacy Policy URL', 'jetpack' ),
2373                'type'              => 'string',
2374                'default'           => '',
2375                'validate_callback' => __CLASS__ . '::validate_string',
2376                'sanitize_callback' => 'sanitize_text_field',
2377                'jp_group'          => 'wordads',
2378            ),
2379            'wordads_cmp_enabled'                       => array(
2380                'description'       => esc_html__( 'Enable GDPR Consent Management Banner for WordAds', 'jetpack' ),
2381                'type'              => 'boolean',
2382                'default'           => 0,
2383                'validate_callback' => __CLASS__ . '::validate_boolean',
2384                'jp_group'          => 'wordads',
2385            ),
2386
2387            // Google Analytics.
2388            'google_analytics_tracking_id'              => array(
2389                'description'       => esc_html__( 'Google Analytics', 'jetpack' ),
2390                'type'              => 'string',
2391                'default'           => '',
2392                'validate_callback' => __CLASS__ . '::validate_alphanum',
2393                'jp_group'          => 'google-analytics',
2394            ),
2395            'jetpack_wga'                               => array(
2396                'description' => esc_html__( 'Google Analytics', 'jetpack' ),
2397                'type'        => 'object',
2398                'jp_group'    => 'settings',
2399            ),
2400
2401            // Stats.
2402            'admin_bar'                                 => array(
2403                'description'       => esc_html__( 'Include a small chart in your admin bar with a 48-hour traffic snapshot.', 'jetpack' ),
2404                'type'              => 'boolean',
2405                'default'           => 1,
2406                'validate_callback' => __CLASS__ . '::validate_boolean',
2407                'jp_group'          => 'stats',
2408            ),
2409            'enable_odyssey_stats'                      => array(
2410                'description'       => esc_html__( 'Preview the new Jetpack Stats experience (Experimental).', 'jetpack' ),
2411                'type'              => 'boolean',
2412                'default'           => 1,
2413                'validate_callback' => __CLASS__ . '::validate_boolean',
2414                'jp_group'          => 'stats',
2415            ),
2416            'roles'                                     => array(
2417                'description'       => esc_html__( 'Select the roles that will be able to view stats reports.', 'jetpack' ),
2418                'type'              => 'array',
2419                'items'             => array(
2420                    'type' => 'string',
2421                ),
2422                'default'           => array( 'administrator' ),
2423                'validate_callback' => __CLASS__ . '::validate_stats_roles',
2424                'sanitize_callback' => __CLASS__ . '::sanitize_stats_allowed_roles',
2425                'jp_group'          => 'stats',
2426            ),
2427            'count_roles'                               => array(
2428                'description'       => esc_html__( 'Count the page views of registered users who are logged in.', 'jetpack' ),
2429                'type'              => 'array',
2430                'items'             => array(
2431                    'type' => 'string',
2432                ),
2433                'default'           => array( 'administrator' ),
2434                'validate_callback' => __CLASS__ . '::validate_stats_roles',
2435                'jp_group'          => 'stats',
2436            ),
2437            'blog_id'                                   => array(
2438                'description'       => esc_html__( 'Blog ID.', 'jetpack' ),
2439                'type'              => 'boolean',
2440                'default'           => 0,
2441                'validate_callback' => __CLASS__ . '::validate_boolean',
2442                'jp_group'          => 'stats',
2443            ),
2444            'do_not_track'                              => array(
2445                'description'       => esc_html__( 'Do not track.', 'jetpack' ),
2446                'type'              => 'boolean',
2447                'default'           => 1,
2448                'validate_callback' => __CLASS__ . '::validate_boolean',
2449                'jp_group'          => 'stats',
2450            ),
2451            'version'                                   => array(
2452                'description'       => esc_html__( 'Version.', 'jetpack' ),
2453                'type'              => 'integer',
2454                'default'           => 9,
2455                'validate_callback' => __CLASS__ . '::validate_posint',
2456                'jp_group'          => 'stats',
2457            ),
2458            'collapse_nudges'                           => array(
2459                'description'       => esc_html__( 'Collapse upgrade nudges', 'jetpack' ),
2460                'type'              => 'boolean',
2461                'default'           => 0,
2462                'validate_callback' => __CLASS__ . '::validate_boolean',
2463                'jp_group'          => 'stats',
2464            ),
2465
2466            // Whether to share stats views with WordPress.com Reader.
2467            'wpcom_reader_views_enabled'                => array(
2468                'description'       => esc_html__( 'Show post views in the WordPress.com Reader.', 'jetpack' ),
2469                'type'              => 'boolean',
2470                'default'           => 1,
2471                'validate_callback' => __CLASS__ . '::validate_boolean',
2472                'jp_group'          => 'settings',
2473            ),
2474
2475            // Akismet - Not a module, but a plugin. The options can be passed and handled differently.
2476            'akismet_show_user_comments_approved'       => array(
2477                'description'       => '',
2478                'type'              => 'boolean',
2479                'default'           => 0,
2480                'validate_callback' => __CLASS__ . '::validate_boolean',
2481                'jp_group'          => 'settings',
2482            ),
2483
2484            'wordpress_api_key'                         => array(
2485                'description'       => '',
2486                'type'              => 'string',
2487                'default'           => '',
2488                'validate_callback' => __CLASS__ . '::validate_alphanum',
2489                'jp_group'          => 'settings',
2490            ),
2491
2492            // Empty stats card dismiss.
2493            'dismiss_empty_stats_card'                  => array(
2494                'description'       => '',
2495                'type'              => 'boolean',
2496                'default'           => 0,
2497                'validate_callback' => __CLASS__ . '::validate_boolean',
2498                'jp_group'          => 'settings',
2499            ),
2500
2501            // Backup Getting Started card on dashboard.
2502            'dismiss_dash_backup_getting_started'       => array(
2503                'description'       => '',
2504                'type'              => 'boolean',
2505                'default'           => 0,
2506                'validate_callback' => __CLASS__ . '::validate_boolean',
2507                'jp_group'          => 'settings',
2508            ),
2509
2510            // Agencies Learn More card on dashboard.
2511            'dismiss_dash_agencies_learn_more'          => array(
2512                'description'       => '',
2513                'type'              => 'boolean',
2514                'default'           => 0,
2515                'validate_callback' => __CLASS__ . '::validate_boolean',
2516                'jp_group'          => 'settings',
2517            ),
2518
2519            'lang_id'                                   => array(
2520                'description' => esc_html__( 'Primary language for the site.', 'jetpack' ),
2521                'type'        => 'string',
2522                'default'     => 'en_US',
2523                'jp_group'    => 'settings',
2524            ),
2525
2526            // SEO Tools.
2527            'advanced_seo_front_page_description'       => array(
2528                'description'       => esc_html__( 'Front page meta description.', 'jetpack' ),
2529                'type'              => 'string',
2530                'default'           => '',
2531                'sanitize_callback' => 'Jetpack_SEO_Utils::sanitize_front_page_meta_description',
2532                'jp_group'          => 'seo-tools',
2533            ),
2534
2535            'advanced_seo_title_formats'                => array(
2536                'description'       => esc_html__( 'SEO page title structures.', 'jetpack' ),
2537                'type'              => 'object',
2538                'default'           => array(
2539                    'archives'   => array(),
2540                    'front_page' => array(),
2541                    'groups'     => array(),
2542                    'pages'      => array(),
2543                    'posts'      => array(),
2544                ),
2545                'jp_group'          => 'seo-tools',
2546                'validate_callback' => 'Jetpack_SEO_Titles::are_valid_title_formats',
2547                'sanitize_callback' => 'Jetpack_SEO_Titles::sanitize_title_formats',
2548            ),
2549
2550            // GEO tab (Jetpack > SEO). Plain option the SEO package reads to serve
2551            // /llms.txt. The front-end behavior is gated inside the package; this
2552            // only round-trips the persisted state alongside the other seo-tools
2553            // settings.
2554            'jetpack_seo_llms_txt_enabled'              => array(
2555                'description'       => esc_html__( 'Generate an llms.txt file to guide AI assistants around your content.', 'jetpack' ),
2556                'type'              => 'boolean',
2557                'default'           => 0,
2558                'validate_callback' => __CLASS__ . '::validate_boolean',
2559                'jp_group'          => 'seo-tools',
2560            ),
2561
2562            // VideoPress.
2563            'videopress_private_enabled_for_site'       => array(
2564                'description'       => esc_html__( 'Video Privacy: Restrict views to members of this site', 'jetpack' ),
2565                'type'              => 'boolean',
2566                'default'           => 0,
2567                'validate_callback' => __CLASS__ . '::validate_boolean',
2568                'jp_group'          => 'videopress',
2569            ),
2570            'videopress_share_menu_disabled'            => array(
2571                'description'       => esc_html__( 'Hide the share menu on every video, overriding each video’s own setting', 'jetpack' ),
2572                'type'              => 'boolean',
2573                'default'           => 0,
2574                'validate_callback' => __CLASS__ . '::validate_boolean',
2575                'jp_group'          => 'videopress',
2576            ),
2577        );
2578
2579        // SEO Tools - SEO Enhancer.
2580        // TODO: move this to the main options array? The filter was there while developing the feature.
2581        // It might come in handy to hold its availability behind the filter since it still depends on AI to be available.
2582        if ( apply_filters( 'ai_seo_enhancer_enabled', true ) ) {
2583            $options['ai_seo_enhancer_enabled'] = array(
2584                'description'       => esc_html__( 'Automatically generate SEO title, SEO description, and image alt text for new posts.', 'jetpack' ),
2585                'type'              => 'boolean',
2586                'default'           => 0,
2587                'validate_callback' => __CLASS__ . '::validate_boolean',
2588                'jp_group'          => 'seo-tools',
2589            );
2590        }
2591
2592        // Add modules to list so they can be toggled.
2593        $modules = Jetpack::get_available_modules();
2594        if ( is_array( $modules ) && ! empty( $modules ) ) {
2595            $module_args = array(
2596                'description'       => '',
2597                'type'              => 'boolean',
2598                'default'           => 0,
2599                'validate_callback' => __CLASS__ . '::validate_boolean',
2600                'jp_group'          => 'modules',
2601            );
2602            foreach ( $modules as $module ) {
2603                $options[ $module ] = $module_args;
2604            }
2605        }
2606
2607        if ( is_array( $selector ) ) {
2608
2609            // Return only those options whose keys match $selector keys.
2610            return array_intersect_key( $options, $selector );
2611        }
2612
2613        if ( 'any' === $selector ) {
2614
2615            // Toggle module or update any module option or any general setting.
2616            return $options;
2617        }
2618
2619        // We're updating the options for a single module.
2620        if ( empty( $selector ) ) {
2621            $selector = self::get_module_requested();
2622        }
2623        $selected = array();
2624        foreach ( $options as $option => $attributes ) {
2625
2626            // Not adding an isset( $attributes['jp_group'] ) because if it's not set, it must be fixed, otherwise options will fail.
2627            if ( $selector === $attributes['jp_group'] ) {
2628                $selected[ $option ] = $attributes;
2629            }
2630        }
2631        return $selected;
2632    }
2633
2634    /**
2635     * Validates that the parameters are proper values that can be set during Jetpack onboarding.
2636     *
2637     * @since 5.4.0
2638     *
2639     * @deprecated since 13.9
2640     *
2641     * @param array           $onboarding_data Values to check.
2642     * @param WP_REST_Request $request         The request sent to the WP REST API.
2643     * @param string          $param           Name of the parameter passed to endpoint holding $value.
2644     *
2645     * @return bool|WP_Error
2646     */
2647    public static function validate_onboarding( $onboarding_data, $request, $param ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
2648        _deprecated_function( __METHOD__, '13.9' );
2649        return true;
2650    }
2651
2652    /**
2653     * Validates that the parameter is either a pure boolean or a numeric string that can be mapped to a boolean.
2654     *
2655     * @since 4.3.0
2656     *
2657     * @param string|bool     $value Value to check.
2658     * @param WP_REST_Request $request The request sent to the WP REST API.
2659     * @param string          $param Name of the parameter passed to endpoint holding $value.
2660     *
2661     * @return bool|WP_Error
2662     */
2663    public static function validate_boolean( $value, $request, $param ) {
2664        // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict -- Other code depends on loose comparison here.
2665        if ( ! is_bool( $value ) && ! ( ctype_digit( (string) $value ) && in_array( $value, array( 0, 1 ) ) ) ) {
2666            return new WP_Error(
2667                'invalid_param',
2668                sprintf(
2669                    /* Translators: Placeholder is a parameter name. */
2670                    esc_html__( '%s must be true, false, 0 or 1.', 'jetpack' ),
2671                    $param
2672                )
2673            );
2674        }
2675        return true;
2676    }
2677
2678    /**
2679     * Validates that the parameter is a positive integer.
2680     *
2681     * @since 4.3.0
2682     *
2683     * @param int             $value Value to check.
2684     * @param WP_REST_Request $request The request sent to the WP REST API.
2685     * @param string          $param Name of the parameter passed to endpoint holding $value.
2686     *
2687     * @return bool|WP_Error
2688     */
2689    public static function validate_posint( $value, $request, $param ) {
2690        if ( ! is_numeric( $value ) || $value <= 0 ) {
2691            return new WP_Error(
2692                'invalid_param',
2693                sprintf(
2694                    /* Translators: Placeholder is a parameter name. */
2695                    esc_html__( '%s must be a positive integer.', 'jetpack' ),
2696                    $param
2697                )
2698            );
2699        }
2700        return true;
2701    }
2702
2703    /**
2704     * Validates that the parameter is a non-negative integer (includes 0).
2705     *
2706     * @since 10.4.0
2707     *
2708     * @param int             $value Value to check.
2709     * @param WP_REST_Request $request The request sent to the WP REST API.
2710     * @param string          $param Name of the parameter passed to endpoint holding $value.
2711     *
2712     * @return bool|WP_Error
2713     */
2714    public static function validate_non_neg_int( $value, $request, $param ) {
2715        if ( ! is_numeric( $value ) || $value < 0 ) {
2716            return new WP_Error(
2717                'invalid_param',
2718                /* translators: %s: The literal parameter name. Should not be translated. */
2719                sprintf( esc_html__( '%s must be a non-negative integer.', 'jetpack' ), $param )
2720            );
2721        }
2722        return true;
2723    }
2724
2725    /**
2726     * Validates that the parameter belongs to a list of admitted values.
2727     *
2728     * @since 4.3.0
2729     *
2730     * @param string          $value Value to check.
2731     * @param WP_REST_Request $request The request sent to the WP REST API.
2732     * @param string          $param Name of the parameter passed to endpoint holding $value.
2733     *
2734     * @return bool|WP_Error
2735     */
2736    public static function validate_list_item( $value, $request, $param ) {
2737        $attributes = $request->get_attributes();
2738        if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
2739            return new WP_Error(
2740                'invalid_param',
2741                sprintf(
2742                    /* Translators: Placeholder is a parameter name. */
2743                    esc_html__( '%s not recognized', 'jetpack' ),
2744                    $param
2745                )
2746            );
2747        }
2748        $args = $attributes['args'][ $param ];
2749        if ( ! empty( $args['enum'] ) ) {
2750            // If it's an associative array, use the keys to check that the value is among those admitted.
2751            $enum = ( count( array_filter( array_keys( $args['enum'] ), 'is_string' ) ) > 0 )
2752                ? array_keys( $args['enum'] )
2753                : $args['enum'];
2754            $enum = array_map( 'strval', $enum );
2755            if ( ! in_array( $value, $enum, true ) ) {
2756                return new WP_Error(
2757                    'invalid_param_value',
2758                    sprintf(
2759                    /* Translators: first variable is the parameter passed to endpoint that holds the list item, the second is a list of admitted values. */
2760                        esc_html__( '%1$s must be one of %2$s', 'jetpack' ),
2761                        $param,
2762                        implode( ', ', $enum )
2763                    )
2764                );
2765            }
2766        }
2767        return true;
2768    }
2769
2770    /**
2771     * Validates that the parameter belongs to a list of admitted values.
2772     *
2773     * @since 4.3.0
2774     *
2775     * @param string          $value Value to check.
2776     * @param WP_REST_Request $request The request sent to the WP REST API.
2777     * @param string          $param Name of the parameter passed to endpoint holding $value.
2778     *
2779     * @return bool|WP_Error
2780     */
2781    public static function validate_module_list( $value, $request, $param ) {
2782        if ( ! is_array( $value ) ) {
2783            return new WP_Error(
2784                'invalid_param_value',
2785                sprintf(
2786                    /* Translators: Placeholder is a parameter name. */
2787                    esc_html__( '%s must be an array', 'jetpack' ),
2788                    $param
2789                )
2790            );
2791        }
2792
2793        $modules = Jetpack::get_available_modules();
2794
2795        if ( count( array_intersect( $value, $modules ) ) !== count( $value ) ) {
2796            return new WP_Error(
2797                'invalid_param_value',
2798                sprintf(
2799                    /* Translators: Placeholder is a parameter name. */
2800                    esc_html__( '%s must be a list of valid modules', 'jetpack' ),
2801                    $param
2802                )
2803            );
2804        }
2805
2806        return true;
2807    }
2808
2809    /**
2810     * Validates that the parameter is an alphanumeric or empty string (to be able to clear the field).
2811     *
2812     * @since 4.3.0
2813     *
2814     * @param string          $value Value to check.
2815     * @param WP_REST_Request $request The request sent to the WP REST API.
2816     * @param string          $param Name of the parameter passed to endpoint holding $value.
2817     *
2818     * @return bool|WP_Error
2819     */
2820    public static function validate_alphanum( $value, $request, $param ) {
2821        if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/^[a-z0-9]+$/i', $value ) ) ) {
2822            return new WP_Error(
2823                'invalid_param',
2824                sprintf(
2825                    /* Translators: Placeholder is a parameter name. */
2826                    esc_html__( '%s must be an alphanumeric string.', 'jetpack' ),
2827                    $param
2828                )
2829            );
2830        }
2831        return true;
2832    }
2833
2834    /**
2835     * Validates that the parameter is a tag or id for a verification service, or an empty string (to be able to clear the field).
2836     *
2837     * @since 4.6.0
2838     *
2839     * @param string          $value   Value to check.
2840     * @param WP_REST_Request $request The request sent to the WP REST API.
2841     * @param string          $param   Name of the parameter passed to endpoint holding $value.
2842     *
2843     * @return bool|WP_Error
2844     */
2845    public static function validate_verification_service( $value, $request, $param ) {
2846        if ( ! empty( $value ) && ( ! is_string( $value ) || false === jetpack_verification_validate_code( $value ) ) ) {
2847            return new WP_Error(
2848                'invalid_param',
2849                sprintf(
2850                    /* Translators: Placeholder is a verification string used to verify a service like Google Webmaster Console. */
2851                    esc_html__( '%s must be a valid verification code or verification tag.', 'jetpack' ),
2852                    $param
2853                )
2854            );
2855        }
2856        return true;
2857    }
2858
2859    /**
2860     * Validates that the parameter is among the roles allowed for Stats.
2861     *
2862     * @since 4.3.0
2863     *
2864     * @param mixed           $value Value to check.
2865     * @param WP_REST_Request $request The request sent to the WP REST API.
2866     * @param string          $param Name of the parameter passed to endpoint holding $value.
2867     *
2868     * @return bool|WP_Error
2869     */
2870    public static function validate_stats_roles( $value, $request, $param ) {
2871        // An empty value clears the setting; sanitize_stats_allowed_roles() falls back to 'administrator'.
2872        if ( empty( $value ) ) {
2873            return true;
2874        }
2875
2876        // Enforce the schema's list-of-strings contract before array_intersect() below sees the value.
2877        if ( ! is_array( $value ) || count( array_filter( $value, 'is_string' ) ) !== count( $value ) ) {
2878            return new WP_Error(
2879                'invalid_param',
2880                sprintf(
2881                    /* Translators: Placeholder is a parameter name. */
2882                    esc_html__( '%s must be an array of user roles.', 'jetpack' ),
2883                    $param
2884                )
2885            );
2886        }
2887
2888        if ( ! function_exists( 'get_editable_roles' ) ) {
2889            require_once ABSPATH . 'wp-admin/includes/user.php';
2890        }
2891        $editable_roles = array_keys( get_editable_roles() );
2892        if ( ! array_intersect( $editable_roles, $value ) ) {
2893            return new WP_Error(
2894                'invalid_param',
2895                sprintf(
2896                    /* Translators: first variable is the name of a parameter passed to endpoint holding the role that will be checked, the second is a list of roles allowed to see stats. The parameter is checked against this list. */
2897                    esc_html__( '%1$s must be %2$s.', 'jetpack' ),
2898                    $param,
2899                    implode( ', ', $editable_roles )
2900                )
2901            );
2902        }
2903        return true;
2904    }
2905
2906    /**
2907     * Validates that the parameter is among the views where the Sharing can be displayed.
2908     *
2909     * @since 4.3.0
2910     *
2911     * @param string|bool     $value Value to check.
2912     * @param WP_REST_Request $request The request sent to the WP REST API.
2913     * @param string          $param Name of the parameter passed to endpoint holding $value.
2914     *
2915     * @return bool|WP_Error
2916     */
2917    public static function validate_sharing_show( $value, $request, $param ) {
2918        $views = array( 'index', 'post', 'page', 'attachment', 'jetpack-portfolio' );
2919        if ( ! is_array( $value ) ) {
2920            return new WP_Error(
2921                'invalid_param',
2922                sprintf(
2923                    /* Translators: Placeholder is a parameter name. */
2924                    esc_html__( '%s must be an array of post types.', 'jetpack' ),
2925                    $param
2926                )
2927            );
2928        }
2929        if ( ! array_intersect( $views, $value ) ) {
2930            return new WP_Error(
2931                'invalid_param',
2932                sprintf(
2933                    /* Translators: first variable is the name of a parameter passed to endpoint holding the post type where Sharing will be displayed, the second is a list of post types where Sharing can be displayed */
2934                    esc_html__( '%1$s must be %2$s.', 'jetpack' ),
2935                    $param,
2936                    implode( ', ', $views )
2937                )
2938            );
2939        }
2940        return true;
2941    }
2942
2943    /**
2944     * Validates that the parameter is among the valid reply-to types for subscriptions.
2945     *
2946     * @since 4.3.0
2947     *
2948     * @param string|bool     $value Value to check.
2949     * @param WP_REST_Request $request The request sent to the WP REST API.
2950     * @param string          $param Name of the parameter passed to endpoint holding $value.
2951     *
2952     * @return bool|WP_Error
2953     */
2954    public static function validate_subscriptions_reply_to( $value, $request, $param ) {
2955        require_once JETPACK__PLUGIN_DIR . 'modules/subscriptions/class-settings.php';
2956        if ( ! empty( $value ) && ! Automattic\Jetpack\Modules\Subscriptions\Settings::is_valid_reply_to( $value ) ) {
2957            return new WP_Error(
2958                'invalid_param',
2959                sprintf(
2960                    /* Translators: Placeholder is a parameter name. */
2961                    esc_html__( '%s must be a valid type.', 'jetpack' ),
2962                    $param
2963                )
2964            );
2965        }
2966        return true;
2967    }
2968
2969    /**
2970     * Validates that the parameter is among the valid reply-to types for subscriptions.
2971     *
2972     * @since 4.3.0
2973     *
2974     * @param string|bool     $value Value to check.
2975     * @param WP_REST_Request $request The request sent to the WP REST API.
2976     * @param string          $param Name of the parameter passed to endpoint holding $value.
2977     *
2978     * @return bool|WP_Error
2979     */
2980    public static function validate_subscriptions_reply_to_name( $value, $request, $param ) {
2981        if ( ! empty( $value ) && ! is_string( $value ) ) {
2982            return new WP_Error(
2983                'invalid_param',
2984                sprintf(
2985                    /* Translators: Placeholder is a parameter name. */
2986                    esc_html__( '%s must be a valid type.', 'jetpack' ),
2987                    $param
2988                )
2989            );
2990        }
2991        return true;
2992    }
2993
2994    /**
2995     * Validates that the parameter is among the views where the Sharing can be displayed.
2996     *
2997     * @since 4.3.0
2998     *
2999     * @param string|bool     $value {
3000     *         Value to check received by request.
3001     *
3002     *     @type array $visible List of slug of services to share to that are displayed directly in the page.
3003     *     @type array $hidden  List of slug of services to share to that are concealed in a folding menu.
3004     * }
3005     * @param WP_REST_Request $request The request sent to the WP REST API.
3006     * @param string          $param Name of the parameter passed to endpoint holding $value.
3007     *
3008     * @return bool|WP_Error
3009     */
3010    public static function validate_services( $value, $request, $param ) {
3011        if ( ! is_array( $value ) || ! isset( $value['visible'] ) || ! isset( $value['hidden'] ) ) {
3012            return new WP_Error(
3013                'invalid_param',
3014                sprintf(
3015                    /* Translators: Placeholder is a parameter name. */
3016                    esc_html__( '%s must be an array with visible and hidden items.', 'jetpack' ),
3017                    $param
3018                )
3019            );
3020        }
3021
3022        // Allow to clear everything.
3023        if ( empty( $value['visible'] ) && empty( $value['hidden'] ) ) {
3024            return true;
3025        }
3026
3027        if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
3028            return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
3029        }
3030        $sharer   = new Sharing_Service();
3031        $services = array_keys( $sharer->get_all_services() );
3032
3033        if (
3034            ( ! empty( $value['visible'] ) && ! array_intersect( $value['visible'], $services ) )
3035            ||
3036            ( ! empty( $value['hidden'] ) && ! array_intersect( $value['hidden'], $services ) ) ) {
3037            return new WP_Error(
3038                'invalid_param',
3039                sprintf(
3040                    /* Translators: placeholder 1 is a parameter holding the services passed to endpoint, placeholder 2 is a list of all Jetpack Sharing services */
3041                    esc_html__( '%1$s visible and hidden items must be a list of %2$s.', 'jetpack' ),
3042                    $param,
3043                    implode( ', ', $services )
3044                )
3045            );
3046        }
3047        return true;
3048    }
3049
3050    /**
3051     * Validates that the parameter has enough information to build a custom sharing button.
3052     *
3053     * @since 4.3.0
3054     *
3055     * @param string|bool     $value Value to check.
3056     * @param WP_REST_Request $request The request sent to the WP REST API.
3057     * @param string          $param Name of the parameter passed to endpoint holding $value.
3058     *
3059     * @return bool|WP_Error
3060     */
3061    public static function validate_custom_service( $value, $request, $param ) {
3062        if ( ! is_array( $value ) || ! isset( $value['sharing_name'] ) || ! isset( $value['sharing_url'] ) || ! isset( $value['sharing_icon'] ) ) {
3063            return new WP_Error(
3064                'invalid_param',
3065                sprintf(
3066                    /* Translators: Placeholder is a parameter name. */
3067                    esc_html__( '%s must be an array with sharing name, url and icon.', 'jetpack' ),
3068                    $param
3069                )
3070            );
3071        }
3072
3073        // Allow to clear everything.
3074        if ( empty( $value['sharing_name'] ) && empty( $value['sharing_url'] ) && empty( $value['sharing_icon'] ) ) {
3075            return true;
3076        }
3077
3078        if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
3079            return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
3080        }
3081
3082        if ( ( ! empty( $value['sharing_name'] ) && ! is_string( $value['sharing_name'] ) )
3083        || ( ! empty( $value['sharing_url'] ) && ! is_string( $value['sharing_url'] ) )
3084        || ( ! empty( $value['sharing_icon'] ) && ! is_string( $value['sharing_icon'] ) ) ) {
3085            return new WP_Error(
3086                'invalid_param',
3087                sprintf(
3088                    /* Translators: Placeholder is a parameter name. */
3089                    esc_html__( '%s needs sharing name, url and icon.', 'jetpack' ),
3090                    $param
3091                )
3092            );
3093        }
3094        return true;
3095    }
3096
3097    /**
3098     * Validates that the parameter is a custom sharing service ID like 'custom-1461976264'.
3099     *
3100     * @since 4.3.0
3101     *
3102     * @param string          $value Value to check.
3103     * @param WP_REST_Request $request The request sent to the WP REST API.
3104     * @param string          $param Name of the parameter passed to endpoint holding $value.
3105     *
3106     * @return bool|WP_Error
3107     */
3108    public static function validate_custom_service_id( $value, $request, $param ) {
3109        if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/custom\-[0-1]+/i', $value ) ) ) {
3110            return new WP_Error(
3111                'invalid_param',
3112                sprintf(
3113                    /* Translators: Placeholder is a parameter name. */
3114                    esc_html__( "%s must be a string prefixed with 'custom-' and followed by a numeric ID.", 'jetpack' ),
3115                    $param
3116                )
3117            );
3118        }
3119
3120        if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
3121            return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
3122        }
3123        $sharer   = new Sharing_Service();
3124        $services = $sharer->get_all_services();
3125
3126        if ( ! empty( $value ) && ! isset( $services[ $value ] ) ) {
3127            return new WP_Error(
3128                'invalid_param',
3129                sprintf(
3130                    /* Translators: Placeholder is a parameter name. */
3131                    esc_html__( '%s is not a registered custom sharing service.', 'jetpack' ),
3132                    $param
3133                )
3134            );
3135        }
3136
3137        return true;
3138    }
3139
3140    /**
3141     * Validates that the parameter is a Twitter username or empty string (to be able to clear the field).
3142     *
3143     * @since 4.3.0
3144     *
3145     * @param string          $value   Value to check.
3146     * @param WP_REST_Request $request The request sent to the WP REST API.
3147     * @param string          $param   Name of the parameter passed to endpoint holding $value.
3148     *
3149     * @return bool|WP_Error
3150     */
3151    public static function validate_twitter_username( $value, $request, $param ) {
3152        if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/^@?\w{1,15}$/i', $value ) ) ) {
3153            return new WP_Error(
3154                'invalid_param',
3155                sprintf(
3156                    /* Translators: Placeholder is a twitter name. */
3157                    esc_html__( '%s must be a Twitter username.', 'jetpack' ),
3158                    $param
3159                )
3160            );
3161        }
3162        return true;
3163    }
3164
3165    /**
3166     * Validates the firewall's IP block list, refusing one that would block the user saving it.
3167     *
3168     * @since 16.4
3169     *
3170     * @param string          $value Value to check.
3171     * @param WP_REST_Request $request The request sent to the WP REST API.
3172     * @param string          $param Name of the parameter passed to endpoint holding $value.
3173     *
3174     * @return bool|WP_Error
3175     */
3176    public static function validate_waf_ip_block_list( $value, $request, $param ) {
3177        $is_string = self::validate_string( $value, $request, $param );
3178        // Another plugin can load an older Protect package without the check.
3179        if ( true !== $is_string || ! method_exists( Protect_Firewall::class, 'validate_ip_block_list' ) ) {
3180            return $is_string;
3181        }
3182
3183        // Check the list as the sanitize_callback will store it, since the firewall reads the stored copy.
3184        return Protect_Firewall::validate_ip_block_list( esc_textarea( $value ) );
3185    }
3186
3187    /**
3188     * Validates that the parameter is a string.
3189     *
3190     * @since 4.3.0
3191     *
3192     * @param string          $value Value to check.
3193     * @param WP_REST_Request $request The request sent to the WP REST API.
3194     * @param string          $param Name of the parameter passed to endpoint holding $value.
3195     *
3196     * @return bool|WP_Error
3197     */
3198    public static function validate_string( $value, $request, $param ) {
3199        if ( ! is_string( $value ) ) {
3200            return new WP_Error(
3201                'invalid_param',
3202                sprintf(
3203                    /* Translators: Placeholder is a parameter name. */
3204                    esc_html__( '%s must be a string.', 'jetpack' ),
3205                    $param
3206                )
3207            );
3208        }
3209        return true;
3210    }
3211
3212    /**
3213     * Validates that the parameter is an array of strings.
3214     *
3215     * @param array           $value Value to check.
3216     * @param WP_REST_Request $request The request sent to the WP REST API.
3217     * @param string          $param Name of the parameter passed to the endpoint holding $value.
3218     *
3219     * @return bool|WP_Error
3220     */
3221    public static function validate_array_of_strings( $value, $request, $param ) {
3222        foreach ( $value as $array_item ) {
3223            $validate = self::validate_string( $array_item, $request, $param );
3224            if ( is_wp_error( $validate ) ) {
3225                return $validate;
3226            }
3227        }
3228
3229        return true;
3230    }
3231
3232    /**
3233     * Validates the subscription_options parameter.
3234     *
3235     * @param array $values Value to check.
3236     *
3237     * @return bool|WP_Error
3238     */
3239    public static function validate_subscription_options( $values ) {
3240        // A REST "object" decodes to a PHP associative array. Reject any other
3241        // type (object, string, int, null, ...) up front so the array_keys()
3242        // loop below never runs against a non-array and triggers a PHP warning.
3243        if ( ! is_array( $values ) ) {
3244            return new WP_Error(
3245                'invalid_param',
3246                /* Translators: subscription_options is a variable name, and shouldn't be translated. */
3247                esc_html__( 'subscription_options must be an object.', 'jetpack' )
3248            );
3249        }
3250        foreach ( array_keys( $values ) as $key ) {
3251            if ( ! in_array( $key, array( 'welcome', 'invitation', 'comment_follow', 'subscribe_modal_heading', 'free_tier_description', 'hide_free_tier' ), true ) ) {
3252                return new WP_Error(
3253                    'invalid_param',
3254                    sprintf(
3255                        /* Translators: Placeholder is the invalid param being sent. */
3256                        esc_html__( '%s is not one of the allowed members of subscription_options.', 'jetpack' ),
3257                        $key
3258                    )
3259                );
3260            }
3261        }
3262        return true;
3263    }
3264
3265    /**
3266     * Validates that the parameter is an array.
3267     *
3268     * @param array           $values Value to check.
3269     * @param WP_REST_Request $request The request sent to the WP REST API.
3270     * @param string          $param Name of the parameter passed to the endpoint holding $value.
3271     *
3272     * @return bool|WP_Error
3273     */
3274    public static function validate_array( $values, $request, $param ) {
3275        if ( ! is_array( $values ) ) {
3276            return new WP_Error(
3277                'invalid_param',
3278                sprintf(
3279                    /* Translators: Placeholder is a parameter name. */
3280                    esc_html__( '%s must be an object.', 'jetpack' ),
3281                    $param
3282                )
3283            );
3284        }
3285        return true;
3286    }
3287
3288    /**
3289     * If for some reason the roles allowed to see Stats are empty (for example, user tampering with checkboxes),
3290     * return an array with only 'administrator' as the allowed role and save it for 'roles' option.
3291     *
3292     * @since 4.3.0
3293     *
3294     * @param mixed $value Value to check.
3295     *
3296     * @return mixed The value as submitted, or an array holding only 'administrator' when it is empty.
3297     */
3298    public static function sanitize_stats_allowed_roles( $value ) {
3299        if ( empty( $value ) ) {
3300            return array( 'administrator' );
3301        }
3302        return $value;
3303    }
3304
3305    /**
3306     * Get the currently accessed route and return the module slug in it.
3307     *
3308     * @since 4.3.0
3309     *
3310     * @param string $route Regular expression for the endpoint with the module slug to return.
3311     *
3312     * @return array|string
3313     */
3314    public static function get_module_requested( $route = '/module/(?P<slug>[a-z\-]+)' ) {
3315
3316        if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) || ! is_string( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
3317            return '';
3318        }
3319
3320        preg_match( "#$route#", $GLOBALS['wp']->query_vars['rest_route'], $module );
3321
3322        if ( empty( $module['slug'] ) ) {
3323            return '';
3324        }
3325
3326        return $module['slug'];
3327    }
3328
3329    /**
3330     * Adds extra information for modules.
3331     *
3332     * @since 4.3.0
3333     *
3334     * @param string|array $modules Can be a single module or a list of modules.
3335     * @param null|string  $slug    Slug of the module in the first parameter.
3336     *
3337     * @return array|string
3338     */
3339    public static function prepare_modules_for_response( $modules = '', $slug = null ) {
3340        global $wp_rewrite;
3341
3342        /** This filter is documented in modules/sitemaps/sitemaps.php */
3343        $location = apply_filters( 'jetpack_sitemap_location', '' );
3344
3345        if ( $wp_rewrite->using_index_permalinks() ) {
3346            $sitemap_url      = home_url( '/index.php' . $location . '/sitemap.xml' );
3347            $news_sitemap_url = home_url( '/index.php' . $location . '/news-sitemap.xml' );
3348        } elseif ( $wp_rewrite->using_permalinks() ) {
3349            $sitemap_url      = home_url( $location . '/sitemap.xml' );
3350            $news_sitemap_url = home_url( $location . '/news-sitemap.xml' );
3351        } else {
3352            $sitemap_url      = home_url( $location . '/?jetpack-sitemap=sitemap.xml' );
3353            $news_sitemap_url = home_url( $location . '/?jetpack-sitemap=news-sitemap.xml' );
3354        }
3355
3356        if ( $slug === null && isset( $modules['sitemaps'] ) ) {
3357            // Is a list of modules.
3358            $modules['sitemaps']['extra']['sitemap_url']      = $sitemap_url;
3359            $modules['sitemaps']['extra']['news_sitemap_url'] = $news_sitemap_url;
3360        } elseif ( 'sitemaps' === $slug ) {
3361            // It's a single module.
3362            $modules['extra']['sitemap_url']      = $sitemap_url;
3363            $modules['extra']['news_sitemap_url'] = $news_sitemap_url;
3364        }
3365        return $modules;
3366    }
3367
3368    /**
3369     * Remove options the current user cannot read.
3370     *
3371     * Covers every `jetpack_waf_*` option, plus the two Protect options that expose the
3372     * same data under a different name: `jetpack_protect_global_whitelist` is populated
3373     * from `jetpack_waf_ip_allow_list`, and `jetpack_protect_key` is a shared secret.
3374     *
3375     * @since 16.2
3376     *
3377     * @param array $options Option definitions keyed by option name.
3378     * @return array
3379     */
3380    public static function filter_options_for_response( $options ) {
3381        if ( current_user_can( 'manage_options' ) ) {
3382            return $options;
3383        }
3384
3385        $restricted = array(
3386            'jetpack_protect_key',
3387            'jetpack_protect_global_whitelist',
3388        );
3389
3390        return array_filter(
3391            $options,
3392            static function ( $option_name ) use ( $restricted ) {
3393                return 0 !== strpos( $option_name, 'jetpack_waf_' )
3394                    && ! in_array( $option_name, $restricted, true );
3395            },
3396            ARRAY_FILTER_USE_KEY
3397        );
3398    }
3399
3400    /**
3401     * Remove 'validate_callback' item from options available for module.
3402     * Fetch current option value and add to array of module options.
3403     * Prepare values of module options that need special handling, like those saved in wpcom.
3404     *
3405     * @since 4.3.0
3406     *
3407     * @param string $module Module slug.
3408     * @return array
3409     */
3410    public static function prepare_options_for_response( $module = '' ) {
3411        $options = self::get_updateable_data_list( $module );
3412
3413        if ( ! is_array( $options ) || empty( $options ) ) {
3414            return $options;
3415        }
3416
3417        // Some modules need special treatment.
3418        switch ( $module ) {
3419
3420            case 'monitor':
3421                // Status of user notifications.
3422                $options['monitor_receive_notifications']['current_value'] = self::cast_value( self::get_remote_value( 'monitor', 'monitor_receive_notifications' ), $options['monitor_receive_notifications'] );
3423                break;
3424
3425            case 'post-by-email':
3426                // Email address.
3427                $options['post_by_email_address']['current_value'] = self::cast_value( self::get_remote_value( 'post-by-email', 'post_by_email_address' ), $options['post_by_email_address'] );
3428                break;
3429
3430            case 'protect':
3431                // Protect.
3432                $options['jetpack_protect_key']['current_value']              = get_site_option( 'jetpack_protect_key', false );
3433                $options['jetpack_protect_global_whitelist']['current_value'] = Brute_Force_Protection_Shared_Functions::format_allow_list();
3434                break;
3435
3436            case 'related-posts':
3437                // It's local, but it must be broken apart since it's saved as an array.
3438                $options = self::split_options( $options, Jetpack_Options::get_option( 'relatedposts' ) );
3439                break;
3440
3441            case 'verification-tools':
3442                // It's local, but it must be broken apart since it's saved as an array.
3443                $options = self::split_options( $options, get_option( 'verification_services_codes' ) );
3444                break;
3445
3446            case 'google-analytics':
3447                $wga  = get_option( 'jetpack_wga' );
3448                $code = '';
3449                if ( is_array( $wga ) && array_key_exists( 'code', $wga ) ) {
3450                    $code = $wga['code'];
3451                }
3452                $options['google_analytics_tracking_id']['current_value'] = $code;
3453                break;
3454
3455            case 'sharedaddy':
3456                // It's local, but it must be broken apart since it's saved as an array.
3457                if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
3458                    break;
3459                }
3460                $sharer                                       = new Sharing_Service();
3461                $options                                      = self::split_options( $options, $sharer->get_global_options() );
3462                $options['sharing_services']['current_value'] = $sharer->get_blog_services();
3463                $other_sharedaddy_options                     = array( 'jetpack-twitter-cards-site-tag', 'sharedaddy_disable_resources', 'sharing_delete_service' );
3464                foreach ( $other_sharedaddy_options as $key ) {
3465                    $default_value                    = $options[ $key ]['default'] ?? '';
3466                    $current_value                    = get_option( $key, $default_value );
3467                    $options[ $key ]['current_value'] = self::cast_value( $current_value, $options[ $key ] );
3468                }
3469                break;
3470
3471            case 'stats':
3472                // It's local, but it must be broken apart since it's saved as an array.
3473                $options = self::split_options( $options, Stats_Options::get_options() );
3474                break;
3475            default:
3476                // These option are just stored as plain WordPress options.
3477                foreach ( $options as $key => $value ) {
3478                    $default_value                    = $options[ $key ]['default'] ?? '';
3479                    $current_value                    = get_option( $key, $default_value );
3480                    $options[ $key ]['current_value'] = self::cast_value( $current_value, $options[ $key ] );
3481                }
3482        }
3483        // At this point some options have current_value not set because they're options
3484        // that only get written on update, so we set current_value to the default one.
3485        foreach ( $options as $key => $value ) {
3486            // We don't need validate_callback in the response.
3487            if ( isset( $options[ $key ]['validate_callback'] ) ) {
3488                unset( $options[ $key ]['validate_callback'] );
3489            }
3490            $default_value = $options[ $key ]['default'] ?? '';
3491            if ( ! array_key_exists( 'current_value', $options[ $key ] ) ) {
3492                $options[ $key ]['current_value'] = self::cast_value( $default_value, $options[ $key ] );
3493            }
3494        }
3495
3496        // Filter last: the switch above assigns current_value by key without isset(),
3497        // so filtering earlier would let those assignments re-add a removed option.
3498        return self::filter_options_for_response( $options );
3499    }
3500
3501    /**
3502     * Splits module options saved as arrays like relatedposts or verification_services_codes into separate options to be returned in the response.
3503     *
3504     * @since 4.3.0
3505     *
3506     * @param array  $separate_options Array of options admitted by the module.
3507     * @param array  $grouped_options Option saved as array to be splitted.
3508     * @param string $prefix Optional prefix for the separate option keys.
3509     *
3510     * @return array
3511     */
3512    public static function split_options( $separate_options, $grouped_options, $prefix = '' ) {
3513        if ( is_array( $grouped_options ) ) {
3514            foreach ( $grouped_options as $key => $value ) {
3515                $option_key = $prefix . $key;
3516                if ( isset( $separate_options[ $option_key ] ) ) {
3517                    $separate_options[ $option_key ]['current_value'] = self::cast_value( $grouped_options[ $key ], $separate_options[ $option_key ] );
3518                }
3519            }
3520        }
3521        return $separate_options;
3522    }
3523
3524    /**
3525     * Perform a casting to the value specified in the option definition.
3526     *
3527     * @since 4.3.0
3528     *
3529     * @param mixed $value Value to cast to the proper type.
3530     * @param array $definition Type to cast the value to.
3531     *
3532     * @return bool|float|int|string
3533     */
3534    public static function cast_value( $value, $definition ) {
3535        if ( 'NULL' === $value ) {
3536            return null;
3537        }
3538
3539        if ( isset( $definition['type'] ) ) {
3540            switch ( $definition['type'] ) {
3541                case 'boolean':
3542                    if ( 'true' === $value || 'on' === $value ) {
3543                        return true;
3544                    } elseif ( 'false' === $value || 'off' === $value ) {
3545                        return false;
3546                    }
3547                    $value = (bool) $value;
3548                    break;
3549
3550                case 'integer':
3551                    $value = (int) $value;
3552                    break;
3553
3554                case 'float':
3555                    $value = (float) $value;
3556                    break;
3557
3558                case 'string':
3559                    $value = (string) $value;
3560                    break;
3561            }
3562        }
3563        return $value;
3564    }
3565
3566    /**
3567     * Get a value not saved locally.
3568     *
3569     * @since 4.3.0
3570     *
3571     * @param string $module Module slug.
3572     * @param string $option Option name.
3573     *
3574     * @return bool Whether user is receiving notifications or not.
3575     */
3576    public static function get_remote_value( $module, $option ) {
3577
3578        // These are per-user values on WordPress.com, so each user gets their own local copy.
3579        if ( in_array( $module, array( 'monitor', 'post-by-email' ), true ) ) {
3580            $option .= get_current_user_id();
3581        }
3582
3583        // If option doesn't exist, 'does_not_exist' will be returned.
3584        $value = get_option( $option, 'does_not_exist' );
3585
3586        // If option exists, just return it.
3587        if ( 'does_not_exist' !== $value ) {
3588            return $value;
3589        }
3590
3591        // Only check a remote option if Jetpack is connected.
3592        if ( ! Jetpack::is_connection_ready() ) {
3593            return false;
3594        }
3595
3596        // Do what is necessary for each module.
3597        switch ( $module ) {
3598            case 'monitor':
3599                // Load the class to use the method. If class can't be found, do nothing.
3600                if ( ! class_exists( 'Jetpack_Monitor' ) && ! include_once Jetpack::get_module_path( $module ) ) {
3601                    return false;
3602                }
3603                $value = Jetpack_Monitor::user_receives_notifications( false );
3604                // Not saved: the user may not be connected yet, and would be stuck with this answer.
3605                if ( is_wp_error( $value ) ) {
3606                    return false;
3607                }
3608                // An integer, as in Monitor::save_notifications_copy().
3609                $value = (int) (bool) $value;
3610                break;
3611
3612            case 'post-by-email':
3613                // Load the class to use the method. If class can't be found, do nothing.
3614                if ( ! class_exists( 'Jetpack_Post_By_Email' ) && ! include_once Jetpack::get_module_path( $module ) ) {
3615                    return false;
3616                }
3617                $value = Jetpack_Post_By_Email::init()->get_post_by_email_address();
3618                if ( null === $value ) {
3619                    $value = 'NULL'; // sentinel value so it actually gets set.
3620                }
3621                break;
3622        }
3623
3624        // Save option to use it next time.
3625        update_option( $option, $value );
3626
3627        return $value;
3628    }
3629
3630    /**
3631     * Get number of plugin updates available.
3632     *
3633     * @since 4.3.0
3634     *
3635     * @return mixed|WP_Error Number of plugin updates available. Otherwise, a WP_Error instance with the corresponding error.
3636     */
3637    public static function get_plugin_update_count() {
3638        $updates = wp_get_update_data();
3639        if ( isset( $updates['counts'] ) && isset( $updates['counts']['plugins'] ) ) {
3640            $count = $updates['counts']['plugins'];
3641            if ( 0 === $count ) {
3642                $response = array(
3643                    'code'    => 'success',
3644                    'message' => esc_html__( 'All plugins are up-to-date. Keep up the good work!', 'jetpack' ),
3645                    'count'   => 0,
3646                );
3647            } else {
3648                $response = array(
3649                    'code'    => 'updates-available',
3650                    'message' => esc_html(
3651                        sprintf(
3652                            /* Translators: placeholders are numbers. */
3653                            _n( '%s plugin needs updating.', '%s plugins need updating.', $count, 'jetpack' ),
3654                            $count
3655                        )
3656                    ),
3657                    'count'   => $count,
3658                );
3659            }
3660            return rest_ensure_response( $response );
3661        }
3662
3663        return new WP_Error( 'not_found', esc_html__( 'Could not check updates for plugins on this site.', 'jetpack' ), array( 'status' => 404 ) );
3664    }
3665
3666    /**
3667     * Get plugins data in site.
3668     *
3669     * @since 4.2.0
3670     *
3671     * @return WP_REST_Response|WP_Error List of plugins in the site. Otherwise, a WP_Error instance with the corresponding error.
3672     */
3673    public static function get_plugins() {
3674        $plugins = Plugins_Installer::get_plugins();
3675
3676        if ( ! empty( $plugins ) ) {
3677            return rest_ensure_response( $plugins );
3678        }
3679
3680        return new WP_Error( 'not_found', esc_html__( 'Unable to list plugins.', 'jetpack' ), array( 'status' => 404 ) );
3681    }
3682
3683    /**
3684     * Install a specific plugin and optionally activates it.
3685     *
3686     * @since 8.9.0
3687     *
3688     * @param WP_REST_Request $request {
3689     *     Array of parameters received by request.
3690     *
3691     *     @type string $slug   Plugin slug.
3692     *     @type string $status Plugin status.
3693     *     @type string $source Where did the plugin installation request originate.
3694     * }
3695     *
3696     * @return WP_REST_Response|WP_Error A response object if the installation and / or activation was successful, or a WP_Error object if it failed.
3697     */
3698    public static function install_plugin( $request ) {
3699        $plugin = stripslashes( $request['slug'] );
3700
3701        // Let's make sure the plugin isn't already installed.
3702        $plugin_id = Plugins_Installer::get_plugin_id_by_slug( $plugin );
3703
3704        // If not installed, let's install now.
3705        if ( ! $plugin_id ) {
3706            $result = Plugins_Installer::install_plugin( $plugin );
3707
3708            if ( is_wp_error( $result ) ) {
3709                return new WP_Error(
3710                    'install_plugin_failed',
3711                    sprintf(
3712                        /* translators: %1$s: plugin name. -- %2$s: error message. */
3713                        __( 'Unable to install %1$s: %2$s ', 'jetpack' ),
3714                        $plugin,
3715                        $result->get_error_message()
3716                    ),
3717                    array( 'status' => 500 )
3718                );
3719            }
3720        }
3721
3722        /*
3723         * We may want to activate the plugin as well.
3724         * Let's check for the status parameter in the request to find out.
3725         * If none was passed (or something other than active), let's return now.
3726         */
3727        if ( empty( $request['status'] ) || 'active' !== $request['status'] ) {
3728            return rest_ensure_response(
3729                array(
3730                    'code'    => 'success',
3731                    'message' => esc_html(
3732                        sprintf(
3733                            /* translators: placeholder is a plugin name. */
3734                            __( 'Installed %s', 'jetpack' ),
3735                            $plugin
3736                        )
3737                    ),
3738                )
3739            );
3740        }
3741
3742        /*
3743         * Proceed with plugin activation.
3744         * Let's check again for the plugin's ID if we don't already have it.
3745         */
3746        if ( ! $plugin_id ) {
3747            $plugin_id = Plugins_Installer::get_plugin_id_by_slug( $plugin );
3748            if ( ! $plugin_id ) {
3749                return new WP_Error(
3750                    'unable_to_determine_installed_plugin',
3751                    __( 'Unable to determine what plugin was installed.', 'jetpack' ),
3752                    array( 'status' => 500 )
3753                );
3754            }
3755        }
3756
3757        $source      = ! empty( $request['source'] ) ? stripslashes( $request['source'] ) : 'rest_api';
3758        $plugin_args = array(
3759            'plugin' => substr( $plugin_id, 0, - 4 ),
3760            'status' => 'active',
3761            'source' => $source,
3762        );
3763        return self::activate_plugin( $plugin_args );
3764    }
3765
3766    /**
3767     * Activate a specific plugin.
3768     *
3769     * @since 8.9.0
3770     *
3771     * @param WP_REST_Request $request {
3772     *     Array of parameters received by request.
3773     *
3774     *     @type string $plugin Plugin long slug (slug/index-file)
3775     *     @type string $status Plugin status. We only support active in Jetpack.
3776     *     @type string $source Where did the plugin installation request originate.
3777     * }
3778     *
3779     * @return WP_REST_Response|WP_Error A response object if the activation was successful, or a WP_Error object if the activation failed.
3780     */
3781    public static function activate_plugin( $request ) {
3782        /*
3783         * We need an "active" status parameter to be passed to the request
3784         * just like the core plugins endpoind we'll eventually switch to.
3785         */
3786        if ( empty( $request['status'] ) || 'active' !== $request['status'] ) {
3787            return new WP_Error(
3788                'missing_status_parameter',
3789                esc_html__( 'Status parameter missing.', 'jetpack' ),
3790                array( 'status' => 403 )
3791            );
3792        }
3793
3794        $plugins = Plugins_Installer::get_plugins();
3795
3796        if ( empty( $plugins ) ) {
3797            return new WP_Error( 'no_plugins_found', esc_html__( 'This site has no plugins.', 'jetpack' ), array( 'status' => 404 ) );
3798        }
3799
3800        if ( empty( $request['plugin'] ) ) {
3801            return new WP_Error( 'no_plugin_specified', esc_html__( 'You did not specify a plugin.', 'jetpack' ), array( 'status' => 404 ) );
3802        }
3803
3804        $plugin = $request['plugin'] . '.php';
3805
3806        // Is the plugin installed?
3807        if ( ! array_key_exists( $plugin, $plugins ) ) {
3808            return new WP_Error(
3809                'plugin_not_found',
3810                esc_html(
3811                    sprintf(
3812                        /* translators: placeholder is a plugin slug. */
3813                        __( 'Plugin %s is not installed.', 'jetpack' ),
3814                        $plugin
3815                    )
3816                ),
3817                array( 'status' => 404 )
3818            );
3819        }
3820
3821        // Is the plugin active already?
3822        $status = Plugins_Installer::get_plugin_status( $plugin );
3823        if ( in_array( $status, array( 'active', 'network-active' ), true ) ) {
3824            return new WP_Error(
3825                'plugin_already_active',
3826                esc_html(
3827                    sprintf(
3828                        /* translators: placeholder is a plugin slug. */
3829                        __( 'Plugin %s is already active.', 'jetpack' ),
3830                        $plugin
3831                    )
3832                ),
3833                array( 'status' => 404 )
3834            );
3835        }
3836
3837        // Now try to activate the plugin.
3838        $activated = activate_plugin( $plugin );
3839
3840        if ( is_wp_error( $activated ) ) {
3841            return $activated;
3842        } else {
3843            $source = ! empty( $request['source'] ) ? stripslashes( $request['source'] ) : 'rest_api';
3844            /**
3845             * Fires when Jetpack installs a plugin for you.
3846             *
3847             * @since 8.9.0
3848             *
3849             * @param string $plugin_file Plugin file.
3850             * @param string $source      Where did the plugin installation originate.
3851             */
3852            do_action( 'jetpack_activated_plugin', $plugin, $source );
3853            return rest_ensure_response(
3854                array(
3855                    'code'    => 'success',
3856                    'message' => sprintf(
3857                        /* translators: placeholder is a plugin name. */
3858                        esc_html__( 'Activated %s', 'jetpack' ),
3859                        $plugin
3860                    ),
3861                )
3862            );
3863        }
3864    }
3865
3866    /**
3867     * Check if a plugin can be activated.
3868     *
3869     * @since 8.9.0
3870     *
3871     * @param string|bool     $value   Value to check.
3872     * @param WP_REST_Request $request The request sent to the WP REST API.
3873     * @param string          $param   Name of the parameter passed to endpoint holding $value.
3874     */
3875    public static function validate_activate_plugin( $value, $request, $param ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
3876        return 'active' === $value;
3877    }
3878
3879    /**
3880     * Get data about the queried plugin. Currently it only returns whether the plugin is active or not.
3881     *
3882     * @since 4.2.0
3883     *
3884     * @param WP_REST_Request $request {
3885     *     Array of parameters received by request.
3886     *
3887     *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
3888     * }
3889     *
3890     * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
3891     */
3892    public static function get_plugin( $request ) {
3893        $plugins = Plugins_Installer::get_plugins();
3894
3895        if ( empty( $plugins ) ) {
3896            return new WP_Error( 'no_plugins_found', esc_html__( 'This site has no plugins.', 'jetpack' ), array( 'status' => 404 ) );
3897        }
3898
3899        $plugin = stripslashes( $request['plugin'] );
3900
3901        if ( ! array_key_exists( $plugin, $plugins ) ) {
3902            return new WP_Error(
3903                'plugin_not_found',
3904                esc_html(
3905                    sprintf(
3906                        /* Translators: placeholder is a plugin name. */
3907                        __( 'Plugin %s is not installed.', 'jetpack' ),
3908                        $plugin
3909                    )
3910                ),
3911                array( 'status' => 404 )
3912            );
3913        }
3914
3915        $plugin_data = $plugins[ $plugin ];
3916
3917        $plugin_data['active'] = in_array( Plugins_Installer::get_plugin_status( $plugin ), array( 'active', 'network-active' ), true );
3918
3919        return rest_ensure_response(
3920            array(
3921                'code'    => 'success',
3922                'message' => esc_html__( 'Plugin found.', 'jetpack' ),
3923                'data'    => $plugin_data,
3924            )
3925        );
3926    }
3927
3928    /**
3929     * Returns the Jetpack CRM data.
3930     *
3931     * @return WP_REST_Response A response object containing the Jetpack CRM data.
3932     */
3933    public static function get_jetpack_crm_data() {
3934        $jetpack_crm_data = ( new Jetpack_CRM_Data() )->get_crm_data();
3935        return rest_ensure_response( $jetpack_crm_data );
3936    }
3937
3938    /**
3939     * Activates Jetpack CRM's Jetpack Forms extension.
3940     *
3941     * @param WP_REST_Request $request The request sent to the WP REST API.
3942     * @return WP_REST_Response|WP_Error A response object if the extension activation was successful, or a WP_Error object if it failed.
3943     */
3944    public static function activate_crm_jetpack_forms_extension( $request ) {
3945        if ( ! isset( $request['extension'] ) || 'jetpackforms' !== $request['extension'] ) {
3946            return new WP_Error( 'invalid_param', esc_html__( 'Missing or invalid extension parameter.', 'jetpack' ), array( 'status' => 404 ) );
3947        }
3948
3949        $result = ( new Jetpack_CRM_Data() )->activate_crm_jetpackforms_extension();
3950
3951        if ( is_wp_error( $result ) ) {
3952            return $result;
3953        }
3954
3955        return rest_ensure_response( array( 'code' => 'success' ) );
3956    }
3957
3958    /**
3959     * Verifies that the current user has the required permission for accessing the CRM data.
3960     *
3961     * @return true|WP_Error Returns true if the user has the required capability, else a WP_Error object.
3962     */
3963    public static function jetpack_crm_data_permission_check() {
3964        if ( current_user_can( 'publish_posts' ) ) {
3965            return true;
3966        }
3967
3968        return new WP_Error(
3969            'invalid_user_permission_jetpack_crm_data',
3970            REST_Connector::get_user_permissions_error_msg(),
3971            array( 'status' => rest_authorization_required_code() )
3972        );
3973    }
3974
3975    /**
3976     * Verifies that the current user has the required capability for activating Jetpack CRM extensions.
3977     *
3978     * @return true|WP_Error Returns true if the user has the required capability, else a WP_Error object.
3979     */
3980    public static function activate_crm_extensions_permission_check() {
3981        // phpcs:ignore WordPress.WP.Capabilities.Unknown
3982        if ( current_user_can( 'admin_zerobs_manage_options' ) ) {
3983            return true;
3984        }
3985
3986        return new WP_Error(
3987            'invalid_user_permission_activate_jetpack_crm_ext',
3988            REST_Connector::get_user_permissions_error_msg(),
3989            array( 'status' => rest_authorization_required_code() )
3990        );
3991    }
3992
3993    /**
3994     * Set hasSeenWCConnectionModal to true when the site has displayed it
3995     *
3996     * @since 10.4.0
3997     *
3998     * @return bool
3999     */
4000    public static function set_has_seen_wc_connection_modal() {
4001        $updated_option = Jetpack_Options::update_option( 'has_seen_wc_connection_modal', true );
4002
4003        return rest_ensure_response( array( 'success' => $updated_option ) );
4004    }
4005
4006    /**
4007     * Return the list of available features.
4008     *
4009     * @return array
4010     */
4011    public static function get_features_available() {
4012        $raw_modules = Jetpack::get_available_modules();
4013        $modules     = array();
4014        foreach ( $raw_modules as $module ) {
4015            $modules[] = Jetpack::get_module_slug( $module );
4016        }
4017
4018        return $modules;
4019    }
4020
4021    /**
4022     * Returns what features are enabled. Uses the slug of the modules files.
4023     *
4024     * @return array
4025     */
4026    public static function get_features_enabled() {
4027        $raw_modules = Jetpack::get_active_modules();
4028        $modules     = array();
4029        foreach ( $raw_modules as $module ) {
4030            $modules[] = Jetpack::get_module_slug( $module );
4031        }
4032
4033        return $modules;
4034    }
4035
4036    /**
4037     * Verify that the API client is allowed to replace user token.
4038     *
4039     * @since 1.29.0
4040     *
4041     * @return bool|WP_Error
4042     */
4043    public static function get_features_permission_check() {
4044        if ( ! Rest_Authentication::is_signed_with_blog_token() ) {
4045            $message = esc_html__(
4046                'You do not have the correct user permissions to perform this action. Please contact your site admin if you think this is a mistake.',
4047                'jetpack'
4048            );
4049            return new WP_Error( 'invalid_permission_fetch_features', $message, array( 'status' => rest_authorization_required_code() ) );
4050        }
4051
4052        return true;
4053    }
4054} // class end