Completed
Push — fix/disconnected-settings ( d97055...213165 )
by
unknown
82:42 queued 70:39
created

_inc/lib/class.core-rest-api-endpoints.php (5 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
	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
	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 View Code Duplication
		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__( 'Color scheme.', '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'              => 'boolean',
1170
				'default'           => 0,
1171
				'validate_callback' => __CLASS__ . '::validate_boolean',
1172
				'jp_group'          => 'minileven',
1173
			),
1174
			'wp_mobile_featured_images' => array(
1175
				'description'       => esc_html__( 'Featured Images', 'jetpack' ),
1176
				'type'              => 'boolean',
1177
				'default'           => 0,
1178
				'validate_callback' => __CLASS__ . '::validate_boolean',
1179
				'jp_group'          => 'minileven',
1180
			),
1181
			'wp_mobile_app_promos' => array(
1182
				'description'       => esc_html__( 'Show a promo for the WordPress mobile apps in the footer of the mobile theme.', 'jetpack' ),
1183
				'type'              => 'boolean',
1184
				'default'           => 0,
1185
				'validate_callback' => __CLASS__ . '::validate_boolean',
1186
				'jp_group'          => 'minileven',
1187
			),
1188
1189
			// Monitor
1190
			'monitor_receive_notifications' => array(
1191
				'description'       => esc_html__( 'Receive Monitor Email Notifications.', 'jetpack' ),
1192
				'type'              => 'boolean',
1193
				'default'           => 0,
1194
				'validate_callback' => __CLASS__ . '::validate_boolean',
1195
				'jp_group'          => 'monitor',
1196
			),
1197
1198
			// Post by Email
1199
			'post_by_email_address' => array(
1200
				'description'       => esc_html__( 'Email Address', 'jetpack' ),
1201
				'type'              => 'string',
1202
				'default'           => 'noop',
1203
				'enum'              => array(
1204
					'noop',
1205
					'create',
1206
					'regenerate',
1207
					'delete',
1208
				),
1209
				'enum_labels' => array(
1210
					'noop'       => '',
1211
					'create'     => esc_html__( 'Create Post by Email address', 'jetpack' ),
1212
					'regenerate' => esc_html__( 'Regenerate Post by Email address', 'jetpack' ),
1213
					'delete'     => esc_html__( 'Delete Post by Email address', 'jetpack' ),
1214
				),
1215
				'validate_callback' => __CLASS__ . '::validate_list_item',
1216
				'jp_group'          => 'post-by-email',
1217
			),
1218
1219
			// Protect
1220
			'jetpack_protect_key' => array(
1221
				'description'       => esc_html__( 'Protect API key', 'jetpack' ),
1222
				'type'              => 'string',
1223
				'default'           => '',
1224
				'validate_callback' => __CLASS__ . '::validate_alphanum',
1225
				'jp_group'          => 'protect',
1226
			),
1227
			'jetpack_protect_global_whitelist' => array(
1228
				'description'       => esc_html__( 'Protect global whitelist', 'jetpack' ),
1229
				'type'              => 'string',
1230
				'default'           => '',
1231
				'validate_callback' => __CLASS__ . '::validate_string',
1232
				'sanitize_callback' => 'esc_textarea',
1233
				'jp_group'          => 'protect',
1234
			),
1235
1236
			// Sharing
1237
			'sharing_services' => array(
1238
				'description'       => esc_html__( 'Enabled Services and those hidden behind a button', 'jetpack' ),
1239
				'type'              => 'object',
1240
				'default'           => array(
1241
					'visible' => array( 'twitter', 'facebook', 'google-plus-1' ),
1242
					'hidden'  => array(),
1243
				),
1244
				'validate_callback' => __CLASS__ . '::validate_services',
1245
				'jp_group'          => 'sharedaddy',
1246
			),
1247
			'button_style' => array(
1248
				'description'       => esc_html__( 'Button Style', 'jetpack' ),
1249
				'type'              => 'string',
1250
				'default'           => 'icon',
1251
				'enum'              => array(
1252
					'icon-text',
1253
					'icon',
1254
					'text',
1255
					'official',
1256
				),
1257
				'enum_labels' => array(
1258
					'icon-text' => esc_html__( 'Icon + text', 'jetpack' ),
1259
					'icon'      => esc_html__( 'Icon only', 'jetpack' ),
1260
					'text'      => esc_html__( 'Text only', 'jetpack' ),
1261
					'official'  => esc_html__( 'Official buttons', 'jetpack' ),
1262
				),
1263
				'validate_callback' => __CLASS__ . '::validate_list_item',
1264
				'jp_group'          => 'sharedaddy',
1265
			),
1266
			'sharing_label' => array(
1267
				'description'       => esc_html__( 'Sharing Label', 'jetpack' ),
1268
				'type'              => 'string',
1269
				'default'           => '',
1270
				'validate_callback' => __CLASS__ . '::validate_string',
1271
				'sanitize_callback' => 'esc_html',
1272
				'jp_group'          => 'sharedaddy',
1273
			),
1274
			'show' => array(
1275
				'description'       => esc_html__( 'Views where buttons are shown', 'jetpack' ),
1276
				'type'              => 'array',
1277
				'items'             => array(
1278
					'type' => 'string'
1279
				),
1280
				'default'           => array( 'post' ),
1281
				'validate_callback' => __CLASS__ . '::validate_sharing_show',
1282
				'jp_group'          => 'sharedaddy',
1283
			),
1284
			'jetpack-twitter-cards-site-tag' => array(
1285
				'description'       => esc_html__( "The Twitter username of the owner of this site's domain.", 'jetpack' ),
1286
				'type'              => 'string',
1287
				'default'           => '',
1288
				'validate_callback' => __CLASS__ . '::validate_twitter_username',
1289
				'sanitize_callback' => 'esc_html',
1290
				'jp_group'          => 'sharedaddy',
1291
			),
1292
			'sharedaddy_disable_resources' => array(
1293
				'description'       => esc_html__( 'Disable CSS and JS', 'jetpack' ),
1294
				'type'              => 'boolean',
1295
				'default'           => 0,
1296
				'validate_callback' => __CLASS__ . '::validate_boolean',
1297
				'jp_group'          => 'sharedaddy',
1298
			),
1299
			'custom' => array(
1300
				'description'       => esc_html__( 'Custom sharing services added by user.', 'jetpack' ),
1301
				'type'              => 'object',
1302
				'default'           => array(
1303
					'sharing_name' => '',
1304
					'sharing_url'  => '',
1305
					'sharing_icon' => '',
1306
				),
1307
				'validate_callback' => __CLASS__ . '::validate_custom_service',
1308
				'jp_group'          => 'sharedaddy',
1309
			),
1310
			// Not an option, but an action that can be perfomed on the list of custom services passing the service ID.
1311
			'sharing_delete_service' => array(
1312
				'description'       => esc_html__( 'Delete custom sharing service.', 'jetpack' ),
1313
				'type'              => 'string',
1314
				'default'           => '',
1315
				'validate_callback' => __CLASS__ . '::validate_custom_service_id',
1316
				'jp_group'          => 'sharedaddy',
1317
			),
1318
1319
			// SSO
1320
			'jetpack_sso_require_two_step' => array(
1321
				'description'       => esc_html__( 'Require Two-Step Authentication', 'jetpack' ),
1322
				'type'              => 'boolean',
1323
				'default'           => 0,
1324
				'validate_callback' => __CLASS__ . '::validate_boolean',
1325
				'jp_group'          => 'sso',
1326
			),
1327
			'jetpack_sso_match_by_email' => array(
1328
				'description'       => esc_html__( 'Match by Email', 'jetpack' ),
1329
				'type'              => 'boolean',
1330
				'default'           => 0,
1331
				'validate_callback' => __CLASS__ . '::validate_boolean',
1332
				'jp_group'          => 'sso',
1333
			),
1334
1335
			// Subscriptions
1336
			'stb_enabled' => array(
1337
				'description'       => esc_html__( "Show a <em>'follow blog'</em> option in the comment form", 'jetpack' ),
1338
				'type'              => 'boolean',
1339
				'default'           => 1,
1340
				'validate_callback' => __CLASS__ . '::validate_boolean',
1341
				'jp_group'          => 'subscriptions',
1342
			),
1343
			'stc_enabled' => array(
1344
				'description'       => esc_html__( "Show a <em>'follow comments'</em> option in the comment form", 'jetpack' ),
1345
				'type'              => 'boolean',
1346
				'default'           => 1,
1347
				'validate_callback' => __CLASS__ . '::validate_boolean',
1348
				'jp_group'          => 'subscriptions',
1349
			),
1350
1351
			// Related Posts
1352
			'show_headline' => array(
1353
				'description'       => esc_html__( 'Show a "Related" header to more clearly separate the related section from posts', 'jetpack' ),
1354
				'type'              => 'boolean',
1355
				'default'           => 1,
1356
				'validate_callback' => __CLASS__ . '::validate_boolean',
1357
				'jp_group'          => 'related-posts',
1358
			),
1359
			'show_thumbnails' => array(
1360
				'description'       => esc_html__( 'Use a large and visually striking layout', 'jetpack' ),
1361
				'type'              => 'boolean',
1362
				'default'           => 0,
1363
				'validate_callback' => __CLASS__ . '::validate_boolean',
1364
				'jp_group'          => 'related-posts',
1365
			),
1366
1367
			// Spelling and Grammar - After the Deadline
1368
			'onpublish' => array(
1369
				'description'       => esc_html__( 'Proofread when a post or page is first published.', 'jetpack' ),
1370
				'type'              => 'boolean',
1371
				'default'           => 0,
1372
				'validate_callback' => __CLASS__ . '::validate_boolean',
1373
				'jp_group'          => 'after-the-deadline',
1374
			),
1375
			'onupdate' => array(
1376
				'description'       => esc_html__( 'Proofread when a post or page is updated.', 'jetpack' ),
1377
				'type'              => 'boolean',
1378
				'default'           => 0,
1379
				'validate_callback' => __CLASS__ . '::validate_boolean',
1380
				'jp_group'          => 'after-the-deadline',
1381
			),
1382
			'Bias Language' => array(
1383
				'description'       => esc_html__( 'Bias Language', 'jetpack' ),
1384
				'type'              => 'boolean',
1385
				'default'           => 0,
1386
				'validate_callback' => __CLASS__ . '::validate_boolean',
1387
				'jp_group'          => 'after-the-deadline',
1388
			),
1389
			'Cliches' => array(
1390
				'description'       => esc_html__( 'Clichés', 'jetpack' ),
1391
				'type'              => 'boolean',
1392
				'default'           => 0,
1393
				'validate_callback' => __CLASS__ . '::validate_boolean',
1394
				'jp_group'          => 'after-the-deadline',
1395
			),
1396
			'Complex Expression' => array(
1397
				'description'       => esc_html__( 'Complex Phrases', 'jetpack' ),
1398
				'type'              => 'boolean',
1399
				'default'           => 0,
1400
				'validate_callback' => __CLASS__ . '::validate_boolean',
1401
				'jp_group'          => 'after-the-deadline',
1402
			),
1403
			'Diacritical Marks' => array(
1404
				'description'       => esc_html__( 'Diacritical Marks', 'jetpack' ),
1405
				'type'              => 'boolean',
1406
				'default'           => 0,
1407
				'validate_callback' => __CLASS__ . '::validate_boolean',
1408
				'jp_group'          => 'after-the-deadline',
1409
			),
1410
			'Double Negative' => array(
1411
				'description'       => esc_html__( 'Double Negatives', 'jetpack' ),
1412
				'type'              => 'boolean',
1413
				'default'           => 0,
1414
				'validate_callback' => __CLASS__ . '::validate_boolean',
1415
				'jp_group'          => 'after-the-deadline',
1416
			),
1417
			'Hidden Verbs' => array(
1418
				'description'       => esc_html__( 'Hidden Verbs', 'jetpack' ),
1419
				'type'              => 'boolean',
1420
				'default'           => 0,
1421
				'validate_callback' => __CLASS__ . '::validate_boolean',
1422
				'jp_group'          => 'after-the-deadline',
1423
			),
1424
			'Jargon Language' => array(
1425
				'description'       => esc_html__( 'Jargon', 'jetpack' ),
1426
				'type'              => 'boolean',
1427
				'default'           => 0,
1428
				'validate_callback' => __CLASS__ . '::validate_boolean',
1429
				'jp_group'          => 'after-the-deadline',
1430
			),
1431
			'Passive voice' => array(
1432
				'description'       => esc_html__( 'Passive Voice', 'jetpack' ),
1433
				'type'              => 'boolean',
1434
				'default'           => 0,
1435
				'validate_callback' => __CLASS__ . '::validate_boolean',
1436
				'jp_group'          => 'after-the-deadline',
1437
			),
1438
			'Phrases to Avoid' => array(
1439
				'description'       => esc_html__( 'Phrases to Avoid', 'jetpack' ),
1440
				'type'              => 'boolean',
1441
				'default'           => 0,
1442
				'validate_callback' => __CLASS__ . '::validate_boolean',
1443
				'jp_group'          => 'after-the-deadline',
1444
			),
1445
			'Redundant Expression' => array(
1446
				'description'       => esc_html__( 'Redundant Phrases', 'jetpack' ),
1447
				'type'              => 'boolean',
1448
				'default'           => 0,
1449
				'validate_callback' => __CLASS__ . '::validate_boolean',
1450
				'jp_group'          => 'after-the-deadline',
1451
			),
1452
			'guess_lang' => array(
1453
				'description'       => esc_html__( 'Use automatically detected language to proofread posts and pages', 'jetpack' ),
1454
				'type'              => 'boolean',
1455
				'default'           => 0,
1456
				'validate_callback' => __CLASS__ . '::validate_boolean',
1457
				'jp_group'          => 'after-the-deadline',
1458
			),
1459
			'ignored_phrases' => array(
1460
				'description'       => esc_html__( 'Add Phrase to be ignored', 'jetpack' ),
1461
				'type'              => 'string',
1462
				'default'           => '',
1463
				'sanitize_callback' => 'esc_html',
1464
				'jp_group'          => 'after-the-deadline',
1465
			),
1466
			'unignore_phrase' => array(
1467
				'description'       => esc_html__( 'Remove Phrase from being ignored', 'jetpack' ),
1468
				'type'              => 'string',
1469
				'default'           => '',
1470
				'sanitize_callback' => 'esc_html',
1471
				'jp_group'          => 'after-the-deadline',
1472
			),
1473
1474
			// Verification Tools
1475
			'google' => array(
1476
				'description'       => esc_html__( 'Google Search Console', 'jetpack' ),
1477
				'type'              => 'string',
1478
				'default'           => '',
1479
				'validate_callback' => __CLASS__ . '::validate_verification_service',
1480
				'jp_group'          => 'verification-tools',
1481
			),
1482
			'bing' => array(
1483
				'description'       => esc_html__( 'Bing Webmaster Center', 'jetpack' ),
1484
				'type'              => 'string',
1485
				'default'           => '',
1486
				'validate_callback' => __CLASS__ . '::validate_verification_service',
1487
				'jp_group'          => 'verification-tools',
1488
			),
1489
			'pinterest' => array(
1490
				'description'       => esc_html__( 'Pinterest Site Verification', 'jetpack' ),
1491
				'type'              => 'string',
1492
				'default'           => '',
1493
				'validate_callback' => __CLASS__ . '::validate_verification_service',
1494
				'jp_group'          => 'verification-tools',
1495
			),
1496
			'yandex' => array(
1497
				'description'       => esc_html__( 'Yandex Site Verification', 'jetpack' ),
1498
				'type'              => 'string',
1499
				'default'           => '',
1500
				'validate_callback' => __CLASS__ . '::validate_verification_service',
1501
				'jp_group'          => 'verification-tools',
1502
			),
1503
			'enable_header_ad' => array(
1504
				'description'        => esc_html__( 'Display an ad unit at the top of each page.', 'jetpack' ),
1505
				'type'               => 'boolean',
1506
				'default'            => 0,
1507
				'validate_callback'  => __CLASS__ . '::validate_boolean',
1508
				'jp_group'           => 'wordads',
1509
			),
1510
			'wordads_approved' => array(
1511
				'description'        => esc_html__( 'Is site approved for WordAds?', 'jetpack' ),
1512
				'type'               => 'boolean',
1513
				'default'            => 0,
1514
				'validate_callback'  => __CLASS__ . '::validate_boolean',
1515
				'jp_group'           => 'wordads',
1516
			),
1517
1518
			// Google Analytics
1519
			'google_analytics_tracking_id' => array(
1520
				'description'        => esc_html__( 'Google Analytics', 'jetpack' ),
1521
				'type'               => 'string',
1522
				'default'            => '',
1523
				'validate_callback'  => __CLASS__ . '::validate_alphanum',
1524
				'jp_group'           => 'google-analytics',
1525
			),
1526
1527
			// Stats
1528
			'admin_bar' => array(
1529
				'description'       => esc_html__( 'Put a chart showing 48 hours of views in the admin bar.', 'jetpack' ),
1530
				'type'              => 'boolean',
1531
				'default'           => 1,
1532
				'validate_callback' => __CLASS__ . '::validate_boolean',
1533
				'jp_group'          => 'stats',
1534
			),
1535
			'roles' => array(
1536
				'description'       => esc_html__( 'Select the roles that will be able to view stats reports.', 'jetpack' ),
1537
				'type'              => 'array',
1538
				'items'             => array(
1539
					'type' => 'string'
1540
				),
1541
				'default'           => array( 'administrator' ),
1542
				'validate_callback' => __CLASS__ . '::validate_stats_roles',
1543
				'sanitize_callback' => __CLASS__ . '::sanitize_stats_allowed_roles',
1544
				'jp_group'          => 'stats',
1545
			),
1546
			'count_roles' => array(
1547
				'description'       => esc_html__( 'Count the page views of registered users who are logged in.', 'jetpack' ),
1548
				'type'              => 'array',
1549
				'items'             => array(
1550
					'type' => 'string'
1551
				),
1552
				'default'           => array( 'administrator' ),
1553
				'validate_callback' => __CLASS__ . '::validate_stats_roles',
1554
				'jp_group'          => 'stats',
1555
			),
1556
			'blog_id' => array(
1557
				'description'       => esc_html__( 'Blog ID.', 'jetpack' ),
1558
				'type'              => 'boolean',
1559
				'default'           => 0,
1560
				'validate_callback' => __CLASS__ . '::validate_boolean',
1561
				'jp_group'          => 'stats',
1562
			),
1563
			'do_not_track' => array(
1564
				'description'       => esc_html__( 'Do not track.', 'jetpack' ),
1565
				'type'              => 'boolean',
1566
				'default'           => 1,
1567
				'validate_callback' => __CLASS__ . '::validate_boolean',
1568
				'jp_group'          => 'stats',
1569
			),
1570
			'hide_smile' => array(
1571
				'description'       => esc_html__( 'Hide the stats smiley face image.', 'jetpack' ),
1572
				'type'              => 'boolean',
1573
				'default'           => 1,
1574
				'validate_callback' => __CLASS__ . '::validate_boolean',
1575
				'jp_group'          => 'stats',
1576
			),
1577
			'version' => array(
1578
				'description'       => esc_html__( 'Version.', 'jetpack' ),
1579
				'type'              => 'integer',
1580
				'default'           => 9,
1581
				'validate_callback' => __CLASS__ . '::validate_posint',
1582
				'jp_group'          => 'stats',
1583
			),
1584
1585
			// Settings - Not a module
1586
			self::holiday_snow_option_name() => array(
1587
				'description'       => '',
1588
				'type'              => 'boolean',
1589
				'default'           => 0,
1590
				'validate_callback' => __CLASS__ . '::validate_boolean',
1591
				'jp_group'          => 'settings',
1592
			),
1593
1594
			// Akismet - Not a module, but a plugin. The options can be passed and handled differently.
1595
			'akismet_show_user_comments_approved' => array(
1596
				'description'       => '',
1597
				'type'              => 'boolean',
1598
				'default'           => 0,
1599
				'validate_callback' => __CLASS__ . '::validate_boolean',
1600
				'jp_group'          => 'settings',
1601
			),
1602
1603
		);
1604
1605
		// Add modules to list so they can be toggled
1606
		$modules = Jetpack::get_available_modules();
1607
		if ( is_array( $modules ) && ! empty( $modules ) ) {
1608
			$module_args = array(
1609
				'description'       => '',
1610
				'type'              => 'boolean',
1611
				'default'           => 0,
1612
				'validate_callback' => __CLASS__ . '::validate_boolean',
1613
				'jp_group'          => 'modules',
1614
			);
1615
			foreach( $modules as $module ) {
1616
				$options[ $module ] = $module_args;
1617
			}
1618
		}
1619
1620
		if ( is_array( $selector ) ) {
1621
1622
			// Return only those options whose keys match $selector keys
1623
			return array_intersect_key( $options, $selector );
1624
		}
1625
1626
		if ( 'any' === $selector ) {
1627
1628
			// Toggle module or update any module option or any general setting
1629
			return $options;
1630
		}
1631
1632
		// We're updating the options for a single module.
1633
		if ( empty( $selector ) ) {
1634
			$selector = self::get_module_requested();
1635
		}
1636
		$selected = array();
1637
		foreach ( $options as $option => $attributes ) {
1638
1639
			// Not adding an isset( $attributes['jp_group'] ) because if it's not set, it must be fixed, otherwise options will fail.
1640
			if ( $selector === $attributes['jp_group'] ) {
1641
				$selected[ $option ] = $attributes;
1642
			}
1643
		}
1644
		return $selected;
1645
	}
1646
1647
	/**
1648
	 * Validates that the parameter is either a pure boolean or a numeric string that can be mapped to a boolean.
1649
	 *
1650
	 * @since 4.3.0
1651
	 *
1652
	 * @param string|bool $value Value to check.
1653
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1654
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1655
	 *
1656
	 * @return bool
1657
	 */
1658
	public static function validate_boolean( $value, $request, $param ) {
1659
		if ( ! is_bool( $value ) && ! ( ( ctype_digit( $value ) || is_numeric( $value ) ) && in_array( $value, array( 0, 1 ) ) ) ) {
1660
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be true, false, 0 or 1.', 'jetpack' ), $param ) );
1661
		}
1662
		return true;
1663
	}
1664
1665
	/**
1666
	 * Validates that the parameter is a positive integer.
1667
	 *
1668
	 * @since 4.3.0
1669
	 *
1670
	 * @param int $value Value to check.
1671
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1672
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1673
	 *
1674
	 * @return bool
1675
	 */
1676
	public static function validate_posint( $value = 0, $request, $param ) {
1677
		if ( ! is_numeric( $value ) || $value <= 0 ) {
1678
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a positive integer.', 'jetpack' ), $param ) );
1679
		}
1680
		return true;
1681
	}
1682
1683
	/**
1684
	 * Validates that the parameter belongs to a list of admitted values.
1685
	 *
1686
	 * @since 4.3.0
1687
	 *
1688
	 * @param string $value Value to check.
1689
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1690
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1691
	 *
1692
	 * @return bool
1693
	 */
1694
	public static function validate_list_item( $value = '', $request, $param ) {
1695
		$attributes = $request->get_attributes();
1696
		if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
1697
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s not recognized', 'jetpack' ), $param ) );
1698
		}
1699
		$args = $attributes['args'][ $param ];
1700
		if ( ! empty( $args['enum'] ) ) {
1701
1702
			// If it's an associative array, use the keys to check that the value is among those admitted.
1703
			$enum = ( count( array_filter( array_keys( $args['enum'] ), 'is_string' ) ) > 0 ) ? array_keys( $args['enum'] ) : $args['enum'];
1704 View Code Duplication
			if ( ! in_array( $value, $enum ) ) {
1705
				return new WP_Error( 'invalid_param_value', sprintf(
1706
					/* Translators: first variable is the parameter passed to endpoint that holds the list item, the second is a list of admitted values. */
1707
					esc_html__( '%1$s must be one of %2$s', 'jetpack' ), $param, implode( ', ', $enum )
1708
				) );
1709
			}
1710
		}
1711
		return true;
1712
	}
1713
1714
	/**
1715
	 * Validates that the parameter belongs to a list of admitted values.
1716
	 *
1717
	 * @since 4.3.0
1718
	 *
1719
	 * @param string $value Value to check.
1720
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1721
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1722
	 *
1723
	 * @return bool
1724
	 */
1725
	public static function validate_module_list( $value = '', $request, $param ) {
1726 View Code Duplication
		if ( ! is_array( $value ) ) {
1727
			return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be an array', 'jetpack' ), $param ) );
1728
		}
1729
1730
		$modules = Jetpack::get_available_modules();
1731
1732 View Code Duplication
		if ( count( array_intersect( $value, $modules ) ) != count( $value ) ) {
1733
			return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be a list of valid modules', 'jetpack' ), $param ) );
1734
		}
1735
1736
		return true;
1737
	}
1738
1739
	/**
1740
	 * Validates that the parameter is an alphanumeric or empty string (to be able to clear the field).
1741
	 *
1742
	 * @since 4.3.0
1743
	 *
1744
	 * @param string $value Value to check.
1745
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1746
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1747
	 *
1748
	 * @return bool
1749
	 */
1750
	public static function validate_alphanum( $value = '', $request, $param ) {
1751 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/^[a-z0-9]+$/i', $value ) ) ) {
1752
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an alphanumeric string.', 'jetpack' ), $param ) );
1753
		}
1754
		return true;
1755
	}
1756
1757
	/**
1758
	 * Validates that the parameter is a tag or id for a verification service, or an empty string (to be able to clear the field).
1759
	 *
1760
	 * @since 4.6.0
1761
	 *
1762
	 * @param string $value Value to check.
1763
	 * @param WP_REST_Request $request
1764
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1765
	 *
1766
	 * @return bool
1767
	 */
1768
	public static function validate_verification_service( $value = '', $request, $param ) {
1769 View Code Duplication
		if ( ! empty( $value ) && ! ( is_string( $value ) && ( preg_match( '/^[a-z0-9_-]+$/i', $value ) || preg_match( '#^<meta name="([a-z0-9_\-.:]+)?" content="([a-z0-9_-]+)?" />$#i', $value ) ) ) ) {
1770
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an alphanumeric string or a verification tag.', 'jetpack' ), $param ) );
1771
		}
1772
		return true;
1773
	}
1774
1775
	/**
1776
	 * Validates that the parameter is among the roles allowed for Stats.
1777
	 *
1778
	 * @since 4.3.0
1779
	 *
1780
	 * @param string|bool $value Value to check.
1781
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1782
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1783
	 *
1784
	 * @return bool
1785
	 */
1786
	public static function validate_stats_roles( $value, $request, $param ) {
1787
		if ( ! empty( $value ) && ! array_intersect( self::$stats_roles, $value ) ) {
1788
			return new WP_Error( 'invalid_param', sprintf(
1789
				/* 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. */
1790
				esc_html__( '%1$s must be %2$s.', 'jetpack' ), $param, join( ', ', self::$stats_roles )
1791
			) );
1792
		}
1793
		return true;
1794
	}
1795
1796
	/**
1797
	 * Validates that the parameter is among the views where the Sharing can be displayed.
1798
	 *
1799
	 * @since 4.3.0
1800
	 *
1801
	 * @param string|bool $value Value to check.
1802
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1803
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1804
	 *
1805
	 * @return bool
1806
	 */
1807
	public static function validate_sharing_show( $value, $request, $param ) {
1808
		$views = array( 'index', 'post', 'page', 'attachment', 'jetpack-portfolio' );
1809 View Code Duplication
		if ( ! is_array( $value ) ) {
1810
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array of post types.', 'jetpack' ), $param ) );
1811
		}
1812
		if ( ! array_intersect( $views, $value ) ) {
1813
			return new WP_Error( 'invalid_param', sprintf(
1814
				/* 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 */
1815
				esc_html__( '%1$s must be %2$s.', 'jetpack' ), $param, join( ', ', $views )
1816
			) );
1817
		}
1818
		return true;
1819
	}
1820
1821
	/**
1822
	 * Validates that the parameter is among the views where the Sharing can be displayed.
1823
	 *
1824
	 * @since 4.3.0
1825
	 *
1826
	 * @param string|bool $value {
1827
	 *     Value to check received by request.
1828
	 *
1829
	 *     @type array $visible List of slug of services to share to that are displayed directly in the page.
1830
	 *     @type array $hidden  List of slug of services to share to that are concealed in a folding menu.
1831
	 * }
1832
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1833
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1834
	 *
1835
	 * @return bool
1836
	 */
1837
	public static function validate_services( $value, $request, $param ) {
1838 View Code Duplication
		if ( ! is_array( $value ) || ! isset( $value['visible'] ) || ! isset( $value['hidden'] ) ) {
1839
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array with visible and hidden items.', 'jetpack' ), $param ) );
1840
		}
1841
1842
		// Allow to clear everything.
1843
		if ( empty( $value['visible'] ) && empty( $value['hidden'] ) ) {
1844
			return true;
1845
		}
1846
1847 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
1848
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
1849
		}
1850
		$sharer = new Sharing_Service();
1851
		$services = array_keys( $sharer->get_all_services() );
1852
1853
		if (
1854
			( ! empty( $value['visible'] ) && ! array_intersect( $value['visible'], $services ) )
1855
			||
1856
			( ! empty( $value['hidden'] ) && ! array_intersect( $value['hidden'], $services ) ) )
1857
		{
1858
			return new WP_Error( 'invalid_param', sprintf(
1859
				/* Translators: placeholder 1 is a parameter holding the services passed to endpoint, placeholder 2 is a list of all Jetpack Sharing services */
1860
				esc_html__( '%1$s visible and hidden items must be a list of %2$s.', 'jetpack' ), $param, join( ', ', $services )
1861
			) );
1862
		}
1863
		return true;
1864
	}
1865
1866
	/**
1867
	 * Validates that the parameter has enough information to build a custom sharing button.
1868
	 *
1869
	 * @since 4.3.0
1870
	 *
1871
	 * @param string|bool $value Value to check.
1872
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1873
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1874
	 *
1875
	 * @return bool
1876
	 */
1877
	public static function validate_custom_service( $value, $request, $param ) {
1878 View Code Duplication
		if ( ! is_array( $value ) || ! isset( $value['sharing_name'] ) || ! isset( $value['sharing_url'] ) || ! isset( $value['sharing_icon'] ) ) {
1879
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array with sharing name, url and icon.', 'jetpack' ), $param ) );
1880
		}
1881
1882
		// Allow to clear everything.
1883
		if ( empty( $value['sharing_name'] ) && empty( $value['sharing_url'] ) && empty( $value['sharing_icon'] ) ) {
1884
			return true;
1885
		}
1886
1887 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
1888
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
1889
		}
1890
1891
		if ( ( ! empty( $value['sharing_name'] ) && ! is_string( $value['sharing_name'] ) )
1892
		|| ( ! empty( $value['sharing_url'] ) && ! is_string( $value['sharing_url'] ) )
1893
		|| ( ! empty( $value['sharing_icon'] ) && ! is_string( $value['sharing_icon'] ) ) ) {
1894
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s needs sharing name, url and icon.', 'jetpack' ), $param ) );
1895
		}
1896
		return true;
1897
	}
1898
1899
	/**
1900
	 * Validates that the parameter is a custom sharing service ID like 'custom-1461976264'.
1901
	 *
1902
	 * @since 4.3.0
1903
	 *
1904
	 * @param string $value Value to check.
1905
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1906
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1907
	 *
1908
	 * @return bool
1909
	 */
1910
	public static function validate_custom_service_id( $value = '', $request, $param ) {
1911 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/custom\-[0-1]+/i', $value ) ) ) {
1912
			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 ) );
1913
		}
1914
1915 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
1916
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
1917
		}
1918
		$sharer = new Sharing_Service();
1919
		$services = array_keys( $sharer->get_all_services() );
1920
1921 View Code Duplication
		if ( ! empty( $value ) && ! in_array( $value, $services ) ) {
1922
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s is not a registered custom sharing service.', 'jetpack' ), $param ) );
1923
		}
1924
1925
		return true;
1926
	}
1927
1928
	/**
1929
	 * Validates that the parameter is a Twitter username or empty string (to be able to clear the field).
1930
	 *
1931
	 * @since 4.3.0
1932
	 *
1933
	 * @param string $value Value to check.
1934
	 * @param WP_REST_Request $request
1935
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1936
	 *
1937
	 * @return bool
1938
	 */
1939
	public static function validate_twitter_username( $value = '', $request, $param ) {
1940 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/^@?\w{1,15}$/i', $value ) ) ) {
1941
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a Twitter username.', 'jetpack' ), $param ) );
1942
		}
1943
		return true;
1944
	}
1945
1946
	/**
1947
	 * Validates that the parameter is a string.
1948
	 *
1949
	 * @since 4.3.0
1950
	 *
1951
	 * @param string $value Value to check.
1952
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1953
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1954
	 *
1955
	 * @return bool
1956
	 */
1957
	public static function validate_string( $value = '', $request, $param ) {
1958
		if ( ! is_string( $value ) ) {
1959
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a string.', 'jetpack' ), $param ) );
1960
		}
1961
		return true;
1962
	}
1963
1964
	/**
1965
	 * If for some reason the roles allowed to see Stats are empty (for example, user tampering with checkboxes),
1966
	 * return an array with only 'administrator' as the allowed role and save it for 'roles' option.
1967
	 *
1968
	 * @since 4.3.0
1969
	 *
1970
	 * @param string|bool $value Value to check.
1971
	 *
1972
	 * @return bool
1973
	 */
1974
	public static function sanitize_stats_allowed_roles( $value ) {
1975
		if ( empty( $value ) ) {
1976
			return array( 'administrator' );
1977
		}
1978
		return $value;
1979
	}
1980
1981
	/**
1982
	 * Get the currently accessed route and return the module slug in it.
1983
	 *
1984
	 * @since 4.3.0
1985
	 *
1986
	 * @param string $route Regular expression for the endpoint with the module slug to return.
1987
	 *
1988
	 * @return array
1989
	 */
1990
	public static function get_module_requested( $route = '/module/(?P<slug>[a-z\-]+)' ) {
1991
1992
		if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
1993
			return '';
1994
		}
1995
1996
		preg_match( "#$route#", $GLOBALS['wp']->query_vars['rest_route'], $module );
1997
1998
		if ( empty( $module['slug'] ) ) {
1999
			return '';
2000
		}
2001
2002
		return $module['slug'];
2003
	}
2004
2005
	/**
2006
	 * Adds extra information for modules.
2007
	 *
2008
	 * @since 4.3.0
2009
	 *
2010
	 * @param string      $modules Can be a single module or a list of modules.
2011
	 * @param null|string $slug    Slug of the module in the first parameter.
2012
	 *
2013
	 * @return array
2014
	 */
2015
	public static function prepare_modules_for_response( $modules = '', $slug = null ) {
2016
		if ( get_option( 'permalink_structure' ) ) {
2017
			$sitemap_url = home_url( '/sitemap.xml' );
2018
			$news_sitemap_url = home_url( '/news-sitemap.xml' );
2019
		} else {
2020
			$sitemap_url = home_url( '/?jetpack-sitemap=true' );
2021
			$news_sitemap_url = home_url( '/?jetpack-news-sitemap=true' );
2022
		}
2023
		/** This filter is documented in modules/sitemaps/sitemaps.php */
2024
		$sitemap_url = apply_filters( 'jetpack_sitemap_location', $sitemap_url );
2025
		/** This filter is documented in modules/sitemaps/sitemaps.php */
2026
		$news_sitemap_url = apply_filters( 'jetpack_news_sitemap_location', $news_sitemap_url );
2027
2028
		if ( is_null( $slug ) && isset( $modules['sitemaps'] ) ) {
2029
			// Is a list of modules
2030
			$modules['sitemaps']['extra']['sitemap_url'] = $sitemap_url;
2031
			$modules['sitemaps']['extra']['news_sitemap_url'] = $news_sitemap_url;
2032
		} elseif ( 'sitemaps' == $slug ) {
2033
			// It's a single module
2034
			$modules['extra']['sitemap_url'] = $sitemap_url;
2035
			$modules['extra']['news_sitemap_url'] = $news_sitemap_url;
2036
		}
2037
		return $modules;
2038
	}
2039
2040
	/**
2041
	 * Remove 'validate_callback' item from options available for module.
2042
	 * Fetch current option value and add to array of module options.
2043
	 * Prepare values of module options that need special handling, like those saved in wpcom.
2044
	 *
2045
	 * @since 4.3.0
2046
	 *
2047
	 * @param string $module Module slug.
2048
	 * @return array
2049
	 */
2050
	public static function prepare_options_for_response( $module = '' ) {
2051
		$options = self::get_updateable_data_list( $module );
2052
2053
		if ( ! is_array( $options ) || empty( $options ) ) {
2054
			return $options;
2055
		}
2056
2057
		foreach ( $options as $key => $value ) {
2058
2059
			if ( isset( $options[ $key ]['validate_callback'] ) ) {
2060
				unset( $options[ $key ]['validate_callback'] );
2061
			}
2062
2063
			$default_value = isset( $options[ $key ]['default'] ) ? $options[ $key ]['default'] : '';
2064
2065
			$current_value = get_option( $key, $default_value );
2066
2067
			$options[ $key ]['current_value'] = self::cast_value( $current_value, $options[ $key ] );
2068
		}
2069
2070
		// Some modules need special treatment.
2071
		switch ( $module ) {
2072
2073
			case 'monitor':
2074
				// Status of user notifications
2075
				$options['monitor_receive_notifications']['current_value'] = self::cast_value( self::get_remote_value( 'monitor', 'monitor_receive_notifications' ), $options['monitor_receive_notifications'] );
2076
				break;
2077
2078
			case 'post-by-email':
2079
				// Email address
2080
				$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'] );
2081
				break;
2082
2083
			case 'protect':
2084
				// Protect
2085
				$options['jetpack_protect_key']['current_value'] = get_site_option( 'jetpack_protect_key', false );
2086
				if ( ! function_exists( 'jetpack_protect_format_whitelist' ) ) {
2087
					@include( JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php' );
2088
				}
2089
				$options['jetpack_protect_global_whitelist']['current_value'] = jetpack_protect_format_whitelist();
2090
				break;
2091
2092
			case 'related-posts':
2093
				// It's local, but it must be broken apart since it's saved as an array.
2094
				$options = self::split_options( $options, Jetpack_Options::get_option( 'relatedposts' ) );
2095
				break;
2096
2097
			case 'verification-tools':
2098
				// It's local, but it must be broken apart since it's saved as an array.
2099
				$options = self::split_options( $options, get_option( 'verification_services_codes' ) );
2100
				break;
2101
2102
			case 'google-analytics':
2103
				$wga = get_option( 'jetpack_wga' );
2104
				$code = '';
2105
				if ( is_array( $wga ) && array_key_exists( 'code', $wga ) ) {
2106
					 $code = $wga[ 'code' ];
2107
				}
2108
				$options[ 'google_analytics_tracking_id' ][ 'current_value' ] = $code;
2109
				break;
2110
2111 View Code Duplication
			case 'sharedaddy':
2112
				// It's local, but it must be broken apart since it's saved as an array.
2113
				if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
2114
					break;
2115
				}
2116
				$sharer = new Sharing_Service();
2117
				$options = self::split_options( $options, $sharer->get_global_options() );
2118
				$options['sharing_services']['current_value'] = $sharer->get_blog_services();
2119
				break;
2120
2121
			case 'after-the-deadline':
2122
				if ( ! function_exists( 'AtD_get_options' ) ) {
2123
					@include( JETPACK__PLUGIN_DIR . 'modules/after-the-deadline.php' );
2124
				}
2125
				$atd_options = array_merge( AtD_get_options( get_current_user_id(), 'AtD_options' ), AtD_get_options( get_current_user_id(), 'AtD_check_when' ) );
2126
				unset( $atd_options['name'] );
2127
				foreach ( $atd_options as $key => $value ) {
2128
					$options[ $key ]['current_value'] = self::cast_value( $value, $options[ $key ] );
2129
				}
2130
				$atd_options = AtD_get_options( get_current_user_id(), 'AtD_guess_lang' );
2131
				$options['guess_lang']['current_value'] = self::cast_value( isset( $atd_options['true'] ), $options[ 'guess_lang' ] );
2132
				$options['ignored_phrases']['current_value'] = AtD_get_setting( get_current_user_id(), 'AtD_ignored_phrases' );
2133
				unset( $options['unignore_phrase'] );
2134
				break;
2135
2136
			case 'stats':
2137
				// It's local, but it must be broken apart since it's saved as an array.
2138
				if ( ! function_exists( 'stats_get_options' ) ) {
2139
					@include( JETPACK__PLUGIN_DIR . 'modules/stats.php' );
2140
				}
2141
				$options = self::split_options( $options, stats_get_options() );
2142
				break;
2143
		}
2144
2145
		return $options;
2146
	}
2147
2148
	/**
2149
	 * Splits module options saved as arrays like relatedposts or verification_services_codes into separate options to be returned in the response.
2150
	 *
2151
	 * @since 4.3.0
2152
	 *
2153
	 * @param array  $separate_options Array of options admitted by the module.
2154
	 * @param array  $grouped_options Option saved as array to be splitted.
2155
	 * @param string $prefix Optional prefix for the separate option keys.
2156
	 *
2157
	 * @return array
2158
	 */
2159
	public static function split_options( $separate_options, $grouped_options, $prefix = '' ) {
2160
		if ( is_array( $grouped_options ) ) {
2161
			foreach ( $grouped_options as $key => $value ) {
2162
				$option_key = $prefix . $key;
2163
				if ( isset( $separate_options[ $option_key ] ) ) {
2164
					$separate_options[ $option_key ]['current_value'] = self::cast_value( $grouped_options[ $key ], $separate_options[ $option_key ] );
2165
				}
2166
			}
2167
		}
2168
		return $separate_options;
2169
	}
2170
2171
	/**
2172
	 * Perform a casting to the value specified in the option definition.
2173
	 *
2174
	 * @since 4.3.0
2175
	 *
2176
	 * @param mixed $value Value to cast to the proper type.
2177
	 * @param array $definition Type to cast the value to.
2178
	 *
2179
	 * @return bool|float|int|string
2180
	 */
2181
	public static function cast_value( $value, $definition ) {
2182
		if ( $value === 'NULL' ) {
2183
			return null;
2184
		}
2185
2186
		if ( isset( $definition['type'] ) ) {
2187
			switch ( $definition['type'] ) {
2188
				case 'boolean':
2189
					if ( 'true' === $value ) {
2190
						return true;
2191
					} elseif ( 'false' === $value ) {
2192
						return false;
2193
					}
2194
					return (bool) $value;
2195
					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...
2196
2197
				case 'integer':
2198
					return (int) $value;
2199
					break;
2200
2201
				case 'float':
2202
					return (float) $value;
2203
					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...
2204
2205
				case 'string':
2206
					return (string) $value;
2207
					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...
2208
			}
2209
		}
2210
		return $value;
2211
	}
2212
2213
	/**
2214
	 * Get a value not saved locally.
2215
	 *
2216
	 * @since 4.3.0
2217
	 *
2218
	 * @param string $module Module slug.
2219
	 * @param string $option Option name.
2220
	 *
2221
	 * @return bool Whether user is receiving notifications or not.
2222
	 */
2223
	public static function get_remote_value( $module, $option ) {
2224
2225
		if ( in_array( $module, array( 'post-by-email' ), true ) ) {
2226
			$option .= get_current_user_id();
2227
		}
2228
2229
		// If option doesn't exist, 'does_not_exist' will be returned.
2230
		$value = get_option( $option, 'does_not_exist' );
2231
2232
		// If option exists, just return it.
2233
		if ( 'does_not_exist' !== $value ) {
2234
			return $value;
2235
		}
2236
2237
		// Only check a remote option if Jetpack is connected.
2238
		if ( ! Jetpack::is_active() ) {
2239
			return false;
2240
		}
2241
2242
		// If the module is inactive, load the class to use the method.
2243
		if ( ! did_action( 'jetpack_module_loaded_' . $module ) ) {
2244
			// Class can't be found so do nothing.
2245
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
2246
				return false;
2247
			}
2248
		}
2249
2250
		// Do what is necessary for each module.
2251
		switch ( $module ) {
2252
			case 'monitor':
2253
				$monitor = new Jetpack_Monitor();
2254
				$value = $monitor->user_receives_notifications( false );
2255
				break;
2256
2257
			case 'post-by-email':
2258
				$post_by_email = new Jetpack_Post_By_Email();
2259
				$value = $post_by_email->get_post_by_email_address();
2260
				if ( $value === null ) {
2261
					$value = 'NULL'; // sentinel value so it actually gets set
2262
				}
2263
				break;
2264
		}
2265
2266
		// Normalize value to boolean.
2267
		if ( is_wp_error( $value ) || is_null( $value ) ) {
2268
			$value = false;
2269
		}
2270
2271
		// Save option to use it next time.
2272
		update_option( $option, $value );
2273
2274
		return $value;
2275
	}
2276
2277
	/**
2278
	 * Get number of plugin updates available.
2279
	 *
2280
	 * @since 4.3.0
2281
	 *
2282
	 * @return mixed|WP_Error Number of plugin updates available. Otherwise, a WP_Error instance with the corresponding error.
2283
	 */
2284
	public static function get_plugin_update_count() {
2285
		$updates = wp_get_update_data();
2286
		if ( isset( $updates['counts'] ) && isset( $updates['counts']['plugins'] ) ) {
2287
			$count = $updates['counts']['plugins'];
2288
			if ( 0 == $count ) {
2289
				$response = array(
2290
					'code'    => 'success',
2291
					'message' => esc_html__( 'All plugins are up-to-date. Keep up the good work!', 'jetpack' ),
2292
					'count'   => 0,
2293
				);
2294
			} else {
2295
				$response = array(
2296
					'code'    => 'updates-available',
2297
					'message' => esc_html( sprintf( _n( '%s plugin need updating.', '%s plugins need updating.', $count, 'jetpack' ), $count ) ),
2298
					'count'   => $count,
2299
				);
2300
			}
2301
			return rest_ensure_response( $response );
2302
		}
2303
2304
		return new WP_Error( 'not_found', esc_html__( 'Could not check updates for plugins on this site.', 'jetpack' ), array( 'status' => 404 ) );
2305
	}
2306
2307
2308
	/**
2309
	 * Returns a list of all plugins in the site.
2310
	 *
2311
	 * @since 4.2.0
2312
	 * @uses get_plugins()
2313
	 *
2314
	 * @return array
2315
	 */
2316
	private static function core_get_plugins() {
2317
		if ( ! function_exists( 'get_plugins' ) ) {
2318
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2319
		}
2320
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2321
		$plugins = apply_filters( 'all_plugins', get_plugins() );
2322
2323
		if ( is_array( $plugins ) && ! empty( $plugins ) ) {
2324
			foreach ( $plugins as $plugin_slug => $plugin_data ) {
2325
				$plugins[ $plugin_slug ]['active'] = self::core_is_plugin_active( $plugin_slug );
2326
			}
2327
			return $plugins;
2328
		}
2329
2330
		return array();
2331
	}
2332
2333
	/**
2334
	 * Checks if the queried plugin is active.
2335
	 *
2336
	 * @since 4.2.0
2337
	 * @uses is_plugin_active()
2338
	 *
2339
	 * @return bool
2340
	 */
2341
	private static function core_is_plugin_active( $plugin ) {
2342
		if ( ! function_exists( 'get_plugins' ) ) {
2343
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2344
		}
2345
2346
		return is_plugin_active( $plugin );
2347
	}
2348
2349
	/**
2350
	 * Get plugins data in site.
2351
	 *
2352
	 * @since 4.2.0
2353
	 *
2354
	 * @return WP_REST_Response|WP_Error List of plugins in the site. Otherwise, a WP_Error instance with the corresponding error.
2355
	 */
2356
	public static function get_plugins() {
2357
		$plugins = self::core_get_plugins();
2358
2359
		if ( ! empty( $plugins ) ) {
2360
			return rest_ensure_response( $plugins );
2361
		}
2362
2363
		return new WP_Error( 'not_found', esc_html__( 'Unable to list plugins.', 'jetpack' ), array( 'status' => 404 ) );
2364
	}
2365
2366
	/**
2367
	 * Get data about the queried plugin. Currently it only returns whether the plugin is active or not.
2368
	 *
2369
	 * @since 4.2.0
2370
	 *
2371
	 * @param WP_REST_Request $request {
2372
	 *     Array of parameters received by request.
2373
	 *
2374
	 *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
2375
	 * }
2376
	 *
2377
	 * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
2378
	 */
2379
	public static function get_plugin( $request ) {
2380
2381
		$plugins = self::core_get_plugins();
2382
2383
		if ( empty( $plugins ) ) {
2384
			return new WP_Error( 'no_plugins_found', esc_html__( 'This site has no plugins.', 'jetpack' ), array( 'status' => 404 ) );
2385
		}
2386
2387
		$plugin = stripslashes( $request['plugin'] );
2388
2389
		if ( ! in_array( $plugin, array_keys( $plugins ) ) ) {
2390
			return new WP_Error( 'plugin_not_found', esc_html( sprintf( __( 'Plugin %s is not installed.', 'jetpack' ), $plugin ) ), array( 'status' => 404 ) );
2391
		}
2392
2393
		$plugin_data = $plugins[ $plugin ];
2394
2395
		$plugin_data['active'] = self::core_is_plugin_active( $plugin );
2396
2397
		return rest_ensure_response( array(
2398
			'code'    => 'success',
2399
			'message' => esc_html__( 'Plugin found.', 'jetpack' ),
2400
			'data'    => $plugin_data
2401
		) );
2402
	}
2403
2404
} // class end
2405