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