Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
72.16% covered (warning)
72.16%
1698 / 2353
24.32% covered (danger)
24.32%
18 / 74
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Core_Json_Api_Endpoints
72.35% covered (warning)
72.35%
1698 / 2347
24.32% covered (danger)
24.32%
18 / 74
2662.62
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%
875 / 875
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%
15 / 15
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 16.4
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__( 'Deprecated. Use jetpack_waf_ip_allow_list instead. Writing this key replaces the site 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            // Not a module option: the free check runs without the Brute Force Protection module.
1966            'jetpack_protect_vulnerability_checks'      => array(
1967                'description'       => esc_html__( 'Check the site every day for known vulnerabilities in WordPress, plugins and themes.', 'jetpack' ),
1968                'type'              => 'boolean',
1969                'default'           => 1,
1970                'validate_callback' => __CLASS__ . '::validate_boolean',
1971                'jp_group'          => 'settings',
1972            ),
1973
1974            // Sharing.
1975            'sharing_services'                          => array(
1976                'description'       => esc_html__( 'Enabled Services and those hidden behind a button', 'jetpack' ),
1977                'type'              => 'object',
1978                'default'           => array(
1979                    'visible' => array( 'facebook', 'x' ),
1980                    'hidden'  => array(),
1981                ),
1982                'validate_callback' => __CLASS__ . '::validate_services',
1983                'jp_group'          => 'sharedaddy',
1984            ),
1985            'button_style'                              => array(
1986                'description'       => esc_html__( 'Button Style', 'jetpack' ),
1987                'type'              => 'string',
1988                'default'           => 'icon',
1989                'enum'              => array(
1990                    'icon-text',
1991                    'icon',
1992                    'text',
1993                    'official',
1994                ),
1995                'enum_labels'       => array(
1996                    'icon-text' => esc_html__( 'Icon + text', 'jetpack' ),
1997                    'icon'      => esc_html__( 'Icon only', 'jetpack' ),
1998                    'text'      => esc_html__( 'Text only', 'jetpack' ),
1999                    'official'  => esc_html__( 'Official buttons', 'jetpack' ),
2000                ),
2001                'validate_callback' => __CLASS__ . '::validate_list_item',
2002                'jp_group'          => 'sharedaddy',
2003            ),
2004            'sharing_label'                             => array(
2005                'description'       => esc_html__( 'Sharing Label', 'jetpack' ),
2006                'type'              => 'string',
2007                'default'           => '',
2008                'validate_callback' => __CLASS__ . '::validate_string',
2009                'sanitize_callback' => 'esc_html',
2010                'jp_group'          => 'sharedaddy',
2011            ),
2012            'show'                                      => array(
2013                'description'       => esc_html__( 'Views where buttons are shown', 'jetpack' ),
2014                'type'              => 'array',
2015                'items'             => array(
2016                    'type' => 'string',
2017                ),
2018                'default'           => array( 'post' ),
2019                'validate_callback' => __CLASS__ . '::validate_sharing_show',
2020                'jp_group'          => 'sharedaddy',
2021            ),
2022            'jetpack-twitter-cards-site-tag'            => array(
2023                'description'       => esc_html__( "The Twitter username of the owner of this site's domain.", 'jetpack' ),
2024                'type'              => 'string',
2025                'default'           => '',
2026                'validate_callback' => __CLASS__ . '::validate_twitter_username',
2027                'sanitize_callback' => 'esc_html',
2028                'jp_group'          => 'sharedaddy',
2029            ),
2030            'sharedaddy_disable_resources'              => array(
2031                'description'       => esc_html__( 'Disable CSS and JS', 'jetpack' ),
2032                'type'              => 'boolean',
2033                'default'           => 0,
2034                'validate_callback' => __CLASS__ . '::validate_boolean',
2035                'jp_group'          => 'sharedaddy',
2036            ),
2037            'custom'                                    => array(
2038                'description'       => esc_html__( 'Custom sharing services added by user.', 'jetpack' ),
2039                'type'              => 'object',
2040                'default'           => array(
2041                    'sharing_name' => '',
2042                    'sharing_url'  => '',
2043                    'sharing_icon' => '',
2044                ),
2045                'validate_callback' => __CLASS__ . '::validate_custom_service',
2046                'jp_group'          => 'sharedaddy',
2047            ),
2048            // Not an option, but an action that can be performed on the list of custom services passing the service ID.
2049            'sharing_delete_service'                    => array(
2050                'description'       => esc_html__( 'Delete custom sharing service.', 'jetpack' ),
2051                'type'              => 'string',
2052                'default'           => '',
2053                'validate_callback' => __CLASS__ . '::validate_custom_service_id',
2054                'jp_group'          => 'sharedaddy',
2055            ),
2056
2057            // SSO.
2058            'jetpack_sso_require_two_step'              => array(
2059                'description'       => esc_html__( 'Require Two-Step Authentication', 'jetpack' ),
2060                'type'              => 'boolean',
2061                'default'           => SSO\Helpers::is_require_two_step_checkbox_disabled(),
2062                'validate_callback' => __CLASS__ . '::validate_boolean',
2063                'jp_group'          => 'sso',
2064            ),
2065            'jetpack_sso_match_by_email'                => array(
2066                'description'       => esc_html__( 'Match by Email', 'jetpack' ),
2067                'type'              => 'boolean',
2068                'default'           => 1,
2069                'validate_callback' => __CLASS__ . '::validate_boolean',
2070                'jp_group'          => 'sso',
2071            ),
2072
2073            // Subscriptions.
2074            'stb_enabled'                               => array(
2075                'description'       => esc_html__( "Show a <em>'follow blog'</em> option in the comment form", 'jetpack' ),
2076                'type'              => 'boolean',
2077                'default'           => 1,
2078                'validate_callback' => __CLASS__ . '::validate_boolean',
2079                'jp_group'          => 'subscriptions',
2080            ),
2081            'stc_enabled'                               => array(
2082                'description'       => esc_html__( "Show a <em>'follow comments'</em> option in the comment form", 'jetpack' ),
2083                'type'              => 'boolean',
2084                'default'           => 1,
2085                'validate_callback' => __CLASS__ . '::validate_boolean',
2086                'jp_group'          => 'subscriptions',
2087            ),
2088            'wpcom_newsletter_categories'               => array(
2089                'description'       => esc_html__( 'Array of post category ids that are marked as newsletter categories', 'jetpack' ),
2090                'type'              => 'array',
2091                'default'           => array(),
2092                'validate_callback' => __CLASS__ . '::validate_array',
2093                'jp_group'          => 'subscriptions',
2094            ),
2095            'wpcom_newsletter_categories_enabled'       => array(
2096                'description'       => esc_html__( 'Whether the newsletter categories are enabled or not', 'jetpack' ),
2097                'type'              => 'boolean',
2098                'default'           => 0,
2099                'validate_callback' => __CLASS__ . '::validate_boolean',
2100                'jp_group'          => 'subscriptions',
2101            ),
2102            'wpcom_newsletter_send_default'             => array(
2103                'description'       => esc_html__( 'Whether to send newsletter emails by default when publishing a post', 'jetpack' ),
2104                'type'              => 'boolean',
2105                'default'           => 1,
2106                'validate_callback' => __CLASS__ . '::validate_boolean',
2107                'jp_group'          => 'subscriptions',
2108            ),
2109            'wpcom_featured_image_in_email'             => array(
2110                'description'       => esc_html__( 'Whether to include the featured image in the email or not', 'jetpack' ),
2111                'type'              => 'boolean',
2112                'default'           => 0,
2113                'validate_callback' => __CLASS__ . '::validate_boolean',
2114                'jp_group'          => 'subscriptions',
2115            ),
2116            'jetpack_gravatar_in_email'                 => array(
2117                'description'       => esc_html__( 'Whether to show author avatar in the email byline', 'jetpack' ),
2118                'type'              => 'boolean',
2119                'default'           => 1,
2120                'validate_callback' => __CLASS__ . '::validate_boolean',
2121                'jp_group'          => 'subscriptions',
2122            ),
2123            'jetpack_author_in_email'                   => array(
2124                'description'       => esc_html__( 'Whether to show author display name in the email byline', 'jetpack' ),
2125                'type'              => 'boolean',
2126                'default'           => 1,
2127                'validate_callback' => __CLASS__ . '::validate_boolean',
2128                'jp_group'          => 'subscriptions',
2129            ),
2130            'jetpack_post_date_in_email'                => array(
2131                'description'       => esc_html__( 'Whether to show date in the email byline', 'jetpack' ),
2132                'type'              => 'boolean',
2133                'default'           => 1,
2134                'validate_callback' => __CLASS__ . '::validate_boolean',
2135                'jp_group'          => 'subscriptions',
2136            ),
2137            'wpcom_subscription_emails_use_excerpt'     => array(
2138                'description'       => esc_html__( 'Whether to use the excerpt in the email or not', 'jetpack' ),
2139                'type'              => 'boolean',
2140                'default'           => 0,
2141                'validate_callback' => __CLASS__ . '::validate_boolean',
2142                'jp_group'          => 'subscriptions',
2143            ),
2144            'jetpack_subscriptions_reply_to'            => array(
2145                'description'       => esc_html__( 'Reply to email behaviour for newsletters emails', 'jetpack' ),
2146                'type'              => 'string',
2147                'default'           => Automattic\Jetpack\Modules\Subscriptions\Settings::$default_reply_to,
2148                'validate_callback' => __CLASS__ . '::validate_subscriptions_reply_to',
2149                'jp_group'          => 'subscriptions',
2150            ),
2151            'jetpack_subscriptions_from_name'           => array(
2152                'description'       => esc_html__( 'From name for newsletters emails', 'jetpack' ),
2153                'type'              => 'string',
2154                'default'           => '',
2155                'validate_callback' => __CLASS__ . '::validate_subscriptions_reply_to_name',
2156                'jp_group'          => 'subscriptions',
2157            ),
2158            'sm_enabled'                                => array(
2159                'description'       => esc_html__( 'Show popup Subscribe modal to readers.', 'jetpack' ),
2160                'type'              => 'boolean',
2161                'default'           => 0,
2162                'validate_callback' => __CLASS__ . '::validate_boolean',
2163                'jp_group'          => 'subscriptions',
2164            ),
2165            'jetpack_subscribe_overlay_enabled'         => array(
2166                'description'       => esc_html__( 'Show subscribe overlay on homepage.', 'jetpack' ),
2167                'type'              => 'boolean',
2168                'default'           => 0,
2169                'validate_callback' => __CLASS__ . '::validate_boolean',
2170                'jp_group'          => 'subscriptions',
2171            ),
2172            'jetpack_subscribe_floating_button_enabled' => array(
2173                'description'       => esc_html__( 'Show a floating subscribe button.', 'jetpack' ),
2174                'type'              => 'boolean',
2175                'default'           => 0,
2176                'validate_callback' => __CLASS__ . '::validate_boolean',
2177                'jp_group'          => 'subscriptions',
2178            ),
2179            'jetpack_subscriptions_subscribe_post_end_enabled' => array(
2180                'description'       => esc_html__( 'Add Subscribe block at the end of each post.', 'jetpack' ),
2181                'type'              => 'boolean',
2182                'default'           => 0,
2183                'validate_callback' => __CLASS__ . '::validate_boolean',
2184                'jp_group'          => 'subscriptions',
2185            ),
2186            'jetpack_subscriptions_login_navigation_enabled' => array(
2187                'description'       => esc_html__( 'Add Subscriber Login block to the navigation.', 'jetpack' ),
2188                'type'              => 'boolean',
2189                'default'           => 0,
2190                'validate_callback' => __CLASS__ . '::validate_boolean',
2191                'jp_group'          => 'subscriptions',
2192            ),
2193            'jetpack_subscriptions_subscribe_navigation_enabled' => array(
2194                'description'       => esc_html__( 'Add Subscribe block to the navigation.', 'jetpack' ),
2195                'type'              => 'boolean',
2196                'default'           => 0,
2197                'validate_callback' => __CLASS__ . '::validate_boolean',
2198                'jp_group'          => 'subscriptions',
2199            ),
2200            'social_notifications_subscribe'            => array(
2201                'description'       => esc_html__( 'Send email notification when someone subscribes to my blog', 'jetpack' ),
2202                'type'              => 'boolean',
2203                'default'           => 0,
2204                'validate_callback' => __CLASS__ . '::validate_boolean',
2205                'jp_group'          => 'subscriptions',
2206            ),
2207            'subscription_options'                      => array(
2208                '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' ),
2209                'type'              => 'object',
2210                'default'           => array(
2211                    'invitation'              => '',
2212                    'welcome'                 => '',
2213                    'comment_follow'          => '',
2214                    'subscribe_modal_heading' => '',
2215                    'free_tier_description'   => '',
2216                    'hide_free_tier'          => false,
2217                ),
2218                'validate_callback' => __CLASS__ . '::validate_subscription_options',
2219                'jp_group'          => 'subscriptions',
2220            ),
2221
2222            // Related Posts.
2223            'show_headline'                             => array(
2224                'description'       => esc_html__( 'Highlight related content with a heading', 'jetpack' ),
2225                'type'              => 'boolean',
2226                'default'           => 1,
2227                'validate_callback' => __CLASS__ . '::validate_boolean',
2228                'jp_group'          => 'related-posts',
2229            ),
2230            'show_thumbnails'                           => array(
2231                'description'       => esc_html__( 'Show a thumbnail image where available', 'jetpack' ),
2232                'type'              => 'boolean',
2233                'default'           => 0,
2234                'validate_callback' => __CLASS__ . '::validate_boolean',
2235                'jp_group'          => 'related-posts',
2236            ),
2237
2238            // Search.
2239            'instant_search_enabled'                    => array(
2240                'description'       => esc_html__( 'Enable Instant Search', 'jetpack' ),
2241                'type'              => 'boolean',
2242                'default'           => 0,
2243                'validate_callback' => __CLASS__ . '::validate_boolean',
2244                'jp_group'          => 'search',
2245            ),
2246
2247            'has_jetpack_search_product'                => array(
2248                'description'       => esc_html__( 'Has an active Jetpack Search product purchase', 'jetpack' ),
2249                'type'              => 'boolean',
2250                'default'           => 0,
2251                'validate_callback' => __CLASS__ . '::validate_boolean',
2252                'jp_group'          => 'settings',
2253            ),
2254
2255            'search_auto_config'                        => array(
2256                'description'       => esc_html__( 'Trigger an auto config of instant search', 'jetpack' ),
2257                'type'              => 'boolean',
2258                'default'           => 0,
2259                'validate_callback' => __CLASS__ . '::validate_boolean',
2260                'jp_group'          => 'search',
2261            ),
2262
2263            // Verification Tools.
2264            'google'                                    => array(
2265                'description'       => esc_html__( 'Google Search Console', 'jetpack' ),
2266                'type'              => 'string',
2267                'default'           => '',
2268                'validate_callback' => __CLASS__ . '::validate_verification_service',
2269                'jp_group'          => 'verification-tools',
2270            ),
2271            'bing'                                      => array(
2272                'description'       => esc_html__( 'Bing Webmaster Center', 'jetpack' ),
2273                'type'              => 'string',
2274                'default'           => '',
2275                'validate_callback' => __CLASS__ . '::validate_verification_service',
2276                'jp_group'          => 'verification-tools',
2277            ),
2278            'pinterest'                                 => array(
2279                'description'       => esc_html__( 'Pinterest Site Verification', 'jetpack' ),
2280                'type'              => 'string',
2281                'default'           => '',
2282                'validate_callback' => __CLASS__ . '::validate_verification_service',
2283                'jp_group'          => 'verification-tools',
2284            ),
2285            'yandex'                                    => array(
2286                'description'       => esc_html__( 'Yandex Site Verification', 'jetpack' ),
2287                'type'              => 'string',
2288                'default'           => '',
2289                'validate_callback' => __CLASS__ . '::validate_verification_service',
2290                'jp_group'          => 'verification-tools',
2291            ),
2292            'facebook'                                  => array(
2293                'description'       => esc_html__( 'Facebook Domain Verification', 'jetpack' ),
2294                'type'              => 'string',
2295                'default'           => '',
2296                'validate_callback' => __CLASS__ . '::validate_verification_service',
2297                'jp_group'          => 'verification-tools',
2298            ),
2299
2300            // WordAds.
2301            'enable_header_ad'                          => array(
2302                'description'       => esc_html__( 'Display an ad unit at the top of each page.', 'jetpack' ),
2303                'type'              => 'boolean',
2304                'default'           => 1,
2305                'validate_callback' => __CLASS__ . '::validate_boolean',
2306                'jp_group'          => 'wordads',
2307            ),
2308            'wordads_approved'                          => array(
2309                'description'       => esc_html__( 'Is site approved for WordAds?', 'jetpack' ),
2310                'type'              => 'boolean',
2311                'default'           => 0,
2312                'validate_callback' => __CLASS__ . '::validate_boolean',
2313                'jp_group'          => 'wordads',
2314            ),
2315            'wordads_second_belowpost'                  => array(
2316                'description'       => esc_html__( 'Display second ad below post?', 'jetpack' ),
2317                'type'              => 'boolean',
2318                'default'           => 1,
2319                'validate_callback' => __CLASS__ . '::validate_boolean',
2320                'jp_group'          => 'wordads',
2321            ),
2322            'wordads_inline_enabled'                    => array(
2323                'description'       => esc_html__( 'Display inline ad within post content?', 'jetpack' ),
2324                'type'              => 'boolean',
2325                'default'           => 1,
2326                'validate_callback' => __CLASS__ . '::validate_boolean',
2327                'jp_group'          => 'wordads',
2328            ),
2329            'wordads_display_front_page'                => array(
2330                'description'       => esc_html__( 'Display ads on the front page?', 'jetpack' ),
2331                'type'              => 'boolean',
2332                'default'           => 1,
2333                'validate_callback' => __CLASS__ . '::validate_boolean',
2334                'jp_group'          => 'wordads',
2335            ),
2336            'wordads_display_post'                      => array(
2337                'description'       => esc_html__( 'Display ads on posts?', 'jetpack' ),
2338                'type'              => 'boolean',
2339                'default'           => 1,
2340                'validate_callback' => __CLASS__ . '::validate_boolean',
2341                'jp_group'          => 'wordads',
2342            ),
2343            'wordads_display_page'                      => array(
2344                'description'       => esc_html__( 'Display ads on pages?', 'jetpack' ),
2345                'type'              => 'boolean',
2346                'default'           => 1,
2347                'validate_callback' => __CLASS__ . '::validate_boolean',
2348                'jp_group'          => 'wordads',
2349            ),
2350            'wordads_display_archive'                   => array(
2351                'description'       => esc_html__( 'Display ads on archive pages?', 'jetpack' ),
2352                'type'              => 'boolean',
2353                'default'           => 1,
2354                'validate_callback' => __CLASS__ . '::validate_boolean',
2355                'jp_group'          => 'wordads',
2356            ),
2357            'wordads_custom_adstxt_enabled'             => array(
2358                'description'       => esc_html__( 'Custom ads.txt', 'jetpack' ),
2359                'type'              => 'boolean',
2360                'default'           => 0,
2361                'validate_callback' => __CLASS__ . '::validate_boolean',
2362                'jp_group'          => 'wordads',
2363            ),
2364            'wordads_custom_adstxt'                     => array(
2365                'description'       => esc_html__( 'Custom ads.txt entries', 'jetpack' ),
2366                'type'              => 'string',
2367                'default'           => '',
2368                'validate_callback' => __CLASS__ . '::validate_string',
2369                'sanitize_callback' => 'sanitize_textarea_field',
2370                'jp_group'          => 'wordads',
2371            ),
2372            'wordads_ccpa_enabled'                      => array(
2373                'description'       => esc_html__( 'Enable support for California Consumer Privacy Act', 'jetpack' ),
2374                'type'              => 'boolean',
2375                'default'           => 0,
2376                'validate_callback' => __CLASS__ . '::validate_boolean',
2377                'jp_group'          => 'wordads',
2378            ),
2379            'wordads_ccpa_privacy_policy_url'           => array(
2380                'description'       => esc_html__( 'Privacy Policy URL', 'jetpack' ),
2381                'type'              => 'string',
2382                'default'           => '',
2383                'validate_callback' => __CLASS__ . '::validate_string',
2384                'sanitize_callback' => 'sanitize_text_field',
2385                'jp_group'          => 'wordads',
2386            ),
2387            'wordads_cmp_enabled'                       => array(
2388                'description'       => esc_html__( 'Enable GDPR Consent Management Banner for WordAds', 'jetpack' ),
2389                'type'              => 'boolean',
2390                'default'           => 0,
2391                'validate_callback' => __CLASS__ . '::validate_boolean',
2392                'jp_group'          => 'wordads',
2393            ),
2394
2395            // Google Analytics.
2396            'google_analytics_tracking_id'              => array(
2397                'description'       => esc_html__( 'Google Analytics', 'jetpack' ),
2398                'type'              => 'string',
2399                'default'           => '',
2400                'validate_callback' => __CLASS__ . '::validate_alphanum',
2401                'jp_group'          => 'google-analytics',
2402            ),
2403            'jetpack_wga'                               => array(
2404                'description' => esc_html__( 'Google Analytics', 'jetpack' ),
2405                'type'        => 'object',
2406                'jp_group'    => 'settings',
2407            ),
2408
2409            // Stats.
2410            'admin_bar'                                 => array(
2411                'description'       => esc_html__( 'Include a small chart in your admin bar with a 48-hour traffic snapshot.', 'jetpack' ),
2412                'type'              => 'boolean',
2413                'default'           => 1,
2414                'validate_callback' => __CLASS__ . '::validate_boolean',
2415                'jp_group'          => 'stats',
2416            ),
2417            'enable_odyssey_stats'                      => array(
2418                'description'       => esc_html__( 'Preview the new Jetpack Stats experience (Experimental).', 'jetpack' ),
2419                'type'              => 'boolean',
2420                'default'           => 1,
2421                'validate_callback' => __CLASS__ . '::validate_boolean',
2422                'jp_group'          => 'stats',
2423            ),
2424            'roles'                                     => array(
2425                'description'       => esc_html__( 'Select the roles that will be able to view stats reports.', 'jetpack' ),
2426                'type'              => 'array',
2427                'items'             => array(
2428                    'type' => 'string',
2429                ),
2430                'default'           => array( 'administrator' ),
2431                'validate_callback' => __CLASS__ . '::validate_stats_roles',
2432                'sanitize_callback' => __CLASS__ . '::sanitize_stats_allowed_roles',
2433                'jp_group'          => 'stats',
2434            ),
2435            'count_roles'                               => array(
2436                'description'       => esc_html__( 'Count the page views of registered users who are logged in.', 'jetpack' ),
2437                'type'              => 'array',
2438                'items'             => array(
2439                    'type' => 'string',
2440                ),
2441                'default'           => array( 'administrator' ),
2442                'validate_callback' => __CLASS__ . '::validate_stats_roles',
2443                'jp_group'          => 'stats',
2444            ),
2445            'blog_id'                                   => array(
2446                'description'       => esc_html__( 'Blog ID.', 'jetpack' ),
2447                'type'              => 'boolean',
2448                'default'           => 0,
2449                'validate_callback' => __CLASS__ . '::validate_boolean',
2450                'jp_group'          => 'stats',
2451            ),
2452            'do_not_track'                              => array(
2453                'description'       => esc_html__( 'Do not track.', 'jetpack' ),
2454                'type'              => 'boolean',
2455                'default'           => 1,
2456                'validate_callback' => __CLASS__ . '::validate_boolean',
2457                'jp_group'          => 'stats',
2458            ),
2459            'version'                                   => array(
2460                'description'       => esc_html__( 'Version.', 'jetpack' ),
2461                'type'              => 'integer',
2462                'default'           => 9,
2463                'validate_callback' => __CLASS__ . '::validate_posint',
2464                'jp_group'          => 'stats',
2465            ),
2466            'collapse_nudges'                           => array(
2467                'description'       => esc_html__( 'Collapse upgrade nudges', 'jetpack' ),
2468                'type'              => 'boolean',
2469                'default'           => 0,
2470                'validate_callback' => __CLASS__ . '::validate_boolean',
2471                'jp_group'          => 'stats',
2472            ),
2473
2474            // Whether to share stats views with WordPress.com Reader.
2475            'wpcom_reader_views_enabled'                => array(
2476                'description'       => esc_html__( 'Show post views in the WordPress.com Reader.', 'jetpack' ),
2477                'type'              => 'boolean',
2478                'default'           => 1,
2479                'validate_callback' => __CLASS__ . '::validate_boolean',
2480                'jp_group'          => 'settings',
2481            ),
2482
2483            // Akismet - Not a module, but a plugin. The options can be passed and handled differently.
2484            'akismet_show_user_comments_approved'       => array(
2485                'description'       => '',
2486                'type'              => 'boolean',
2487                'default'           => 0,
2488                'validate_callback' => __CLASS__ . '::validate_boolean',
2489                'jp_group'          => 'settings',
2490            ),
2491
2492            'wordpress_api_key'                         => array(
2493                'description'       => '',
2494                'type'              => 'string',
2495                'default'           => '',
2496                'validate_callback' => __CLASS__ . '::validate_alphanum',
2497                'jp_group'          => 'settings',
2498            ),
2499
2500            // Empty stats card dismiss.
2501            'dismiss_empty_stats_card'                  => array(
2502                'description'       => '',
2503                'type'              => 'boolean',
2504                'default'           => 0,
2505                'validate_callback' => __CLASS__ . '::validate_boolean',
2506                'jp_group'          => 'settings',
2507            ),
2508
2509            // Backup Getting Started card on dashboard.
2510            'dismiss_dash_backup_getting_started'       => array(
2511                'description'       => '',
2512                'type'              => 'boolean',
2513                'default'           => 0,
2514                'validate_callback' => __CLASS__ . '::validate_boolean',
2515                'jp_group'          => 'settings',
2516            ),
2517
2518            // Agencies Learn More card on dashboard.
2519            'dismiss_dash_agencies_learn_more'          => array(
2520                'description'       => '',
2521                'type'              => 'boolean',
2522                'default'           => 0,
2523                'validate_callback' => __CLASS__ . '::validate_boolean',
2524                'jp_group'          => 'settings',
2525            ),
2526
2527            'lang_id'                                   => array(
2528                'description' => esc_html__( 'Primary language for the site.', 'jetpack' ),
2529                'type'        => 'string',
2530                'default'     => 'en_US',
2531                'jp_group'    => 'settings',
2532            ),
2533
2534            // SEO Tools.
2535            'advanced_seo_front_page_description'       => array(
2536                'description'       => esc_html__( 'Front page meta description.', 'jetpack' ),
2537                'type'              => 'string',
2538                'default'           => '',
2539                'sanitize_callback' => 'Jetpack_SEO_Utils::sanitize_front_page_meta_description',
2540                'jp_group'          => 'seo-tools',
2541            ),
2542
2543            'advanced_seo_title_formats'                => array(
2544                'description'       => esc_html__( 'SEO page title structures.', 'jetpack' ),
2545                'type'              => 'object',
2546                'default'           => array(
2547                    'archives'   => array(),
2548                    'front_page' => array(),
2549                    'groups'     => array(),
2550                    'pages'      => array(),
2551                    'posts'      => array(),
2552                ),
2553                'jp_group'          => 'seo-tools',
2554                'validate_callback' => 'Jetpack_SEO_Titles::are_valid_title_formats',
2555                'sanitize_callback' => 'Jetpack_SEO_Titles::sanitize_title_formats',
2556            ),
2557
2558            // GEO tab (Jetpack > SEO). Plain option the SEO package reads to serve
2559            // /llms.txt. The front-end behavior is gated inside the package; this
2560            // only round-trips the persisted state alongside the other seo-tools
2561            // settings.
2562            'jetpack_seo_llms_txt_enabled'              => array(
2563                'description'       => esc_html__( 'Generate an llms.txt file to guide AI assistants around your content.', 'jetpack' ),
2564                'type'              => 'boolean',
2565                'default'           => 0,
2566                'validate_callback' => __CLASS__ . '::validate_boolean',
2567                'jp_group'          => 'seo-tools',
2568            ),
2569
2570            // VideoPress.
2571            'videopress_private_enabled_for_site'       => array(
2572                'description'       => esc_html__( 'Video Privacy: Restrict views to members of this site', 'jetpack' ),
2573                'type'              => 'boolean',
2574                'default'           => 0,
2575                'validate_callback' => __CLASS__ . '::validate_boolean',
2576                'jp_group'          => 'videopress',
2577            ),
2578            'videopress_share_menu_disabled'            => array(
2579                'description'       => esc_html__( 'Hide the share menu on every video, overriding each video’s own setting', 'jetpack' ),
2580                'type'              => 'boolean',
2581                'default'           => 0,
2582                'validate_callback' => __CLASS__ . '::validate_boolean',
2583                'jp_group'          => 'videopress',
2584            ),
2585        );
2586
2587        // SEO Tools - SEO Enhancer.
2588        // TODO: move this to the main options array? The filter was there while developing the feature.
2589        // It might come in handy to hold its availability behind the filter since it still depends on AI to be available.
2590        if ( apply_filters( 'ai_seo_enhancer_enabled', true ) ) {
2591            $options['ai_seo_enhancer_enabled'] = array(
2592                'description'       => esc_html__( 'Automatically generate SEO title, SEO description, and image alt text for new posts.', 'jetpack' ),
2593                'type'              => 'boolean',
2594                'default'           => 0,
2595                'validate_callback' => __CLASS__ . '::validate_boolean',
2596                'jp_group'          => 'seo-tools',
2597            );
2598        }
2599
2600        // Add modules to list so they can be toggled.
2601        $modules = Jetpack::get_available_modules();
2602        if ( is_array( $modules ) && ! empty( $modules ) ) {
2603            $module_args = array(
2604                'description'       => '',
2605                'type'              => 'boolean',
2606                'default'           => 0,
2607                'validate_callback' => __CLASS__ . '::validate_boolean',
2608                'jp_group'          => 'modules',
2609            );
2610            foreach ( $modules as $module ) {
2611                $options[ $module ] = $module_args;
2612            }
2613        }
2614
2615        if ( is_array( $selector ) ) {
2616
2617            // Return only those options whose keys match $selector keys.
2618            return array_intersect_key( $options, $selector );
2619        }
2620
2621        if ( 'any' === $selector ) {
2622
2623            // Toggle module or update any module option or any general setting.
2624            return $options;
2625        }
2626
2627        // We're updating the options for a single module.
2628        if ( empty( $selector ) ) {
2629            $selector = self::get_module_requested();
2630        }
2631        $selected = array();
2632        foreach ( $options as $option => $attributes ) {
2633
2634            // Not adding an isset( $attributes['jp_group'] ) because if it's not set, it must be fixed, otherwise options will fail.
2635            if ( $selector === $attributes['jp_group'] ) {
2636                $selected[ $option ] = $attributes;
2637            }
2638        }
2639        return $selected;
2640    }
2641
2642    /**
2643     * Validates that the parameters are proper values that can be set during Jetpack onboarding.
2644     *
2645     * @since 5.4.0
2646     *
2647     * @deprecated since 13.9
2648     *
2649     * @param array           $onboarding_data Values to check.
2650     * @param WP_REST_Request $request         The request sent to the WP REST API.
2651     * @param string          $param           Name of the parameter passed to endpoint holding $value.
2652     *
2653     * @return bool|WP_Error
2654     */
2655    public static function validate_onboarding( $onboarding_data, $request, $param ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
2656        _deprecated_function( __METHOD__, '13.9' );
2657        return true;
2658    }
2659
2660    /**
2661     * Validates that the parameter is either a pure boolean or a numeric string that can be mapped to a boolean.
2662     *
2663     * @since 4.3.0
2664     *
2665     * @param string|bool     $value Value to check.
2666     * @param WP_REST_Request $request The request sent to the WP REST API.
2667     * @param string          $param Name of the parameter passed to endpoint holding $value.
2668     *
2669     * @return bool|WP_Error
2670     */
2671    public static function validate_boolean( $value, $request, $param ) {
2672        // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict -- Other code depends on loose comparison here.
2673        if ( ! is_bool( $value ) && ! ( ctype_digit( (string) $value ) && in_array( $value, array( 0, 1 ) ) ) ) {
2674            return new WP_Error(
2675                'invalid_param',
2676                sprintf(
2677                    /* Translators: Placeholder is a parameter name. */
2678                    esc_html__( '%s must be true, false, 0 or 1.', 'jetpack' ),
2679                    $param
2680                )
2681            );
2682        }
2683        return true;
2684    }
2685
2686    /**
2687     * Validates that the parameter is a positive integer.
2688     *
2689     * @since 4.3.0
2690     *
2691     * @param int             $value Value to check.
2692     * @param WP_REST_Request $request The request sent to the WP REST API.
2693     * @param string          $param Name of the parameter passed to endpoint holding $value.
2694     *
2695     * @return bool|WP_Error
2696     */
2697    public static function validate_posint( $value, $request, $param ) {
2698        if ( ! is_numeric( $value ) || $value <= 0 ) {
2699            return new WP_Error(
2700                'invalid_param',
2701                sprintf(
2702                    /* Translators: Placeholder is a parameter name. */
2703                    esc_html__( '%s must be a positive integer.', 'jetpack' ),
2704                    $param
2705                )
2706            );
2707        }
2708        return true;
2709    }
2710
2711    /**
2712     * Validates that the parameter is a non-negative integer (includes 0).
2713     *
2714     * @since 10.4.0
2715     *
2716     * @param int             $value Value to check.
2717     * @param WP_REST_Request $request The request sent to the WP REST API.
2718     * @param string          $param Name of the parameter passed to endpoint holding $value.
2719     *
2720     * @return bool|WP_Error
2721     */
2722    public static function validate_non_neg_int( $value, $request, $param ) {
2723        if ( ! is_numeric( $value ) || $value < 0 ) {
2724            return new WP_Error(
2725                'invalid_param',
2726                /* translators: %s: The literal parameter name. Should not be translated. */
2727                sprintf( esc_html__( '%s must be a non-negative integer.', 'jetpack' ), $param )
2728            );
2729        }
2730        return true;
2731    }
2732
2733    /**
2734     * Validates that the parameter belongs to a list of admitted values.
2735     *
2736     * @since 4.3.0
2737     *
2738     * @param string          $value Value to check.
2739     * @param WP_REST_Request $request The request sent to the WP REST API.
2740     * @param string          $param Name of the parameter passed to endpoint holding $value.
2741     *
2742     * @return bool|WP_Error
2743     */
2744    public static function validate_list_item( $value, $request, $param ) {
2745        $attributes = $request->get_attributes();
2746        if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
2747            return new WP_Error(
2748                'invalid_param',
2749                sprintf(
2750                    /* Translators: Placeholder is a parameter name. */
2751                    esc_html__( '%s not recognized', 'jetpack' ),
2752                    $param
2753                )
2754            );
2755        }
2756        $args = $attributes['args'][ $param ];
2757        if ( ! empty( $args['enum'] ) ) {
2758            // If it's an associative array, use the keys to check that the value is among those admitted.
2759            $enum = ( count( array_filter( array_keys( $args['enum'] ), 'is_string' ) ) > 0 )
2760                ? array_keys( $args['enum'] )
2761                : $args['enum'];
2762            $enum = array_map( 'strval', $enum );
2763            if ( ! in_array( $value, $enum, true ) ) {
2764                return new WP_Error(
2765                    'invalid_param_value',
2766                    sprintf(
2767                    /* Translators: first variable is the parameter passed to endpoint that holds the list item, the second is a list of admitted values. */
2768                        esc_html__( '%1$s must be one of %2$s', 'jetpack' ),
2769                        $param,
2770                        implode( ', ', $enum )
2771                    )
2772                );
2773            }
2774        }
2775        return true;
2776    }
2777
2778    /**
2779     * Validates that the parameter belongs to a list of admitted values.
2780     *
2781     * @since 4.3.0
2782     *
2783     * @param string          $value Value to check.
2784     * @param WP_REST_Request $request The request sent to the WP REST API.
2785     * @param string          $param Name of the parameter passed to endpoint holding $value.
2786     *
2787     * @return bool|WP_Error
2788     */
2789    public static function validate_module_list( $value, $request, $param ) {
2790        if ( ! is_array( $value ) ) {
2791            return new WP_Error(
2792                'invalid_param_value',
2793                sprintf(
2794                    /* Translators: Placeholder is a parameter name. */
2795                    esc_html__( '%s must be an array', 'jetpack' ),
2796                    $param
2797                )
2798            );
2799        }
2800
2801        $modules = Jetpack::get_available_modules();
2802
2803        if ( count( array_intersect( $value, $modules ) ) !== count( $value ) ) {
2804            return new WP_Error(
2805                'invalid_param_value',
2806                sprintf(
2807                    /* Translators: Placeholder is a parameter name. */
2808                    esc_html__( '%s must be a list of valid modules', 'jetpack' ),
2809                    $param
2810                )
2811            );
2812        }
2813
2814        return true;
2815    }
2816
2817    /**
2818     * Validates that the parameter is an alphanumeric or empty string (to be able to clear the field).
2819     *
2820     * @since 4.3.0
2821     *
2822     * @param string          $value Value to check.
2823     * @param WP_REST_Request $request The request sent to the WP REST API.
2824     * @param string          $param Name of the parameter passed to endpoint holding $value.
2825     *
2826     * @return bool|WP_Error
2827     */
2828    public static function validate_alphanum( $value, $request, $param ) {
2829        if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/^[a-z0-9]+$/i', $value ) ) ) {
2830            return new WP_Error(
2831                'invalid_param',
2832                sprintf(
2833                    /* Translators: Placeholder is a parameter name. */
2834                    esc_html__( '%s must be an alphanumeric string.', 'jetpack' ),
2835                    $param
2836                )
2837            );
2838        }
2839        return true;
2840    }
2841
2842    /**
2843     * Validates that the parameter is a tag or id for a verification service, or an empty string (to be able to clear the field).
2844     *
2845     * @since 4.6.0
2846     *
2847     * @param string          $value   Value to check.
2848     * @param WP_REST_Request $request The request sent to the WP REST API.
2849     * @param string          $param   Name of the parameter passed to endpoint holding $value.
2850     *
2851     * @return bool|WP_Error
2852     */
2853    public static function validate_verification_service( $value, $request, $param ) {
2854        if ( ! empty( $value ) && ( ! is_string( $value ) || false === jetpack_verification_validate_code( $value ) ) ) {
2855            return new WP_Error(
2856                'invalid_param',
2857                sprintf(
2858                    /* Translators: Placeholder is a verification string used to verify a service like Google Webmaster Console. */
2859                    esc_html__( '%s must be a valid verification code or verification tag.', 'jetpack' ),
2860                    $param
2861                )
2862            );
2863        }
2864        return true;
2865    }
2866
2867    /**
2868     * Validates that the parameter is among the roles allowed for Stats.
2869     *
2870     * @since 4.3.0
2871     *
2872     * @param mixed           $value Value to check.
2873     * @param WP_REST_Request $request The request sent to the WP REST API.
2874     * @param string          $param Name of the parameter passed to endpoint holding $value.
2875     *
2876     * @return bool|WP_Error
2877     */
2878    public static function validate_stats_roles( $value, $request, $param ) {
2879        // An empty value clears the setting; sanitize_stats_allowed_roles() falls back to 'administrator'.
2880        if ( empty( $value ) ) {
2881            return true;
2882        }
2883
2884        // Enforce the schema's list-of-strings contract before array_intersect() below sees the value.
2885        if ( ! is_array( $value ) || count( array_filter( $value, 'is_string' ) ) !== count( $value ) ) {
2886            return new WP_Error(
2887                'invalid_param',
2888                sprintf(
2889                    /* Translators: Placeholder is a parameter name. */
2890                    esc_html__( '%s must be an array of user roles.', 'jetpack' ),
2891                    $param
2892                )
2893            );
2894        }
2895
2896        if ( ! function_exists( 'get_editable_roles' ) ) {
2897            require_once ABSPATH . 'wp-admin/includes/user.php';
2898        }
2899        $editable_roles = array_keys( get_editable_roles() );
2900        if ( ! array_intersect( $editable_roles, $value ) ) {
2901            return new WP_Error(
2902                'invalid_param',
2903                sprintf(
2904                    /* 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. */
2905                    esc_html__( '%1$s must be %2$s.', 'jetpack' ),
2906                    $param,
2907                    implode( ', ', $editable_roles )
2908                )
2909            );
2910        }
2911        return true;
2912    }
2913
2914    /**
2915     * Validates that the parameter is among the views where the Sharing can be displayed.
2916     *
2917     * @since 4.3.0
2918     *
2919     * @param string|bool     $value Value to check.
2920     * @param WP_REST_Request $request The request sent to the WP REST API.
2921     * @param string          $param Name of the parameter passed to endpoint holding $value.
2922     *
2923     * @return bool|WP_Error
2924     */
2925    public static function validate_sharing_show( $value, $request, $param ) {
2926        $views = array( 'index', 'post', 'page', 'attachment', 'jetpack-portfolio' );
2927        if ( ! is_array( $value ) ) {
2928            return new WP_Error(
2929                'invalid_param',
2930                sprintf(
2931                    /* Translators: Placeholder is a parameter name. */
2932                    esc_html__( '%s must be an array of post types.', 'jetpack' ),
2933                    $param
2934                )
2935            );
2936        }
2937        if ( ! array_intersect( $views, $value ) ) {
2938            return new WP_Error(
2939                'invalid_param',
2940                sprintf(
2941                    /* 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 */
2942                    esc_html__( '%1$s must be %2$s.', 'jetpack' ),
2943                    $param,
2944                    implode( ', ', $views )
2945                )
2946            );
2947        }
2948        return true;
2949    }
2950
2951    /**
2952     * Validates that the parameter is among the valid reply-to types for subscriptions.
2953     *
2954     * @since 4.3.0
2955     *
2956     * @param string|bool     $value Value to check.
2957     * @param WP_REST_Request $request The request sent to the WP REST API.
2958     * @param string          $param Name of the parameter passed to endpoint holding $value.
2959     *
2960     * @return bool|WP_Error
2961     */
2962    public static function validate_subscriptions_reply_to( $value, $request, $param ) {
2963        require_once JETPACK__PLUGIN_DIR . 'modules/subscriptions/class-settings.php';
2964        if ( ! empty( $value ) && ! Automattic\Jetpack\Modules\Subscriptions\Settings::is_valid_reply_to( $value ) ) {
2965            return new WP_Error(
2966                'invalid_param',
2967                sprintf(
2968                    /* Translators: Placeholder is a parameter name. */
2969                    esc_html__( '%s must be a valid type.', 'jetpack' ),
2970                    $param
2971                )
2972            );
2973        }
2974        return true;
2975    }
2976
2977    /**
2978     * Validates that the parameter is among the valid reply-to types for subscriptions.
2979     *
2980     * @since 4.3.0
2981     *
2982     * @param string|bool     $value Value to check.
2983     * @param WP_REST_Request $request The request sent to the WP REST API.
2984     * @param string          $param Name of the parameter passed to endpoint holding $value.
2985     *
2986     * @return bool|WP_Error
2987     */
2988    public static function validate_subscriptions_reply_to_name( $value, $request, $param ) {
2989        if ( ! empty( $value ) && ! is_string( $value ) ) {
2990            return new WP_Error(
2991                'invalid_param',
2992                sprintf(
2993                    /* Translators: Placeholder is a parameter name. */
2994                    esc_html__( '%s must be a valid type.', 'jetpack' ),
2995                    $param
2996                )
2997            );
2998        }
2999        return true;
3000    }
3001
3002    /**
3003     * Validates that the parameter is among the views where the Sharing can be displayed.
3004     *
3005     * @since 4.3.0
3006     *
3007     * @param string|bool     $value {
3008     *         Value to check received by request.
3009     *
3010     *     @type array $visible List of slug of services to share to that are displayed directly in the page.
3011     *     @type array $hidden  List of slug of services to share to that are concealed in a folding menu.
3012     * }
3013     * @param WP_REST_Request $request The request sent to the WP REST API.
3014     * @param string          $param Name of the parameter passed to endpoint holding $value.
3015     *
3016     * @return bool|WP_Error
3017     */
3018    public static function validate_services( $value, $request, $param ) {
3019        if ( ! is_array( $value ) || ! isset( $value['visible'] ) || ! isset( $value['hidden'] ) ) {
3020            return new WP_Error(
3021                'invalid_param',
3022                sprintf(
3023                    /* Translators: Placeholder is a parameter name. */
3024                    esc_html__( '%s must be an array with visible and hidden items.', 'jetpack' ),
3025                    $param
3026                )
3027            );
3028        }
3029
3030        // Allow to clear everything.
3031        if ( empty( $value['visible'] ) && empty( $value['hidden'] ) ) {
3032            return true;
3033        }
3034
3035        if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
3036            return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
3037        }
3038        $sharer   = new Sharing_Service();
3039        $services = array_keys( $sharer->get_all_services() );
3040
3041        if (
3042            ( ! empty( $value['visible'] ) && ! array_intersect( $value['visible'], $services ) )
3043            ||
3044            ( ! empty( $value['hidden'] ) && ! array_intersect( $value['hidden'], $services ) ) ) {
3045            return new WP_Error(
3046                'invalid_param',
3047                sprintf(
3048                    /* Translators: placeholder 1 is a parameter holding the services passed to endpoint, placeholder 2 is a list of all Jetpack Sharing services */
3049                    esc_html__( '%1$s visible and hidden items must be a list of %2$s.', 'jetpack' ),
3050                    $param,
3051                    implode( ', ', $services )
3052                )
3053            );
3054        }
3055        return true;
3056    }
3057
3058    /**
3059     * Validates that the parameter has enough information to build a custom sharing button.
3060     *
3061     * @since 4.3.0
3062     *
3063     * @param string|bool     $value Value to check.
3064     * @param WP_REST_Request $request The request sent to the WP REST API.
3065     * @param string          $param Name of the parameter passed to endpoint holding $value.
3066     *
3067     * @return bool|WP_Error
3068     */
3069    public static function validate_custom_service( $value, $request, $param ) {
3070        if ( ! is_array( $value ) || ! isset( $value['sharing_name'] ) || ! isset( $value['sharing_url'] ) || ! isset( $value['sharing_icon'] ) ) {
3071            return new WP_Error(
3072                'invalid_param',
3073                sprintf(
3074                    /* Translators: Placeholder is a parameter name. */
3075                    esc_html__( '%s must be an array with sharing name, url and icon.', 'jetpack' ),
3076                    $param
3077                )
3078            );
3079        }
3080
3081        // Allow to clear everything.
3082        if ( empty( $value['sharing_name'] ) && empty( $value['sharing_url'] ) && empty( $value['sharing_icon'] ) ) {
3083            return true;
3084        }
3085
3086        if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
3087            return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
3088        }
3089
3090        if ( ( ! empty( $value['sharing_name'] ) && ! is_string( $value['sharing_name'] ) )
3091        || ( ! empty( $value['sharing_url'] ) && ! is_string( $value['sharing_url'] ) )
3092        || ( ! empty( $value['sharing_icon'] ) && ! is_string( $value['sharing_icon'] ) ) ) {
3093            return new WP_Error(
3094                'invalid_param',
3095                sprintf(
3096                    /* Translators: Placeholder is a parameter name. */
3097                    esc_html__( '%s needs sharing name, url and icon.', 'jetpack' ),
3098                    $param
3099                )
3100            );
3101        }
3102        return true;
3103    }
3104
3105    /**
3106     * Validates that the parameter is a custom sharing service ID like 'custom-1461976264'.
3107     *
3108     * @since 4.3.0
3109     *
3110     * @param string          $value Value to check.
3111     * @param WP_REST_Request $request The request sent to the WP REST API.
3112     * @param string          $param Name of the parameter passed to endpoint holding $value.
3113     *
3114     * @return bool|WP_Error
3115     */
3116    public static function validate_custom_service_id( $value, $request, $param ) {
3117        if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/custom\-[0-1]+/i', $value ) ) ) {
3118            return new WP_Error(
3119                'invalid_param',
3120                sprintf(
3121                    /* Translators: Placeholder is a parameter name. */
3122                    esc_html__( "%s must be a string prefixed with 'custom-' and followed by a numeric ID.", 'jetpack' ),
3123                    $param
3124                )
3125            );
3126        }
3127
3128        if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
3129            return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
3130        }
3131        $sharer   = new Sharing_Service();
3132        $services = $sharer->get_all_services();
3133
3134        if ( ! empty( $value ) && ! isset( $services[ $value ] ) ) {
3135            return new WP_Error(
3136                'invalid_param',
3137                sprintf(
3138                    /* Translators: Placeholder is a parameter name. */
3139                    esc_html__( '%s is not a registered custom sharing service.', 'jetpack' ),
3140                    $param
3141                )
3142            );
3143        }
3144
3145        return true;
3146    }
3147
3148    /**
3149     * Validates that the parameter is a Twitter username or empty string (to be able to clear the field).
3150     *
3151     * @since 4.3.0
3152     *
3153     * @param string          $value   Value to check.
3154     * @param WP_REST_Request $request The request sent to the WP REST API.
3155     * @param string          $param   Name of the parameter passed to endpoint holding $value.
3156     *
3157     * @return bool|WP_Error
3158     */
3159    public static function validate_twitter_username( $value, $request, $param ) {
3160        if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/^@?\w{1,15}$/i', $value ) ) ) {
3161            return new WP_Error(
3162                'invalid_param',
3163                sprintf(
3164                    /* Translators: Placeholder is a twitter name. */
3165                    esc_html__( '%s must be a Twitter username.', 'jetpack' ),
3166                    $param
3167                )
3168            );
3169        }
3170        return true;
3171    }
3172
3173    /**
3174     * Validates the firewall's IP block list, refusing one that would block the user saving it.
3175     *
3176     * @since 16.4
3177     *
3178     * @param string          $value Value to check.
3179     * @param WP_REST_Request $request The request sent to the WP REST API.
3180     * @param string          $param Name of the parameter passed to endpoint holding $value.
3181     *
3182     * @return bool|WP_Error
3183     */
3184    public static function validate_waf_ip_block_list( $value, $request, $param ) {
3185        $is_string = self::validate_string( $value, $request, $param );
3186        // Another plugin can load an older Protect package without the check.
3187        if ( true !== $is_string || ! method_exists( Protect_Firewall::class, 'validate_ip_block_list' ) ) {
3188            return $is_string;
3189        }
3190
3191        // Check the list as the sanitize_callback will store it, since the firewall reads the stored copy.
3192        return Protect_Firewall::validate_ip_block_list( esc_textarea( $value ) );
3193    }
3194
3195    /**
3196     * Validates that the parameter is a string.
3197     *
3198     * @since 4.3.0
3199     *
3200     * @param string          $value Value to check.
3201     * @param WP_REST_Request $request The request sent to the WP REST API.
3202     * @param string          $param Name of the parameter passed to endpoint holding $value.
3203     *
3204     * @return bool|WP_Error
3205     */
3206    public static function validate_string( $value, $request, $param ) {
3207        if ( ! is_string( $value ) ) {
3208            return new WP_Error(
3209                'invalid_param',
3210                sprintf(
3211                    /* Translators: Placeholder is a parameter name. */
3212                    esc_html__( '%s must be a string.', 'jetpack' ),
3213                    $param
3214                )
3215            );
3216        }
3217        return true;
3218    }
3219
3220    /**
3221     * Validates that the parameter is an array of strings.
3222     *
3223     * @param array           $value Value to check.
3224     * @param WP_REST_Request $request The request sent to the WP REST API.
3225     * @param string          $param Name of the parameter passed to the endpoint holding $value.
3226     *
3227     * @return bool|WP_Error
3228     */
3229    public static function validate_array_of_strings( $value, $request, $param ) {
3230        foreach ( $value as $array_item ) {
3231            $validate = self::validate_string( $array_item, $request, $param );
3232            if ( is_wp_error( $validate ) ) {
3233                return $validate;
3234            }
3235        }
3236
3237        return true;
3238    }
3239
3240    /**
3241     * Validates the subscription_options parameter.
3242     *
3243     * @param array $values Value to check.
3244     *
3245     * @return bool|WP_Error
3246     */
3247    public static function validate_subscription_options( $values ) {
3248        // A REST "object" decodes to a PHP associative array. Reject any other
3249        // type (object, string, int, null, ...) up front so the array_keys()
3250        // loop below never runs against a non-array and triggers a PHP warning.
3251        if ( ! is_array( $values ) ) {
3252            return new WP_Error(
3253                'invalid_param',
3254                /* Translators: subscription_options is a variable name, and shouldn't be translated. */
3255                esc_html__( 'subscription_options must be an object.', 'jetpack' )
3256            );
3257        }
3258        foreach ( array_keys( $values ) as $key ) {
3259            if ( ! in_array( $key, array( 'welcome', 'invitation', 'comment_follow', 'subscribe_modal_heading', 'free_tier_description', 'hide_free_tier' ), true ) ) {
3260                return new WP_Error(
3261                    'invalid_param',
3262                    sprintf(
3263                        /* Translators: Placeholder is the invalid param being sent. */
3264                        esc_html__( '%s is not one of the allowed members of subscription_options.', 'jetpack' ),
3265                        $key
3266                    )
3267                );
3268            }
3269        }
3270        return true;
3271    }
3272
3273    /**
3274     * Validates that the parameter is an array.
3275     *
3276     * @param array           $values Value to check.
3277     * @param WP_REST_Request $request The request sent to the WP REST API.
3278     * @param string          $param Name of the parameter passed to the endpoint holding $value.
3279     *
3280     * @return bool|WP_Error
3281     */
3282    public static function validate_array( $values, $request, $param ) {
3283        if ( ! is_array( $values ) ) {
3284            return new WP_Error(
3285                'invalid_param',
3286                sprintf(
3287                    /* Translators: Placeholder is a parameter name. */
3288                    esc_html__( '%s must be an object.', 'jetpack' ),
3289                    $param
3290                )
3291            );
3292        }
3293        return true;
3294    }
3295
3296    /**
3297     * If for some reason the roles allowed to see Stats are empty (for example, user tampering with checkboxes),
3298     * return an array with only 'administrator' as the allowed role and save it for 'roles' option.
3299     *
3300     * @since 4.3.0
3301     *
3302     * @param mixed $value Value to check.
3303     *
3304     * @return mixed The value as submitted, or an array holding only 'administrator' when it is empty.
3305     */
3306    public static function sanitize_stats_allowed_roles( $value ) {
3307        if ( empty( $value ) ) {
3308            return array( 'administrator' );
3309        }
3310        return $value;
3311    }
3312
3313    /**
3314     * Get the currently accessed route and return the module slug in it.
3315     *
3316     * @since 4.3.0
3317     *
3318     * @param string $route Regular expression for the endpoint with the module slug to return.
3319     *
3320     * @return array|string
3321     */
3322    public static function get_module_requested( $route = '/module/(?P<slug>[a-z\-]+)' ) {
3323
3324        if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) || ! is_string( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
3325            return '';
3326        }
3327
3328        preg_match( "#$route#", $GLOBALS['wp']->query_vars['rest_route'], $module );
3329
3330        if ( empty( $module['slug'] ) ) {
3331            return '';
3332        }
3333
3334        return $module['slug'];
3335    }
3336
3337    /**
3338     * Adds extra information for modules.
3339     *
3340     * @since 4.3.0
3341     *
3342     * @param string|array $modules Can be a single module or a list of modules.
3343     * @param null|string  $slug    Slug of the module in the first parameter.
3344     *
3345     * @return array|string
3346     */
3347    public static function prepare_modules_for_response( $modules = '', $slug = null ) {
3348        global $wp_rewrite;
3349
3350        /** This filter is documented in modules/sitemaps/sitemaps.php */
3351        $location = apply_filters( 'jetpack_sitemap_location', '' );
3352
3353        if ( $wp_rewrite->using_index_permalinks() ) {
3354            $sitemap_url      = home_url( '/index.php' . $location . '/sitemap.xml' );
3355            $news_sitemap_url = home_url( '/index.php' . $location . '/news-sitemap.xml' );
3356        } elseif ( $wp_rewrite->using_permalinks() ) {
3357            $sitemap_url      = home_url( $location . '/sitemap.xml' );
3358            $news_sitemap_url = home_url( $location . '/news-sitemap.xml' );
3359        } else {
3360            $sitemap_url      = home_url( $location . '/?jetpack-sitemap=sitemap.xml' );
3361            $news_sitemap_url = home_url( $location . '/?jetpack-sitemap=news-sitemap.xml' );
3362        }
3363
3364        if ( $slug === null && isset( $modules['sitemaps'] ) ) {
3365            // Is a list of modules.
3366            $modules['sitemaps']['extra']['sitemap_url']      = $sitemap_url;
3367            $modules['sitemaps']['extra']['news_sitemap_url'] = $news_sitemap_url;
3368        } elseif ( 'sitemaps' === $slug ) {
3369            // It's a single module.
3370            $modules['extra']['sitemap_url']      = $sitemap_url;
3371            $modules['extra']['news_sitemap_url'] = $news_sitemap_url;
3372        }
3373        return $modules;
3374    }
3375
3376    /**
3377     * Remove options the current user cannot read.
3378     *
3379     * Covers every `jetpack_waf_*` option, `jetpack_protect_global_whitelist` (populated from
3380     * `jetpack_waf_ip_allow_list`), the `jetpack_protect_key` shared secret, and
3381     * `wordpress_api_key`, the site's Akismet API key.
3382     *
3383     * @since 16.2
3384     *
3385     * @param array $options Option definitions keyed by option name.
3386     * @return array
3387     */
3388    public static function filter_options_for_response( $options ) {
3389        if ( current_user_can( 'manage_options' ) ) {
3390            return $options;
3391        }
3392
3393        $restricted = array(
3394            'jetpack_protect_key',
3395            'jetpack_protect_global_whitelist',
3396            'wordpress_api_key',
3397        );
3398
3399        return array_filter(
3400            $options,
3401            static function ( $option_name ) use ( $restricted ) {
3402                return 0 !== strpos( $option_name, 'jetpack_waf_' )
3403                    && ! in_array( $option_name, $restricted, true );
3404            },
3405            ARRAY_FILTER_USE_KEY
3406        );
3407    }
3408
3409    /**
3410     * Remove 'validate_callback' item from options available for module.
3411     * Fetch current option value and add to array of module options.
3412     * Prepare values of module options that need special handling, like those saved in wpcom.
3413     *
3414     * @since 4.3.0
3415     *
3416     * @param string $module Module slug.
3417     * @return array
3418     */
3419    public static function prepare_options_for_response( $module = '' ) {
3420        $options = self::get_updateable_data_list( $module );
3421
3422        if ( ! is_array( $options ) || empty( $options ) ) {
3423            return $options;
3424        }
3425
3426        // Some modules need special treatment.
3427        switch ( $module ) {
3428
3429            case 'monitor':
3430                // Status of user notifications.
3431                $options['monitor_receive_notifications']['current_value'] = self::cast_value( self::get_remote_value( 'monitor', 'monitor_receive_notifications' ), $options['monitor_receive_notifications'] );
3432                break;
3433
3434            case 'post-by-email':
3435                // Email address.
3436                $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'] );
3437                break;
3438
3439            case 'protect':
3440                // Protect.
3441                $options['jetpack_protect_key']['current_value']              = get_site_option( 'jetpack_protect_key', false );
3442                $options['jetpack_protect_global_whitelist']['current_value'] = Brute_Force_Protection_Shared_Functions::format_allow_list();
3443                break;
3444
3445            case 'related-posts':
3446                // It's local, but it must be broken apart since it's saved as an array.
3447                $options = self::split_options( $options, Jetpack_Options::get_option( 'relatedposts' ) );
3448                break;
3449
3450            case 'verification-tools':
3451                // It's local, but it must be broken apart since it's saved as an array.
3452                $options = self::split_options( $options, get_option( 'verification_services_codes' ) );
3453                break;
3454
3455            case 'google-analytics':
3456                $wga  = get_option( 'jetpack_wga' );
3457                $code = '';
3458                if ( is_array( $wga ) && array_key_exists( 'code', $wga ) ) {
3459                    $code = $wga['code'];
3460                }
3461                $options['google_analytics_tracking_id']['current_value'] = $code;
3462                break;
3463
3464            case 'sharedaddy':
3465                // It's local, but it must be broken apart since it's saved as an array.
3466                if ( ! class_exists( 'Sharing_Service' ) && ! include_once JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) {
3467                    break;
3468                }
3469                $sharer                                       = new Sharing_Service();
3470                $options                                      = self::split_options( $options, $sharer->get_global_options() );
3471                $options['sharing_services']['current_value'] = $sharer->get_blog_services();
3472                $other_sharedaddy_options                     = array( 'jetpack-twitter-cards-site-tag', 'sharedaddy_disable_resources', 'sharing_delete_service' );
3473                foreach ( $other_sharedaddy_options as $key ) {
3474                    $default_value                    = $options[ $key ]['default'] ?? '';
3475                    $current_value                    = get_option( $key, $default_value );
3476                    $options[ $key ]['current_value'] = self::cast_value( $current_value, $options[ $key ] );
3477                }
3478                break;
3479
3480            case 'stats':
3481                // It's local, but it must be broken apart since it's saved as an array.
3482                $options = self::split_options( $options, Stats_Options::get_options() );
3483                break;
3484            default:
3485                // These option are just stored as plain WordPress options.
3486                foreach ( $options as $key => $value ) {
3487                    $default_value                    = $options[ $key ]['default'] ?? '';
3488                    $current_value                    = get_option( $key, $default_value );
3489                    $options[ $key ]['current_value'] = self::cast_value( $current_value, $options[ $key ] );
3490                }
3491        }
3492        // At this point some options have current_value not set because they're options
3493        // that only get written on update, so we set current_value to the default one.
3494        foreach ( $options as $key => $value ) {
3495            // We don't need validate_callback in the response.
3496            if ( isset( $options[ $key ]['validate_callback'] ) ) {
3497                unset( $options[ $key ]['validate_callback'] );
3498            }
3499            $default_value = $options[ $key ]['default'] ?? '';
3500            if ( ! array_key_exists( 'current_value', $options[ $key ] ) ) {
3501                $options[ $key ]['current_value'] = self::cast_value( $default_value, $options[ $key ] );
3502            }
3503        }
3504
3505        // Filter last: the switch above assigns current_value by key without isset(),
3506        // so filtering earlier would let those assignments re-add a removed option.
3507        return self::filter_options_for_response( $options );
3508    }
3509
3510    /**
3511     * Splits module options saved as arrays like relatedposts or verification_services_codes into separate options to be returned in the response.
3512     *
3513     * @since 4.3.0
3514     *
3515     * @param array  $separate_options Array of options admitted by the module.
3516     * @param array  $grouped_options Option saved as array to be splitted.
3517     * @param string $prefix Optional prefix for the separate option keys.
3518     *
3519     * @return array
3520     */
3521    public static function split_options( $separate_options, $grouped_options, $prefix = '' ) {
3522        if ( is_array( $grouped_options ) ) {
3523            foreach ( $grouped_options as $key => $value ) {
3524                $option_key = $prefix . $key;
3525                if ( isset( $separate_options[ $option_key ] ) ) {
3526                    $separate_options[ $option_key ]['current_value'] = self::cast_value( $grouped_options[ $key ], $separate_options[ $option_key ] );
3527                }
3528            }
3529        }
3530        return $separate_options;
3531    }
3532
3533    /**
3534     * Perform a casting to the value specified in the option definition.
3535     *
3536     * @since 4.3.0
3537     *
3538     * @param mixed $value Value to cast to the proper type.
3539     * @param array $definition Type to cast the value to.
3540     *
3541     * @return bool|float|int|string
3542     */
3543    public static function cast_value( $value, $definition ) {
3544        if ( 'NULL' === $value ) {
3545            return null;
3546        }
3547
3548        if ( isset( $definition['type'] ) ) {
3549            switch ( $definition['type'] ) {
3550                case 'boolean':
3551                    if ( 'true' === $value || 'on' === $value ) {
3552                        return true;
3553                    } elseif ( 'false' === $value || 'off' === $value ) {
3554                        return false;
3555                    }
3556                    $value = (bool) $value;
3557                    break;
3558
3559                case 'integer':
3560                    $value = (int) $value;
3561                    break;
3562
3563                case 'float':
3564                    $value = (float) $value;
3565                    break;
3566
3567                case 'string':
3568                    $value = (string) $value;
3569                    break;
3570            }
3571        }
3572        return $value;
3573    }
3574
3575    /**
3576     * Get a value not saved locally.
3577     *
3578     * @since 4.3.0
3579     *
3580     * @param string $module Module slug.
3581     * @param string $option Option name.
3582     *
3583     * @return bool Whether user is receiving notifications or not.
3584     */
3585    public static function get_remote_value( $module, $option ) {
3586
3587        // These are per-user values on WordPress.com, so each user gets their own local copy.
3588        if ( in_array( $module, array( 'monitor', 'post-by-email' ), true ) ) {
3589            $option .= get_current_user_id();
3590        }
3591
3592        // If option doesn't exist, 'does_not_exist' will be returned.
3593        $value = get_option( $option, 'does_not_exist' );
3594
3595        // If option exists, just return it.
3596        if ( 'does_not_exist' !== $value ) {
3597            return $value;
3598        }
3599
3600        // Only check a remote option if Jetpack is connected.
3601        if ( ! Jetpack::is_connection_ready() ) {
3602            return false;
3603        }
3604
3605        // Do what is necessary for each module.
3606        switch ( $module ) {
3607            case 'monitor':
3608                // Load the class to use the method. If class can't be found, do nothing.
3609                if ( ! class_exists( 'Jetpack_Monitor' ) && ! include_once Jetpack::get_module_path( $module ) ) {
3610                    return false;
3611                }
3612                $value = Jetpack_Monitor::user_receives_notifications( false );
3613                // Not saved: the user may not be connected yet, and would be stuck with this answer.
3614                if ( is_wp_error( $value ) ) {
3615                    return false;
3616                }
3617                // An integer, as in Monitor::save_notifications_copy().
3618                $value = (int) (bool) $value;
3619                break;
3620
3621            case 'post-by-email':
3622                // Load the class to use the method. If class can't be found, do nothing.
3623                if ( ! class_exists( 'Jetpack_Post_By_Email' ) && ! include_once Jetpack::get_module_path( $module ) ) {
3624                    return false;
3625                }
3626                $value = Jetpack_Post_By_Email::init()->get_post_by_email_address();
3627                if ( null === $value ) {
3628                    $value = 'NULL'; // sentinel value so it actually gets set.
3629                }
3630                break;
3631        }
3632
3633        // Save option to use it next time.
3634        update_option( $option, $value );
3635
3636        return $value;
3637    }
3638
3639    /**
3640     * Get number of plugin updates available.
3641     *
3642     * @since 4.3.0
3643     *
3644     * @return mixed|WP_Error Number of plugin updates available. Otherwise, a WP_Error instance with the corresponding error.
3645     */
3646    public static function get_plugin_update_count() {
3647        $updates = wp_get_update_data();
3648        if ( isset( $updates['counts'] ) && isset( $updates['counts']['plugins'] ) ) {
3649            $count = $updates['counts']['plugins'];
3650            if ( 0 === $count ) {
3651                $response = array(
3652                    'code'    => 'success',
3653                    'message' => esc_html__( 'All plugins are up-to-date. Keep up the good work!', 'jetpack' ),
3654                    'count'   => 0,
3655                );
3656            } else {
3657                $response = array(
3658                    'code'    => 'updates-available',
3659                    'message' => esc_html(
3660                        sprintf(
3661                            /* Translators: placeholders are numbers. */
3662                            _n( '%s plugin needs updating.', '%s plugins need updating.', $count, 'jetpack' ),
3663                            $count
3664                        )
3665                    ),
3666                    'count'   => $count,
3667                );
3668            }
3669            return rest_ensure_response( $response );
3670        }
3671
3672        return new WP_Error( 'not_found', esc_html__( 'Could not check updates for plugins on this site.', 'jetpack' ), array( 'status' => 404 ) );
3673    }
3674
3675    /**
3676     * Get plugins data in site.
3677     *
3678     * @since 4.2.0
3679     *
3680     * @return WP_REST_Response|WP_Error List of plugins in the site. Otherwise, a WP_Error instance with the corresponding error.
3681     */
3682    public static function get_plugins() {
3683        $plugins = Plugins_Installer::get_plugins();
3684
3685        if ( ! empty( $plugins ) ) {
3686            return rest_ensure_response( $plugins );
3687        }
3688
3689        return new WP_Error( 'not_found', esc_html__( 'Unable to list plugins.', 'jetpack' ), array( 'status' => 404 ) );
3690    }
3691
3692    /**
3693     * Install a specific plugin and optionally activates it.
3694     *
3695     * @since 8.9.0
3696     *
3697     * @param WP_REST_Request $request {
3698     *     Array of parameters received by request.
3699     *
3700     *     @type string $slug   Plugin slug.
3701     *     @type string $status Plugin status.
3702     *     @type string $source Where did the plugin installation request originate.
3703     * }
3704     *
3705     * @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.
3706     */
3707    public static function install_plugin( $request ) {
3708        $plugin = stripslashes( $request['slug'] );
3709
3710        // Let's make sure the plugin isn't already installed.
3711        $plugin_id = Plugins_Installer::get_plugin_id_by_slug( $plugin );
3712
3713        // If not installed, let's install now.
3714        if ( ! $plugin_id ) {
3715            $result = Plugins_Installer::install_plugin( $plugin );
3716
3717            if ( is_wp_error( $result ) ) {
3718                return new WP_Error(
3719                    'install_plugin_failed',
3720                    sprintf(
3721                        /* translators: %1$s: plugin name. -- %2$s: error message. */
3722                        __( 'Unable to install %1$s: %2$s ', 'jetpack' ),
3723                        $plugin,
3724                        $result->get_error_message()
3725                    ),
3726                    array( 'status' => 500 )
3727                );
3728            }
3729        }
3730
3731        /*
3732         * We may want to activate the plugin as well.
3733         * Let's check for the status parameter in the request to find out.
3734         * If none was passed (or something other than active), let's return now.
3735         */
3736        if ( empty( $request['status'] ) || 'active' !== $request['status'] ) {
3737            return rest_ensure_response(
3738                array(
3739                    'code'    => 'success',
3740                    'message' => esc_html(
3741                        sprintf(
3742                            /* translators: placeholder is a plugin name. */
3743                            __( 'Installed %s', 'jetpack' ),
3744                            $plugin
3745                        )
3746                    ),
3747                )
3748            );
3749        }
3750
3751        /*
3752         * Proceed with plugin activation.
3753         * Let's check again for the plugin's ID if we don't already have it.
3754         */
3755        if ( ! $plugin_id ) {
3756            $plugin_id = Plugins_Installer::get_plugin_id_by_slug( $plugin );
3757            if ( ! $plugin_id ) {
3758                return new WP_Error(
3759                    'unable_to_determine_installed_plugin',
3760                    __( 'Unable to determine what plugin was installed.', 'jetpack' ),
3761                    array( 'status' => 500 )
3762                );
3763            }
3764        }
3765
3766        $source      = ! empty( $request['source'] ) ? stripslashes( $request['source'] ) : 'rest_api';
3767        $plugin_args = array(
3768            'plugin' => substr( $plugin_id, 0, - 4 ),
3769            'status' => 'active',
3770            'source' => $source,
3771        );
3772        return self::activate_plugin( $plugin_args );
3773    }
3774
3775    /**
3776     * Activate a specific plugin.
3777     *
3778     * @since 8.9.0
3779     *
3780     * @param WP_REST_Request $request {
3781     *     Array of parameters received by request.
3782     *
3783     *     @type string $plugin Plugin long slug (slug/index-file)
3784     *     @type string $status Plugin status. We only support active in Jetpack.
3785     *     @type string $source Where did the plugin installation request originate.
3786     * }
3787     *
3788     * @return WP_REST_Response|WP_Error A response object if the activation was successful, or a WP_Error object if the activation failed.
3789     */
3790    public static function activate_plugin( $request ) {
3791        /*
3792         * We need an "active" status parameter to be passed to the request
3793         * just like the core plugins endpoind we'll eventually switch to.
3794         */
3795        if ( empty( $request['status'] ) || 'active' !== $request['status'] ) {
3796            return new WP_Error(
3797                'missing_status_parameter',
3798                esc_html__( 'Status parameter missing.', 'jetpack' ),
3799                array( 'status' => 403 )
3800            );
3801        }
3802
3803        $plugins = Plugins_Installer::get_plugins();
3804
3805        if ( empty( $plugins ) ) {
3806            return new WP_Error( 'no_plugins_found', esc_html__( 'This site has no plugins.', 'jetpack' ), array( 'status' => 404 ) );
3807        }
3808
3809        if ( empty( $request['plugin'] ) ) {
3810            return new WP_Error( 'no_plugin_specified', esc_html__( 'You did not specify a plugin.', 'jetpack' ), array( 'status' => 404 ) );
3811        }
3812
3813        $plugin = $request['plugin'] . '.php';
3814
3815        // Is the plugin installed?
3816        if ( ! array_key_exists( $plugin, $plugins ) ) {
3817            return new WP_Error(
3818                'plugin_not_found',
3819                esc_html(
3820                    sprintf(
3821                        /* translators: placeholder is a plugin slug. */
3822                        __( 'Plugin %s is not installed.', 'jetpack' ),
3823                        $plugin
3824                    )
3825                ),
3826                array( 'status' => 404 )
3827            );
3828        }
3829
3830        // Is the plugin active already?
3831        $status = Plugins_Installer::get_plugin_status( $plugin );
3832        if ( in_array( $status, array( 'active', 'network-active' ), true ) ) {
3833            return new WP_Error(
3834                'plugin_already_active',
3835                esc_html(
3836                    sprintf(
3837                        /* translators: placeholder is a plugin slug. */
3838                        __( 'Plugin %s is already active.', 'jetpack' ),
3839                        $plugin
3840                    )
3841                ),
3842                array( 'status' => 404 )
3843            );
3844        }
3845
3846        // Now try to activate the plugin.
3847        $activated = activate_plugin( $plugin );
3848
3849        if ( is_wp_error( $activated ) ) {
3850            return $activated;
3851        } else {
3852            $source = ! empty( $request['source'] ) ? stripslashes( $request['source'] ) : 'rest_api';
3853            /**
3854             * Fires when Jetpack installs a plugin for you.
3855             *
3856             * @since 8.9.0
3857             *
3858             * @param string $plugin_file Plugin file.
3859             * @param string $source      Where did the plugin installation originate.
3860             */
3861            do_action( 'jetpack_activated_plugin', $plugin, $source );
3862            return rest_ensure_response(
3863                array(
3864                    'code'    => 'success',
3865                    'message' => sprintf(
3866                        /* translators: placeholder is a plugin name. */
3867                        esc_html__( 'Activated %s', 'jetpack' ),
3868                        $plugin
3869                    ),
3870                )
3871            );
3872        }
3873    }
3874
3875    /**
3876     * Check if a plugin can be activated.
3877     *
3878     * @since 8.9.0
3879     *
3880     * @param string|bool     $value   Value to check.
3881     * @param WP_REST_Request $request The request sent to the WP REST API.
3882     * @param string          $param   Name of the parameter passed to endpoint holding $value.
3883     */
3884    public static function validate_activate_plugin( $value, $request, $param ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
3885        return 'active' === $value;
3886    }
3887
3888    /**
3889     * Get data about the queried plugin. Currently it only returns whether the plugin is active or not.
3890     *
3891     * @since 4.2.0
3892     *
3893     * @param WP_REST_Request $request {
3894     *     Array of parameters received by request.
3895     *
3896     *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
3897     * }
3898     *
3899     * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
3900     */
3901    public static function get_plugin( $request ) {
3902        $plugins = Plugins_Installer::get_plugins();
3903
3904        if ( empty( $plugins ) ) {
3905            return new WP_Error( 'no_plugins_found', esc_html__( 'This site has no plugins.', 'jetpack' ), array( 'status' => 404 ) );
3906        }
3907
3908        $plugin = stripslashes( $request['plugin'] );
3909
3910        if ( ! array_key_exists( $plugin, $plugins ) ) {
3911            return new WP_Error(
3912                'plugin_not_found',
3913                esc_html(
3914                    sprintf(
3915                        /* Translators: placeholder is a plugin name. */
3916                        __( 'Plugin %s is not installed.', 'jetpack' ),
3917                        $plugin
3918                    )
3919                ),
3920                array( 'status' => 404 )
3921            );
3922        }
3923
3924        $plugin_data = $plugins[ $plugin ];
3925
3926        $plugin_data['active'] = in_array( Plugins_Installer::get_plugin_status( $plugin ), array( 'active', 'network-active' ), true );
3927
3928        return rest_ensure_response(
3929            array(
3930                'code'    => 'success',
3931                'message' => esc_html__( 'Plugin found.', 'jetpack' ),
3932                'data'    => $plugin_data,
3933            )
3934        );
3935    }
3936
3937    /**
3938     * Returns the Jetpack CRM data.
3939     *
3940     * @return WP_REST_Response A response object containing the Jetpack CRM data.
3941     */
3942    public static function get_jetpack_crm_data() {
3943        $jetpack_crm_data = ( new Jetpack_CRM_Data() )->get_crm_data();
3944        return rest_ensure_response( $jetpack_crm_data );
3945    }
3946
3947    /**
3948     * Activates Jetpack CRM's Jetpack Forms extension.
3949     *
3950     * @param WP_REST_Request $request The request sent to the WP REST API.
3951     * @return WP_REST_Response|WP_Error A response object if the extension activation was successful, or a WP_Error object if it failed.
3952     */
3953    public static function activate_crm_jetpack_forms_extension( $request ) {
3954        if ( ! isset( $request['extension'] ) || 'jetpackforms' !== $request['extension'] ) {
3955            return new WP_Error( 'invalid_param', esc_html__( 'Missing or invalid extension parameter.', 'jetpack' ), array( 'status' => 404 ) );
3956        }
3957
3958        $result = ( new Jetpack_CRM_Data() )->activate_crm_jetpackforms_extension();
3959
3960        if ( is_wp_error( $result ) ) {
3961            return $result;
3962        }
3963
3964        return rest_ensure_response( array( 'code' => 'success' ) );
3965    }
3966
3967    /**
3968     * Verifies that the current user has the required permission for accessing the CRM data.
3969     *
3970     * @return true|WP_Error Returns true if the user has the required capability, else a WP_Error object.
3971     */
3972    public static function jetpack_crm_data_permission_check() {
3973        if ( current_user_can( 'publish_posts' ) ) {
3974            return true;
3975        }
3976
3977        return new WP_Error(
3978            'invalid_user_permission_jetpack_crm_data',
3979            REST_Connector::get_user_permissions_error_msg(),
3980            array( 'status' => rest_authorization_required_code() )
3981        );
3982    }
3983
3984    /**
3985     * Verifies that the current user has the required capability for activating Jetpack CRM extensions.
3986     *
3987     * @return true|WP_Error Returns true if the user has the required capability, else a WP_Error object.
3988     */
3989    public static function activate_crm_extensions_permission_check() {
3990        // phpcs:ignore WordPress.WP.Capabilities.Unknown
3991        if ( current_user_can( 'admin_zerobs_manage_options' ) ) {
3992            return true;
3993        }
3994
3995        return new WP_Error(
3996            'invalid_user_permission_activate_jetpack_crm_ext',
3997            REST_Connector::get_user_permissions_error_msg(),
3998            array( 'status' => rest_authorization_required_code() )
3999        );
4000    }
4001
4002    /**
4003     * Set hasSeenWCConnectionModal to true when the site has displayed it
4004     *
4005     * @since 10.4.0
4006     *
4007     * @return bool
4008     */
4009    public static function set_has_seen_wc_connection_modal() {
4010        $updated_option = Jetpack_Options::update_option( 'has_seen_wc_connection_modal', true );
4011
4012        return rest_ensure_response( array( 'success' => $updated_option ) );
4013    }
4014
4015    /**
4016     * Return the list of available features.
4017     *
4018     * @return array
4019     */
4020    public static function get_features_available() {
4021        $raw_modules = Jetpack::get_available_modules();
4022        $modules     = array();
4023        foreach ( $raw_modules as $module ) {
4024            $modules[] = Jetpack::get_module_slug( $module );
4025        }
4026
4027        return $modules;
4028    }
4029
4030    /**
4031     * Returns what features are enabled. Uses the slug of the modules files.
4032     *
4033     * @return array
4034     */
4035    public static function get_features_enabled() {
4036        $raw_modules = Jetpack::get_active_modules();
4037        $modules     = array();
4038        foreach ( $raw_modules as $module ) {
4039            $modules[] = Jetpack::get_module_slug( $module );
4040        }
4041
4042        return $modules;
4043    }
4044
4045    /**
4046     * Verify that the API client is allowed to replace user token.
4047     *
4048     * @since 1.29.0
4049     *
4050     * @return bool|WP_Error
4051     */
4052    public static function get_features_permission_check() {
4053        if ( ! Rest_Authentication::is_signed_with_blog_token() ) {
4054            $message = esc_html__(
4055                'You do not have the correct user permissions to perform this action. Please contact your site admin if you think this is a mistake.',
4056                'jetpack'
4057            );
4058            return new WP_Error( 'invalid_permission_fetch_features', $message, array( 'status' => rest_authorization_required_code() ) );
4059        }
4060
4061        return true;
4062    }
4063} // class end