Completed
Push — instant-search-master ( 95535d...2c1eb1 )
by
unknown
22:37 queued 16:04
created

_inc/lib/class.core-rest-api-endpoints.php (1 issue)

Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
use Automattic\Jetpack\Connection\Client;
4
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
5
use Automattic\Jetpack\JITM;
6
use Automattic\Jetpack\Tracking;
7
use Automattic\Jetpack\Status;
8
9
/**
10
 * Register WP REST API endpoints for Jetpack.
11
 *
12
 * @author Automattic
13
 */
14
15
/**
16
 * Disable direct access.
17
 */
18
if ( ! defined( 'ABSPATH' ) ) {
19
	exit;
20
}
21
22
// Load WP_Error for error messages.
23
require_once ABSPATH . '/wp-includes/class-wp-error.php';
24
25
// Register endpoints when WP REST API is initialized.
26
add_action( 'rest_api_init', array( 'Jetpack_Core_Json_Api_Endpoints', 'register_endpoints' ) );
27
// Load API endpoints that are synced with WP.com
28
// Each of these is a class that will register its own routes on 'rest_api_init'.
29
require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/load-wpcom-endpoints.php';
30
31
/**
32
 * Class Jetpack_Core_Json_Api_Endpoints
33
 *
34
 * @since 4.3.0
35
 */
36
class Jetpack_Core_Json_Api_Endpoints {
37
38
	/**
39
	 * @var string Generic error message when user is not allowed to perform an action.
40
	 */
41
	public static $user_permissions_error_msg;
42
43
	/**
44
	 * @var array Roles that can access Stats once they're granted access.
45
	 */
46
	public static $stats_roles;
47
48
	/**
49
	 * Declare the Jetpack REST API endpoints.
50
	 *
51
	 * @since 4.3.0
52
	 */
53
	public static function register_endpoints() {
54
55
		// Load API endpoint base classes
56
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-xmlrpc-consumer-endpoint.php';
57
58
		// Load API endpoints
59
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-module-endpoints.php';
60
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-site-endpoints.php';
61
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-widgets-endpoints.php';
62
63
		self::$user_permissions_error_msg = esc_html__(
64
			'You do not have the correct user permissions to perform this action.
65
			Please contact your site admin if you think this is a mistake.',
66
			'jetpack'
67
		);
68
69
		self::$stats_roles = array( 'administrator', 'editor', 'author', 'contributor', 'subscriber' );
70
71
		$ixr_client = new Jetpack_IXR_Client( array( 'user_id' => get_current_user_id() ) );
72
		$core_api_endpoint = new Jetpack_Core_API_Data( $ixr_client );
73
		$module_list_endpoint = new Jetpack_Core_API_Module_List_Endpoint();
74
		$module_data_endpoint = new Jetpack_Core_API_Module_Data_Endpoint();
75
		$module_toggle_endpoint = new Jetpack_Core_API_Module_Toggle_Endpoint( new Jetpack_IXR_Client() );
76
		$site_endpoint = new Jetpack_Core_API_Site_Endpoint();
77
		$widget_endpoint = new Jetpack_Core_API_Widget_Endpoint();
78
79
		register_rest_route( 'jetpack/v4', 'plans', array(
80
			'methods'             => WP_REST_Server::READABLE,
81
			'callback'            => __CLASS__ . '::get_plans',
82
			'permission_callback' => __CLASS__ . '::connect_url_permission_callback',
83
		) );
84
85
		register_rest_route( 'jetpack/v4', 'products', array(
86
			'methods'             => WP_REST_Server::READABLE,
87
			'callback'            => __CLASS__ . '::get_products',
88
			'permission_callback' => __CLASS__ . '::connect_url_permission_callback',
89
		) );
90
91
		register_rest_route( 'jetpack/v4', 'marketing/survey', array(
92
			'methods'             => WP_REST_Server::CREATABLE,
93
			'callback'            => __CLASS__ . '::submit_survey',
94
			'permission_callback' => __CLASS__ . '::disconnect_site_permission_callback',
95
		) );
96
97
		register_rest_route( 'jetpack/v4', '/jitm', array(
98
			'methods'  => WP_REST_Server::READABLE,
99
			'callback' => __CLASS__ . '::get_jitm_message',
100
		) );
101
102
		register_rest_route( 'jetpack/v4', '/jitm', array(
103
			'methods'  => WP_REST_Server::CREATABLE,
104
			'callback' => __CLASS__ . '::delete_jitm_message'
105
		) );
106
107
		// Authorize a remote user
108
		register_rest_route( 'jetpack/v4', '/remote_authorize', array(
109
			'methods' => WP_REST_Server::EDITABLE,
110
			'callback' => __CLASS__ . '::remote_authorize',
111
		) );
112
113
		// Get current connection status of Jetpack
114
		register_rest_route( 'jetpack/v4', '/connection', array(
115
			'methods' => WP_REST_Server::READABLE,
116
			'callback' => __CLASS__ . '::jetpack_connection_status',
117
		) );
118
119
		// Test current connection status of Jetpack
120
		register_rest_route( 'jetpack/v4', '/connection/test', array(
121
			'methods' => WP_REST_Server::READABLE,
122
			'callback' => __CLASS__ . '::jetpack_connection_test',
123
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
124
		) );
125
126
		// Endpoint specific for privileged servers to request detailed debug information.
127
		register_rest_route( 'jetpack/v4', '/connection/test-wpcom/', array(
128
			'methods' => WP_REST_Server::READABLE,
129
			'callback' => __CLASS__ . '::jetpack_connection_test_for_external',
130
			'permission_callback' => __CLASS__ . '::view_jetpack_connection_test_check',
131
		) );
132
133
		register_rest_route( 'jetpack/v4', '/rewind', array(
134
			'methods' => WP_REST_Server::READABLE,
135
			'callback' => __CLASS__ . '::get_rewind_data',
136
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
137
		) );
138
139
		// Fetches a fresh connect URL
140
		register_rest_route( 'jetpack/v4', '/connection/url', array(
141
			'methods' => WP_REST_Server::READABLE,
142
			'callback' => __CLASS__ . '::build_connect_url',
143
			'permission_callback' => __CLASS__ . '::connect_url_permission_callback',
144
		) );
145
146
		// Get current user connection data
147
		register_rest_route( 'jetpack/v4', '/connection/data', array(
148
			'methods' => WP_REST_Server::READABLE,
149
			'callback' => __CLASS__ . '::get_user_connection_data',
150
			'permission_callback' => __CLASS__ . '::get_user_connection_data_permission_callback',
151
		) );
152
153
		// Start the connection process by registering the site on WordPress.com servers.
154
		register_rest_route( 'jetpack/v4', '/connection/register', array(
155
			'methods'             => WP_REST_Server::EDITABLE,
156
			'callback'            => __CLASS__ . '::register_site',
157
			'permission_callback' => __CLASS__ . '::connect_url_permission_callback',
158
			'args'                => array(
159
				'registration_nonce' => array( 'type' => 'string' ),
160
			),
161
		) );
162
163
		// Set the connection owner
164
		register_rest_route( 'jetpack/v4', '/connection/owner', array(
165
			'methods' => WP_REST_Server::EDITABLE,
166
			'callback' => __CLASS__ . '::set_connection_owner',
167
			'permission_callback' => __CLASS__ . '::set_connection_owner_permission_callback',
168
		) );
169
170
		// Current user: get or set tracking settings.
171
		register_rest_route( 'jetpack/v4', '/tracking/settings', array(
172
			array(
173
				'methods'             => WP_REST_Server::READABLE,
174
				'callback'            => __CLASS__ . '::get_user_tracking_settings',
175
				'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
176
			),
177
			array(
178
				'methods'             => WP_REST_Server::EDITABLE,
179
				'callback'            => __CLASS__ . '::update_user_tracking_settings',
180
				'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
181
				'args'                => array(
182
					'tracks_opt_out' => array( 'type' => 'boolean' ),
183
				),
184
			),
185
		) );
186
187
		// Disconnect site from WordPress.com servers
188
		register_rest_route( 'jetpack/v4', '/connection', array(
189
			'methods' => WP_REST_Server::EDITABLE,
190
			'callback' => __CLASS__ . '::disconnect_site',
191
			'permission_callback' => __CLASS__ . '::disconnect_site_permission_callback',
192
		) );
193
194
		// Disconnect/unlink user from WordPress.com servers
195
		register_rest_route( 'jetpack/v4', '/connection/user', array(
196
			'methods' => WP_REST_Server::EDITABLE,
197
			'callback' => __CLASS__ . '::unlink_user',
198
			'permission_callback' => __CLASS__ . '::unlink_user_permission_callback',
199
		) );
200
201
		// Get current site data
202
		register_rest_route( 'jetpack/v4', '/site', array(
203
			'methods' => WP_REST_Server::READABLE,
204
			'callback' => __CLASS__ . '::get_site_data',
205
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
206
		) );
207
208
		// Get current site data
209
		register_rest_route( 'jetpack/v4', '/site/features', array(
210
			'methods' => WP_REST_Server::READABLE,
211
			'callback' => array( $site_endpoint, 'get_features' ),
212
			'permission_callback' => array( $site_endpoint , 'can_request' ),
213
		) );
214
215
		// Get current site purchases.
216
		register_rest_route(
217
			'jetpack/v4',
218
			'/site/purchases',
219
			array(
220
				'methods'             => WP_REST_Server::READABLE,
221
				'callback'            => array( $site_endpoint, 'get_purchases' ),
222
				'permission_callback' => array( $site_endpoint, 'can_request' ),
223
			)
224
		);
225
226
		// Get current site benefits
227
		register_rest_route( 'jetpack/v4', '/site/benefits', array(
228
			'methods'             => WP_REST_Server::READABLE,
229
			'callback'            => array( $site_endpoint, 'get_benefits' ),
230
			'permission_callback' => array( $site_endpoint, 'can_request' ),
231
		) );
232
233
		// Get Activity Log data for this site.
234
		register_rest_route( 'jetpack/v4', '/site/activity', array(
235
			'methods' => WP_REST_Server::READABLE,
236
			'callback' => __CLASS__ . '::get_site_activity',
237
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
238
		) );
239
240
		// Confirm that a site in identity crisis should be in staging mode
241
		register_rest_route( 'jetpack/v4', '/identity-crisis/confirm-safe-mode', array(
242
			'methods' => WP_REST_Server::EDITABLE,
243
			'callback' => __CLASS__ . '::confirm_safe_mode',
244
			'permission_callback' => __CLASS__ . '::identity_crisis_mitigation_permission_check',
245
		) );
246
247
		// IDC resolve: create an entirely new shadow site for this URL.
248
		register_rest_route( 'jetpack/v4', '/identity-crisis/start-fresh', array(
249
			'methods' => WP_REST_Server::EDITABLE,
250
			'callback' => __CLASS__ . '::start_fresh_connection',
251
			'permission_callback' => __CLASS__ . '::identity_crisis_mitigation_permission_check',
252
		) );
253
254
		// Handles the request to migrate stats and subscribers during an identity crisis.
255
		register_rest_route( 'jetpack/v4', 'identity-crisis/migrate', array(
256
			'methods' => WP_REST_Server::EDITABLE,
257
			'callback' => __CLASS__ . '::migrate_stats_and_subscribers',
258
			'permissison_callback' => __CLASS__ . '::identity_crisis_mitigation_permission_check',
259
		) );
260
261
		// Return all modules
262
		register_rest_route( 'jetpack/v4', '/module/all', array(
263
			'methods' => WP_REST_Server::READABLE,
264
			'callback' => array( $module_list_endpoint, 'process' ),
265
			'permission_callback' => array( $module_list_endpoint, 'can_request' ),
266
		) );
267
268
		// Activate many modules
269
		register_rest_route( 'jetpack/v4', '/module/all/active', array(
270
			'methods' => WP_REST_Server::EDITABLE,
271
			'callback' => array( $module_list_endpoint, 'process' ),
272
			'permission_callback' => array( $module_list_endpoint, 'can_request' ),
273
			'args' => array(
274
				'modules' => array(
275
					'default'           => '',
276
					'type'              => 'array',
277
					'items'             => array(
278
						'type'          => 'string',
279
					),
280
					'required'          => true,
281
					'validate_callback' => __CLASS__ . '::validate_module_list',
282
				),
283
				'active' => array(
284
					'default'           => true,
285
					'type'              => 'boolean',
286
					'required'          => false,
287
					'validate_callback' => __CLASS__ . '::validate_boolean',
288
				),
289
			)
290
		) );
291
292
		// Return a single module and update it when needed
293
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)', array(
294
			'methods' => WP_REST_Server::READABLE,
295
			'callback' => array( $core_api_endpoint, 'process' ),
296
			'permission_callback' => array( $core_api_endpoint, 'can_request' ),
297
		) );
298
299
		// Activate and deactivate a module
300
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)/active', array(
301
			'methods' => WP_REST_Server::EDITABLE,
302
			'callback' => array( $module_toggle_endpoint, 'process' ),
303
			'permission_callback' => array( $module_toggle_endpoint, 'can_request' ),
304
			'args' => array(
305
				'active' => array(
306
					'default'           => true,
307
					'type'              => 'boolean',
308
					'required'          => true,
309
					'validate_callback' => __CLASS__ . '::validate_boolean',
310
				),
311
			)
312
		) );
313
314
		// Update a module
315
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)', array(
316
			'methods' => WP_REST_Server::EDITABLE,
317
			'callback' => array( $core_api_endpoint, 'process' ),
318
			'permission_callback' => array( $core_api_endpoint, 'can_request' ),
319
			'args' => self::get_updateable_parameters( 'any' )
320
		) );
321
322
		// Get data for a specific module, i.e. Protect block count, WPCOM stats,
323
		// Akismet spam count, etc.
324
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)/data', array(
325
			'methods' => WP_REST_Server::READABLE,
326
			'callback' => array( $module_data_endpoint, 'process' ),
327
			'permission_callback' => array( $module_data_endpoint, 'can_request' ),
328
			'args' => array(
329
				'range' => array(
330
					'default'           => 'day',
331
					'type'              => 'string',
332
					'required'          => false,
333
					'validate_callback' => __CLASS__ . '::validate_string',
334
				),
335
			)
336
		) );
337
338
		// Check if the API key for a specific service is valid or not
339
		register_rest_route( 'jetpack/v4', '/module/(?P<service>[a-z\-]+)/key/check', array(
340
			'methods' => WP_REST_Server::READABLE,
341
			'callback' => array( $module_data_endpoint, 'key_check' ),
342
			'permission_callback' => __CLASS__ . '::update_settings_permission_check',
343
			'sanitize_callback' => 'sanitize_text_field',
344
		) );
345
346
		register_rest_route( 'jetpack/v4', '/module/(?P<service>[a-z\-]+)/key/check', array(
347
			'methods' => WP_REST_Server::EDITABLE,
348
			'callback' => array( $module_data_endpoint, 'key_check' ),
349
			'permission_callback' => __CLASS__ . '::update_settings_permission_check',
350
			'sanitize_callback' => 'sanitize_text_field',
351
			'args' => array(
352
				'api_key' => array(
353
					'default'           => '',
354
					'type'              => 'string',
355
					'validate_callback' => __CLASS__ . '::validate_alphanum',
356
				),
357
			)
358
		) );
359
360
		// Update any Jetpack module option or setting
361
		register_rest_route( 'jetpack/v4', '/settings', array(
362
			'methods' => WP_REST_Server::EDITABLE,
363
			'callback' => array( $core_api_endpoint, 'process' ),
364
			'permission_callback' => array( $core_api_endpoint, 'can_request' ),
365
			'args' => self::get_updateable_parameters( 'any' )
366
		) );
367
368
		// Update a module
369
		register_rest_route( 'jetpack/v4', '/settings/(?P<slug>[a-z\-]+)', array(
370
			'methods' => WP_REST_Server::EDITABLE,
371
			'callback' => array( $core_api_endpoint, 'process' ),
372
			'permission_callback' => array( $core_api_endpoint, 'can_request' ),
373
			'args' => self::get_updateable_parameters()
374
		) );
375
376
		// Return all module settings
377
		register_rest_route( 'jetpack/v4', '/settings/', array(
378
			'methods' => WP_REST_Server::READABLE,
379
			'callback' => array( $core_api_endpoint, 'process' ),
380
			'permission_callback' => array( $core_api_endpoint, 'can_request' ),
381
		) );
382
383
		// Reset all Jetpack options
384
		register_rest_route( 'jetpack/v4', '/options/(?P<options>[a-z\-]+)', array(
385
			'methods' => WP_REST_Server::EDITABLE,
386
			'callback' => __CLASS__ . '::reset_jetpack_options',
387
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
388
		) );
389
390
		// Updates: get number of plugin updates available
391
		register_rest_route( 'jetpack/v4', '/updates/plugins', array(
392
			'methods' => WP_REST_Server::READABLE,
393
			'callback' => __CLASS__ . '::get_plugin_update_count',
394
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
395
		) );
396
397
		// Dismiss Jetpack Notices
398
		register_rest_route( 'jetpack/v4', '/notice/(?P<notice>[a-z\-_]+)', array(
399
			'methods' => WP_REST_Server::EDITABLE,
400
			'callback' => __CLASS__ . '::dismiss_notice',
401
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
402
		) );
403
404
		// Plugins: get list of all plugins.
405
		register_rest_route( 'jetpack/v4', '/plugins', array(
406
			'methods' => WP_REST_Server::READABLE,
407
			'callback' => __CLASS__ . '::get_plugins',
408
			'permission_callback' => __CLASS__ . '::activate_plugins_permission_check',
409
		) );
410
411
		register_rest_route( 'jetpack/v4', '/plugins/akismet/activate', array(
412
			'methods' => WP_REST_Server::EDITABLE,
413
			'callback' => __CLASS__ . '::activate_akismet',
414
			'permission_callback' => __CLASS__ . '::activate_plugins_permission_check',
415
		) );
416
417
		// Plugins: check if the plugin is active.
418
		register_rest_route( 'jetpack/v4', '/plugin/(?P<plugin>[a-z\/\.\-_]+)', array(
419
			'methods' => WP_REST_Server::READABLE,
420
			'callback' => __CLASS__ . '::get_plugin',
421
			'permission_callback' => __CLASS__ . '::activate_plugins_permission_check',
422
		) );
423
424
		// Widgets: get information about a widget that supports it.
425
		register_rest_route( 'jetpack/v4', '/widgets/(?P<id>[0-9a-z\-_]+)', array(
426
			'methods' => WP_REST_Server::READABLE,
427
			'callback' => array( $widget_endpoint, 'process' ),
428
			'permission_callback' => array( $widget_endpoint, 'can_request' ),
429
		) );
430
431
		// Site Verify: check if the site is verified, and a get verification token if not
432
		register_rest_route( 'jetpack/v4', '/verify-site/(?P<service>[a-z\-_]+)', array(
433
			'methods' => WP_REST_Server::READABLE,
434
			'callback' => __CLASS__ . '::is_site_verified_and_token',
435
			'permission_callback' => __CLASS__ . '::update_settings_permission_check',
436
		) );
437
438
		register_rest_route( 'jetpack/v4', '/verify-site/(?P<service>[a-z\-_]+)/(?<keyring_id>[0-9]+)', array(
439
			'methods' => WP_REST_Server::READABLE,
440
			'callback' => __CLASS__ . '::is_site_verified_and_token',
441
			'permission_callback' => __CLASS__ . '::update_settings_permission_check',
442
		) );
443
444
		// Site Verify: tell a service to verify the site
445
		register_rest_route( 'jetpack/v4', '/verify-site/(?P<service>[a-z\-_]+)', array(
446
			'methods' => WP_REST_Server::EDITABLE,
447
			'callback' => __CLASS__ . '::verify_site',
448
			'permission_callback' => __CLASS__ . '::update_settings_permission_check',
449
			'args' => array(
450
				'keyring_id' => array(
451
					'required'          => true,
452
					'type'              => 'integer',
453
					'validate_callback' => __CLASS__  . '::validate_posint',
454
				),
455
			)
456
		) );
457
458
		// Get and set API keys.
459
		// Note: permission_callback intentionally omitted from the GET method.
460
		// Map block requires open access to API keys on the front end.
461
		register_rest_route(
462
			'jetpack/v4',
463
			'/service-api-keys/(?P<service>[a-z\-_]+)',
464
			array(
465
				array(
466
					'methods'             => WP_REST_Server::READABLE,
467
					'callback'            => __CLASS__ . '::get_service_api_key',
468
				),
469
				array(
470
					'methods'             => WP_REST_Server::EDITABLE,
471
					'callback'            => __CLASS__ . '::update_service_api_key',
472
					'permission_callback' => array( 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys','edit_others_posts_check' ),
473
					'args'                => array(
474
						'service_api_key' => array(
475
							'required' => true,
476
							'type'     => 'text',
477
						),
478
					),
479
				),
480
				array(
481
					'methods'             => WP_REST_Server::DELETABLE,
482
					'callback'            => __CLASS__ . '::delete_service_api_key',
483
					'permission_callback' => array( 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys','edit_others_posts_check' ),
484
				),
485
			)
486
		);
487
488
		register_rest_route(
489
			'jetpack/v4',
490
			'/mobile/send-login-email',
491
			array(
492
				'methods'             => WP_REST_Server::EDITABLE,
493
				'callback'            => __CLASS__ . '::send_mobile_magic_link',
494
				'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
495
			)
496
		);
497
	}
498
499
	public static function get_plans( $request ) {
500
		$request = Client::wpcom_json_api_request_as_user(
501
			'/plans?_locale=' . get_user_locale(),
502
			'2',
503
			array(
504
				'method'  => 'GET',
505
				'headers' => array(
506
					'X-Forwarded-For' => Jetpack::current_user_ip( true ),
507
				),
508
			)
509
		);
510
511
		$body = json_decode( wp_remote_retrieve_body( $request ) );
512
		if ( 200 === wp_remote_retrieve_response_code( $request ) ) {
513
			$data = $body;
514
		} else {
515
			// something went wrong so we'll just return the response without caching
516
			return $body;
517
		}
518
519
		return $data;
520
	}
521
522
	/**
523
	 * Gets the WP.com products that are in use on wpcom.
524
	 * Similar to the WP.com plans that we currently in user on WPCOM.
525
	 *
526
	 * @param WP_REST_Request $request The request.
527
	 *
528
	 * @return string|WP_Error A JSON object of wpcom products if the request was successful, or a WP_Error otherwise.
529
	 */
530
	public static function get_products( $request ) {
531
		$wpcom_request = Client::wpcom_json_api_request_as_user(
532
			'/products?_locale=' . get_user_locale() . '&type=jetpack',
533
			'2',
534
			array(
535
				'method'  => 'GET',
536
				'headers' => array(
537
					'X-Forwarded-For' => Jetpack::current_user_ip( true ),
538
				),
539
			)
540
		);
541
542
		$response_code = wp_remote_retrieve_response_code( $wpcom_request );
543
		if ( 200 === $response_code ) {
544
			return json_decode( wp_remote_retrieve_body( $wpcom_request ) );
545
		} else {
546
			// Something went wrong so we'll just return the response without caching.
547
			return new WP_Error(
548
				'failed_to_fetch_data',
549
				esc_html__( 'Unable to fetch the requested data.', 'jetpack' ),
550
				array( 'status' => $response_code )
551
			);
552
		}
553
	}
554
555
	public static function submit_survey( $request ) {
556
557
		$wpcom_request = Client::wpcom_json_api_request_as_user(
558
			'/marketing/survey',
559
			'v2',
560
			array(
561
				'method'  => 'POST',
562
				'headers' => array(
563
					'Content-Type'    => 'application/json',
564
					'X-Forwarded-For' => Jetpack::current_user_ip( true ),
565
				),
566
			),
567
			$request->get_json_params()
568
		);
569
570
		$wpcom_request_body = json_decode( wp_remote_retrieve_body( $wpcom_request ) );
571
		if ( 200 === wp_remote_retrieve_response_code( $wpcom_request ) ) {
572
			$data = $wpcom_request_body;
573
		} else {
574
			// something went wrong so we'll just return the response without caching
575
			return $wpcom_request_body;
576
		}
577
578
		return $data;
579
	}
580
581
	/**
582
	 * Asks for a jitm, unless they've been disabled, in which case it returns an empty array
583
	 *
584
	 * @param $request WP_REST_Request
585
	 *
586
	 * @return array An array of jitms
587
	 */
588
	public static function get_jitm_message( $request ) {
589
		$jitm = new JITM();
590
591
		if ( ! $jitm->register() ) {
592
			return array();
593
		}
594
595
		return $jitm->get_messages( $request['message_path'], urldecode_deep( $request['query'] ) );
596
	}
597
598
	/**
599
	 * Dismisses a jitm
600
	 * @param $request WP_REST_Request The request
601
	 *
602
	 * @return bool Always True
603
	 */
604
	public static function delete_jitm_message( $request ) {
605
		$jitm = new JITM();
606
607
		if ( ! $jitm->register() ) {
608
			return true;
609
		}
610
611
		return $jitm->dismiss( $request['id'], $request['feature_class'] );
612
	}
613
614
	/**
615
	 * Checks if this site has been verified using a service - only 'google' supported at present - and a specfic
616
	 *  keyring to use to get the token if it is not
617
	 *
618
	 * Returns 'verified' = true/false, and a token if 'verified' is false and site is ready for verification
619
	 *
620
	 * @since 6.6.0
621
	 *
622
	 * @param WP_REST_Request $request The request sent to the WP REST API.
623
	 *
624
	 * @return array|wp-error
625
	 */
626
	public static function is_site_verified_and_token( $request ) {
627
		/**
628
		 * Return an error if the site uses a Maintenance / Coming Soon plugin
629
		 * and if the plugin is configured to make the site private.
630
		 *
631
		 * We currently handle the following plugins:
632
		 * - https://github.com/mojoness/mojo-marketplace-wp-plugin (used by bluehost)
633
		 * - https://wordpress.org/plugins/mojo-under-construction
634
		 * - https://wordpress.org/plugins/under-construction-page
635
		 * - https://wordpress.org/plugins/ultimate-under-construction
636
		 * - https://wordpress.org/plugins/coming-soon
637
		 *
638
		 * You can handle this in your own plugin thanks to the `jetpack_is_under_construction_plugin` filter.
639
		 * If the filter returns true, we will consider the site as under construction.
640
		 */
641
		$mm_coming_soon                       = get_option( 'mm_coming_soon', null );
642
		$under_construction_activation_status = get_option( 'underConstructionActivationStatus', null );
643
		$ucp_options                          = get_option( 'ucp_options', array() );
644
		$uuc_settings                         = get_option( 'uuc_settings', array() );
645
		$csp4                                 = get_option( 'seed_csp4_settings_content', array() );
646
		if (
647
			( Jetpack::is_plugin_active( 'mojo-marketplace-wp-plugin/mojo-marketplace.php' ) && 'true' === $mm_coming_soon )
648
			|| Jetpack::is_plugin_active( 'mojo-under-construction/mojo-contruction.php' ) && 1 == $under_construction_activation_status // WPCS: loose comparison ok.
649
			|| ( Jetpack::is_plugin_active( 'under-construction-page/under-construction.php' ) && isset( $ucp_options['status'] ) && 1 == $ucp_options['status'] ) // WPCS: loose comparison ok.
650
			|| ( Jetpack::is_plugin_active( 'ultimate-under-construction/ultimate-under-construction.php' ) && isset( $uuc_settings['enable'] ) && 1 == $uuc_settings['enable'] ) // WPCS: loose comparison ok.
651
			|| ( Jetpack::is_plugin_active( 'coming-soon/coming-soon.php' ) &&  isset( $csp4['status'] ) && ( 1 == $csp4['status'] || 2 == $csp4['status'] ) ) // WPCS: loose comparison ok.
652
			/**
653
			 * Allow plugins to mark a site as "under construction".
654
			 *
655
			 * @since 6.7.0
656
			 *
657
			 * @param false bool Is the site under construction? Default to false.
658
			 */
659
			|| true === apply_filters( 'jetpack_is_under_construction_plugin', false )
660
		) {
661
			return new WP_Error( 'forbidden', __( 'Site is under construction and cannot be verified', 'jetpack' ) );
662
		}
663
664
 		$xml = new Jetpack_IXR_Client( array(
665
 			'user_id' => get_current_user_id(),
666
		) );
667
668
		$args = array(
669
			'user_id' => get_current_user_id(),
670
			'service' => $request[ 'service' ],
671
		);
672
673
		if ( isset( $request[ 'keyring_id' ] ) ) {
674
			$args[ 'keyring_id' ] = $request[ 'keyring_id' ];
675
		}
676
677
		$xml->query( 'jetpack.isSiteVerified', $args );
678
679
		if ( $xml->isError() ) {
680
			return new WP_Error( 'error_checking_if_site_verified_google', sprintf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() ) );
681
		} else {
682
			return $xml->getResponse();
683
		}
684
	}
685
686
687
688
	public static function verify_site( $request ) {
689
		$xml = new Jetpack_IXR_Client( array(
690
			'user_id' => get_current_user_id(),
691
		) );
692
693
		$params = $request->get_json_params();
694
695
		$xml->query( 'jetpack.verifySite', array(
696
				'user_id' => get_current_user_id(),
697
				'service' => $request[ 'service' ],
698
				'keyring_id' => $params[ 'keyring_id' ],
699
			)
700
		);
701
702
		if ( $xml->isError() ) {
703
			return new WP_Error( 'error_verifying_site_google', sprintf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() ) );
704
		} else {
705
			$response = $xml->getResponse();
706
707
			if ( ! empty( $response['errors'] ) ) {
708
				$error = new WP_Error;
709
				$error->errors = $response['errors'];
710
				return $error;
711
			}
712
713
			return $response;
714
		}
715
	}
716
717
	/**
718
	 * Handles verification that a site is registered
719
	 *
720
	 * @since 5.4.0
721
	 *
722
	 * @param WP_REST_Request $request The request sent to the WP REST API.
723
	 *
724
	 * @return array|wp-error
725
	 */
726
	 public static function remote_authorize( $request ) {
727
		$xmlrpc_server = new Jetpack_XMLRPC_Server();
728
		$result = $xmlrpc_server->remote_authorize( $request );
729
730
		if ( is_a( $result, 'IXR_Error' ) ) {
731
			$result = new WP_Error( $result->code, $result->message );
732
		}
733
734
		return $result;
735
	 }
736
737
	/**
738
	 * Handles dismissing of Jetpack Notices
739
	 *
740
	 * @since 4.3.0
741
	 *
742
	 * @param WP_REST_Request $request The request sent to the WP REST API.
743
	 *
744
	 * @return array|wp-error
745
	 */
746
	public static function dismiss_notice( $request ) {
747
		$notice = $request['notice'];
748
749
		if ( ! isset( $request['dismissed'] ) || $request['dismissed'] !== true ) {
750
			return new WP_Error( 'invalid_param', esc_html__( 'Invalid parameter "dismissed".', 'jetpack' ), array( 'status' => 404 ) );
751
		}
752
753
		if ( isset( $notice ) && ! empty( $notice ) ) {
754
			switch( $notice ) {
755
				case 'feedback_dash_request':
756
				case 'welcome':
757
					$notices = get_option( 'jetpack_dismissed_notices', array() );
758
					$notices[ $notice ] = true;
759
					update_option( 'jetpack_dismissed_notices', $notices );
760
					return rest_ensure_response( get_option( 'jetpack_dismissed_notices', array() ) );
761
762
				default:
763
					return new WP_Error( 'invalid_param', esc_html__( 'Invalid parameter "notice".', 'jetpack' ), array( 'status' => 404 ) );
764
			}
765
		}
766
767
		return new WP_Error( 'required_param', esc_html__( 'Missing parameter "notice".', 'jetpack' ), array( 'status' => 404 ) );
768
	}
769
770
	/**
771
	 * Verify that the user can disconnect the site.
772
	 *
773
	 * @since 4.3.0
774
	 *
775
	 * @return bool|WP_Error True if user is able to disconnect the site.
776
	 */
777 View Code Duplication
	public static function disconnect_site_permission_callback() {
778
		if ( current_user_can( 'jetpack_disconnect' ) ) {
779
			return true;
780
		}
781
782
		return new WP_Error( 'invalid_user_permission_jetpack_disconnect', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
783
784
	}
785
786
	/**
787
	 * Verify that the user can get a connect/link URL
788
	 *
789
	 * @since 4.3.0
790
	 *
791
	 * @return bool|WP_Error True if user is able to disconnect the site.
792
	 */
793 View Code Duplication
	public static function connect_url_permission_callback() {
794
		if ( current_user_can( 'jetpack_connect_user' ) ) {
795
			return true;
796
		}
797
798
		return new WP_Error( 'invalid_user_permission_jetpack_connect', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
799
800
	}
801
802
	/**
803
	 * Verify that a user can get the data about the current user.
804
	 * Only those who can connect.
805
	 *
806
	 * @since 4.3.0
807
	 *
808
	 * @uses Jetpack::is_user_connected();
809
	 *
810
	 * @return bool|WP_Error True if user is able to unlink.
811
	 */
812 View Code Duplication
	public static function get_user_connection_data_permission_callback() {
813
		if ( current_user_can( 'jetpack_connect_user' ) ) {
814
			return true;
815
		}
816
817
		return new WP_Error( 'invalid_user_permission_user_connection_data', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
818
	}
819
820
	/**
821
	 * Check that user has permission to change the master user.
822
	 *
823
	 * @since 6.2.0
824
	 * @since 7.7.0 Update so that any user with jetpack_disconnect privs can set owner.
825
	 *
826
	 * @return bool|WP_Error True if user is able to change master user.
827
	 */
828 View Code Duplication
	public static function set_connection_owner_permission_callback() {
829
		if ( current_user_can( 'jetpack_disconnect' ) ) {
830
			return true;
831
		}
832
833
		return new WP_Error( 'invalid_user_permission_set_connection_owner', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
834
	}
835
836
	/**
837
	 * Verify that a user can use the /connection/user endpoint. Has to be a registered user and be currently linked.
838
	 *
839
	 * @since 4.3.0
840
	 *
841
	 * @uses Jetpack::is_user_connected();
842
	 *
843
	 * @return bool|WP_Error True if user is able to unlink.
844
	 */
845
	public static function unlink_user_permission_callback() {
846
		if ( current_user_can( 'jetpack_connect_user' ) && Jetpack::is_user_connected( get_current_user_id() ) ) {
847
			return true;
848
		}
849
850
		return new WP_Error( 'invalid_user_permission_unlink_user', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
851
	}
852
853
	/**
854
	 * Verify that user can manage Jetpack modules.
855
	 *
856
	 * @since 4.3.0
857
	 *
858
	 * @return bool Whether user has the capability 'jetpack_manage_modules'.
859
	 */
860
	public static function manage_modules_permission_check() {
861
		if ( current_user_can( 'jetpack_manage_modules' ) ) {
862
			return true;
863
		}
864
865
		return new WP_Error( 'invalid_user_permission_manage_modules', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
866
	}
867
868
	/**
869
	 * Verify that user can update Jetpack modules.
870
	 *
871
	 * @since 4.3.0
872
	 *
873
	 * @return bool Whether user has the capability 'jetpack_configure_modules'.
874
	 */
875 View Code Duplication
	public static function configure_modules_permission_check() {
876
		if ( current_user_can( 'jetpack_configure_modules' ) ) {
877
			return true;
878
		}
879
880
		return new WP_Error( 'invalid_user_permission_configure_modules', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
881
	}
882
883
	/**
884
	 * Verify that user can view Jetpack admin page.
885
	 *
886
	 * @since 4.3.0
887
	 *
888
	 * @return bool Whether user has the capability 'jetpack_admin_page'.
889
	 */
890 View Code Duplication
	public static function view_admin_page_permission_check() {
891
		if ( current_user_can( 'jetpack_admin_page' ) ) {
892
			return true;
893
		}
894
895
		return new WP_Error( 'invalid_user_permission_view_admin', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
896
	}
897
898
	/**
899
	 * Verify that user can mitigate an identity crisis.
900
	 *
901
	 * @since 4.4.0
902
	 *
903
	 * @return bool Whether user has capability 'jetpack_disconnect'.
904
	 */
905 View Code Duplication
	public static function identity_crisis_mitigation_permission_check() {
906
		if ( current_user_can( 'jetpack_disconnect' ) ) {
907
			return true;
908
		}
909
910
		return new WP_Error( 'invalid_user_permission_identity_crisis', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
911
	}
912
913
	/**
914
	 * Verify that user can update Jetpack general settings.
915
	 *
916
	 * @since 4.3.0
917
	 *
918
	 * @return bool Whether user has the capability 'update_settings_permission_check'.
919
	 */
920 View Code Duplication
	public static function update_settings_permission_check() {
921
		if ( current_user_can( 'jetpack_configure_modules' ) ) {
922
			return true;
923
		}
924
925
		return new WP_Error( 'invalid_user_permission_manage_settings', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
926
	}
927
928
	/**
929
	 * Verify that user can view Jetpack admin page and can activate plugins.
930
	 *
931
	 * @since 4.3.0
932
	 *
933
	 * @return bool Whether user has the capability 'jetpack_admin_page' and 'activate_plugins'.
934
	 */
935 View Code Duplication
	public static function activate_plugins_permission_check() {
936
		if ( current_user_can( 'jetpack_admin_page' ) && current_user_can( 'activate_plugins' ) ) {
937
			return true;
938
		}
939
940
		return new WP_Error( 'invalid_user_permission_activate_plugins', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
941
	}
942
943
	/**
944
	 * Verify that user can edit other's posts (Editors and Administrators).
945
	 *
946
	 * @return bool Whether user has the capability 'edit_others_posts'.
947
	 */
948
	public static function edit_others_posts_check() {
949
		if ( current_user_can( 'edit_others_posts' ) ) {
950
			return true;
951
		}
952
953
		return new WP_Error( 'invalid_user_permission_edit_others_posts', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
954
	}
955
956
	/**
957
	 * Contextual HTTP error code for authorization failure.
958
	 *
959
	 * Taken from rest_authorization_required_code() in WP-API plugin until is added to core.
960
	 * @see https://github.com/WP-API/WP-API/commit/7ba0ae6fe4f605d5ffe4ee85b1cd5f9fb46900a6
961
	 *
962
	 * @since 4.3.0
963
	 *
964
	 * @return int
965
	 */
966
	public static function rest_authorization_required_code() {
967
		return is_user_logged_in() ? 403 : 401;
968
	}
969
970
	/**
971
	 * Get connection status for this Jetpack site.
972
	 *
973
	 * @since 4.3.0
974
	 *
975
	 * @return bool True if site is connected
976
	 */
977
	public static function jetpack_connection_status() {
978
		$status = new Status();
979
		return rest_ensure_response( array(
980
			'isActive'     => Jetpack::is_active(),
981
			'isStaging'    => $status->is_staging_site(),
982
			'isRegistered' => Jetpack::connection()->is_registered(),
983
			'devMode'      => array(
984
				'isActive' => $status->is_development_mode(),
985
				'constant' => defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG,
986
				'url'      => site_url() && false === strpos( site_url(), '.' ),
987
				'filter'   => apply_filters( 'jetpack_development_mode', false ),
988
			),
989
			)
990
		);
991
	}
992
993
	/**
994
	 * Test connection status for this Jetpack site.
995
	 *
996
	 * @since 6.8.0
997
	 *
998
	 * @return array|WP_Error WP_Error returned if connection test does not succeed.
999
	 */
1000
	public static function jetpack_connection_test() {
1001
		jetpack_require_lib( 'debugger' );
1002
		$cxntests = new Jetpack_Cxn_Tests();
1003
1004
		if ( $cxntests->pass() ) {
1005
			return rest_ensure_response(
1006
				array(
1007
					'code'    => 'success',
1008
					'message' => __( 'All connection tests passed.', 'jetpack' ),
1009
				)
1010
			);
1011
		} else {
1012
			return $cxntests->output_fails_as_wp_error();
1013
		}
1014
	}
1015
1016
	/**
1017
	 * Test connection permission check method.
1018
	 *
1019
	 * @since 7.1.0
1020
	 *
1021
	 * @return bool
1022
	 */
1023
	public static function view_jetpack_connection_test_check() {
1024
		if ( ! isset( $_GET['signature'], $_GET['timestamp'], $_GET['url'] ) ) {
1025
			return false;
1026
		}
1027
		$signature = base64_decode( $_GET['signature'] );
1028
1029
		$signature_data = wp_json_encode(
1030
			array(
1031
				'rest_route' => $_GET['rest_route'],
1032
				'timestamp' => intval( $_GET['timestamp'] ),
1033
				'url' => wp_unslash( $_GET['url'] ),
1034
			)
1035
		);
1036
1037
		if (
1038
			! function_exists( 'openssl_verify' )
1039
			|| ! openssl_verify(
1040
				$signature_data,
1041
				$signature,
1042
				JETPACK__DEBUGGER_PUBLIC_KEY
1043
			)
1044
		) {
1045
			return false;
1046
		}
1047
1048
		// signature timestamp must be within 5min of current time
1049
		if ( abs( time() - intval( $_GET['timestamp'] ) ) > 300 ) {
1050
			return false;
1051
		}
1052
1053
		return true;
1054
	}
1055
1056
	/**
1057
	 * Test connection status for this Jetpack site, encrypt the results for decryption by a third-party.
1058
	 *
1059
	 * @since 7.1.0
1060
	 *
1061
	 * @return array|mixed|object|WP_Error
1062
	 */
1063
	public static function jetpack_connection_test_for_external() {
1064
		// Since we are running this test for inclusion in the WP.com testing suite, let's not try to run them as part of these results.
1065
		add_filter( 'jetpack_debugger_run_self_test', '__return_false' );
1066
		jetpack_require_lib( 'debugger' );
1067
		$cxntests = new Jetpack_Cxn_Tests();
1068
1069
		if ( $cxntests->pass() ) {
1070
			$result = array(
1071
				'code'    => 'success',
1072
				'message' => __( 'All connection tests passed.', 'jetpack' ),
1073
			);
1074
		} else {
1075
			$error  = $cxntests->output_fails_as_wp_error(); // Using this so the output is similar both ways.
1076
			$errors = array();
1077
1078
			// Borrowed from WP_REST_Server::error_to_response().
1079
			foreach ( (array) $error->errors as $code => $messages ) {
1080
				foreach ( (array) $messages as $message ) {
1081
					$errors[] = array(
1082
						'code'    => $code,
1083
						'message' => $message,
1084
						'data'    => $error->get_error_data( $code ),
1085
					);
1086
				}
1087
			}
1088
1089
			$result = $errors[0];
1090
			if ( count( $errors ) > 1 ) {
1091
				// Remove the primary error.
1092
				array_shift( $errors );
1093
				$result['additional_errors'] = $errors;
1094
			}
1095
		}
1096
1097
		$result = wp_json_encode( $result );
1098
1099
		$encrypted = $cxntests->encrypt_string_for_wpcom( $result );
1100
1101
		if ( ! $encrypted || ! is_array( $encrypted ) ) {
1102
			return rest_ensure_response(
1103
				array(
1104
					'code'    => 'action_required',
1105
					'message' => 'Please request results from the in-plugin debugger',
1106
				)
1107
			);
1108
		}
1109
1110
		return rest_ensure_response(
1111
			array(
1112
				'code'  => 'response',
1113
				'debug' => array(
1114
					'data' => $encrypted['data'],
1115
					'key'  => $encrypted['key'],
1116
				),
1117
			)
1118
		);
1119
	}
1120
1121
	public static function rewind_data() {
1122
		$site_id = Jetpack_Options::get_option( 'id' );
1123
1124
		if ( ! $site_id ) {
1125
			return new WP_Error( 'site_id_missing' );
1126
		}
1127
1128
		$response = Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d/rewind', $site_id ) .'?force=wpcom', '2', array(), null, 'wpcom' );
1129
1130
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
1131
			return new WP_Error( 'rewind_data_fetch_failed' );
1132
		}
1133
1134
		$body = wp_remote_retrieve_body( $response );
1135
1136
		return json_decode( $body );
1137
	}
1138
1139
	/**
1140
	 * Get rewind data
1141
	 *
1142
	 * @since 5.7.0
1143
	 *
1144
	 * @return array Array of rewind properties.
1145
	 */
1146
	public static function get_rewind_data() {
1147
		$rewind_data = self::rewind_data();
1148
1149 View Code Duplication
		if ( ! is_wp_error( $rewind_data ) ) {
1150
			return rest_ensure_response( array(
1151
					'code' => 'success',
1152
					'message' => esc_html__( 'Backup & Scan data correctly received.', 'jetpack' ),
1153
					'data' => wp_json_encode( $rewind_data ),
1154
				)
1155
			);
1156
		}
1157
1158
		if ( $rewind_data->get_error_code() === 'rewind_data_fetch_failed' ) {
1159
			return new WP_Error( 'rewind_data_fetch_failed', esc_html__( 'Failed fetching rewind data. Try again later.', 'jetpack' ), array( 'status' => 400 ) );
1160
		}
1161
1162 View Code Duplication
		if ( $rewind_data->get_error_code() === 'site_id_missing' ) {
1163
			return new WP_Error( 'site_id_missing', esc_html__( 'The ID of this site does not exist.', 'jetpack' ), array( 'status' => 404 ) );
1164
		}
1165
1166
		return new WP_Error(
1167
			'error_get_rewind_data',
1168
			esc_html__( 'Could not retrieve Backup & Scan data.', 'jetpack' ),
1169
			array( 'status' => 500 )
1170
		);
1171
	}
1172
1173
	/**
1174
	 * Disconnects Jetpack from the WordPress.com Servers
1175
	 *
1176
	 * @uses Jetpack::disconnect();
1177
	 * @since 4.3.0
1178
	 *
1179
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1180
	 *
1181
	 * @return bool|WP_Error True if Jetpack successfully disconnected.
1182
	 */
1183 View Code Duplication
	public static function disconnect_site( $request ) {
1184
1185
		if ( ! isset( $request['isActive'] ) || $request['isActive'] !== false ) {
1186
			return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
1187
		}
1188
1189
		if ( Jetpack::is_active() ) {
1190
			Jetpack::disconnect();
1191
			return rest_ensure_response( array( 'code' => 'success' ) );
1192
		}
1193
1194
		return new WP_Error( 'disconnect_failed', esc_html__( 'Was not able to disconnect the site.  Please try again.', 'jetpack' ), array( 'status' => 400 ) );
1195
	}
1196
1197
	/**
1198
	 * Registers the Jetpack site
1199
	 *
1200
	 * @uses Jetpack::try_registration();
1201
	 * @since 7.7.0
1202
	 *
1203
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1204
	 *
1205
	 * @return bool|WP_Error True if Jetpack successfully registered
1206
	 */
1207
	public static function register_site( $request ) {
1208
		if ( ! wp_verify_nonce( $request->get_param( 'registration_nonce' ), 'jetpack-registration-nonce' ) ) {
1209
			return new WP_Error( 'invalid_nonce', __( 'Unable to verify your request.', 'jetpack' ), array( 'status' => 403 ) );
1210
		}
1211
1212
		$response = Jetpack::try_registration();
1213
1214
		if ( is_wp_error( $response ) ) {
1215
			return $response;
1216
		}
1217
1218
		return rest_ensure_response(
1219
			array(
1220
				'authorizeUrl' => Jetpack::build_authorize_url( false, true )
1221
			) );
1222
	}
1223
1224
	/**
1225
	 * Gets a new connect raw URL with fresh nonce.
1226
	 *
1227
	 * @uses Jetpack::disconnect();
1228
	 * @since 4.3.0
1229
	 *
1230
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1231
	 *
1232
	 * @return string|WP_Error A raw URL if the connection URL could be built; error message otherwise.
1233
	 */
1234
	public static function build_connect_url() {
1235
		$url = Jetpack::init()->build_connect_url( true, false, false );
1236
		if ( $url ) {
1237
			return rest_ensure_response( $url );
1238
		}
1239
1240
		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 ) );
1241
	}
1242
1243
	/**
1244
	 * Get miscellaneous user data related to the connection. Similar data available in old "My Jetpack".
1245
	 * Information about the master/primary user.
1246
	 * Information about the current user.
1247
	 *
1248
	 * @since 4.3.0
1249
	 *
1250
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1251
	 *
1252
	 * @return object
1253
	 */
1254
	public static function get_user_connection_data() {
1255
		require_once( JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class.jetpack-react-page.php' );
1256
1257
		$response = array(
1258
//			'othersLinked' => Jetpack::get_other_linked_admins(),
1259
			'currentUser'  => jetpack_current_user_data(),
1260
		);
1261
		return rest_ensure_response( $response );
1262
	}
1263
1264
	/**
1265
	 * Change the master user.
1266
	 *
1267
	 * @since 6.2.0
1268
	 *
1269
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1270
	 *
1271
	 * @return bool|WP_Error True if owner successfully changed.
1272
	 */
1273
	public static function set_connection_owner( $request ) {
1274
		if ( ! isset( $request['owner'] ) ) {
1275
			return new WP_Error(
1276
				'invalid_param',
1277
				esc_html__( 'Invalid Parameter', 'jetpack' ),
1278
				array( 'status' => 400 )
1279
			);
1280
		}
1281
1282
		$new_owner_id = $request['owner'];
1283
		if ( ! user_can( $new_owner_id, 'administrator' ) ) {
1284
			return new WP_Error(
1285
				'new_owner_not_admin',
1286
				esc_html__( 'New owner is not admin', 'jetpack' ),
1287
				array( 'status' => 400 )
1288
			);
1289
		}
1290
1291
		if ( $new_owner_id === get_current_user_id() ) {
1292
			return new WP_Error(
1293
				'new_owner_is_current_user',
1294
				esc_html__( 'New owner is same as current user', 'jetpack' ),
1295
				array( 'status' => 400 )
1296
			);
1297
		}
1298
1299
		if ( ! Jetpack::is_user_connected( $new_owner_id ) ) {
1300
			return new WP_Error(
1301
				'new_owner_not_connected',
1302
				esc_html__( 'New owner is not connected', 'jetpack' ),
1303
				array( 'status' => 400 )
1304
			);
1305
		}
1306
1307
		// Update the master user in Jetpack
1308
		$updated = Jetpack_Options::update_option( 'master_user', $new_owner_id );
1309
1310
		// Notify WPCOM about the master user change
1311
		$xml = new Jetpack_IXR_Client( array(
1312
			'user_id' => get_current_user_id(),
1313
		) );
1314
		$xml->query( 'jetpack.switchBlogOwner', array(
1315
			'new_blog_owner' => $new_owner_id,
1316
		) );
1317
1318
		if ( $updated && ! $xml->isError() ) {
1319
1320
			// Track it
1321
			if ( class_exists( 'Automattic\Jetpack\Tracking' ) ) {
1322
				$tracking = new Tracking();
1323
				$tracking->record_user_event( 'set_connection_owner_success' );
1324
			}
1325
1326
			return rest_ensure_response(
1327
				array(
1328
					'code' => 'success',
1329
				)
1330
			);
1331
		}
1332
		return new WP_Error(
1333
			'error_setting_new_owner',
1334
			esc_html__( 'Could not confirm new owner.', 'jetpack' ),
1335
			array( 'status' => 500 )
1336
		);
1337
	}
1338
1339
	/**
1340
	 * Unlinks current user from the WordPress.com Servers.
1341
	 *
1342
	 * @since 4.3.0
1343
	 * @uses  Automattic\Jetpack\Connection\Manager::disconnect_user
1344
	 *
1345
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1346
	 *
1347
	 * @return bool|WP_Error True if user successfully unlinked.
1348
	 */
1349 View Code Duplication
	public static function unlink_user( $request ) {
1350
1351
		if ( ! isset( $request['linked'] ) || $request['linked'] !== false ) {
1352
			return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
1353
		}
1354
1355
		if ( Connection_Manager::disconnect_user() ) {
1356
			return rest_ensure_response(
1357
				array(
1358
					'code' => 'success'
1359
				)
1360
			);
1361
		}
1362
1363
		return new WP_Error( 'unlink_user_failed', esc_html__( 'Was not able to unlink the user.  Please try again.', 'jetpack' ), array( 'status' => 400 ) );
1364
	}
1365
1366
	/**
1367
	 * Gets current user's tracking settings.
1368
	 *
1369
	 * @since 6.0.0
1370
	 *
1371
	 * @param  WP_REST_Request $request The request sent to the WP REST API.
1372
	 *
1373
	 * @return WP_REST_Response|WP_Error Response, else error.
1374
	 */
1375 View Code Duplication
	public static function get_user_tracking_settings( $request ) {
1376
		if ( ! Jetpack::is_user_connected() ) {
1377
			$response = array(
1378
				'tracks_opt_out' => true, // Default to opt-out if not connected to wp.com.
1379
			);
1380
		} else {
1381
			$response = Client::wpcom_json_api_request_as_user(
1382
				'/jetpack-user-tracking',
1383
				'v2',
1384
				array(
1385
					'method'  => 'GET',
1386
					'headers' => array(
1387
						'X-Forwarded-For' => Jetpack::current_user_ip( true ),
1388
					),
1389
				)
1390
			);
1391
			if ( ! is_wp_error( $response ) ) {
1392
				$response = json_decode( wp_remote_retrieve_body( $response ), true );
1393
			}
1394
		}
1395
1396
		return rest_ensure_response( $response );
1397
	}
1398
1399
	/**
1400
	 * Updates current user's tracking settings.
1401
	 *
1402
	 * @since 6.0.0
1403
	 *
1404
	 * @param  WP_REST_Request $request The request sent to the WP REST API.
1405
	 *
1406
	 * @return WP_REST_Response|WP_Error Response, else error.
1407
	 */
1408 View Code Duplication
	public static function update_user_tracking_settings( $request ) {
1409
		if ( ! Jetpack::is_user_connected() ) {
1410
			$response = array(
1411
				'tracks_opt_out' => true, // Default to opt-out if not connected to wp.com.
1412
			);
1413
		} else {
1414
			$response = Client::wpcom_json_api_request_as_user(
1415
				'/jetpack-user-tracking',
1416
				'v2',
1417
				array(
1418
					'method'  => 'PUT',
1419
					'headers' => array(
1420
						'Content-Type'    => 'application/json',
1421
						'X-Forwarded-For' => Jetpack::current_user_ip( true ),
1422
					),
1423
				),
1424
				wp_json_encode( $request->get_params() )
1425
			);
1426
			if ( ! is_wp_error( $response ) ) {
1427
				$response = json_decode( wp_remote_retrieve_body( $response ), true );
1428
			}
1429
		}
1430
1431
		return rest_ensure_response( $response );
1432
	}
1433
1434
	/**
1435
	 * Fetch site data from .com including the site's current plan.
1436
	 *
1437
	 * @since 5.5.0
1438
	 *
1439
	 * @return array Array of site properties.
1440
	 */
1441
	public static function site_data() {
1442
		$site_id = Jetpack_Options::get_option( 'id' );
1443
1444
		if ( ! $site_id ) {
1445
			new WP_Error( 'site_id_missing' );
1446
		}
1447
1448
		$args = array( 'headers' => array() );
1449
1450
		// Allow use a store sandbox. Internal ref: PCYsg-IA-p2.
1451
		if ( isset( $_COOKIE ) && isset( $_COOKIE['store_sandbox'] ) ) {
1452
			$secret                    = $_COOKIE['store_sandbox'];
1453
			$args['headers']['Cookie'] = "store_sandbox=$secret;";
1454
		}
1455
1456
		$response = Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d', $site_id ) .'?force=wpcom', '1.1', $args );
1457
1458
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
1459
			return new WP_Error( 'site_data_fetch_failed' );
1460
		}
1461
1462
		Jetpack_Plan::update_from_sites_response( $response );
1463
1464
		$body = wp_remote_retrieve_body( $response );
1465
1466
		return json_decode( $body );
1467
	}
1468
	/**
1469
	 * Get site data, including for example, the site's current plan.
1470
	 *
1471
	 * @since 4.3.0
1472
	 *
1473
	 * @return array Array of site properties.
1474
	 */
1475
	public static function get_site_data() {
1476
		$site_data = self::site_data();
1477
1478 View Code Duplication
		if ( ! is_wp_error( $site_data ) ) {
1479
			return rest_ensure_response( array(
1480
					'code' => 'success',
1481
					'message' => esc_html__( 'Site data correctly received.', 'jetpack' ),
1482
					'data' => json_encode( $site_data ),
1483
				)
1484
			);
1485
		}
1486 View Code Duplication
		if ( $site_data->get_error_code() === 'site_data_fetch_failed' ) {
1487
			return new WP_Error( 'site_data_fetch_failed', esc_html__( 'Failed fetching site data. Try again later.', 'jetpack' ), array( 'status' => 400 ) );
1488
		}
1489
1490
		if ( $site_data->get_error_code() === 'site_id_missing' ) {
1491
			return new WP_Error( 'site_id_missing', esc_html__( 'The ID of this site does not exist.', 'jetpack' ), array( 'status' => 404 ) );
1492
		}
1493
	}
1494
1495
	/**
1496
	 * Fetch AL data for this site and return it.
1497
	 *
1498
	 * @since 7.4
1499
	 *
1500
	 * @return array|WP_Error
1501
	 */
1502
	public static function get_site_activity() {
1503
		$site_id = Jetpack_Options::get_option( 'id' );
1504
1505
		if ( ! $site_id ) {
1506
			return new WP_Error(
1507
				'site_id_missing',
1508
				esc_html__( 'Site ID is missing.', 'jetpack' ),
1509
				array( 'status' => 400 )
1510
			);
1511
		}
1512
1513
		$response = Client::wpcom_json_api_request_as_user( "/sites/$site_id/activity", '2', array(
1514
			'method'  => 'GET',
1515
			'headers' => array(
1516
				'X-Forwarded-For' => Jetpack::current_user_ip( true ),
1517
			),
1518
		), null, 'wpcom' );
1519
		$response_code = wp_remote_retrieve_response_code( $response );
1520
1521 View Code Duplication
		if ( 200 !== $response_code ) {
1522
			return new WP_Error(
1523
				'activity_fetch_failed',
1524
				esc_html__( 'Could not retrieve site activity.', 'jetpack' ),
1525
				array( 'status' => $response_code )
1526
			);
1527
		}
1528
1529
		$data = json_decode( wp_remote_retrieve_body( $response ) );
1530
1531
		if ( ! isset( $data->current->orderedItems ) ) {
1532
			return new WP_Error(
1533
				'activity_not_found',
1534
				esc_html__( 'No activity found', 'jetpack' ),
1535
				array( 'status' => 204 ) // no content
1536
			);
1537
		}
1538
1539
		return rest_ensure_response( array(
1540
				'code' => 'success',
1541
				'data' => $data->current->orderedItems,
1542
			)
1543
		);
1544
	}
1545
1546
	/**
1547
	 * Handles identity crisis mitigation, confirming safe mode for this site.
1548
	 *
1549
	 * @since 4.4.0
1550
	 *
1551
	 * @return bool | WP_Error True if option is properly set.
1552
	 */
1553
	public static function confirm_safe_mode() {
1554
		$updated = Jetpack_Options::update_option( 'safe_mode_confirmed', true );
1555
		if ( $updated ) {
1556
			return rest_ensure_response(
1557
				array(
1558
					'code' => 'success'
1559
				)
1560
			);
1561
		}
1562
		return new WP_Error(
1563
			'error_setting_jetpack_safe_mode',
1564
			esc_html__( 'Could not confirm safe mode.', 'jetpack' ),
1565
			array( 'status' => 500 )
1566
		);
1567
	}
1568
1569
	/**
1570
	 * Handles identity crisis mitigation, migrating stats and subscribers from old url to this, new url.
1571
	 *
1572
	 * @since 4.4.0
1573
	 *
1574
	 * @return bool | WP_Error True if option is properly set.
1575
	 */
1576
	public static function migrate_stats_and_subscribers() {
1577
		if ( Jetpack_Options::get_option( 'sync_error_idc' ) && ! Jetpack_Options::delete_option( 'sync_error_idc' ) ) {
1578
			return new WP_Error(
1579
				'error_deleting_sync_error_idc',
1580
				esc_html__( 'Could not delete sync error option.', 'jetpack' ),
1581
				array( 'status' => 500 )
1582
			);
1583
		}
1584
1585
		if ( Jetpack_Options::get_option( 'migrate_for_idc' ) || Jetpack_Options::update_option( 'migrate_for_idc', true ) ) {
1586
			return rest_ensure_response(
1587
				array(
1588
					'code' => 'success'
1589
				)
1590
			);
1591
		}
1592
		return new WP_Error(
1593
			'error_setting_jetpack_migrate',
1594
			esc_html__( 'Could not confirm migration.', 'jetpack' ),
1595
			array( 'status' => 500 )
1596
		);
1597
	}
1598
1599
	/**
1600
	 * This IDC resolution will disconnect the site and re-connect to a completely new
1601
	 * and separate shadow site than the original.
1602
	 *
1603
	 * It will first will disconnect the site without phoning home as to not disturb the production site.
1604
	 * It then builds a fresh connection URL and sends it back along with the response.
1605
	 *
1606
	 * @since 4.4.0
1607
	 * @return bool|WP_Error
1608
	 */
1609
	public static function start_fresh_connection() {
1610
		// First clear the options / disconnect.
1611
		Jetpack::disconnect();
1612
		return self::build_connect_url();
1613
	}
1614
1615
	/**
1616
	 * Reset Jetpack options
1617
	 *
1618
	 * @since 4.3.0
1619
	 *
1620
	 * @param WP_REST_Request $request {
1621
	 *     Array of parameters received by request.
1622
	 *
1623
	 *     @type string $options Available options to reset are options|modules
1624
	 * }
1625
	 *
1626
	 * @return bool|WP_Error True if options were reset. Otherwise, a WP_Error instance with the corresponding error.
1627
	 */
1628
	public static function reset_jetpack_options( $request ) {
1629
1630
		if ( ! isset( $request['reset'] ) || $request['reset'] !== true ) {
1631
			return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
1632
		}
1633
1634
		if ( isset( $request['options'] ) ) {
1635
			$data = $request['options'];
1636
1637
			switch( $data ) {
1638
				case ( 'options' ) :
1639
					$options_to_reset = Jetpack::get_jetpack_options_for_reset();
1640
1641
					// Reset the Jetpack options
1642
					foreach ( $options_to_reset['jp_options'] as $option_to_reset ) {
1643
						Jetpack_Options::delete_option( $option_to_reset );
1644
					}
1645
1646
					foreach ( $options_to_reset['wp_options'] as $option_to_reset ) {
1647
						delete_option( $option_to_reset );
1648
					}
1649
1650
					// Reset to default modules
1651
					$default_modules = Jetpack::get_default_modules();
1652
					Jetpack::update_active_modules( $default_modules );
1653
1654
					return rest_ensure_response( array(
1655
						'code' 	  => 'success',
1656
						'message' => esc_html__( 'Jetpack options reset.', 'jetpack' ),
1657
					) );
1658
					break;
1659
1660
				case 'modules':
1661
					$default_modules = Jetpack::get_default_modules();
1662
					Jetpack::update_active_modules( $default_modules );
1663
					return rest_ensure_response( array(
1664
						'code' 	  => 'success',
1665
						'message' => esc_html__( 'Modules reset to default.', 'jetpack' ),
1666
					) );
1667
					break;
1668
1669
				default:
1670
					return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
1671
			}
1672
		}
1673
1674
		return new WP_Error( 'required_param', esc_html__( 'Missing parameter "type".', 'jetpack' ), array( 'status' => 404 ) );
1675
	}
1676
1677
	/**
1678
	 * Get the query parameters to update module options or general settings.
1679
	 *
1680
	 * @since 4.3.0
1681
	 * @since 4.4.0 Accepts a $selector parameter.
1682
	 *
1683
	 * @param string $selector Selects a set of options to update, Can be empty, a module slug or 'any'.
1684
	 *
1685
	 * @return array
1686
	 */
1687
	public static function get_updateable_parameters( $selector = '' ) {
1688
		$parameters = array(
1689
			'context'     => array(
1690
				'default' => 'edit',
1691
			),
1692
		);
1693
1694
		return array_merge( $parameters, self::get_updateable_data_list( $selector ) );
1695
	}
1696
1697
	/**
1698
	 * Returns a list of module options or general settings that can be updated.
1699
	 *
1700
	 * @since 4.3.0
1701
	 * @since 4.4.0 Accepts 'any' as a parameter which will make it return the entire list.
1702
	 *
1703
	 * @param string|array $selector Module slug, 'any', or an array of parameters.
1704
	 *                               If empty, it's assumed we're updating a module and we'll try to get its slug.
1705
	 *                               If 'any' the full list is returned.
1706
	 *                               If it's an array of parameters, includes the elements by matching keys.
1707
	 *
1708
	 * @return array
1709
	 */
1710
	public static function get_updateable_data_list( $selector = '' ) {
1711
1712
		$options = array(
1713
1714
			// Carousel
1715
			'carousel_background_color' => array(
1716
				'description'       => esc_html__( 'Color scheme.', 'jetpack' ),
1717
				'type'              => 'string',
1718
				'default'           => 'black',
1719
				'enum'              => array(
1720
					'black',
1721
					'white',
1722
				),
1723
				'enum_labels' => array(
1724
					'black' => esc_html__( 'Black', 'jetpack' ),
1725
					'white' => esc_html__( 'White', 'jetpack' ),
1726
				),
1727
				'validate_callback' => __CLASS__ . '::validate_list_item',
1728
				'jp_group'          => 'carousel',
1729
			),
1730
			'carousel_display_exif' => array(
1731
				'description'       => wp_kses( sprintf( __( 'Show photo metadata (<a href="https://en.wikipedia.org/wiki/Exchangeable_image_file_format" target="_blank">Exif</a>) in carousel, when available.', 'jetpack' ) ), array( 'a' => array( 'href' => true, 'target' => true ) ) ),
1732
				'type'              => 'boolean',
1733
				'default'           => 0,
1734
				'validate_callback' => __CLASS__ . '::validate_boolean',
1735
				'jp_group'          => 'carousel',
1736
			),
1737
1738
			// Comments
1739
			'highlander_comment_form_prompt' => array(
1740
				'description'       => esc_html__( 'Greeting Text', 'jetpack' ),
1741
				'type'              => 'string',
1742
				'default'           => esc_html__( 'Leave a Reply', 'jetpack' ),
1743
				'sanitize_callback' => 'sanitize_text_field',
1744
				'jp_group'          => 'comments',
1745
			),
1746
			'jetpack_comment_form_color_scheme' => array(
1747
				'description'       => esc_html__( "Color scheme", 'jetpack' ),
1748
				'type'              => 'string',
1749
				'default'           => 'light',
1750
				'enum'              => array(
1751
					'light',
1752
					'dark',
1753
					'transparent',
1754
				),
1755
				'enum_labels' => array(
1756
					'light'       => esc_html__( 'Light', 'jetpack' ),
1757
					'dark'        => esc_html__( 'Dark', 'jetpack' ),
1758
					'transparent' => esc_html__( 'Transparent', 'jetpack' ),
1759
				),
1760
				'validate_callback' => __CLASS__ . '::validate_list_item',
1761
				'jp_group'          => 'comments',
1762
			),
1763
1764
			// Custom Content Types
1765
			'jetpack_portfolio' => array(
1766
				'description'       => esc_html__( 'Enable or disable Jetpack portfolio post type.', 'jetpack' ),
1767
				'type'              => 'boolean',
1768
				'default'           => 0,
1769
				'validate_callback' => __CLASS__ . '::validate_boolean',
1770
				'jp_group'          => 'custom-content-types',
1771
			),
1772
			'jetpack_portfolio_posts_per_page' => array(
1773
				'description'       => esc_html__( 'Number of entries to show at most in Portfolio pages.', 'jetpack' ),
1774
				'type'              => 'integer',
1775
				'default'           => 10,
1776
				'validate_callback' => __CLASS__ . '::validate_posint',
1777
				'jp_group'          => 'custom-content-types',
1778
			),
1779
			'jetpack_testimonial' => array(
1780
				'description'       => esc_html__( 'Enable or disable Jetpack testimonial post type.', 'jetpack' ),
1781
				'type'              => 'boolean',
1782
				'default'           => 0,
1783
				'validate_callback' => __CLASS__ . '::validate_boolean',
1784
				'jp_group'          => 'custom-content-types',
1785
			),
1786
			'jetpack_testimonial_posts_per_page' => array(
1787
				'description'       => esc_html__( 'Number of entries to show at most in Testimonial pages.', 'jetpack' ),
1788
				'type'              => 'integer',
1789
				'default'           => 10,
1790
				'validate_callback' => __CLASS__ . '::validate_posint',
1791
				'jp_group'          => 'custom-content-types',
1792
			),
1793
1794
			// Galleries
1795
			'tiled_galleries' => array(
1796
				'description'       => esc_html__( 'Display all your gallery pictures in a cool mosaic.', 'jetpack' ),
1797
				'type'              => 'boolean',
1798
				'default'           => 0,
1799
				'validate_callback' => __CLASS__ . '::validate_boolean',
1800
				'jp_group'          => 'tiled-gallery',
1801
			),
1802
1803
			'gravatar_disable_hovercards' => array(
1804
				'description'       => esc_html__( "View people's profiles when you mouse over their Gravatars", 'jetpack' ),
1805
				'type'              => 'string',
1806
				'default'           => 'enabled',
1807
				// Not visible. This is used as the checkbox value.
1808
				'enum'              => array(
1809
					'enabled',
1810
					'disabled',
1811
				),
1812
				'enum_labels' => array(
1813
					'enabled'  => esc_html__( 'Enabled', 'jetpack' ),
1814
					'disabled' => esc_html__( 'Disabled', 'jetpack' ),
1815
				),
1816
				'validate_callback' => __CLASS__ . '::validate_list_item',
1817
				'jp_group'          => 'gravatar-hovercards',
1818
			),
1819
1820
			// Infinite Scroll
1821
			'infinite_scroll' => array(
1822
				'description'       => esc_html__( 'To infinity and beyond', 'jetpack' ),
1823
				'type'              => 'boolean',
1824
				'default'           => 1,
1825
				'validate_callback' => __CLASS__ . '::validate_boolean',
1826
				'jp_group'          => 'infinite-scroll',
1827
			),
1828
			'infinite_scroll_google_analytics' => array(
1829
				'description'       => esc_html__( 'Use Google Analytics with Infinite Scroll', 'jetpack' ),
1830
				'type'              => 'boolean',
1831
				'default'           => 0,
1832
				'validate_callback' => __CLASS__ . '::validate_boolean',
1833
				'jp_group'          => 'infinite-scroll',
1834
			),
1835
1836
			// Likes
1837
			'wpl_default' => array(
1838
				'description'       => esc_html__( 'WordPress.com Likes are', 'jetpack' ),
1839
				'type'              => 'string',
1840
				'default'           => 'on',
1841
				'enum'              => array(
1842
					'on',
1843
					'off',
1844
				),
1845
				'enum_labels' => array(
1846
					'on'  => esc_html__( 'On for all posts', 'jetpack' ),
1847
					'off' => esc_html__( 'Turned on per post', 'jetpack' ),
1848
				),
1849
				'validate_callback' => __CLASS__ . '::validate_list_item',
1850
				'jp_group'          => 'likes',
1851
			),
1852
			'social_notifications_like' => array(
1853
				'description'       => esc_html__( 'Send email notification when someone likes a post', 'jetpack' ),
1854
				'type'              => 'boolean',
1855
				'default'           => 1,
1856
				'validate_callback' => __CLASS__ . '::validate_boolean',
1857
				'jp_group'          => 'likes',
1858
			),
1859
1860
			// Markdown
1861
			'wpcom_publish_comments_with_markdown' => array(
1862
				'description'       => esc_html__( 'Use Markdown for comments.', 'jetpack' ),
1863
				'type'              => 'boolean',
1864
				'default'           => 0,
1865
				'validate_callback' => __CLASS__ . '::validate_boolean',
1866
				'jp_group'          => 'markdown',
1867
			),
1868
			'wpcom_publish_posts_with_markdown' => array(
1869
				'description'       => esc_html__( 'Use Markdown for posts.', 'jetpack' ),
1870
				'type'              => 'boolean',
1871
				'default'           => 0,
1872
				'validate_callback' => __CLASS__ . '::validate_boolean',
1873
				'jp_group'          => 'markdown',
1874
			),
1875
1876
			// Mobile Theme
1877
			'wp_mobile_excerpt' => array(
1878
				'description'       => esc_html__( 'Excerpts', 'jetpack' ),
1879
				'type'              => 'boolean',
1880
				'default'           => 0,
1881
				'validate_callback' => __CLASS__ . '::validate_boolean',
1882
				'jp_group'          => 'minileven',
1883
			),
1884
			'wp_mobile_featured_images' => array(
1885
				'description'       => esc_html__( 'Featured Images', 'jetpack' ),
1886
				'type'              => 'boolean',
1887
				'default'           => 0,
1888
				'validate_callback' => __CLASS__ . '::validate_boolean',
1889
				'jp_group'          => 'minileven',
1890
			),
1891
			'wp_mobile_app_promos' => array(
1892
				'description'       => esc_html__( 'Show a promo for the WordPress mobile apps in the footer of the mobile theme.', 'jetpack' ),
1893
				'type'              => 'boolean',
1894
				'default'           => 0,
1895
				'validate_callback' => __CLASS__ . '::validate_boolean',
1896
				'jp_group'          => 'minileven',
1897
			),
1898
1899
			// Monitor
1900
			'monitor_receive_notifications' => array(
1901
				'description'       => esc_html__( 'Receive Monitor Email Notifications.', 'jetpack' ),
1902
				'type'              => 'boolean',
1903
				'default'           => 0,
1904
				'validate_callback' => __CLASS__ . '::validate_boolean',
1905
				'jp_group'          => 'monitor',
1906
			),
1907
1908
			// Post by Email
1909
			'post_by_email_address' => array(
1910
				'description'       => esc_html__( 'Email Address', 'jetpack' ),
1911
				'type'              => 'string',
1912
				'default'           => 'noop',
1913
				'enum'              => array(
1914
					'noop',
1915
					'create',
1916
					'regenerate',
1917
					'delete',
1918
				),
1919
				'enum_labels' => array(
1920
					'noop'       => '',
1921
					'create'     => esc_html__( 'Create Post by Email address', 'jetpack' ),
1922
					'regenerate' => esc_html__( 'Regenerate Post by Email address', 'jetpack' ),
1923
					'delete'     => esc_html__( 'Delete Post by Email address', 'jetpack' ),
1924
				),
1925
				'validate_callback' => __CLASS__ . '::validate_list_item',
1926
				'jp_group'          => 'post-by-email',
1927
			),
1928
1929
			// Protect
1930
			'jetpack_protect_key' => array(
1931
				'description'       => esc_html__( 'Protect API key', 'jetpack' ),
1932
				'type'              => 'string',
1933
				'default'           => '',
1934
				'validate_callback' => __CLASS__ . '::validate_alphanum',
1935
				'jp_group'          => 'protect',
1936
			),
1937
			'jetpack_protect_global_whitelist' => array(
1938
				'description'       => esc_html__( 'Protect global whitelist', 'jetpack' ),
1939
				'type'              => 'string',
1940
				'default'           => '',
1941
				'validate_callback' => __CLASS__ . '::validate_string',
1942
				'sanitize_callback' => 'esc_textarea',
1943
				'jp_group'          => 'protect',
1944
			),
1945
1946
			// Sharing
1947
			'sharing_services' => array(
1948
				'description'       => esc_html__( 'Enabled Services and those hidden behind a button', 'jetpack' ),
1949
				'type'              => 'object',
1950
				'default'           => array(
1951
					'visible' => array( 'twitter', 'facebook', 'google-plus-1' ),
1952
					'hidden'  => array(),
1953
				),
1954
				'validate_callback' => __CLASS__ . '::validate_services',
1955
				'jp_group'          => 'sharedaddy',
1956
			),
1957
			'button_style' => array(
1958
				'description'       => esc_html__( 'Button Style', 'jetpack' ),
1959
				'type'              => 'string',
1960
				'default'           => 'icon',
1961
				'enum'              => array(
1962
					'icon-text',
1963
					'icon',
1964
					'text',
1965
					'official',
1966
				),
1967
				'enum_labels' => array(
1968
					'icon-text' => esc_html__( 'Icon + text', 'jetpack' ),
1969
					'icon'      => esc_html__( 'Icon only', 'jetpack' ),
1970
					'text'      => esc_html__( 'Text only', 'jetpack' ),
1971
					'official'  => esc_html__( 'Official buttons', 'jetpack' ),
1972
				),
1973
				'validate_callback' => __CLASS__ . '::validate_list_item',
1974
				'jp_group'          => 'sharedaddy',
1975
			),
1976
			'sharing_label' => array(
1977
				'description'       => esc_html__( 'Sharing Label', 'jetpack' ),
1978
				'type'              => 'string',
1979
				'default'           => '',
1980
				'validate_callback' => __CLASS__ . '::validate_string',
1981
				'sanitize_callback' => 'esc_html',
1982
				'jp_group'          => 'sharedaddy',
1983
			),
1984
			'show' => array(
1985
				'description'       => esc_html__( 'Views where buttons are shown', 'jetpack' ),
1986
				'type'              => 'array',
1987
				'items'             => array(
1988
					'type' => 'string'
1989
				),
1990
				'default'           => array( 'post' ),
1991
				'validate_callback' => __CLASS__ . '::validate_sharing_show',
1992
				'jp_group'          => 'sharedaddy',
1993
			),
1994
			'jetpack-twitter-cards-site-tag' => array(
1995
				'description'       => esc_html__( "The Twitter username of the owner of this site's domain.", 'jetpack' ),
1996
				'type'              => 'string',
1997
				'default'           => '',
1998
				'validate_callback' => __CLASS__ . '::validate_twitter_username',
1999
				'sanitize_callback' => 'esc_html',
2000
				'jp_group'          => 'sharedaddy',
2001
			),
2002
			'sharedaddy_disable_resources' => array(
2003
				'description'       => esc_html__( 'Disable CSS and JS', 'jetpack' ),
2004
				'type'              => 'boolean',
2005
				'default'           => 0,
2006
				'validate_callback' => __CLASS__ . '::validate_boolean',
2007
				'jp_group'          => 'sharedaddy',
2008
			),
2009
			'custom' => array(
2010
				'description'       => esc_html__( 'Custom sharing services added by user.', 'jetpack' ),
2011
				'type'              => 'object',
2012
				'default'           => array(
2013
					'sharing_name' => '',
2014
					'sharing_url'  => '',
2015
					'sharing_icon' => '',
2016
				),
2017
				'validate_callback' => __CLASS__ . '::validate_custom_service',
2018
				'jp_group'          => 'sharedaddy',
2019
			),
2020
			// Not an option, but an action that can be perfomed on the list of custom services passing the service ID.
2021
			'sharing_delete_service' => array(
2022
				'description'       => esc_html__( 'Delete custom sharing service.', 'jetpack' ),
2023
				'type'              => 'string',
2024
				'default'           => '',
2025
				'validate_callback' => __CLASS__ . '::validate_custom_service_id',
2026
				'jp_group'          => 'sharedaddy',
2027
			),
2028
2029
			// SSO
2030
			'jetpack_sso_require_two_step' => array(
2031
				'description'       => esc_html__( 'Require Two-Step Authentication', 'jetpack' ),
2032
				'type'              => 'boolean',
2033
				'default'           => 0,
2034
				'validate_callback' => __CLASS__ . '::validate_boolean',
2035
				'jp_group'          => 'sso',
2036
			),
2037
			'jetpack_sso_match_by_email' => array(
2038
				'description'       => esc_html__( 'Match by Email', 'jetpack' ),
2039
				'type'              => 'boolean',
2040
				'default'           => 0,
2041
				'validate_callback' => __CLASS__ . '::validate_boolean',
2042
				'jp_group'          => 'sso',
2043
			),
2044
2045
			// Subscriptions
2046
			'stb_enabled' => array(
2047
				'description'       => esc_html__( "Show a <em>'follow blog'</em> option in the comment form", 'jetpack' ),
2048
				'type'              => 'boolean',
2049
				'default'           => 1,
2050
				'validate_callback' => __CLASS__ . '::validate_boolean',
2051
				'jp_group'          => 'subscriptions',
2052
			),
2053
			'stc_enabled' => array(
2054
				'description'       => esc_html__( "Show a <em>'follow comments'</em> option in the comment form", 'jetpack' ),
2055
				'type'              => 'boolean',
2056
				'default'           => 1,
2057
				'validate_callback' => __CLASS__ . '::validate_boolean',
2058
				'jp_group'          => 'subscriptions',
2059
			),
2060
			'social_notifications_subscribe' => array(
2061
				'description'       => esc_html__( 'Send email notification when someone follows my blog', 'jetpack' ),
2062
				'type'              => 'boolean',
2063
				'default'           => 0,
2064
				'validate_callback' => __CLASS__ . '::validate_boolean',
2065
				'jp_group'          => 'subscriptions',
2066
			),
2067
2068
			// Related Posts
2069
			'show_headline' => array(
2070
				'description'       => esc_html__( 'Highlight related content with a heading', 'jetpack' ),
2071
				'type'              => 'boolean',
2072
				'default'           => 1,
2073
				'validate_callback' => __CLASS__ . '::validate_boolean',
2074
				'jp_group'          => 'related-posts',
2075
			),
2076
			'show_thumbnails' => array(
2077
				'description'       => esc_html__( 'Show a thumbnail image where available', 'jetpack' ),
2078
				'type'              => 'boolean',
2079
				'default'           => 0,
2080
				'validate_callback' => __CLASS__ . '::validate_boolean',
2081
				'jp_group'          => 'related-posts',
2082
			),
2083
2084
			// Verification Tools
2085
			'google' => array(
2086
				'description'       => esc_html__( 'Google Search Console', 'jetpack' ),
2087
				'type'              => 'string',
2088
				'default'           => '',
2089
				'validate_callback' => __CLASS__ . '::validate_verification_service',
2090
				'jp_group'          => 'verification-tools',
2091
			),
2092
			'bing' => array(
2093
				'description'       => esc_html__( 'Bing Webmaster Center', 'jetpack' ),
2094
				'type'              => 'string',
2095
				'default'           => '',
2096
				'validate_callback' => __CLASS__ . '::validate_verification_service',
2097
				'jp_group'          => 'verification-tools',
2098
			),
2099
			'pinterest' => array(
2100
				'description'       => esc_html__( 'Pinterest Site Verification', 'jetpack' ),
2101
				'type'              => 'string',
2102
				'default'           => '',
2103
				'validate_callback' => __CLASS__ . '::validate_verification_service',
2104
				'jp_group'          => 'verification-tools',
2105
			),
2106
			'yandex' => array(
2107
				'description'       => esc_html__( 'Yandex Site Verification', 'jetpack' ),
2108
				'type'              => 'string',
2109
				'default'           => '',
2110
				'validate_callback' => __CLASS__ . '::validate_verification_service',
2111
				'jp_group'          => 'verification-tools',
2112
			),
2113
			'enable_header_ad' => array(
2114
				'description'        => esc_html__( 'Display an ad unit at the top of each page.', 'jetpack' ),
2115
				'type'               => 'boolean',
2116
				'default'            => 1,
2117
				'validate_callback'  => __CLASS__ . '::validate_boolean',
2118
				'jp_group'           => 'wordads',
2119
			),
2120
			'wordads_approved' => array(
2121
				'description'        => esc_html__( 'Is site approved for WordAds?', 'jetpack' ),
2122
				'type'               => 'boolean',
2123
				'default'            => 0,
2124
				'validate_callback'  => __CLASS__ . '::validate_boolean',
2125
				'jp_group'           => 'wordads',
2126
			),
2127
			'wordads_second_belowpost' => array(
2128
				'description'        => esc_html__( 'Display second ad below post?', 'jetpack' ),
2129
				'type'               => 'boolean',
2130
				'default'            => 1,
2131
				'validate_callback'  => __CLASS__ . '::validate_boolean',
2132
				'jp_group'           => 'wordads',
2133
			),
2134
			'wordads_display_front_page' => array(
2135
				'description'        => esc_html__( 'Display ads on the front page?', 'jetpack' ),
2136
				'type'               => 'boolean',
2137
				'default'            => 1,
2138
				'validate_callback'  => __CLASS__ . '::validate_boolean',
2139
				'jp_group'           => 'wordads',
2140
			),
2141
			'wordads_display_post' => array(
2142
				'description'        => esc_html__( 'Display ads on posts?', 'jetpack' ),
2143
				'type'               => 'boolean',
2144
				'default'            => 1,
2145
				'validate_callback'  => __CLASS__ . '::validate_boolean',
2146
				'jp_group'           => 'wordads',
2147
			),
2148
			'wordads_display_page' => array(
2149
				'description'        => esc_html__( 'Display ads on pages?', 'jetpack' ),
2150
				'type'               => 'boolean',
2151
				'default'            => 1,
2152
				'validate_callback'  => __CLASS__ . '::validate_boolean',
2153
				'jp_group'           => 'wordads',
2154
			),
2155
			'wordads_display_archive' => array(
2156
				'description'        => esc_html__( 'Display ads on archive pages?', 'jetpack' ),
2157
				'type'               => 'boolean',
2158
				'default'            => 1,
2159
				'validate_callback'  => __CLASS__ . '::validate_boolean',
2160
				'jp_group'           => 'wordads',
2161
			),
2162
			'wordads_custom_adstxt' => array(
2163
				'description'        => esc_html__( 'Custom ads.txt entries', 'jetpack' ),
2164
				'type'               => 'string',
2165
				'default'            => '',
2166
				'validate_callback'  => __CLASS__ . '::validate_string',
2167
				'sanitize_callback'  => 'sanitize_textarea_field',
2168
				'jp_group'           => 'wordads',
2169
			),
2170
2171
			// Google Analytics
2172
			'google_analytics_tracking_id' => array(
2173
				'description'        => esc_html__( 'Google Analytics', 'jetpack' ),
2174
				'type'               => 'string',
2175
				'default'            => '',
2176
				'validate_callback'  => __CLASS__ . '::validate_alphanum',
2177
				'jp_group'           => 'google-analytics',
2178
			),
2179
2180
			// Stats
2181
			'admin_bar' => array(
2182
				'description'       => esc_html__( 'Include a small chart in your admin bar with a 48-hour traffic snapshot.', 'jetpack' ),
2183
				'type'              => 'boolean',
2184
				'default'           => 1,
2185
				'validate_callback' => __CLASS__ . '::validate_boolean',
2186
				'jp_group'          => 'stats',
2187
			),
2188
			'roles' => array(
2189
				'description'       => esc_html__( 'Select the roles that will be able to view stats reports.', 'jetpack' ),
2190
				'type'              => 'array',
2191
				'items'             => array(
2192
					'type' => 'string'
2193
				),
2194
				'default'           => array( 'administrator' ),
2195
				'validate_callback' => __CLASS__ . '::validate_stats_roles',
2196
				'sanitize_callback' => __CLASS__ . '::sanitize_stats_allowed_roles',
2197
				'jp_group'          => 'stats',
2198
			),
2199
			'count_roles' => array(
2200
				'description'       => esc_html__( 'Count the page views of registered users who are logged in.', 'jetpack' ),
2201
				'type'              => 'array',
2202
				'items'             => array(
2203
					'type' => 'string'
2204
				),
2205
				'default'           => array( 'administrator' ),
2206
				'validate_callback' => __CLASS__ . '::validate_stats_roles',
2207
				'jp_group'          => 'stats',
2208
			),
2209
			'blog_id' => array(
2210
				'description'       => esc_html__( 'Blog ID.', 'jetpack' ),
2211
				'type'              => 'boolean',
2212
				'default'           => 0,
2213
				'validate_callback' => __CLASS__ . '::validate_boolean',
2214
				'jp_group'          => 'stats',
2215
			),
2216
			'do_not_track' => array(
2217
				'description'       => esc_html__( 'Do not track.', 'jetpack' ),
2218
				'type'              => 'boolean',
2219
				'default'           => 1,
2220
				'validate_callback' => __CLASS__ . '::validate_boolean',
2221
				'jp_group'          => 'stats',
2222
			),
2223
			'hide_smile' => array(
2224
				'description'       => esc_html__( 'Hide the stats smiley face image.', 'jetpack' ),
2225
				'type'              => 'boolean',
2226
				'default'           => 1,
2227
				'validate_callback' => __CLASS__ . '::validate_boolean',
2228
				'jp_group'          => 'stats',
2229
			),
2230
			'version' => array(
2231
				'description'       => esc_html__( 'Version.', 'jetpack' ),
2232
				'type'              => 'integer',
2233
				'default'           => 9,
2234
				'validate_callback' => __CLASS__ . '::validate_posint',
2235
				'jp_group'          => 'stats',
2236
			),
2237
2238
			// Akismet - Not a module, but a plugin. The options can be passed and handled differently.
2239
			'akismet_show_user_comments_approved' => array(
2240
				'description'       => '',
2241
				'type'              => 'boolean',
2242
				'default'           => 0,
2243
				'validate_callback' => __CLASS__ . '::validate_boolean',
2244
				'jp_group'          => 'settings',
2245
			),
2246
2247
			'wordpress_api_key' => array(
2248
				'description'       => '',
2249
				'type'              => 'string',
2250
				'default'           => '',
2251
				'validate_callback' => __CLASS__ . '::validate_alphanum',
2252
				'jp_group'          => 'settings',
2253
			),
2254
2255
			// Apps card on dashboard
2256
			'dismiss_dash_app_card' => array(
2257
				'description'       => '',
2258
				'type'              => 'boolean',
2259
				'default'           => 0,
2260
				'validate_callback' => __CLASS__ . '::validate_boolean',
2261
				'jp_group'          => 'settings',
2262
			),
2263
2264
			// Empty stats card dismiss
2265
			'dismiss_empty_stats_card' => array(
2266
				'description'       => '',
2267
				'type'              => 'boolean',
2268
				'default'           => 0,
2269
				'validate_callback' => __CLASS__ . '::validate_boolean',
2270
				'jp_group'          => 'settings',
2271
			),
2272
2273
			'lang_id' => array(
2274
				'description' => esc_html__( 'Primary language for the site.', 'jetpack' ),
2275
				'type' => 'string',
2276
				'default' => 'en_US',
2277
				'jp_group' => 'settings',
2278
			),
2279
2280
			'onboarding' => array(
2281
				'description'       => '',
2282
				'type'              => 'object',
2283
				'default'           => array(
2284
					'siteTitle'          => '',
2285
					'siteDescription'    => '',
2286
					'siteType'           => 'personal',
2287
					'homepageFormat'     => 'posts',
2288
					'addContactForm'     => 0,
2289
					'businessAddress'    => array(
2290
						'name'   => '',
2291
						'street' => '',
2292
						'city'   => '',
2293
						'state'  => '',
2294
						'zip'    => '',
2295
					),
2296
					'installWooCommerce' => false,
2297
				),
2298
				'validate_callback' => __CLASS__ . '::validate_onboarding',
2299
				'jp_group'          => 'settings',
2300
			),
2301
2302
		);
2303
2304
		// Add modules to list so they can be toggled
2305
		$modules = Jetpack::get_available_modules();
2306
		if ( is_array( $modules ) && ! empty( $modules ) ) {
2307
			$module_args = array(
2308
				'description'       => '',
2309
				'type'              => 'boolean',
2310
				'default'           => 0,
2311
				'validate_callback' => __CLASS__ . '::validate_boolean',
2312
				'jp_group'          => 'modules',
2313
			);
2314
			foreach( $modules as $module ) {
2315
				$options[ $module ] = $module_args;
2316
			}
2317
		}
2318
2319
		if ( is_array( $selector ) ) {
2320
2321
			// Return only those options whose keys match $selector keys
2322
			return array_intersect_key( $options, $selector );
2323
		}
2324
2325
		if ( 'any' === $selector ) {
2326
2327
			// Toggle module or update any module option or any general setting
2328
			return $options;
2329
		}
2330
2331
		// We're updating the options for a single module.
2332
		if ( empty( $selector ) ) {
2333
			$selector = self::get_module_requested();
2334
		}
2335
		$selected = array();
2336
		foreach ( $options as $option => $attributes ) {
2337
2338
			// Not adding an isset( $attributes['jp_group'] ) because if it's not set, it must be fixed, otherwise options will fail.
2339
			if ( $selector === $attributes['jp_group'] ) {
2340
				$selected[ $option ] = $attributes;
2341
			}
2342
		}
2343
		return $selected;
2344
	}
2345
2346
	/**
2347
	 * Validates that the parameters are proper values that can be set during Jetpack onboarding.
2348
	 *
2349
	 * @since 5.4.0
2350
	 *
2351
	 * @param array           $onboarding_data Values to check.
2352
	 * @param WP_REST_Request $request         The request sent to the WP REST API.
2353
	 * @param string          $param           Name of the parameter passed to endpoint holding $value.
2354
	 *
2355
	 * @return bool|WP_Error
2356
	 */
2357
	public static function validate_onboarding( $onboarding_data, $request, $param ) {
2358
		if ( ! is_array( $onboarding_data ) ) {
2359
			return new WP_Error( 'invalid_param', esc_html__( 'Not valid onboarding data.', 'jetpack' ) );
2360
		}
2361
		foreach ( $onboarding_data as $value ) {
2362
			if ( is_string( $value ) ) {
2363
				$onboarding_choice = self::validate_string( $value, $request, $param );
2364
			} elseif ( is_array( $value ) ) {
2365
				$onboarding_choice = self::validate_onboarding( $value, $request, $param );
2366
			} else {
2367
				$onboarding_choice = self::validate_boolean( $value, $request, $param );
2368
			}
2369
			if ( is_wp_error( $onboarding_choice ) ) {
2370
				return $onboarding_choice;
2371
			}
2372
		}
2373
		return true;
2374
	}
2375
2376
	/**
2377
	 * Validates that the parameter is either a pure boolean or a numeric string that can be mapped to a boolean.
2378
	 *
2379
	 * @since 4.3.0
2380
	 *
2381
	 * @param string|bool $value Value to check.
2382
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2383
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2384
	 *
2385
	 * @return bool|WP_Error
2386
	 */
2387
	public static function validate_boolean( $value, $request, $param ) {
2388
		if ( ! is_bool( $value ) && ! ( ( ctype_digit( $value ) || is_numeric( $value ) ) && in_array( $value, array( 0, 1 ) ) ) ) {
2389
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be true, false, 0 or 1.', 'jetpack' ), $param ) );
2390
		}
2391
		return true;
2392
	}
2393
2394
	/**
2395
	 * Validates that the parameter is a positive integer.
2396
	 *
2397
	 * @since 4.3.0
2398
	 *
2399
	 * @param int $value Value to check.
2400
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2401
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2402
	 *
2403
	 * @return bool|WP_Error
2404
	 */
2405
	public static function validate_posint( $value = 0, $request, $param ) {
2406
		if ( ! is_numeric( $value ) || $value <= 0 ) {
2407
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a positive integer.', 'jetpack' ), $param ) );
2408
		}
2409
		return true;
2410
	}
2411
2412
	/**
2413
	 * Validates that the parameter belongs to a list of admitted values.
2414
	 *
2415
	 * @since 4.3.0
2416
	 *
2417
	 * @param string $value Value to check.
2418
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2419
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2420
	 *
2421
	 * @return bool|WP_Error
2422
	 */
2423
	public static function validate_list_item( $value = '', $request, $param ) {
2424
		$attributes = $request->get_attributes();
2425
		if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
2426
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s not recognized', 'jetpack' ), $param ) );
2427
		}
2428
		$args = $attributes['args'][ $param ];
2429
		if ( ! empty( $args['enum'] ) ) {
2430
2431
			// If it's an associative array, use the keys to check that the value is among those admitted.
2432
			$enum = ( count( array_filter( array_keys( $args['enum'] ), 'is_string' ) ) > 0 ) ? array_keys( $args['enum'] ) : $args['enum'];
2433 View Code Duplication
			if ( ! in_array( $value, $enum ) ) {
2434
				return new WP_Error( 'invalid_param_value', sprintf(
2435
					/* Translators: first variable is the parameter passed to endpoint that holds the list item, the second is a list of admitted values. */
2436
					esc_html__( '%1$s must be one of %2$s', 'jetpack' ), $param, implode( ', ', $enum )
2437
				) );
2438
			}
2439
		}
2440
		return true;
2441
	}
2442
2443
	/**
2444
	 * Validates that the parameter belongs to a list of admitted values.
2445
	 *
2446
	 * @since 4.3.0
2447
	 *
2448
	 * @param string $value Value to check.
2449
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2450
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2451
	 *
2452
	 * @return bool|WP_Error
2453
	 */
2454
	public static function validate_module_list( $value = '', $request, $param ) {
2455 View Code Duplication
		if ( ! is_array( $value ) ) {
2456
			return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be an array', 'jetpack' ), $param ) );
2457
		}
2458
2459
		$modules = Jetpack::get_available_modules();
2460
2461 View Code Duplication
		if ( count( array_intersect( $value, $modules ) ) != count( $value ) ) {
2462
			return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be a list of valid modules', 'jetpack' ), $param ) );
2463
		}
2464
2465
		return true;
2466
	}
2467
2468
	/**
2469
	 * Validates that the parameter is an alphanumeric or empty string (to be able to clear the field).
2470
	 *
2471
	 * @since 4.3.0
2472
	 *
2473
	 * @param string $value Value to check.
2474
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2475
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2476
	 *
2477
	 * @return bool|WP_Error
2478
	 */
2479
	public static function validate_alphanum( $value = '', $request, $param ) {
2480 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/^[a-z0-9]+$/i', $value ) ) ) {
2481
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an alphanumeric string.', 'jetpack' ), $param ) );
2482
		}
2483
		return true;
2484
	}
2485
2486
	/**
2487
	 * Validates that the parameter is a tag or id for a verification service, or an empty string (to be able to clear the field).
2488
	 *
2489
	 * @since 4.6.0
2490
	 *
2491
	 * @param string $value Value to check.
2492
	 * @param WP_REST_Request $request
2493
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2494
	 *
2495
	 * @return bool|WP_Error
2496
	 */
2497
	public static function validate_verification_service( $value = '', $request, $param ) {
2498
		if ( ! empty( $value ) && ! ( is_string( $value ) && ( preg_match( '/^[a-z0-9_-]+$/i', $value ) || jetpack_verification_get_code( $value ) !== false ) ) ) {
2499
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an alphanumeric string or a verification tag.', 'jetpack' ), $param ) );
2500
		}
2501
		return true;
2502
	}
2503
2504
	/**
2505
	 * Validates that the parameter is among the roles allowed for Stats.
2506
	 *
2507
	 * @since 4.3.0
2508
	 *
2509
	 * @param string|bool $value Value to check.
2510
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2511
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2512
	 *
2513
	 * @return bool|WP_Error
2514
	 */
2515
	public static function validate_stats_roles( $value, $request, $param ) {
2516
		if ( ! empty( $value ) && ! array_intersect( self::$stats_roles, $value ) ) {
2517
			return new WP_Error( 'invalid_param', sprintf(
2518
				/* 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. */
2519
				esc_html__( '%1$s must be %2$s.', 'jetpack' ), $param, join( ', ', self::$stats_roles )
2520
			) );
2521
		}
2522
		return true;
2523
	}
2524
2525
	/**
2526
	 * Validates that the parameter is among the views where the Sharing can be displayed.
2527
	 *
2528
	 * @since 4.3.0
2529
	 *
2530
	 * @param string|bool $value Value to check.
2531
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2532
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2533
	 *
2534
	 * @return bool|WP_Error
2535
	 */
2536
	public static function validate_sharing_show( $value, $request, $param ) {
2537
		$views = array( 'index', 'post', 'page', 'attachment', 'jetpack-portfolio' );
2538 View Code Duplication
		if ( ! is_array( $value ) ) {
2539
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array of post types.', 'jetpack' ), $param ) );
2540
		}
2541
		if ( ! array_intersect( $views, $value ) ) {
2542
			return new WP_Error( 'invalid_param', sprintf(
2543
				/* 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 */
2544
				esc_html__( '%1$s must be %2$s.', 'jetpack' ), $param, join( ', ', $views )
2545
			) );
2546
		}
2547
		return true;
2548
	}
2549
2550
	/**
2551
	 * Validates that the parameter is among the views where the Sharing can be displayed.
2552
	 *
2553
	 * @since 4.3.0
2554
	 *
2555
	 * @param string|bool $value {
2556
	 *     Value to check received by request.
2557
	 *
2558
	 *     @type array $visible List of slug of services to share to that are displayed directly in the page.
2559
	 *     @type array $hidden  List of slug of services to share to that are concealed in a folding menu.
2560
	 * }
2561
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2562
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2563
	 *
2564
	 * @return bool|WP_Error
2565
	 */
2566
	public static function validate_services( $value, $request, $param ) {
2567
		if ( ! is_array( $value ) || ! isset( $value['visible'] ) || ! isset( $value['hidden'] ) ) {
2568
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array with visible and hidden items.', 'jetpack' ), $param ) );
2569
		}
2570
2571
		// Allow to clear everything.
2572
		if ( empty( $value['visible'] ) && empty( $value['hidden'] ) ) {
2573
			return true;
2574
		}
2575
2576 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! include_once( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
2577
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
2578
		}
2579
		$sharer = new Sharing_Service();
2580
		$services = array_keys( $sharer->get_all_services() );
2581
2582
		if (
2583
			( ! empty( $value['visible'] ) && ! array_intersect( $value['visible'], $services ) )
2584
			||
2585
			( ! empty( $value['hidden'] ) && ! array_intersect( $value['hidden'], $services ) ) )
2586
		{
2587
			return new WP_Error( 'invalid_param', sprintf(
2588
				/* Translators: placeholder 1 is a parameter holding the services passed to endpoint, placeholder 2 is a list of all Jetpack Sharing services */
2589
				esc_html__( '%1$s visible and hidden items must be a list of %2$s.', 'jetpack' ), $param, join( ', ', $services )
2590
			) );
2591
		}
2592
		return true;
2593
	}
2594
2595
	/**
2596
	 * Validates that the parameter has enough information to build a custom sharing button.
2597
	 *
2598
	 * @since 4.3.0
2599
	 *
2600
	 * @param string|bool $value Value to check.
2601
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2602
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2603
	 *
2604
	 * @return bool|WP_Error
2605
	 */
2606
	public static function validate_custom_service( $value, $request, $param ) {
2607
		if ( ! is_array( $value ) || ! isset( $value['sharing_name'] ) || ! isset( $value['sharing_url'] ) || ! isset( $value['sharing_icon'] ) ) {
2608
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array with sharing name, url and icon.', 'jetpack' ), $param ) );
2609
		}
2610
2611
		// Allow to clear everything.
2612
		if ( empty( $value['sharing_name'] ) && empty( $value['sharing_url'] ) && empty( $value['sharing_icon'] ) ) {
2613
			return true;
2614
		}
2615
2616 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! include_once( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
2617
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
2618
		}
2619
2620
		if ( ( ! empty( $value['sharing_name'] ) && ! is_string( $value['sharing_name'] ) )
2621
		|| ( ! empty( $value['sharing_url'] ) && ! is_string( $value['sharing_url'] ) )
2622
		|| ( ! empty( $value['sharing_icon'] ) && ! is_string( $value['sharing_icon'] ) ) ) {
2623
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s needs sharing name, url and icon.', 'jetpack' ), $param ) );
2624
		}
2625
		return true;
2626
	}
2627
2628
	/**
2629
	 * Validates that the parameter is a custom sharing service ID like 'custom-1461976264'.
2630
	 *
2631
	 * @since 4.3.0
2632
	 *
2633
	 * @param string $value Value to check.
2634
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2635
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2636
	 *
2637
	 * @return bool|WP_Error
2638
	 */
2639
	public static function validate_custom_service_id( $value = '', $request, $param ) {
2640 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/custom\-[0-1]+/i', $value ) ) ) {
2641
			return new WP_Error( 'invalid_param', sprintf( esc_html__( "%s must be a string prefixed with 'custom-' and followed by a numeric ID.", 'jetpack' ), $param ) );
2642
		}
2643
2644 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! include_once( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
2645
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
2646
		}
2647
		$sharer = new Sharing_Service();
2648
		$services = array_keys( $sharer->get_all_services() );
2649
2650 View Code Duplication
		if ( ! empty( $value ) && ! in_array( $value, $services ) ) {
2651
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s is not a registered custom sharing service.', 'jetpack' ), $param ) );
2652
		}
2653
2654
		return true;
2655
	}
2656
2657
	/**
2658
	 * Validates that the parameter is a Twitter username or empty string (to be able to clear the field).
2659
	 *
2660
	 * @since 4.3.0
2661
	 *
2662
	 * @param string $value Value to check.
2663
	 * @param WP_REST_Request $request
2664
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2665
	 *
2666
	 * @return bool|WP_Error
2667
	 */
2668
	public static function validate_twitter_username( $value = '', $request, $param ) {
2669 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/^@?\w{1,15}$/i', $value ) ) ) {
2670
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a Twitter username.', 'jetpack' ), $param ) );
2671
		}
2672
		return true;
2673
	}
2674
2675
	/**
2676
	 * Validates that the parameter is a string.
2677
	 *
2678
	 * @since 4.3.0
2679
	 *
2680
	 * @param string $value Value to check.
2681
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2682
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2683
	 *
2684
	 * @return bool|WP_Error
2685
	 */
2686
	public static function validate_string( $value = '', $request, $param ) {
2687
		if ( ! is_string( $value ) ) {
2688
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a string.', 'jetpack' ), $param ) );
2689
		}
2690
		return true;
2691
	}
2692
2693
	/**
2694
	 * If for some reason the roles allowed to see Stats are empty (for example, user tampering with checkboxes),
2695
	 * return an array with only 'administrator' as the allowed role and save it for 'roles' option.
2696
	 *
2697
	 * @since 4.3.0
2698
	 *
2699
	 * @param string|bool $value Value to check.
2700
	 *
2701
	 * @return bool|array
2702
	 */
2703
	public static function sanitize_stats_allowed_roles( $value ) {
2704
		if ( empty( $value ) ) {
2705
			return array( 'administrator' );
2706
		}
2707
		return $value;
2708
	}
2709
2710
	/**
2711
	 * Get the currently accessed route and return the module slug in it.
2712
	 *
2713
	 * @since 4.3.0
2714
	 *
2715
	 * @param string $route Regular expression for the endpoint with the module slug to return.
2716
	 *
2717
	 * @return array|string
2718
	 */
2719
	public static function get_module_requested( $route = '/module/(?P<slug>[a-z\-]+)' ) {
2720
2721
		if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
2722
			return '';
2723
		}
2724
2725
		preg_match( "#$route#", $GLOBALS['wp']->query_vars['rest_route'], $module );
2726
2727
		if ( empty( $module['slug'] ) ) {
2728
			return '';
2729
		}
2730
2731
		return $module['slug'];
2732
	}
2733
2734
	/**
2735
	 * Adds extra information for modules.
2736
	 *
2737
	 * @since 4.3.0
2738
	 *
2739
	 * @param string|array $modules Can be a single module or a list of modules.
2740
	 * @param null|string  $slug    Slug of the module in the first parameter.
2741
	 *
2742
	 * @return array|string
2743
	 */
2744
	public static function prepare_modules_for_response( $modules = '', $slug = null ) {
2745
		global $wp_rewrite;
2746
2747
		/** This filter is documented in modules/sitemaps/sitemaps.php */
2748
		$location = apply_filters( 'jetpack_sitemap_location', '' );
2749
2750
		if ( $wp_rewrite->using_index_permalinks() ) {
2751
			$sitemap_url = home_url( '/index.php' . $location . '/sitemap.xml' );
2752
			$news_sitemap_url = home_url( '/index.php' . $location . '/news-sitemap.xml' );
2753
		} else if ( $wp_rewrite->using_permalinks() ) {
2754
			$sitemap_url = home_url( $location . '/sitemap.xml' );
2755
			$news_sitemap_url = home_url( $location . '/news-sitemap.xml' );
2756
		} else {
2757
			$sitemap_url = home_url( $location . '/?jetpack-sitemap=sitemap.xml' );
2758
			$news_sitemap_url = home_url( $location . '/?jetpack-sitemap=news-sitemap.xml' );
2759
		}
2760
2761
		if ( is_null( $slug ) && isset( $modules['sitemaps'] ) ) {
2762
			// Is a list of modules
2763
			$modules['sitemaps']['extra']['sitemap_url'] = $sitemap_url;
2764
			$modules['sitemaps']['extra']['news_sitemap_url'] = $news_sitemap_url;
2765
		} elseif ( 'sitemaps' == $slug ) {
2766
			// It's a single module
2767
			$modules['extra']['sitemap_url'] = $sitemap_url;
2768
			$modules['extra']['news_sitemap_url'] = $news_sitemap_url;
2769
		}
2770
		return $modules;
2771
	}
2772
2773
	/**
2774
	 * Remove 'validate_callback' item from options available for module.
2775
	 * Fetch current option value and add to array of module options.
2776
	 * Prepare values of module options that need special handling, like those saved in wpcom.
2777
	 *
2778
	 * @since 4.3.0
2779
	 *
2780
	 * @param string $module Module slug.
2781
	 * @return array
2782
	 */
2783
	public static function prepare_options_for_response( $module = '' ) {
2784
		$options = self::get_updateable_data_list( $module );
2785
2786
		if ( ! is_array( $options ) || empty( $options ) ) {
2787
			return $options;
2788
		}
2789
2790
		// Some modules need special treatment.
2791
		switch ( $module ) {
2792
2793
			case 'monitor':
2794
				// Status of user notifications
2795
				$options['monitor_receive_notifications']['current_value'] = self::cast_value( self::get_remote_value( 'monitor', 'monitor_receive_notifications' ), $options['monitor_receive_notifications'] );
2796
				break;
2797
2798
			case 'post-by-email':
2799
				// Email address
2800
				$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'] );
2801
				break;
2802
2803
			case 'protect':
2804
				// Protect
2805
				$options['jetpack_protect_key']['current_value'] = get_site_option( 'jetpack_protect_key', false );
2806
				if ( ! function_exists( 'jetpack_protect_format_whitelist' ) ) {
2807
					include_once( JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php' );
2808
				}
2809
				$options['jetpack_protect_global_whitelist']['current_value'] = jetpack_protect_format_whitelist();
2810
				break;
2811
2812
			case 'related-posts':
2813
				// It's local, but it must be broken apart since it's saved as an array.
2814
				$options = self::split_options( $options, Jetpack_Options::get_option( 'relatedposts' ) );
2815
				break;
2816
2817
			case 'verification-tools':
2818
				// It's local, but it must be broken apart since it's saved as an array.
2819
				$options = self::split_options( $options, get_option( 'verification_services_codes' ) );
2820
				break;
2821
2822
			case 'google-analytics':
2823
				$wga = get_option( 'jetpack_wga' );
2824
				$code = '';
2825
				if ( is_array( $wga ) && array_key_exists( 'code', $wga ) ) {
2826
					 $code = $wga[ 'code' ];
2827
				}
2828
				$options[ 'google_analytics_tracking_id' ][ 'current_value' ] = $code;
2829
				break;
2830
2831
			case 'sharedaddy':
2832
				// It's local, but it must be broken apart since it's saved as an array.
2833
				if ( ! class_exists( 'Sharing_Service' ) && ! include_once( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
2834
					break;
2835
				}
2836
				$sharer = new Sharing_Service();
2837
				$options = self::split_options( $options, $sharer->get_global_options() );
2838
				$options['sharing_services']['current_value'] = $sharer->get_blog_services();
2839
				$other_sharedaddy_options = array( 'jetpack-twitter-cards-site-tag', 'sharedaddy_disable_resources', 'sharing_delete_service' );
2840 View Code Duplication
				foreach ( $other_sharedaddy_options as $key ) {
2841
					$default_value = isset( $options[ $key ]['default'] ) ? $options[ $key ]['default'] : '';
2842
					$current_value = get_option( $key, $default_value );
2843
					$options[ $key ]['current_value'] = self::cast_value( $current_value, $options[ $key ] );
2844
				}
2845
				break;
2846
2847
			case 'stats':
2848
				// It's local, but it must be broken apart since it's saved as an array.
2849
				if ( ! function_exists( 'stats_get_options' ) ) {
2850
					include_once( JETPACK__PLUGIN_DIR . 'modules/stats.php' );
2851
				}
2852
				$options = self::split_options( $options, stats_get_options() );
2853
				break;
2854
			default:
2855
				// These option are just stored as plain WordPress options.
2856 View Code Duplication
				foreach ( $options as $key => $value ) {
2857
					$default_value = isset( $options[ $key ]['default'] ) ? $options[ $key ]['default'] : '';
2858
					$current_value = get_option( $key, $default_value );
2859
					$options[ $key ]['current_value'] = self::cast_value( $current_value, $options[ $key ] );
2860
				}
2861
		}
2862
		// At this point some options have current_value not set because they're options
2863
		// that only get written on update, so we set current_value to the default one.
2864
		foreach ( $options as $key => $value ) {
2865
			// We don't need validate_callback in the response
2866
			if ( isset( $options[ $key ]['validate_callback'] ) ) {
2867
				unset( $options[ $key ]['validate_callback'] );
2868
			}
2869
			$default_value = isset( $options[ $key ]['default'] ) ? $options[ $key ]['default'] : '';
2870
			if ( ! array_key_exists( 'current_value', $options[ $key ] ) ) {
2871
				$options[ $key ]['current_value'] = self::cast_value( $default_value, $options[ $key ] );
2872
			}
2873
		}
2874
		return $options;
2875
	}
2876
2877
	/**
2878
	 * Splits module options saved as arrays like relatedposts or verification_services_codes into separate options to be returned in the response.
2879
	 *
2880
	 * @since 4.3.0
2881
	 *
2882
	 * @param array  $separate_options Array of options admitted by the module.
2883
	 * @param array  $grouped_options Option saved as array to be splitted.
2884
	 * @param string $prefix Optional prefix for the separate option keys.
2885
	 *
2886
	 * @return array
2887
	 */
2888
	public static function split_options( $separate_options, $grouped_options, $prefix = '' ) {
2889
		if ( is_array( $grouped_options ) ) {
2890
			foreach ( $grouped_options as $key => $value ) {
2891
				$option_key = $prefix . $key;
2892
				if ( isset( $separate_options[ $option_key ] ) ) {
2893
					$separate_options[ $option_key ]['current_value'] = self::cast_value( $grouped_options[ $key ], $separate_options[ $option_key ] );
2894
				}
2895
			}
2896
		}
2897
		return $separate_options;
2898
	}
2899
2900
	/**
2901
	 * Perform a casting to the value specified in the option definition.
2902
	 *
2903
	 * @since 4.3.0
2904
	 *
2905
	 * @param mixed $value Value to cast to the proper type.
2906
	 * @param array $definition Type to cast the value to.
2907
	 *
2908
	 * @return bool|float|int|string
2909
	 */
2910
	public static function cast_value( $value, $definition ) {
2911
		if ( $value === 'NULL' ) {
2912
			return null;
2913
		}
2914
2915
		if ( isset( $definition['type'] ) ) {
2916
			switch ( $definition['type'] ) {
2917
				case 'boolean':
2918
					if ( 'true' === $value || 'on' === $value ) {
2919
						return true;
2920
					} elseif ( 'false' === $value || 'off' === $value ) {
2921
						return false;
2922
					}
2923
					return (bool) $value;
2924
					break;
2925
2926
				case 'integer':
2927
					return (int) $value;
2928
					break;
2929
2930
				case 'float':
2931
					return (float) $value;
2932
					break;
0 ignored issues
show
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
2933
2934
				case 'string':
2935
					return (string) $value;
2936
					break;
2937
			}
2938
		}
2939
		return $value;
2940
	}
2941
2942
	/**
2943
	 * Get a value not saved locally.
2944
	 *
2945
	 * @since 4.3.0
2946
	 *
2947
	 * @param string $module Module slug.
2948
	 * @param string $option Option name.
2949
	 *
2950
	 * @return bool Whether user is receiving notifications or not.
2951
	 */
2952
	public static function get_remote_value( $module, $option ) {
2953
2954
		if ( in_array( $module, array( 'post-by-email' ), true ) ) {
2955
			$option .= get_current_user_id();
2956
		}
2957
2958
		// If option doesn't exist, 'does_not_exist' will be returned.
2959
		$value = get_option( $option, 'does_not_exist' );
2960
2961
		// If option exists, just return it.
2962
		if ( 'does_not_exist' !== $value ) {
2963
			return $value;
2964
		}
2965
2966
		// Only check a remote option if Jetpack is connected.
2967
		if ( ! Jetpack::is_active() ) {
2968
			return false;
2969
		}
2970
2971
		// Do what is necessary for each module.
2972
		switch ( $module ) {
2973
			case 'monitor':
2974
				// Load the class to use the method. If class can't be found, do nothing.
2975
				if ( ! class_exists( 'Jetpack_Monitor' ) && ! include_once( Jetpack::get_module_path( $module ) ) ) {
2976
					return false;
2977
				}
2978
				$value = Jetpack_Monitor::user_receives_notifications( false );
2979
				break;
2980
2981
			case 'post-by-email':
2982
				// Load the class to use the method. If class can't be found, do nothing.
2983
				if ( ! class_exists( 'Jetpack_Post_By_Email' ) && ! include_once( Jetpack::get_module_path( $module ) ) ) {
2984
					return false;
2985
				}
2986
				$post_by_email = new Jetpack_Post_By_Email();
2987
				$value = $post_by_email->get_post_by_email_address();
2988
				if ( $value === null ) {
2989
					$value = 'NULL'; // sentinel value so it actually gets set
2990
				}
2991
				break;
2992
		}
2993
2994
		// Normalize value to boolean.
2995
		if ( is_wp_error( $value ) || is_null( $value ) ) {
2996
			$value = false;
2997
		}
2998
2999
		// Save option to use it next time.
3000
		update_option( $option, $value );
3001
3002
		return $value;
3003
	}
3004
3005
	/**
3006
	 * Get number of plugin updates available.
3007
	 *
3008
	 * @since 4.3.0
3009
	 *
3010
	 * @return mixed|WP_Error Number of plugin updates available. Otherwise, a WP_Error instance with the corresponding error.
3011
	 */
3012
	public static function get_plugin_update_count() {
3013
		$updates = wp_get_update_data();
3014
		if ( isset( $updates['counts'] ) && isset( $updates['counts']['plugins'] ) ) {
3015
			$count = $updates['counts']['plugins'];
3016
			if ( 0 == $count ) {
3017
				$response = array(
3018
					'code'    => 'success',
3019
					'message' => esc_html__( 'All plugins are up-to-date. Keep up the good work!', 'jetpack' ),
3020
					'count'   => 0,
3021
				);
3022
			} else {
3023
				$response = array(
3024
					'code'    => 'updates-available',
3025
					'message' => esc_html( sprintf( _n( '%s plugin need updating.', '%s plugins need updating.', $count, 'jetpack' ), $count ) ),
3026
					'count'   => $count,
3027
				);
3028
			}
3029
			return rest_ensure_response( $response );
3030
		}
3031
3032
		return new WP_Error( 'not_found', esc_html__( 'Could not check updates for plugins on this site.', 'jetpack' ), array( 'status' => 404 ) );
3033
	}
3034
3035
3036
	/**
3037
	 * Returns a list of all plugins in the site.
3038
	 *
3039
	 * @since 4.2.0
3040
	 * @uses get_plugins()
3041
	 *
3042
	 * @return array
3043
	 */
3044
	private static function core_get_plugins() {
3045
		if ( ! function_exists( 'get_plugins' ) ) {
3046
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
3047
		}
3048
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
3049
		$plugins = apply_filters( 'all_plugins', get_plugins() );
3050
3051
		if ( is_array( $plugins ) && ! empty( $plugins ) ) {
3052
			foreach ( $plugins as $plugin_slug => $plugin_data ) {
3053
				$plugins[ $plugin_slug ]['active'] = self::core_is_plugin_active( $plugin_slug );
3054
			}
3055
			return $plugins;
3056
		}
3057
3058
		return array();
3059
	}
3060
3061
	/**
3062
	 * Deprecated - Get third party plugin API keys.
3063
	 * @deprecated
3064
	 *
3065
	 * @param WP_REST_Request $request {
3066
	 *     Array of parameters received by request.
3067
	 *
3068
	 *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
3069
	 * }
3070
	 */
3071
	public static function get_service_api_key( $request ) {
3072
		_deprecated_function( __METHOD__, 'jetpack-6.9.0', 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys::get_service_api_key' );
3073
		return WPCOM_REST_API_V2_Endpoint_Service_API_Keys::get_service_api_key( $request );
3074
	}
3075
3076
	/**
3077
	 * Deprecated - Update third party plugin API keys.
3078
	 * @deprecated
3079
	 *
3080
	 * @param WP_REST_Request $request {
3081
	 *     Array of parameters received by request.
3082
	 *
3083
	 *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
3084
	 * }
3085
	 */
3086
	public static function update_service_api_key( $request ) {
3087
		_deprecated_function( __METHOD__, 'jetpack-6.9.0', 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys::update_service_api_key' );
3088
		return WPCOM_REST_API_V2_Endpoint_Service_API_Keys::update_service_api_key( $request ) ;
3089
	}
3090
3091
	/**
3092
	 * Deprecated - Delete a third party plugin API key.
3093
	 * @deprecated
3094
	 *
3095
	 * @param WP_REST_Request $request {
3096
	 *     Array of parameters received by request.
3097
	 *
3098
	 *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
3099
	 * }
3100
	 */
3101
	public static function delete_service_api_key( $request ) {
3102
		_deprecated_function( __METHOD__, 'jetpack-6.9.0', 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys::delete_service_api_key' );
3103
		return WPCOM_REST_API_V2_Endpoint_Service_API_Keys::delete_service_api_key( $request );
3104
	}
3105
3106
	/**
3107
	 * Deprecated - Validate the service provided in /service-api-keys/ endpoints.
3108
	 * To add a service to these endpoints, add the service name to $valid_services
3109
	 * and add '{service name}_api_key' to the non-compact return array in get_option_names(),
3110
	 * in class-jetpack-options.php
3111
	 * @deprecated
3112
	 *
3113
	 * @param string $service The service the API key is for.
3114
	 * @return string Returns the service name if valid, null if invalid.
3115
	 */
3116
	public static function validate_service_api_service( $service = null ) {
3117
		_deprecated_function( __METHOD__, 'jetpack-6.9.0', 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys::validate_service_api_service' );
3118
		return WPCOM_REST_API_V2_Endpoint_Service_API_Keys::validate_service_api_service( $service );
3119
	}
3120
3121
	/**
3122
	 * Error response for invalid service API key requests with an invalid service.
3123
	 */
3124
	public static function service_api_invalid_service_response() {
3125
		_deprecated_function( __METHOD__, 'jetpack-6.9.0', 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys::service_api_invalid_service_response' );
3126
		return WPCOM_REST_API_V2_Endpoint_Service_API_Keys::service_api_invalid_service_response();
3127
	}
3128
3129
	/**
3130
	 * Deprecated - Validate API Key
3131
	 * @deprecated
3132
	 *
3133
	 * @param string $key The API key to be validated.
3134
	 * @param string $service The service the API key is for.
3135
	 *
3136
	 */
3137
	public static function validate_service_api_key( $key = null, $service = null ) {
3138
		_deprecated_function( __METHOD__, 'jetpack-6.9.0', 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys::validate_service_api_key' );
3139
		return WPCOM_REST_API_V2_Endpoint_Service_API_Keys::validate_service_api_key( $key , $service  );
3140
	}
3141
3142
	/**
3143
	 * Deprecated - Validate Mapbox API key
3144
	 * Based loosely on https://github.com/mapbox/geocoding-example/blob/master/php/MapboxTest.php
3145
	 * @deprecated
3146
	 *
3147
	 * @param string $key The API key to be validated.
3148
	 */
3149
	public static function validate_service_api_key_mapbox( $key ) {
3150
		_deprecated_function( __METHOD__, 'jetpack-6.9.0', 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys::validate_service_api_key' );
3151
		return WPCOM_REST_API_V2_Endpoint_Service_API_Keys::validate_service_api_key_mapbox( $key );
3152
3153
	}
3154
3155
	/**
3156
	 * Checks if the queried plugin is active.
3157
	 *
3158
	 * @since 4.2.0
3159
	 * @uses is_plugin_active()
3160
	 *
3161
	 * @return bool
3162
	 */
3163
	private static function core_is_plugin_active( $plugin ) {
3164
		if ( ! function_exists( 'is_plugin_active' ) ) {
3165
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
3166
		}
3167
3168
		return is_plugin_active( $plugin );
3169
	}
3170
3171
	/**
3172
	 * Get plugins data in site.
3173
	 *
3174
	 * @since 4.2.0
3175
	 *
3176
	 * @return WP_REST_Response|WP_Error List of plugins in the site. Otherwise, a WP_Error instance with the corresponding error.
3177
	 */
3178
	public static function get_plugins() {
3179
		$plugins = self::core_get_plugins();
3180
3181
		if ( ! empty( $plugins ) ) {
3182
			return rest_ensure_response( $plugins );
3183
		}
3184
3185
		return new WP_Error( 'not_found', esc_html__( 'Unable to list plugins.', 'jetpack' ), array( 'status' => 404 ) );
3186
	}
3187
3188
	/**
3189
	 * Ensures that Akismet is installed and activated.
3190
	 *
3191
	 * @since 7.7
3192
	 *
3193
	 * @return WP_REST_Response A response indicating whether or not the installation was successful.
3194
	 */
3195
	public static function activate_akismet() {
3196
		jetpack_require_lib( 'plugins' );
3197
		$result = Jetpack_Plugins::install_and_activate_plugin('akismet');
3198
3199
		if ( is_wp_error( $result ) ) {
3200
			return rest_ensure_response( array(
3201
				'code'    => 'failure',
3202
				'message' => esc_html__( 'Unable to activate Akismet', 'jetpack' )
3203
			) );
3204
		} else {
3205
			return rest_ensure_response( array(
3206
				'code'    => 'success',
3207
				'message' => esc_html__( 'Activated Akismet', 'jetpack' )
3208
			) );
3209
		}
3210
	}
3211
3212
	/**
3213
	 * Get data about the queried plugin. Currently it only returns whether the plugin is active or not.
3214
	 *
3215
	 * @since 4.2.0
3216
	 *
3217
	 * @param WP_REST_Request $request {
3218
	 *     Array of parameters received by request.
3219
	 *
3220
	 *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
3221
	 * }
3222
	 *
3223
	 * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
3224
	 */
3225
	public static function get_plugin( $request ) {
3226
3227
		$plugins = self::core_get_plugins();
3228
3229
		if ( empty( $plugins ) ) {
3230
			return new WP_Error( 'no_plugins_found', esc_html__( 'This site has no plugins.', 'jetpack' ), array( 'status' => 404 ) );
3231
		}
3232
3233
		$plugin = stripslashes( $request['plugin'] );
3234
3235
		if ( ! in_array( $plugin, array_keys( $plugins ) ) ) {
3236
			return new WP_Error( 'plugin_not_found', esc_html( sprintf( __( 'Plugin %s is not installed.', 'jetpack' ), $plugin ) ), array( 'status' => 404 ) );
3237
		}
3238
3239
		$plugin_data = $plugins[ $plugin ];
3240
3241
		$plugin_data['active'] = self::core_is_plugin_active( $plugin );
3242
3243
		return rest_ensure_response( array(
3244
			'code'    => 'success',
3245
			'message' => esc_html__( 'Plugin found.', 'jetpack' ),
3246
			'data'    => $plugin_data
3247
		) );
3248
	}
3249
3250
	/**
3251
	 * Proxies a request to WordPress.com to request that a magic link be sent to the current user
3252
	 * to log this user in to the mobile app via email.
3253
	 *
3254
	 * @param WP_REST_REQUEST $request The request parameters.
3255
	 * @return bool|WP_Error
3256
	 */
3257
	public static function send_mobile_magic_link( $request ) {
3258
		$xml = new Jetpack_IXR_Client(
3259
			array(
3260
				'user_id' => get_current_user_id(),
3261
			)
3262
		);
3263
3264
		$xml->query( 'jetpack.sendMobileMagicLink', array() );
3265
		if ( $xml->isError() ) {
3266
			return new WP_Error(
3267
				'error_sending_mobile_magic_link',
3268
				sprintf(
3269
					'%s: %s',
3270
					$xml->getErrorCode(),
3271
					$xml->getErrorMessage()
3272
				)
3273
			);
3274
		}
3275
3276
		$response = $xml->getResponse();
3277
3278
		return rest_ensure_response(
3279
			array(
3280
				'code' => 'success',
3281
			)
3282
		);
3283
	}
3284
} // class end
3285