Completed
Push — add/changelog-55 ( 8beac4...406ec3 )
by Jeremy
15:59 queued 07:35
created

_inc/lib/class.core-rest-api-endpoints.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
2221
		if ( ! is_string( $value ) ) {
2222
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a string.', 'jetpack' ), $param ) );
2223
		}
2224
		return true;
2225
	}
2226
2227
	/**
2228
	 * If for some reason the roles allowed to see Stats are empty (for example, user tampering with checkboxes),
2229
	 * return an array with only 'administrator' as the allowed role and save it for 'roles' option.
2230
	 *
2231
	 * @since 4.3.0
2232
	 *
2233
	 * @param string|bool $value Value to check.
2234
	 *
2235
	 * @return bool|array
2236
	 */
2237
	public static function sanitize_stats_allowed_roles( $value ) {
2238
		if ( empty( $value ) ) {
2239
			return array( 'administrator' );
2240
		}
2241
		return $value;
2242
	}
2243
2244
	/**
2245
	 * Get the currently accessed route and return the module slug in it.
2246
	 *
2247
	 * @since 4.3.0
2248
	 *
2249
	 * @param string $route Regular expression for the endpoint with the module slug to return.
2250
	 *
2251
	 * @return array|string
2252
	 */
2253
	public static function get_module_requested( $route = '/module/(?P<slug>[a-z\-]+)' ) {
2254
2255
		if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
2256
			return '';
2257
		}
2258
2259
		preg_match( "#$route#", $GLOBALS['wp']->query_vars['rest_route'], $module );
2260
2261
		if ( empty( $module['slug'] ) ) {
2262
			return '';
2263
		}
2264
2265
		return $module['slug'];
2266
	}
2267
2268
	/**
2269
	 * Adds extra information for modules.
2270
	 *
2271
	 * @since 4.3.0
2272
	 *
2273
	 * @param string|array $modules Can be a single module or a list of modules.
2274
	 * @param null|string  $slug    Slug of the module in the first parameter.
2275
	 *
2276
	 * @return array|string
2277
	 */
2278
	public static function prepare_modules_for_response( $modules = '', $slug = null ) {
2279
		global $wp_rewrite;
2280
2281
		/** This filter is documented in modules/sitemaps/sitemaps.php */
2282
		$location = apply_filters( 'jetpack_sitemap_location', '' );
2283
2284
		if ( $wp_rewrite->using_index_permalinks() ) {
2285
			$sitemap_url = home_url( '/index.php' . $location . '/sitemap.xml' );
2286
			$news_sitemap_url = home_url( '/index.php' . $location . '/news-sitemap.xml' );
2287
		} else if ( $wp_rewrite->using_permalinks() ) {
2288
			$sitemap_url = home_url( $location . '/sitemap.xml' );
2289
			$news_sitemap_url = home_url( $location . '/news-sitemap.xml' );
2290
		} else {
2291
			$sitemap_url = home_url( $location . '/?jetpack-sitemap=sitemap.xml' );
2292
			$news_sitemap_url = home_url( $location . '/?jetpack-sitemap=news-sitemap.xml' );
2293
		}
2294
2295
		if ( is_null( $slug ) && isset( $modules['sitemaps'] ) ) {
2296
			// Is a list of modules
2297
			$modules['sitemaps']['extra']['sitemap_url'] = $sitemap_url;
2298
			$modules['sitemaps']['extra']['news_sitemap_url'] = $news_sitemap_url;
2299
		} elseif ( 'sitemaps' == $slug ) {
2300
			// It's a single module
2301
			$modules['extra']['sitemap_url'] = $sitemap_url;
2302
			$modules['extra']['news_sitemap_url'] = $news_sitemap_url;
2303
		}
2304
		return $modules;
2305
	}
2306
2307
	/**
2308
	 * Remove 'validate_callback' item from options available for module.
2309
	 * Fetch current option value and add to array of module options.
2310
	 * Prepare values of module options that need special handling, like those saved in wpcom.
2311
	 *
2312
	 * @since 4.3.0
2313
	 *
2314
	 * @param string $module Module slug.
2315
	 * @return array
2316
	 */
2317
	public static function prepare_options_for_response( $module = '' ) {
2318
		$options = self::get_updateable_data_list( $module );
2319
2320
		if ( ! is_array( $options ) || empty( $options ) ) {
2321
			return $options;
2322
		}
2323
2324
		foreach ( $options as $key => $value ) {
2325
2326
			if ( isset( $options[ $key ]['validate_callback'] ) ) {
2327
				unset( $options[ $key ]['validate_callback'] );
2328
			}
2329
2330
			$default_value = isset( $options[ $key ]['default'] ) ? $options[ $key ]['default'] : '';
2331
2332
			$current_value = get_option( $key, $default_value );
2333
2334
			$options[ $key ]['current_value'] = self::cast_value( $current_value, $options[ $key ] );
2335
		}
2336
2337
		// Some modules need special treatment.
2338
		switch ( $module ) {
2339
2340
			case 'monitor':
2341
				// Status of user notifications
2342
				$options['monitor_receive_notifications']['current_value'] = self::cast_value( self::get_remote_value( 'monitor', 'monitor_receive_notifications' ), $options['monitor_receive_notifications'] );
2343
				break;
2344
2345
			case 'post-by-email':
2346
				// Email address
2347
				$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'] );
2348
				break;
2349
2350
			case 'protect':
2351
				// Protect
2352
				$options['jetpack_protect_key']['current_value'] = get_site_option( 'jetpack_protect_key', false );
2353
				if ( ! function_exists( 'jetpack_protect_format_whitelist' ) ) {
2354
					include_once( JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php' );
2355
				}
2356
				$options['jetpack_protect_global_whitelist']['current_value'] = jetpack_protect_format_whitelist();
2357
				break;
2358
2359
			case 'related-posts':
2360
				// It's local, but it must be broken apart since it's saved as an array.
2361
				$options = self::split_options( $options, Jetpack_Options::get_option( 'relatedposts' ) );
2362
				break;
2363
2364
			case 'verification-tools':
2365
				// It's local, but it must be broken apart since it's saved as an array.
2366
				$options = self::split_options( $options, get_option( 'verification_services_codes' ) );
2367
				break;
2368
2369
			case 'google-analytics':
2370
				$wga = get_option( 'jetpack_wga' );
2371
				$code = '';
2372
				if ( is_array( $wga ) && array_key_exists( 'code', $wga ) ) {
2373
					 $code = $wga[ 'code' ];
2374
				}
2375
				$options[ 'google_analytics_tracking_id' ][ 'current_value' ] = $code;
2376
				break;
2377
2378 View Code Duplication
			case 'sharedaddy':
2379
				// It's local, but it must be broken apart since it's saved as an array.
2380
				if ( ! class_exists( 'Sharing_Service' ) && ! include_once( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
2381
					break;
2382
				}
2383
				$sharer = new Sharing_Service();
2384
				$options = self::split_options( $options, $sharer->get_global_options() );
2385
				$options['sharing_services']['current_value'] = $sharer->get_blog_services();
2386
				break;
2387
2388
			case 'after-the-deadline':
2389
				if ( ! function_exists( 'AtD_get_options' ) ) {
2390
					include_once( JETPACK__PLUGIN_DIR . 'modules/after-the-deadline.php' );
2391
				}
2392
				$atd_options = array_merge( AtD_get_options( get_current_user_id(), 'AtD_options' ), AtD_get_options( get_current_user_id(), 'AtD_check_when' ) );
2393
				unset( $atd_options['name'] );
2394
				foreach ( $atd_options as $key => $value ) {
2395
					$options[ $key ]['current_value'] = self::cast_value( $value, $options[ $key ] );
2396
				}
2397
				$atd_options = AtD_get_options( get_current_user_id(), 'AtD_guess_lang' );
2398
				$options['guess_lang']['current_value'] = self::cast_value( isset( $atd_options['true'] ), $options[ 'guess_lang' ] );
2399
				$options['ignored_phrases']['current_value'] = AtD_get_setting( get_current_user_id(), 'AtD_ignored_phrases' );
2400
				unset( $options['unignore_phrase'] );
2401
				break;
2402
2403
			case 'stats':
2404
				// It's local, but it must be broken apart since it's saved as an array.
2405
				if ( ! function_exists( 'stats_get_options' ) ) {
2406
					include_once( JETPACK__PLUGIN_DIR . 'modules/stats.php' );
2407
				}
2408
				$options = self::split_options( $options, stats_get_options() );
2409
				break;
2410
		}
2411
2412
		return $options;
2413
	}
2414
2415
	/**
2416
	 * Splits module options saved as arrays like relatedposts or verification_services_codes into separate options to be returned in the response.
2417
	 *
2418
	 * @since 4.3.0
2419
	 *
2420
	 * @param array  $separate_options Array of options admitted by the module.
2421
	 * @param array  $grouped_options Option saved as array to be splitted.
2422
	 * @param string $prefix Optional prefix for the separate option keys.
2423
	 *
2424
	 * @return array
2425
	 */
2426
	public static function split_options( $separate_options, $grouped_options, $prefix = '' ) {
2427
		if ( is_array( $grouped_options ) ) {
2428
			foreach ( $grouped_options as $key => $value ) {
2429
				$option_key = $prefix . $key;
2430
				if ( isset( $separate_options[ $option_key ] ) ) {
2431
					$separate_options[ $option_key ]['current_value'] = self::cast_value( $grouped_options[ $key ], $separate_options[ $option_key ] );
2432
				}
2433
			}
2434
		}
2435
		return $separate_options;
2436
	}
2437
2438
	/**
2439
	 * Perform a casting to the value specified in the option definition.
2440
	 *
2441
	 * @since 4.3.0
2442
	 *
2443
	 * @param mixed $value Value to cast to the proper type.
2444
	 * @param array $definition Type to cast the value to.
2445
	 *
2446
	 * @return bool|float|int|string
2447
	 */
2448
	public static function cast_value( $value, $definition ) {
2449
		if ( $value === 'NULL' ) {
2450
			return null;
2451
		}
2452
2453
		if ( isset( $definition['type'] ) ) {
2454
			switch ( $definition['type'] ) {
2455
				case 'boolean':
2456
					if ( 'true' === $value ) {
2457
						return true;
2458
					} elseif ( 'false' === $value ) {
2459
						return false;
2460
					}
2461
					return (bool) $value;
2462
					break;
2463
2464
				case 'integer':
2465
					return (int) $value;
2466
					break;
2467
2468
				case 'float':
2469
					return (float) $value;
2470
					break;
2471
2472
				case 'string':
2473
					return (string) $value;
2474
					break;
2475
			}
2476
		}
2477
		return $value;
2478
	}
2479
2480
	/**
2481
	 * Get a value not saved locally.
2482
	 *
2483
	 * @since 4.3.0
2484
	 *
2485
	 * @param string $module Module slug.
2486
	 * @param string $option Option name.
2487
	 *
2488
	 * @return bool Whether user is receiving notifications or not.
2489
	 */
2490
	public static function get_remote_value( $module, $option ) {
2491
2492
		if ( in_array( $module, array( 'post-by-email' ), true ) ) {
2493
			$option .= get_current_user_id();
2494
		}
2495
2496
		// If option doesn't exist, 'does_not_exist' will be returned.
2497
		$value = get_option( $option, 'does_not_exist' );
2498
2499
		// If option exists, just return it.
2500
		if ( 'does_not_exist' !== $value ) {
2501
			return $value;
2502
		}
2503
2504
		// Only check a remote option if Jetpack is connected.
2505
		if ( ! Jetpack::is_active() ) {
2506
			return false;
2507
		}
2508
2509
		// Do what is necessary for each module.
2510
		switch ( $module ) {
2511
			case 'monitor':
2512
				// Load the class to use the method. If class can't be found, do nothing.
2513
				if ( ! class_exists( 'Jetpack_Monitor' ) && ! include_once( Jetpack::get_module_path( $module ) ) ) {
2514
					return false;
2515
				}
2516
				$value = Jetpack_Monitor::user_receives_notifications( false );
2517
				break;
2518
2519
			case 'post-by-email':
2520
				// Load the class to use the method. If class can't be found, do nothing.
2521
				if ( ! class_exists( 'Jetpack_Post_By_Email' ) && ! include_once( Jetpack::get_module_path( $module ) ) ) {
2522
					return false;
2523
				}
2524
				$post_by_email = new Jetpack_Post_By_Email();
2525
				$value = $post_by_email->get_post_by_email_address();
2526
				if ( $value === null ) {
2527
					$value = 'NULL'; // sentinel value so it actually gets set
2528
				}
2529
				break;
2530
		}
2531
2532
		// Normalize value to boolean.
2533
		if ( is_wp_error( $value ) || is_null( $value ) ) {
2534
			$value = false;
2535
		}
2536
2537
		// Save option to use it next time.
2538
		update_option( $option, $value );
2539
2540
		return $value;
2541
	}
2542
2543
	/**
2544
	 * Get number of plugin updates available.
2545
	 *
2546
	 * @since 4.3.0
2547
	 *
2548
	 * @return mixed|WP_Error Number of plugin updates available. Otherwise, a WP_Error instance with the corresponding error.
2549
	 */
2550
	public static function get_plugin_update_count() {
2551
		$updates = wp_get_update_data();
2552
		if ( isset( $updates['counts'] ) && isset( $updates['counts']['plugins'] ) ) {
2553
			$count = $updates['counts']['plugins'];
2554
			if ( 0 == $count ) {
2555
				$response = array(
2556
					'code'    => 'success',
2557
					'message' => esc_html__( 'All plugins are up-to-date. Keep up the good work!', 'jetpack' ),
2558
					'count'   => 0,
2559
				);
2560
			} else {
2561
				$response = array(
2562
					'code'    => 'updates-available',
2563
					'message' => esc_html( sprintf( _n( '%s plugin need updating.', '%s plugins need updating.', $count, 'jetpack' ), $count ) ),
2564
					'count'   => $count,
2565
				);
2566
			}
2567
			return rest_ensure_response( $response );
2568
		}
2569
2570
		return new WP_Error( 'not_found', esc_html__( 'Could not check updates for plugins on this site.', 'jetpack' ), array( 'status' => 404 ) );
2571
	}
2572
2573
2574
	/**
2575
	 * Returns a list of all plugins in the site.
2576
	 *
2577
	 * @since 4.2.0
2578
	 * @uses get_plugins()
2579
	 *
2580
	 * @return array
2581
	 */
2582
	private static function core_get_plugins() {
2583
		if ( ! function_exists( 'get_plugins' ) ) {
2584
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2585
		}
2586
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2587
		$plugins = apply_filters( 'all_plugins', get_plugins() );
2588
2589
		if ( is_array( $plugins ) && ! empty( $plugins ) ) {
2590
			foreach ( $plugins as $plugin_slug => $plugin_data ) {
2591
				$plugins[ $plugin_slug ]['active'] = self::core_is_plugin_active( $plugin_slug );
2592
			}
2593
			return $plugins;
2594
		}
2595
2596
		return array();
2597
	}
2598
2599
	/**
2600
	 * Checks if the queried plugin is active.
2601
	 *
2602
	 * @since 4.2.0
2603
	 * @uses is_plugin_active()
2604
	 *
2605
	 * @return bool
2606
	 */
2607
	private static function core_is_plugin_active( $plugin ) {
2608
		if ( ! function_exists( 'is_plugin_active' ) ) {
2609
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2610
		}
2611
2612
		return is_plugin_active( $plugin );
2613
	}
2614
2615
	/**
2616
	 * Get plugins data in site.
2617
	 *
2618
	 * @since 4.2.0
2619
	 *
2620
	 * @return WP_REST_Response|WP_Error List of plugins in the site. Otherwise, a WP_Error instance with the corresponding error.
2621
	 */
2622
	public static function get_plugins() {
2623
		$plugins = self::core_get_plugins();
2624
2625
		if ( ! empty( $plugins ) ) {
2626
			return rest_ensure_response( $plugins );
2627
		}
2628
2629
		return new WP_Error( 'not_found', esc_html__( 'Unable to list plugins.', 'jetpack' ), array( 'status' => 404 ) );
2630
	}
2631
2632
	/**
2633
	 * Get data about the queried plugin. Currently it only returns whether the plugin is active or not.
2634
	 *
2635
	 * @since 4.2.0
2636
	 *
2637
	 * @param WP_REST_Request $request {
2638
	 *     Array of parameters received by request.
2639
	 *
2640
	 *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
2641
	 * }
2642
	 *
2643
	 * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
2644
	 */
2645
	public static function get_plugin( $request ) {
2646
2647
		$plugins = self::core_get_plugins();
2648
2649
		if ( empty( $plugins ) ) {
2650
			return new WP_Error( 'no_plugins_found', esc_html__( 'This site has no plugins.', 'jetpack' ), array( 'status' => 404 ) );
2651
		}
2652
2653
		$plugin = stripslashes( $request['plugin'] );
2654
2655
		if ( ! in_array( $plugin, array_keys( $plugins ) ) ) {
2656
			return new WP_Error( 'plugin_not_found', esc_html( sprintf( __( 'Plugin %s is not installed.', 'jetpack' ), $plugin ) ), array( 'status' => 404 ) );
2657
		}
2658
2659
		$plugin_data = $plugins[ $plugin ];
2660
2661
		$plugin_data['active'] = self::core_is_plugin_active( $plugin );
2662
2663
		return rest_ensure_response( array(
2664
			'code'    => 'success',
2665
			'message' => esc_html__( 'Plugin found.', 'jetpack' ),
2666
			'data'    => $plugin_data
2667
		) );
2668
	}
2669
2670
} // class end
2671