Completed
Push — master-stable ( 502f21...5dbebd )
by
unknown
34:46 queued 26:29
created

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

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

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

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

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

Loading history...
2195
2196
				case 'integer':
2197
					return (int) $value;
2198
					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...
2199
2200
				case 'float':
2201
					return (float) $value;
2202
					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...
2203
2204
				case 'string':
2205
					return (string) $value;
2206
					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...
2207
			}
2208
		}
2209
		return $value;
2210
	}
2211
2212
	/**
2213
	 * Get a value not saved locally.
2214
	 *
2215
	 * @since 4.3.0
2216
	 *
2217
	 * @param string $module Module slug.
2218
	 * @param string $option Option name.
2219
	 *
2220
	 * @return bool Whether user is receiving notifications or not.
2221
	 */
2222
	public static function get_remote_value( $module, $option ) {
2223
2224
		if ( in_array( $module, array( 'post-by-email' ), true ) ) {
2225
			$option .= get_current_user_id();
2226
		}
2227
2228
		// If option doesn't exist, 'does_not_exist' will be returned.
2229
		$value = get_option( $option, 'does_not_exist' );
2230
2231
		// If option exists, just return it.
2232
		if ( 'does_not_exist' !== $value ) {
2233
			return $value;
2234
		}
2235
2236
		// Only check a remote option if Jetpack is connected.
2237
		if ( ! Jetpack::is_active() ) {
2238
			return false;
2239
		}
2240
2241
		// If the module is inactive, load the class to use the method.
2242
		if ( ! did_action( 'jetpack_module_loaded_' . $module ) ) {
2243
			// Class can't be found so do nothing.
2244
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
2245
				return false;
2246
			}
2247
		}
2248
2249
		// Do what is necessary for each module.
2250
		switch ( $module ) {
2251
			case 'monitor':
2252
				$monitor = new Jetpack_Monitor();
2253
				$value = $monitor->user_receives_notifications( false );
2254
				break;
2255
2256
			case 'post-by-email':
2257
				$post_by_email = new Jetpack_Post_By_Email();
2258
				$value = $post_by_email->get_post_by_email_address();
2259
				if ( $value === null ) {
2260
					$value = 'NULL'; // sentinel value so it actually gets set
2261
				}
2262
				break;
2263
		}
2264
2265
		// Normalize value to boolean.
2266
		if ( is_wp_error( $value ) || is_null( $value ) ) {
2267
			$value = false;
2268
		}
2269
2270
		// Save option to use it next time.
2271
		update_option( $option, $value );
2272
2273
		return $value;
2274
	}
2275
2276
	/**
2277
	 * Get number of plugin updates available.
2278
	 *
2279
	 * @since 4.3.0
2280
	 *
2281
	 * @return mixed|WP_Error Number of plugin updates available. Otherwise, a WP_Error instance with the corresponding error.
2282
	 */
2283
	public static function get_plugin_update_count() {
2284
		$updates = wp_get_update_data();
2285
		if ( isset( $updates['counts'] ) && isset( $updates['counts']['plugins'] ) ) {
2286
			$count = $updates['counts']['plugins'];
2287
			if ( 0 == $count ) {
2288
				$response = array(
2289
					'code'    => 'success',
2290
					'message' => esc_html__( 'All plugins are up-to-date. Keep up the good work!', 'jetpack' ),
2291
					'count'   => 0,
2292
				);
2293
			} else {
2294
				$response = array(
2295
					'code'    => 'updates-available',
2296
					'message' => esc_html( sprintf( _n( '%s plugin need updating.', '%s plugins need updating.', $count, 'jetpack' ), $count ) ),
2297
					'count'   => $count,
2298
				);
2299
			}
2300
			return rest_ensure_response( $response );
2301
		}
2302
2303
		return new WP_Error( 'not_found', esc_html__( 'Could not check updates for plugins on this site.', 'jetpack' ), array( 'status' => 404 ) );
2304
	}
2305
2306
2307
	/**
2308
	 * Returns a list of all plugins in the site.
2309
	 *
2310
	 * @since 4.2.0
2311
	 * @uses get_plugins()
2312
	 *
2313
	 * @return array
2314
	 */
2315
	private static function core_get_plugins() {
2316
		if ( ! function_exists( 'get_plugins' ) ) {
2317
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2318
		}
2319
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2320
		$plugins = apply_filters( 'all_plugins', get_plugins() );
2321
2322
		if ( is_array( $plugins ) && ! empty( $plugins ) ) {
2323
			foreach ( $plugins as $plugin_slug => $plugin_data ) {
2324
				$plugins[ $plugin_slug ]['active'] = self::core_is_plugin_active( $plugin_slug );
2325
			}
2326
			return $plugins;
2327
		}
2328
2329
		return array();
2330
	}
2331
2332
	/**
2333
	 * Checks if the queried plugin is active.
2334
	 *
2335
	 * @since 4.2.0
2336
	 * @uses is_plugin_active()
2337
	 *
2338
	 * @return bool
2339
	 */
2340
	private static function core_is_plugin_active( $plugin ) {
2341
		if ( ! function_exists( 'get_plugins' ) ) {
2342
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2343
		}
2344
2345
		return is_plugin_active( $plugin );
2346
	}
2347
2348
	/**
2349
	 * Get plugins data in site.
2350
	 *
2351
	 * @since 4.2.0
2352
	 *
2353
	 * @return WP_REST_Response|WP_Error List of plugins in the site. Otherwise, a WP_Error instance with the corresponding error.
2354
	 */
2355
	public static function get_plugins() {
2356
		$plugins = self::core_get_plugins();
2357
2358
		if ( ! empty( $plugins ) ) {
2359
			return rest_ensure_response( $plugins );
2360
		}
2361
2362
		return new WP_Error( 'not_found', esc_html__( 'Unable to list plugins.', 'jetpack' ), array( 'status' => 404 ) );
2363
	}
2364
2365
	/**
2366
	 * Get data about the queried plugin. Currently it only returns whether the plugin is active or not.
2367
	 *
2368
	 * @since 4.2.0
2369
	 *
2370
	 * @param WP_REST_Request $request {
2371
	 *     Array of parameters received by request.
2372
	 *
2373
	 *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
2374
	 * }
2375
	 *
2376
	 * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
2377
	 */
2378
	public static function get_plugin( $request ) {
2379
2380
		$plugins = self::core_get_plugins();
2381
2382
		if ( empty( $plugins ) ) {
2383
			return new WP_Error( 'no_plugins_found', esc_html__( 'This site has no plugins.', 'jetpack' ), array( 'status' => 404 ) );
2384
		}
2385
2386
		$plugin = stripslashes( $request['plugin'] );
2387
2388
		if ( ! in_array( $plugin, array_keys( $plugins ) ) ) {
2389
			return new WP_Error( 'plugin_not_found', esc_html( sprintf( __( 'Plugin %s is not installed.', 'jetpack' ), $plugin ) ), array( 'status' => 404 ) );
2390
		}
2391
2392
		$plugin_data = $plugins[ $plugin ];
2393
2394
		$plugin_data['active'] = self::core_is_plugin_active( $plugin );
2395
2396
		return rest_ensure_response( array(
2397
			'code'    => 'success',
2398
			'message' => esc_html__( 'Plugin found.', 'jetpack' ),
2399
			'data'    => $plugin_data
2400
		) );
2401
	}
2402
2403
} // class end
2404