Completed
Push — master-stable ( cf0a45...825187 )
by
unknown
53:23 queued 45:38
created

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