Completed
Push — add/related-posts-customize ( 4a306a...1c5144 )
by
unknown
43:30 queued 35:07
created

_inc/lib/class.core-rest-api-endpoints.php (3 issues)

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