Completed
Push — add/react-videopress-settings ( 1a2dcb...a2519f )
by
unknown
275:56 queued 263:52
created

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

Upgrade to new PHP Analysis Engine

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

1
<?php
2
/**
3
 * Register WP REST API endpoints for Jetpack.
4
 *
5
 * @author Automattic
6
 */
7
8
/**
9
 * Disable direct access.
10
 */
11
if ( ! defined( 'ABSPATH' ) ) {
12
	exit;
13
}
14
15
// Load WP_Error for error messages.
16
require_once ABSPATH . '/wp-includes/class-wp-error.php';
17
18
// Register endpoints when WP REST API is initialized.
19
add_action( 'rest_api_init', array( 'Jetpack_Core_Json_Api_Endpoints', 'register_endpoints' ) );
20
21
/**
22
 * Class Jetpack_Core_Json_Api_Endpoints
23
 *
24
 * @since 4.3.0
25
 */
26
class Jetpack_Core_Json_Api_Endpoints {
27
28
	/**
29
	 * @var string Generic error message when user is not allowed to perform an action.
30
	 */
31
	public static $user_permissions_error_msg;
32
33
	/**
34
	 * @var array Roles that can access Stats once they're granted access.
35
	 */
36
	public static $stats_roles;
37
38
	/**
39
	 * Declare the Jetpack REST API endpoints.
40
	 *
41
	 * @since 4.3.0
42
	 */
43
	public static function register_endpoints() {
44
45
		// Load API endpoint base classes
46
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-xmlrpc-consumer-endpoint.php';
47
48
		// Load API endpoints
49
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-module-endpoints.php';
50
51
		self::$user_permissions_error_msg = esc_html__(
52
			'You do not have the correct user permissions to perform this action.
53
			Please contact your site admin if you think this is a mistake.',
54
			'jetpack'
55
		);
56
57
		self::$stats_roles = array( 'administrator', 'editor', 'author', 'contributor', 'subscriber' );
58
59
		// Get current connection status of Jetpack
60
		register_rest_route( 'jetpack/v4', '/connection', array(
61
			'methods' => WP_REST_Server::READABLE,
62
			'callback' => __CLASS__ . '::jetpack_connection_status',
63
		) );
64
65
		// Fetches a fresh connect URL
66
		register_rest_route( 'jetpack/v4', '/connection/url', array(
67
			'methods' => WP_REST_Server::READABLE,
68
			'callback' => __CLASS__ . '::build_connect_url',
69
			'permission_callback' => __CLASS__ . '::connect_url_permission_callback',
70
		) );
71
72
		// Get current user connection data
73
		register_rest_route( 'jetpack/v4', '/connection/data', array(
74
			'methods' => WP_REST_Server::READABLE,
75
			'callback' => __CLASS__ . '::get_user_connection_data',
76
			'permission_callback' => __CLASS__ . '::get_user_connection_data_permission_callback',
77
		) );
78
79
		// Disconnect site from WordPress.com servers
80
		register_rest_route( 'jetpack/v4', '/connection', array(
81
			'methods' => WP_REST_Server::EDITABLE,
82
			'callback' => __CLASS__ . '::disconnect_site',
83
			'permission_callback' => __CLASS__ . '::disconnect_site_permission_callback',
84
		) );
85
86
		// Disconnect/unlink user from WordPress.com servers
87
		register_rest_route( 'jetpack/v4', '/connection/user', array(
88
			'methods' => WP_REST_Server::EDITABLE,
89
			'callback' => __CLASS__ . '::unlink_user',
90
			'permission_callback' => __CLASS__ . '::unlink_user_permission_callback',
91
		) );
92
93
		// Get current site data
94
		register_rest_route( 'jetpack/v4', '/site', array(
95
			'methods' => WP_REST_Server::READABLE,
96
			'callback' => __CLASS__ . '::get_site_data',
97
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
98
		) );
99
100
		// Return all modules
101
		self::route(
102
			'module/all',
103
			'Jetpack_Core_API_Module_List_Endpoint',
104
			WP_REST_Server::READABLE
105
		);
106
107
		// Activate many modules
108
		self::route(
109
			'/module/all/active',
110
			'Jetpack_Core_API_Module_List_Endpoint',
111
			WP_REST_Server::EDITABLE,
112
			NULL,
113
			array(
114
				'modules' => array(
115
					'default'           => '',
116
					'type'              => 'array',
117
					'required'          => true,
118
					'validate_callback' => __CLASS__ . '::validate_module_list',
119
				),
120
				'active' => array(
121
					'default'           => true,
122
					'type'              => 'boolean',
123
					'required'          => false,
124
					'validate_callback' => __CLASS__ . '::validate_boolean',
125
				),
126
			)
127
		);
128
129
		Jetpack::load_xml_rpc_client();
130
131
		// Return a single module and update it when needed
132
		self::route(
133
			'/module/(?P<slug>[a-z\-]+)',
134
			'Jetpack_Core_API_Module_Endpoint',
135
			WP_REST_Server::READABLE,
136
			new Jetpack_IXR_Client( array( 'user_id' => get_current_user_id() ) )
137
		);
138
139
		// Activate and deactivate a module
140
		self::route(
141
			'/module/(?P<slug>[a-z\-]+)/active',
142
			'Jetpack_Core_API_Module_Toggle_Endpoint',
143
			WP_REST_Server::EDITABLE,
144
			new Jetpack_IXR_Client(),
145
			array(
146
				'active' => array(
147
					'default'           => true,
148
					'type'              => 'boolean',
149
					'required'          => true,
150
					'validate_callback' => __CLASS__ . '::validate_boolean',
151
				),
152
			)
153
		);
154
155
		// Update a module
156
		self::route(
157
			'/module/(?P<slug>[a-z\-]+)',
158
			'Jetpack_Core_API_Module_Endpoint',
159
			WP_REST_Server::EDITABLE,
160
			new Jetpack_IXR_Client( array( 'user_id' => get_current_user_id() ) ),
161
			self::get_module_updating_parameters()
162
		);
163
164
		// Get data for a specific module, i.e. Protect block count, WPCOM stats,
165
		// Akismet spam count, etc.
166
		self::route(
167
			'/module/(?P<slug>[a-z\-]+)/data',
168
			'Jetpack_Core_API_Module_Data_Endpoint',
169
			WP_REST_Server::READABLE,
170
			NULL,
171
			array(
172
				'range' => array(
173
					'default'           => 'day',
174
					'type'              => 'string',
175
					'required'          => false,
176
					'validate_callback' => __CLASS__ . '::validate_string',
177
				),
178
			)
179
		);
180
181
		// Reset all Jetpack options
182
		register_rest_route( 'jetpack/v4', '/options/(?P<options>[a-z\-]+)', array(
183
			'methods' => WP_REST_Server::EDITABLE,
184
			'callback' => __CLASS__ . '::reset_jetpack_options',
185
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
186
		) );
187
188
		// Return miscellaneous settings
189
		register_rest_route( 'jetpack/v4', '/settings', array(
190
			'methods' => WP_REST_Server::READABLE,
191
			'callback' => __CLASS__ . '::get_settings',
192
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
193
		) );
194
195
		// Update miscellaneous setting
196
		register_rest_route( 'jetpack/v4', '/settings', array(
197
			'methods' => WP_REST_Server::EDITABLE,
198
			'callback' => __CLASS__ . '::update_setting',
199
			'permission_callback' => __CLASS__ . '::update_settings_permission_check',
200
		) );
201
202
		// Jumpstart
203
		register_rest_route( 'jetpack/v4', '/jumpstart', array(
204
			'methods' => WP_REST_Server::EDITABLE,
205
			'callback' => __CLASS__ . '::jumpstart_toggle',
206
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
207
			'args' => array(
208
				'active' => array(
209
					'required' => true,
210
					'validate_callback' => __CLASS__  . '::validate_boolean',
211
				),
212
			),
213
		) );
214
215
		// Updates: get number of plugin updates available
216
		register_rest_route( 'jetpack/v4', '/updates/plugins', array(
217
			'methods' => WP_REST_Server::READABLE,
218
			'callback' => __CLASS__ . '::get_plugin_update_count',
219
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
220
		) );
221
222
		// Dismiss Jetpack Notices
223
		register_rest_route( 'jetpack/v4', '/notice/(?P<notice>[a-z\-_]+)', array(
224
			'methods' => WP_REST_Server::EDITABLE,
225
			'callback' => __CLASS__ . '::dismiss_notice',
226
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
227
		) );
228
229
		// Plugins: get list of all plugins.
230
		register_rest_route( 'jetpack/v4', '/plugins', array(
231
			'methods' => WP_REST_Server::READABLE,
232
			'callback' => __CLASS__ . '::get_plugins',
233
			'permission_callback' => __CLASS__ . '::activate_plugins_permission_check',
234
		) );
235
236
		// Plugins: check if the plugin is active.
237
		register_rest_route( 'jetpack/v4', '/plugin/(?P<plugin>[a-z\/\.\-_]+)', array(
238
			'methods' => WP_REST_Server::READABLE,
239
			'callback' => __CLASS__ . '::get_plugin',
240
			'permission_callback' => __CLASS__ . '::activate_plugins_permission_check',
241
		) );
242
	}
243
244
	public static function route( $path, $classname, $method,
245
		$constructor_arguments = NULL,
246
		$endpoint_arguments = NULL
247
	) {
248
		if ( ! empty( $constructor_arguments ) ) {
249
			$endpoint = new $classname( $constructor_arguments );
250
		} else {
251
			$endpoint = new $classname();
252
		}
253
254
		$parameters = array(
255
			'methods' => $method,
256
			'callback' => array( $endpoint, 'process' ),
257
			'permission_callback' => array( $endpoint, 'can_request' )
258
		);
259
260
		if ( ! empty( $endpoint_arguments ) ) {
261
			$parameters['args'] = $endpoint_arguments;
262
		}
263
264
		register_rest_route( 'jetpack/v4', $path, $parameters );
265
	}
266
267
	/**
268
	 * Handles dismissing of Jetpack Notices
269
	 *
270
	 * @since 4.3.0
271
	 *
272
	 * @return array|wp-error
273
	 */
274
	public static function dismiss_notice( $data ) {
275
		$notice = $data['notice'];
276
		$param = $data->get_json_params();
277
278
		if ( ! isset( $param['dismissed'] ) || $param['dismissed'] !== true ) {
279
			return new WP_Error( 'invalid_param', esc_html__( 'Invalid parameter "dismissed".', 'jetpack' ), array( 'status' => 404 ) );
280
		}
281
282
		if ( isset( $notice ) && ! empty( $notice ) ) {
283
			switch( $notice ) {
284
				case 'feedback_dash_request':
285
				case 'welcome':
286
					$notices = get_option( 'jetpack_dismissed_notices', array() );
287
					$notices[ $notice ] = true;
288
					update_option( 'jetpack_dismissed_notices', $notices );
289
					return rest_ensure_response( get_option( 'jetpack_dismissed_notices', array() ) );
290
291
				default:
292
					return new WP_Error( 'invalid_param', esc_html__( 'Invalid parameter "notice".', 'jetpack' ), array( 'status' => 404 ) );
293
			}
294
		}
295
296
		return new WP_Error( 'required_param', esc_html__( 'Missing parameter "notice".', 'jetpack' ), array( 'status' => 404 ) );
297
	}
298
299
	/**
300
	 * Verify that the user can disconnect the site.
301
	 *
302
	 * @since 4.3.0
303
	 *
304
	 * @return bool|WP_Error True if user is able to disconnect the site.
305
	 */
306
	public static function disconnect_site_permission_callback() {
307
		if ( current_user_can( 'jetpack_disconnect' ) ) {
308
			return true;
309
		}
310
311
		return new WP_Error( 'invalid_user_permission_jetpack_disconnect', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
312
313
	}
314
315
	/**
316
	 * Verify that the user can get a connect/link URL
317
	 *
318
	 * @since 4.3.0
319
	 *
320
	 * @return bool|WP_Error True if user is able to disconnect the site.
321
	 */
322 View Code Duplication
	public static function connect_url_permission_callback() {
323
		if ( current_user_can( 'jetpack_connect_user' ) ) {
324
			return true;
325
		}
326
327
		return new WP_Error( 'invalid_user_permission_jetpack_disconnect', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
328
329
	}
330
331
	/**
332
	 * Verify that a user can get the data about the current user.
333
	 * Only those who can connect.
334
	 *
335
	 * @since 4.3.0
336
	 *
337
	 * @uses Jetpack::is_user_connected();
338
	 *
339
	 * @return bool|WP_Error True if user is able to unlink.
340
	 */
341 View Code Duplication
	public static function get_user_connection_data_permission_callback() {
342
		if ( current_user_can( 'jetpack_connect_user' ) ) {
343
			return true;
344
		}
345
346
		return new WP_Error( 'invalid_user_permission_user_connection_data', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
347
	}
348
349
	/**
350
	 * Verify that a user can use the /connection/user endpoint. Has to be a registered user and be currently linked.
351
	 *
352
	 * @since 4.3.0
353
	 *
354
	 * @uses Jetpack::is_user_connected();
355
	 *
356
	 * @return bool|WP_Error True if user is able to unlink.
357
	 */
358
	public static function unlink_user_permission_callback() {
359
		if ( current_user_can( 'jetpack_connect_user' ) && Jetpack::is_user_connected( get_current_user_id() ) ) {
360
			return true;
361
		}
362
363
		return new WP_Error( 'invalid_user_permission_unlink_user', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
364
	}
365
366
	/**
367
	 * Verify that user can manage Jetpack modules.
368
	 *
369
	 * @since 4.3.0
370
	 *
371
	 * @return bool Whether user has the capability 'jetpack_manage_modules'.
372
	 */
373
	public static function manage_modules_permission_check() {
374
		if ( current_user_can( 'jetpack_manage_modules' ) ) {
375
			return true;
376
		}
377
378
		return new WP_Error( 'invalid_user_permission_manage_modules', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
379
	}
380
381
	/**
382
	 * Verify that user can update Jetpack modules.
383
	 *
384
	 * @since 4.3.0
385
	 *
386
	 * @return bool Whether user has the capability 'jetpack_configure_modules'.
387
	 */
388
	public static function configure_modules_permission_check() {
389
		if ( current_user_can( 'jetpack_configure_modules' ) ) {
390
			return true;
391
		}
392
393
		return new WP_Error( 'invalid_user_permission_configure_modules', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
394
	}
395
396
	/**
397
	 * Verify that user can view Jetpack admin page.
398
	 *
399
	 * @since 4.3.0
400
	 *
401
	 * @return bool Whether user has the capability 'jetpack_admin_page'.
402
	 */
403 View Code Duplication
	public static function view_admin_page_permission_check() {
404
		if ( current_user_can( 'jetpack_admin_page' ) ) {
405
			return true;
406
		}
407
408
		return new WP_Error( 'invalid_user_permission_view_admin', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
409
	}
410
411
	/**
412
	 * Verify that user can update Jetpack options.
413
	 *
414
	 * @since 4.3.0
415
	 *
416
	 * @return bool Whether user has the capability 'jetpack_admin_page'.
417
	 */
418
	public static function update_settings_permission_check() {
419
		if ( current_user_can( 'manage_options' ) ) {
420
			return true;
421
		}
422
423
		return new WP_Error( 'invalid_user_permission_manage_settings', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
424
	}
425
426
	/**
427
	 * Verify that user can view Jetpack admin page and can activate plugins.
428
	 *
429
	 * @since 4.3.0
430
	 *
431
	 * @return bool Whether user has the capability 'jetpack_admin_page' and 'activate_plugins'.
432
	 */
433 View Code Duplication
	public static function activate_plugins_permission_check() {
434
		if ( current_user_can( 'jetpack_admin_page' ) && current_user_can( 'activate_plugins' ) ) {
435
			return true;
436
		}
437
438
		return new WP_Error( 'invalid_user_permission_activate_plugins', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
439
	}
440
441
	/**
442
	 * Contextual HTTP error code for authorization failure.
443
	 *
444
	 * Taken from rest_authorization_required_code() in WP-API plugin until is added to core.
445
	 * @see https://github.com/WP-API/WP-API/commit/7ba0ae6fe4f605d5ffe4ee85b1cd5f9fb46900a6
446
	 *
447
	 * @since 4.3.0
448
	 *
449
	 * @return int
450
	 */
451
	public static function rest_authorization_required_code() {
452
		return is_user_logged_in() ? 403 : 401;
453
	}
454
455
	/**
456
	 * Get connection status for this Jetpack site.
457
	 *
458
	 * @since 4.3.0
459
	 *
460
	 * @return bool True if site is connected
461
	 */
462
	public static function jetpack_connection_status() {
463
		return rest_ensure_response( array(
464
				'isActive'  => Jetpack::is_active(),
465
				'isStaging' => Jetpack::is_staging_site(),
466
				'devMode'   => array(
467
					'isActive' => Jetpack::is_development_mode(),
468
					'constant' => defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG,
469
					'url'      => site_url() && false === strpos( site_url(), '.' ),
470
					'filter'   => apply_filters( 'jetpack_development_mode', false ),
471
				),
472
			)
473
		);
474
	}
475
476
	/**
477
	 * Disconnects Jetpack from the WordPress.com Servers
478
	 *
479
	 * @uses Jetpack::disconnect();
480
	 * @since 4.3.0
481
	 * @return bool|WP_Error True if Jetpack successfully disconnected.
482
	 */
483 View Code Duplication
	public static function disconnect_site( $data ) {
484
		$param = $data->get_json_params();
485
486
		if ( ! isset( $param['isActive'] ) || $param['isActive'] !== false ) {
487
			return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
488
		}
489
490
		if ( Jetpack::is_active() ) {
491
			Jetpack::disconnect();
492
			return rest_ensure_response( array( 'code' => 'success' ) );
493
		}
494
495
		return new WP_Error( 'disconnect_failed', esc_html__( 'Was not able to disconnect the site.  Please try again.', 'jetpack' ), array( 'status' => 400 ) );
496
	}
497
498
	/**
499
	 * Gets a new connect raw URL with fresh nonce.
500
	 *
501
	 * @uses Jetpack::disconnect();
502
	 * @since 4.3.0
503
	 * @return string|WP_Error A raw URL if the connection URL could be built; error message otherwise.
504
	 */
505
	public static function build_connect_url() {
506
		$url = Jetpack::init()->build_connect_url( true, false, false );
507
		if ( $url ) {
508
			return rest_ensure_response( $url );
509
		}
510
511
		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 ) );
512
	}
513
514
	/**
515
	 * Get miscellaneous settings for this Jetpack installation, like Holiday Snow.
516
	 *
517
	 * @since 4.3.0
518
	 *
519
	 * @return object $response {
520
	 *     Array of miscellaneous settings.
521
	 *
522
	 *     @type bool $holiday-snow Did Jack steal Christmas?
523
	 * }
524
	 */
525
	public static function get_settings() {
526
		$response = array(
527
			jetpack_holiday_snow_option_name() => get_option( jetpack_holiday_snow_option_name() ) == 'letitsnow',
528
		);
529
		return rest_ensure_response( $response );
530
	}
531
532
	/**
533
	 * Get miscellaneous user data related to the connection. Similar data available in old "My Jetpack".
534
	 * Information about the master/primary user.
535
	 * Information about the current user.
536
	 *
537
	 * @since 4.3.0
538
	 *
539
	 * @return object
540
	 */
541
	public static function get_user_connection_data() {
542
		require_once( JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class.jetpack-react-page.php' );
543
544
		$response = array(
545
//			'othersLinked' => Jetpack::get_other_linked_admins(),
546
			'currentUser'  => jetpack_current_user_data(),
547
		);
548
		return rest_ensure_response( $response );
549
	}
550
551
552
553
	/**
554
	 * Update a single miscellaneous setting for this Jetpack installation, like Holiday Snow.
555
	 *
556
	 * @since 4.3.0
557
	 *
558
	 * @param WP_REST_Request $data
559
	 *
560
	 * @return object Jetpack miscellaneous settings.
561
	 */
562
	public static function update_setting( $data ) {
563
		// Get parameters to update the module.
564
		$param = $data->get_json_params();
565
566
		// Exit if no parameters were passed.
567 View Code Duplication
		if ( ! is_array( $param ) ) {
568
			return new WP_Error( 'missing_setting', esc_html__( 'Missing setting.', 'jetpack' ), array( 'status' => 404 ) );
569
		}
570
571
		// Get option name and value.
572
		$option = key( $param );
573
		$value  = current( $param );
574
575
		// Log success or not
576
		$updated = false;
577
578
		switch ( $option ) {
579
			case jetpack_holiday_snow_option_name():
580
				$updated = update_option( $option, ( true == (bool) $value ) ? 'letitsnow' : '' );
581
				break;
582
		}
583
584
		if ( $updated ) {
585
			return rest_ensure_response( array(
586
				'code' 	  => 'success',
587
				'message' => esc_html__( 'Setting updated.', 'jetpack' ),
588
				'value'   => $value,
589
			) );
590
		}
591
592
		return new WP_Error( 'setting_not_updated', esc_html__( 'The setting was not updated.', 'jetpack' ), array( 'status' => 400 ) );
593
	}
594
595
	/**
596
	 * Unlinks current user from the WordPress.com Servers.
597
	 *
598
	 * @since 4.3.0
599
	 * @uses  Jetpack::unlink_user
600
	 *
601
	 * @return bool|WP_Error True if user successfully unlinked.
602
	 */
603 View Code Duplication
	public static function unlink_user( $data ) {
604
		$param = $data->get_json_params();
605
606
		if ( ! isset( $param['linked'] ) || $param['linked'] !== false ) {
607
			return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
608
		}
609
610
		if ( Jetpack::unlink_user() ) {
611
			return rest_ensure_response(
612
				array(
613
					'code' => 'success'
614
				)
615
			);
616
		}
617
618
		return new WP_Error( 'unlink_user_failed', esc_html__( 'Was not able to unlink the user.  Please try again.', 'jetpack' ), array( 'status' => 400 ) );
619
	}
620
621
	/**
622
	 * Get site data, including for example, the site's current plan.
623
	 *
624
	 * @since 4.3.0
625
	 *
626
	 * @return array Array of Jetpack modules.
627
	 */
628
	public static function get_site_data() {
629
630
		if ( $site_id = Jetpack_Options::get_option( 'id' ) ) {
631
			$response = Jetpack_Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d', $site_id ), '1.1' );
632
633
			if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
634
				return new WP_Error( 'site_data_fetch_failed', esc_html__( 'Failed fetching site data. Try again later.', 'jetpack' ), array( 'status' => 400 ) );
635
			}
636
637
			return rest_ensure_response( array(
638
					'code' => 'success',
639
					'message' => esc_html__( 'Site data correctly received.', 'jetpack' ),
640
					'data' => wp_remote_retrieve_body( $response ),
641
				)
642
			);
643
		}
644
645
		return new WP_Error( 'site_id_missing', esc_html__( 'The ID of this site does not exist.', 'jetpack' ), array( 'status' => 404 ) );
646
	}
647
648
649
	/**
650
	 * Reset Jetpack options
651
	 *
652
	 * @since 4.3.0
653
	 *
654
	 * @param WP_REST_Request $data {
655
	 *     Array of parameters received by request.
656
	 *
657
	 *     @type string $options Available options to reset are options|modules
658
	 * }
659
	 *
660
	 * @return bool|WP_Error True if options were reset. Otherwise, a WP_Error instance with the corresponding error.
661
	 */
662
	public static function reset_jetpack_options( $data ) {
663
		$param = $data->get_json_params();
664
665
		if ( ! isset( $param['reset'] ) || $param['reset'] !== true ) {
666
			return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
667
		}
668
669
		if ( isset( $data['options'] ) ) {
670
			$data = $data['options'];
671
672
			switch( $data ) {
673
				case ( 'options' ) :
674
					$options_to_reset = Jetpack::get_jetpack_options_for_reset();
675
676
					// Reset the Jetpack options
677
					foreach ( $options_to_reset['jp_options'] as $option_to_reset ) {
678
						Jetpack_Options::delete_option( $option_to_reset );
679
					}
680
681
					foreach ( $options_to_reset['wp_options'] as $option_to_reset ) {
682
						delete_option( $option_to_reset );
683
					}
684
685
					// Reset to default modules
686
					$default_modules = Jetpack::get_default_modules();
687
					Jetpack::update_active_modules( $default_modules );
688
689
					// Jumpstart option is special
690
					Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
691
					return rest_ensure_response( array(
692
						'code' 	  => 'success',
693
						'message' => esc_html__( 'Jetpack options reset.', 'jetpack' ),
694
					) );
695
					break;
0 ignored issues
show
break is not strictly necessary here and could be removed.

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

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

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

Loading history...
696
697
				case 'modules':
698
					$default_modules = Jetpack::get_default_modules();
699
					Jetpack::update_active_modules( $default_modules );
700
					return rest_ensure_response( array(
701
						'code' 	  => 'success',
702
						'message' => esc_html__( 'Modules reset to default.', 'jetpack' ),
703
					) );
704
					break;
0 ignored issues
show
break is not strictly necessary here and could be removed.

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

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

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

Loading history...
705
706
				default:
707
					return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
708
			}
709
		}
710
711
		return new WP_Error( 'required_param', esc_html__( 'Missing parameter "type".', 'jetpack' ), array( 'status' => 404 ) );
712
	}
713
714
	/**
715
	 * Toggles activation or deactivation of the JumpStart
716
	 *
717
	 * @since 4.3.0
718
	 *
719
	 * @param WP_REST_Request $data {
720
	 *     Array of parameters received by request.
721
	 * }
722
	 *
723
	 * @return bool|WP_Error True if toggling Jumpstart succeeded. Otherwise, a WP_Error instance with the corresponding error.
724
	 */
725
	public static function jumpstart_toggle( $data ) {
726
		$param = $data->get_json_params();
727
728
		if ( $param[ 'active' ] ) {
729
			return self::jumpstart_activate( $data );
730
		} else {
731
			return self::jumpstart_deactivate( $data );
732
		}
733
	}
734
735
	/**
736
	 * Activates a series of valid Jetpack modules and initializes some options.
737
	 *
738
	 * @since 4.3.0
739
	 *
740
	 * @param WP_REST_Request $data {
741
	 *     Array of parameters received by request.
742
	 * }
743
	 *
744
	 * @return bool|WP_Error True if Jumpstart succeeded. Otherwise, a WP_Error instance with the corresponding error.
745
	 */
746
	public static function jumpstart_activate( $data ) {
747
		$modules = Jetpack::get_available_modules();
748
		$activate_modules = array();
749
		foreach ( $modules as $module ) {
750
			$module_info = Jetpack::get_module( $module );
751
			if ( isset( $module_info['feature'] ) && is_array( $module_info['feature'] ) && in_array( 'Jumpstart', $module_info['feature'] ) ) {
752
				$activate_modules[] = $module;
753
			}
754
		}
755
756
		// Collect success/error messages like modules that are properly activated.
757
		$result = array(
758
			'activated_modules' => array(),
759
			'failed_modules'    => array(),
760
		);
761
762
		// Update the jumpstart option
763
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
764
			$result['jumpstart_activated'] = Jetpack_Options::update_option( 'jumpstart', 'jumpstart_activated' );
765
		}
766
767
		// Check for possible conflicting plugins
768
		$module_slugs_filtered = Jetpack::init()->filter_default_modules( $activate_modules );
769
770
		foreach ( $module_slugs_filtered as $module_slug ) {
771
			Jetpack::log( 'activate', $module_slug );
772
			if ( Jetpack::activate_module( $module_slug, false, false ) ) {
773
				$result['activated_modules'][] = $module_slug;
774
			} else {
775
				$result['failed_modules'][] = $module_slug;
776
			}
777
		}
778
779
		// Set the default sharing buttons and set to display on posts if none have been set.
780
		$sharing_services = get_option( 'sharing-services' );
781
		$sharing_options  = get_option( 'sharing-options' );
782
		if ( empty( $sharing_services['visible'] ) ) {
783
			// Default buttons to set
784
			$visible = array(
785
				'twitter',
786
				'facebook',
787
				'google-plus-1',
788
			);
789
			$hidden = array();
790
791
			// Set some sharing settings
792
			$sharing = new Sharing_Service();
793
			$sharing_options['global'] = array(
794
				'button_style'  => 'icon',
795
				'sharing_label' => $sharing->default_sharing_label,
796
				'open_links'    => 'same',
797
				'show'          => array( 'post' ),
798
				'custom'        => isset( $sharing_options['global']['custom'] ) ? $sharing_options['global']['custom'] : array()
799
			);
800
801
			$result['sharing_options']  = update_option( 'sharing-options', $sharing_options );
802
			$result['sharing_services'] = update_option( 'sharing-services', array( 'visible' => $visible, 'hidden' => $hidden ) );
803
		}
804
805
		// If all Jumpstart modules were activated
806 View Code Duplication
		if ( empty( $result['failed_modules'] ) ) {
807
			return rest_ensure_response( array(
808
				'code' 	  => 'success',
809
				'message' => esc_html__( 'Jumpstart done.', 'jetpack' ),
810
				'data'    => $result,
811
			) );
812
		}
813
814
		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 ) );
815
	}
816
817
	/**
818
	 * Dismisses Jumpstart so user is not prompted to go through it again.
819
	 *
820
	 * @since 4.3.0
821
	 *
822
	 * @param WP_REST_Request $data {
823
	 *     Array of parameters received by request.
824
	 * }
825
	 *
826
	 * @return bool|WP_Error True if Jumpstart was disabled or was nothing to dismiss. Otherwise, a WP_Error instance with a message.
827
	 */
828
	public static function jumpstart_deactivate( $data ) {
829
830
		// If dismissed, flag the jumpstart option as such.
831
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
832
			if ( Jetpack_Options::update_option( 'jumpstart', 'jumpstart_dismissed' ) ) {
833
				return rest_ensure_response( array(
834
					'code' 	  => 'success',
835
					'message' => esc_html__( 'Jumpstart dismissed.', 'jetpack' ),
836
				) );
837
			} else {
838
				return new WP_Error( 'jumpstart_failed_dismiss', esc_html__( 'Jumpstart could not be dismissed.', 'jetpack' ), array( 'status' => 400 ) );
839
			}
840
		}
841
842
		// If this was not a new connection and there was nothing to dismiss, don't fail.
843
		return rest_ensure_response( array(
844
			'code' 	  => 'success',
845
			'message' => esc_html__( 'Nothing to dismiss. This was not a new connection.', 'jetpack' ),
846
		) );
847
	}
848
849
	/**
850
	 * Get the query parameters for module updating.
851
	 *
852
	 * @since 4.3.0
853
	 *
854
	 * @return array
855
	 */
856
	public static function get_module_updating_parameters() {
857
		$parameters = array(
858
			'context'     => array(
859
				'default' => 'edit',
860
			),
861
		);
862
863
		return array_merge( $parameters, self::get_module_available_options() );
864
	}
865
866
	/**
867
	 * Returns a list of module options that can be updated.
868
	 *
869
	 * @since 4.3.0
870
	 *
871
	 * @param string $module Module slug. If empty, it's assumed we're updating a module and we'll try to get its slug.
872
	 * @param bool $cache Whether to cache the options or return always fresh.
873
	 *
874
	 * @return array
875
	 */
876
	public static function get_module_available_options( $module = '' ) {
877
		$options = array();
878
879
		if ( empty( $module ) ) {
880
			$module = self::get_module_requested();
881
		}
882
883
		switch ( $module ) {
884
			// VideoPress
885 View Code Duplication
			case 'videopress':
886
				// Holder for options to send to React
887
				$options = array(
888
					'videopress_free_formats' => array(
889
						'description' => esc_html__( 'Only display videos in free software formats', 'jetpack' ),
890
						'type' => 'boolean',
891
						'default' => 0,
892
						'validate_callback' => __CLASS__ . '::validate_boolean',
893
					),
894
					'videopress_default_quality' => array(
895
						'description' => esc_html__( 'Display higher quality videos by default', 'jetpack' ),
896
						'type' => 'boolean',
897
						'default' => 1,
898
						'validate_callback' => __CLASS__ . '::validate_boolean',
899
					),
900
				);
901
				break;
902
903
			// Carousel
904
			case 'carousel':
905
				$options = array(
906
					'carousel_background_color' => array(
907
						'description'        => esc_html__( 'Background color.', 'jetpack' ),
908
						'type'               => 'string',
909
						'default'            => 'black',
910
						'enum'				 => array(
911
							'black' => esc_html__( 'Black', 'jetpack' ),
912
							'white' => esc_html__( 'White', 'jetpack' ),
913
						),
914
						'validate_callback'  => __CLASS__ . '::validate_list_item',
915
					),
916
					'carousel_display_exif' => array(
917
						'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 ) )  ),
918
						'type'               => 'boolean',
919
						'default'            => 0,
920
						'validate_callback'  => __CLASS__ . '::validate_boolean',
921
					),
922
				);
923
				break;
924
925
			// Comments
926
			case 'comments':
927
				$options = array(
928
					'highlander_comment_form_prompt' => array(
929
						'description'        => esc_html__( 'Greeting Text', 'jetpack' ),
930
						'type'               => 'string',
931
						'default'            => esc_html__( 'Leave a Reply', 'jetpack' ),
932
						'sanitize_callback'  => 'sanitize_text_field',
933
					),
934
					'jetpack_comment_form_color_scheme' => array(
935
						'description'        => esc_html__( "Color Scheme", 'jetpack' ),
936
						'type'               => 'string',
937
						'default'            => 'light',
938
						'enum'				 => array(
939
							'light'       => esc_html__( 'Light', 'jetpack' ),
940
							'dark'        => esc_html__( 'Dark', 'jetpack' ),
941
							'transparent' => esc_html__( 'Transparent', 'jetpack' ),
942
						),
943
						'validate_callback'  => __CLASS__ . '::validate_list_item',
944
					),
945
				);
946
				break;
947
948
			// Custom Content Types
949
			case 'custom-content-types':
950
				$options = array(
951
					'jetpack_portfolio' => array(
952
						'description'        => esc_html__( 'Enable or disable Jetpack portfolio post type.', 'jetpack' ),
953
						'type'               => 'boolean',
954
						'default'            => 0,
955
						'validate_callback'  => __CLASS__ . '::validate_boolean',
956
					),
957
					'jetpack_portfolio_posts_per_page' => array(
958
						'description'        => esc_html__( 'Number of entries to show at most in Portfolio pages.', 'jetpack' ),
959
						'type'               => 'integer',
960
						'default'            => 10,
961
						'validate_callback'  => __CLASS__ . '::validate_posint',
962
					),
963
					'jetpack_testimonial' => array(
964
						'description'        => esc_html__( 'Enable or disable Jetpack testimonial post type.', 'jetpack' ),
965
						'type'               => 'boolean',
966
						'default'            => 0,
967
						'validate_callback'  => __CLASS__ . '::validate_boolean',
968
					),
969
					'jetpack_testimonial_posts_per_page' => array(
970
						'description'        => esc_html__( 'Number of entries to show at most in Testimonial pages.', 'jetpack' ),
971
						'type'               => 'integer',
972
						'default'            => 10,
973
						'validate_callback'  => __CLASS__ . '::validate_posint',
974
					),
975
				);
976
				break;
977
978
			// Galleries
979 View Code Duplication
			case 'tiled-gallery':
980
				$options = array(
981
					'tiled_galleries' => array(
982
						'description'        => esc_html__( 'Display all your gallery pictures in a cool mosaic.', 'jetpack' ),
983
						'type'               => 'boolean',
984
						'default'            => 0,
985
						'validate_callback'  => __CLASS__ . '::validate_boolean',
986
					),
987
				);
988
				break;
989
990
			// Gravatar Hovercards
991
			case 'gravatar-hovercards':
992
				$options = array(
993
					'gravatar_disable_hovercards' => array(
994
						'description'        => esc_html__( "View people's profiles when you mouse over their Gravatars", 'jetpack' ),
995
						'type'               => 'string',
996
						'default'            => 'enabled',
997
						// Not visible. This is used as the checkbox value.
998
						'enum'				 => array(
999
							'enabled' => esc_html__( 'Enabled', 'jetpack' ),
1000
							'disabled' => esc_html__( 'Disabled', 'jetpack' ),
1001
						),
1002
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1003
					),
1004
				);
1005
				break;
1006
1007
			// Infinite Scroll
1008
			case 'infinite-scroll':
1009
				$options = array(
1010
					'infinite_scroll' => array(
1011
						'description'        => esc_html__( 'To infinity and beyond', 'jetpack' ),
1012
						'type'               => 'boolean',
1013
						'default'            => 1,
1014
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1015
					),
1016
					'infinite_scroll_google_analytics' => array(
1017
						'description'        => esc_html__( 'Use Google Analytics with Infinite Scroll', 'jetpack' ),
1018
						'type'               => 'boolean',
1019
						'default'            => 0,
1020
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1021
					),
1022
				);
1023
				break;
1024
1025
			// Likes
1026
			case 'likes':
1027
				$options = array(
1028
					'wpl_default' => array(
1029
						'description'        => esc_html__( 'WordPress.com Likes are', 'jetpack' ),
1030
						'type'               => 'string',
1031
						'default'            => 'on',
1032
						'enum'				 => array(
1033
							'on'  => esc_html__( 'On for all posts', 'jetpack' ),
1034
							'off' => esc_html__( 'Turned on per post', 'jetpack' ),
1035
						),
1036
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1037
					),
1038
					'social_notifications_like' => array(
1039
						'description'        => esc_html__( 'Send email notification when someone likes a post', 'jetpack' ),
1040
						'type'               => 'boolean',
1041
						'default'            => 1,
1042
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1043
					),
1044
				);
1045
				break;
1046
1047
			// Markdown
1048 View Code Duplication
			case 'markdown':
1049
				$options = array(
1050
					'wpcom_publish_comments_with_markdown' => array(
1051
						'description'        => esc_html__( 'Use Markdown for comments.', 'jetpack' ),
1052
						'type'               => 'boolean',
1053
						'default'            => 0,
1054
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1055
					),
1056
				);
1057
				break;
1058
1059
			// Mobile Theme
1060
			case 'minileven':
1061
				$options = array(
1062
					'wp_mobile_excerpt' => array(
1063
						'description'        => esc_html__( 'Excerpts', 'jetpack' ),
1064
						'type'               => 'string',
1065
						'default'            => 'disabled',
1066
						'enum'				 => array(
1067
							'enabled'  => esc_html__( 'Enable excerpts on front page and on archive pages', 'jetpack' ),
1068
							'disabled' => esc_html__( 'Show full posts on front page and on archive pages', 'jetpack' ),
1069
						),
1070
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1071
					),
1072
					'wp_mobile_featured_images' => array(
1073
						'description'        => esc_html__( 'Featured Images', 'jetpack' ),
1074
						'type'               => 'string',
1075
						'default'            => 'disabled',
1076
						'enum'				 => array(
1077
							'enabled' => esc_html__( 'Display featured images', 'jetpack' ),
1078
							'disabled'  => esc_html__( 'Hide all featured images', 'jetpack' ),
1079
						),
1080
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1081
					),
1082
					'wp_mobile_app_promos' => array(
1083
						'description'        => esc_html__( 'Show a promo for the WordPress mobile apps in the footer of the mobile theme.', 'jetpack' ),
1084
						'type'               => 'boolean',
1085
						'default'            => 0,
1086
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1087
					),
1088
				);
1089
				break;
1090
1091
			// Monitor
1092 View Code Duplication
			case 'monitor':
1093
				$options = array(
1094
					'monitor_receive_notifications' => array(
1095
						'description'        => esc_html__( 'Receive Monitor Email Notifications.', 'jetpack' ),
1096
						'type'               => 'boolean',
1097
						'default'            => 0,
1098
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1099
					),
1100
				);
1101
				break;
1102
1103
			// Post by Email
1104 View Code Duplication
			case 'post-by-email':
1105
				$options = array(
1106
					'post_by_email_address' => array(
1107
						'description'       => esc_html__( 'Email Address', 'jetpack' ),
1108
						'type'              => 'string',
1109
						'default'           => '',
1110
						'enum'              => array(
1111
							'create'     => esc_html__( 'Create Post by Email address', 'jetpack' ),
1112
							'regenerate' => esc_html__( 'Regenerate Post by Email address', 'jetpack' ),
1113
							'delete'     => esc_html__( 'Delete Post by Email address', 'jetpack' ),
1114
						),
1115
						'validate_callback' => __CLASS__ . '::validate_list_item',
1116
					),
1117
				);
1118
				break;
1119
1120
			// Protect
1121 View Code Duplication
			case 'protect':
1122
				$options = array(
1123
					'jetpack_protect_key' => array(
1124
						'description'        => esc_html__( 'Protect API key', 'jetpack' ),
1125
						'type'               => 'string',
1126
						'default'            => '',
1127
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1128
					),
1129
					'jetpack_protect_global_whitelist' => array(
1130
						'description'        => esc_html__( 'Protect global whitelist', 'jetpack' ),
1131
						'type'               => 'string',
1132
						'default'            => '',
1133
						'validate_callback'  => __CLASS__ . '::validate_string',
1134
						'sanitize_callback'  => 'esc_textarea',
1135
					),
1136
				);
1137
				break;
1138
1139
			// Sharing
1140
			case 'sharedaddy':
1141
				$options = array(
1142
					'sharing_services' => array(
1143
						'description'        => esc_html__( 'Enabled Services and those hidden behind a button', 'jetpack' ),
1144
						'type'               => 'array',
1145
						'default'            => array(
1146
							'visible' => array( 'twitter', 'facebook', 'google-plus-1' ),
1147
							'hidden'  => array(),
1148
						),
1149
						'validate_callback'  => __CLASS__ . '::validate_services',
1150
					),
1151
					'button_style' => array(
1152
						'description'       => esc_html__( 'Button Style', 'jetpack' ),
1153
						'type'              => 'string',
1154
						'default'           => 'icon',
1155
						'enum'              => array(
1156
							'icon-text' => esc_html__( 'Icon + text', 'jetpack' ),
1157
							'icon'      => esc_html__( 'Icon only', 'jetpack' ),
1158
							'text'      => esc_html__( 'Text only', 'jetpack' ),
1159
							'official'  => esc_html__( 'Official buttons', 'jetpack' ),
1160
						),
1161
						'validate_callback' => __CLASS__ . '::validate_list_item',
1162
					),
1163
					'sharing_label' => array(
1164
						'description'        => esc_html__( 'Sharing Label', 'jetpack' ),
1165
						'type'               => 'string',
1166
						'default'            => '',
1167
						'validate_callback'  => __CLASS__ . '::validate_string',
1168
						'sanitize_callback'  => 'esc_html',
1169
					),
1170
					'show' => array(
1171
						'description'        => esc_html__( 'Views where buttons are shown', 'jetpack' ),
1172
						'type'               => 'array',
1173
						'default'            => array( 'post' ),
1174
						'validate_callback'  => __CLASS__ . '::validate_sharing_show',
1175
					),
1176
					'jetpack-twitter-cards-site-tag' => array(
1177
						'description'        => esc_html__( "The Twitter username of the owner of this site's domain.", 'jetpack' ),
1178
						'type'               => 'string',
1179
						'default'            => '',
1180
						'validate_callback'  => __CLASS__ . '::validate_twitter_username',
1181
						'sanitize_callback'  => 'esc_html',
1182
					),
1183
					'sharedaddy_disable_resources' => array(
1184
						'description'        => esc_html__( 'Disable CSS and JS', 'jetpack' ),
1185
						'type'               => 'boolean',
1186
						'default'            => 0,
1187
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1188
					),
1189
					'custom' => array(
1190
						'description'        => esc_html__( 'Custom sharing services added by user.', 'jetpack' ),
1191
						'type'               => 'array',
1192
						'default'            => array(
1193
							'sharing_name' => '',
1194
							'sharing_url'  => '',
1195
							'sharing_icon' => '',
1196
						),
1197
						'validate_callback'  => __CLASS__ . '::validate_custom_service',
1198
					),
1199
					// Not an option, but an action that can be perfomed on the list of custom services passing the service ID.
1200
					'sharing_delete_service' => array(
1201
						'description'        => esc_html__( 'Delete custom sharing service.', 'jetpack' ),
1202
						'type'               => 'string',
1203
						'default'            => '',
1204
						'validate_callback'  => __CLASS__ . '::validate_custom_service_id',
1205
					),
1206
				);
1207
				break;
1208
1209
			// SSO
1210 View Code Duplication
			case 'sso':
1211
				$options = array(
1212
					'jetpack_sso_require_two_step' => array(
1213
						'description'        => esc_html__( 'Require Two-Step Authentication', 'jetpack' ),
1214
						'type'               => 'boolean',
1215
						'default'            => 0,
1216
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1217
					),
1218
					'jetpack_sso_match_by_email' => array(
1219
						'description'        => esc_html__( 'Match by Email', 'jetpack' ),
1220
						'type'               => 'boolean',
1221
						'default'            => 0,
1222
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1223
					),
1224
				);
1225
				break;
1226
1227
			// Site Icon
1228 View Code Duplication
			case 'site-icon':
1229
				$options = array(
1230
					'site_icon_id' => array(
1231
						'description'        => esc_html__( 'Site Icon ID', 'jetpack' ),
1232
						'type'               => 'integer',
1233
						'default'            => 0,
1234
						'validate_callback'  => __CLASS__ . '::validate_posint',
1235
					),
1236
					'site_icon_url' => array(
1237
						'description'        => esc_html__( 'Site Icon URL', 'jetpack' ),
1238
						'type'               => 'string',
1239
						'default'            => '',
1240
						'sanitize_callback'  => 'esc_url',
1241
					),
1242
				);
1243
				break;
1244
1245
			// Subscriptions
1246
			case 'subscriptions':
1247
				$options = array(
1248
					'stb_enabled' => array(
1249
						'description'        => esc_html__( "Show a <em>'follow blog'</em> option in the comment form", 'jetpack' ),
1250
						'type'               => 'boolean',
1251
						'default'            => 1,
1252
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1253
					),
1254
					'stc_enabled' => array(
1255
						'description'        => esc_html__( "Show a <em>'follow comments'</em> option in the comment form", 'jetpack' ),
1256
						'type'               => 'boolean',
1257
						'default'            => 1,
1258
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1259
					),
1260
				);
1261
				break;
1262
1263
			// Related Posts
1264
			case 'related-posts':
1265
				$options = array(
1266
					'show_headline' => array(
1267
						'description'        => esc_html__( 'Show a "Related" header to more clearly separate the related section from posts', 'jetpack' ),
1268
						'type'               => 'boolean',
1269
						'default'            => 1,
1270
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1271
					),
1272
					'show_thumbnails' => array(
1273
						'description'        => esc_html__( 'Use a large and visually striking layout', 'jetpack' ),
1274
						'type'               => 'boolean',
1275
						'default'            => 0,
1276
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1277
					),
1278
				);
1279
				break;
1280
1281
			// Spelling and Grammar - After the Deadline
1282
			case 'after-the-deadline':
1283
				$options = array(
1284
					'onpublish' => array(
1285
						'description'        => esc_html__( 'Proofread when a post or page is first published.', 'jetpack' ),
1286
						'type'               => 'boolean',
1287
						'default'            => 0,
1288
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1289
					),
1290
					'onupdate' => array(
1291
						'description'        => esc_html__( 'Proofread when a post or page is updated.', 'jetpack' ),
1292
						'type'               => 'boolean',
1293
						'default'            => 0,
1294
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1295
					),
1296
					'Bias Language' => array(
1297
						'description'        => esc_html__( 'Bias Language', 'jetpack' ),
1298
						'type'               => 'boolean',
1299
						'default'            => 0,
1300
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1301
					),
1302
					'Cliches' => array(
1303
						'description'        => esc_html__( 'Clichés', 'jetpack' ),
1304
						'type'               => 'boolean',
1305
						'default'            => 0,
1306
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1307
					),
1308
					'Complex Expression' => array(
1309
						'description'        => esc_html__( 'Complex Phrases', 'jetpack' ),
1310
						'type'               => 'boolean',
1311
						'default'            => 0,
1312
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1313
					),
1314
					'Diacritical Marks' => array(
1315
						'description'        => esc_html__( 'Diacritical Marks', 'jetpack' ),
1316
						'type'               => 'boolean',
1317
						'default'            => 0,
1318
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1319
					),
1320
					'Double Negative' => array(
1321
						'description'        => esc_html__( 'Double Negatives', 'jetpack' ),
1322
						'type'               => 'boolean',
1323
						'default'            => 0,
1324
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1325
					),
1326
					'Hidden Verbs' => array(
1327
						'description'        => esc_html__( 'Hidden Verbs', 'jetpack' ),
1328
						'type'               => 'boolean',
1329
						'default'            => 0,
1330
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1331
					),
1332
					'Jargon Language' => array(
1333
						'description'        => esc_html__( 'Jargon', 'jetpack' ),
1334
						'type'               => 'boolean',
1335
						'default'            => 0,
1336
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1337
					),
1338
					'Passive voice' => array(
1339
						'description'        => esc_html__( 'Passive Voice', 'jetpack' ),
1340
						'type'               => 'boolean',
1341
						'default'            => 0,
1342
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1343
					),
1344
					'Phrases to Avoid' => array(
1345
						'description'        => esc_html__( 'Phrases to Avoid', 'jetpack' ),
1346
						'type'               => 'boolean',
1347
						'default'            => 0,
1348
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1349
					),
1350
					'Redundant Expression' => array(
1351
						'description'        => esc_html__( 'Redundant Phrases', 'jetpack' ),
1352
						'type'               => 'boolean',
1353
						'default'            => 0,
1354
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1355
					),
1356
					'guess_lang' => array(
1357
						'description'        => esc_html__( 'Use automatically detected language to proofread posts and pages', 'jetpack' ),
1358
						'type'               => 'boolean',
1359
						'default'            => 0,
1360
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1361
					),
1362
					'ignored_phrases' => array(
1363
						'description'        => esc_html__( 'Add Phrase to be ignored', 'jetpack' ),
1364
						'type'               => 'string',
1365
						'default'            => '',
1366
						'sanitize_callback'  => 'esc_html',
1367
					),
1368
					'unignore_phrase' => array(
1369
						'description'        => esc_html__( 'Remove Phrase from being ignored', 'jetpack' ),
1370
						'type'               => 'string',
1371
						'default'            => '',
1372
						'sanitize_callback'  => 'esc_html',
1373
					),
1374
				);
1375
				break;
1376
1377
			// Verification Tools
1378
			case 'verification-tools':
1379
				$options = array(
1380
					'google' => array(
1381
						'description'        => esc_html__( 'Google Search Console', 'jetpack' ),
1382
						'type'               => 'string',
1383
						'default'            => '',
1384
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1385
					),
1386
					'bing' => array(
1387
						'description'        => esc_html__( 'Bing Webmaster Center', 'jetpack' ),
1388
						'type'               => 'string',
1389
						'default'            => '',
1390
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1391
					),
1392
					'pinterest' => array(
1393
						'description'        => esc_html__( 'Pinterest Site Verification', 'jetpack' ),
1394
						'type'               => 'string',
1395
						'default'            => '',
1396
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1397
					),
1398
				);
1399
				break;
1400
1401
			// Stats
1402
			/*
1403
				Example:
1404
				'admin_bar' => true
1405
				'roles' => array ( 'administrator', 'editor' )
1406
				'count_roles' => array ( 'editor' )
1407
				'blog_id' => false
1408
				'do_not_track' => true
1409
				'hide_smile' => true
1410
				'version' => '9'
1411
			*/
1412
			case 'stats':
1413
				$options = array(
1414
					'admin_bar' => array(
1415
						'description'        => esc_html__( 'Put a chart showing 48 hours of views in the admin bar.', 'jetpack' ),
1416
						'type'               => 'boolean',
1417
						'default'            => 1,
1418
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1419
					),
1420
					'roles' => array(
1421
						'description'       => esc_html__( 'Select the roles that will be able to view stats reports.', 'jetpack' ),
1422
						'type'              => 'array',
1423
						'default'           => array( 'administrator' ),
1424
						'validate_callback' => __CLASS__ . '::validate_stats_roles',
1425
						'sanitize_callback' => __CLASS__ . '::sanitize_stats_allowed_roles',
1426
					),
1427
					'count_roles' => array(
1428
						'description'       => esc_html__( 'Count the page views of registered users who are logged in.', 'jetpack' ),
1429
						'type'              => 'array',
1430
						'default'           => array( 'administrator' ),
1431
						'validate_callback' => __CLASS__ . '::validate_stats_roles',
1432
					),
1433
					'blog_id' => array(
1434
						'description'        => esc_html__( 'Blog ID.', 'jetpack' ),
1435
						'type'               => 'boolean',
1436
						'default'            => 0,
1437
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1438
					),
1439
					'do_not_track' => array(
1440
						'description'        => esc_html__( 'Do not track.', 'jetpack' ),
1441
						'type'               => 'boolean',
1442
						'default'            => 1,
1443
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1444
					),
1445
					'hide_smile' => array(
1446
						'description'        => esc_html__( 'Hide the stats smiley face image.', 'jetpack' ),
1447
						'type'               => 'boolean',
1448
						'default'            => 1,
1449
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1450
					),
1451
					'version' => array(
1452
						'description'        => esc_html__( 'Version.', 'jetpack' ),
1453
						'type'               => 'integer',
1454
						'default'            => 9,
1455
						'validate_callback'  => __CLASS__ . '::validate_posint',
1456
					),
1457
				);
1458
				break;
1459
		}
1460
1461
		return $options;
1462
	}
1463
1464
	/**
1465
	 * Validates that the parameter is either a pure boolean or a numeric string that can be mapped to a boolean.
1466
	 *
1467
	 * @since 4.3.0
1468
	 *
1469
	 * @param string|bool $value Value to check.
1470
	 * @param WP_REST_Request $request
1471
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1472
	 *
1473
	 * @return bool
1474
	 */
1475
	public static function validate_boolean( $value, $request, $param ) {
1476
		if ( ! is_bool( $value ) && ! ( ( ctype_digit( $value ) || is_numeric( $value ) ) && in_array( $value, array( 0, 1 ) ) ) ) {
1477
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be true, false, 0 or 1.', 'jetpack' ), $param ) );
1478
		}
1479
		return true;
1480
	}
1481
1482
	/**
1483
	 * Validates that the parameter is a positive integer.
1484
	 *
1485
	 * @since 4.3.0
1486
	 *
1487
	 * @param int $value Value to check.
1488
	 * @param WP_REST_Request $request
1489
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1490
	 *
1491
	 * @return bool
1492
	 */
1493
	public static function validate_posint( $value = 0, $request, $param ) {
1494 View Code Duplication
		if ( ! is_numeric( $value ) || $value <= 0 ) {
1495
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a positive integer.', 'jetpack' ), $param ) );
1496
		}
1497
		return true;
1498
	}
1499
1500
	/**
1501
	 * Validates that the parameter belongs to a list of admitted values.
1502
	 *
1503
	 * @since 4.3.0
1504
	 *
1505
	 * @param string $value Value to check.
1506
	 * @param WP_REST_Request $request
1507
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1508
	 *
1509
	 * @return bool
1510
	 */
1511
	public static function validate_list_item( $value = '', $request, $param ) {
1512
		$attributes = $request->get_attributes();
1513
		if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
1514
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s not recognized', 'jetpack' ), $param ) );
1515
		}
1516
		$args = $attributes['args'][ $param ];
1517
		if ( ! empty( $args['enum'] ) ) {
1518
1519
			// If it's an associative array, use the keys to check that the value is among those admitted.
1520
			$enum = ( count( array_filter( array_keys( $args['enum'] ), 'is_string' ) ) > 0 ) ? array_keys( $args['enum'] ) : $args['enum'];
1521 View Code Duplication
			if ( ! in_array( $value, $enum ) ) {
1522
				return new WP_Error( 'invalid_param_value', sprintf(
1523
					/* Translators: first variable is the parameter passed to endpoint that holds the list item, the second is a list of admitted values. */
1524
					esc_html__( '%1$s must be one of %2$s', 'jetpack' ), $param, implode( ', ', $enum )
1525
				) );
1526
			}
1527
		}
1528
		return true;
1529
	}
1530
1531
	/**
1532
	 * Validates that the parameter belongs to a list of admitted values.
1533
	 *
1534
	 * @since 4.3.0
1535
	 *
1536
	 * @param string $value Value to check.
1537
	 * @param WP_REST_Request $request
1538
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1539
	 *
1540
	 * @return bool
1541
	 */
1542
	public static function validate_module_list( $value = '', $request, $param ) {
1543
		if ( ! is_array( $value ) ) {
1544
			return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be an array', 'jetpack' ), $param ) );
1545
		}
1546
1547
		$modules = Jetpack::get_available_modules();
1548
1549 View Code Duplication
		if ( count( array_intersect( $value, $modules ) ) != count( $value ) ) {
1550
			return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be a list of valid modules', 'jetpack' ), $param ) );
1551
		}
1552
1553
		return true;
1554
	}
1555
1556
	/**
1557
	 * Validates that the parameter is an alphanumeric or empty string (to be able to clear the field).
1558
	 *
1559
	 * @since 4.3.0
1560
	 *
1561
	 * @param string $value Value to check.
1562
	 * @param WP_REST_Request $request
1563
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1564
	 *
1565
	 * @return bool
1566
	 */
1567
	public static function validate_alphanum( $value = '', $request, $param ) {
1568 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/[a-z0-9]+/i', $value ) ) ) {
1569
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an alphanumeric string.', 'jetpack' ), $param ) );
1570
		}
1571
		return true;
1572
	}
1573
1574
	/**
1575
	 * Validates that the parameter is among the roles allowed for Stats.
1576
	 *
1577
	 * @since 4.3.0
1578
	 *
1579
	 * @param string|bool $value Value to check.
1580
	 * @param WP_REST_Request $request
1581
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1582
	 *
1583
	 * @return bool
1584
	 */
1585
	public static function validate_stats_roles( $value, $request, $param ) {
1586
		if ( ! empty( $value ) && ! array_intersect( self::$stats_roles, $value ) ) {
1587
			return new WP_Error( 'invalid_param', sprintf(
1588
				/* 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. */
1589
				esc_html__( '%1$s must be %2$s.', 'jetpack' ), $param, join( ', ', self::$stats_roles )
1590
			) );
1591
		}
1592
		return true;
1593
	}
1594
1595
	/**
1596
	 * Validates that the parameter is among the views where the Sharing can be displayed.
1597
	 *
1598
	 * @since 4.3.0
1599
	 *
1600
	 * @param string|bool $value Value to check.
1601
	 * @param WP_REST_Request $request
1602
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1603
	 *
1604
	 * @return bool
1605
	 */
1606
	public static function validate_sharing_show( $value, $request, $param ) {
1607
		$views = array( 'index', 'post', 'page', 'attachment', 'jetpack-portfolio' );
1608 View Code Duplication
		if ( ! array_intersect( $views, $value ) ) {
1609
			return new WP_Error( 'invalid_param', sprintf(
1610
				/* 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 */
1611
				esc_html__( '%1$s must be %2$s.', 'jetpack' ), $param, join( ', ', $views )
1612
			) );
1613
		}
1614
		return true;
1615
	}
1616
1617
	/**
1618
	 * Validates that the parameter is among the views where the Sharing can be displayed.
1619
	 *
1620
	 * @since 4.3.0
1621
	 *
1622
	 * @param string|bool $value {
1623
	 *     Value to check received by request.
1624
	 *
1625
	 *     @type array $visible List of slug of services to share to that are displayed directly in the page.
1626
	 *     @type array $hidden  List of slug of services to share to that are concealed in a folding menu.
1627
	 * }
1628
	 * @param WP_REST_Request $request
1629
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1630
	 *
1631
	 * @return bool
1632
	 */
1633
	public static function validate_services( $value, $request, $param ) {
1634 View Code Duplication
		if ( ! is_array( $value ) || ! isset( $value['visible'] ) || ! isset( $value['hidden'] ) ) {
1635
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array with visible and hidden items.', 'jetpack' ), $param ) );
1636
		}
1637
1638
		// Allow to clear everything.
1639
		if ( empty( $value['visible'] ) && empty( $value['hidden'] ) ) {
1640
			return true;
1641
		}
1642
1643 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
1644
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
1645
		}
1646
		$sharer = new Sharing_Service();
1647
		$services = array_keys( $sharer->get_all_services() );
1648
1649
		if (
1650
			( ! empty( $value['visible'] ) && ! array_intersect( $value['visible'], $services ) )
1651
			||
1652
			( ! empty( $value['hidden'] ) && ! array_intersect( $value['hidden'], $services ) ) )
1653
		{
1654
			return new WP_Error( 'invalid_param', sprintf(
1655
				/* Translators: placeholder 1 is a parameter holding the services passed to endpoint, placeholder 2 is a list of all Jetpack Sharing services */
1656
				esc_html__( '%1$s visible and hidden items must be a list of %2$s.', 'jetpack' ), $param, join( ', ', $services )
1657
			) );
1658
		}
1659
		return true;
1660
	}
1661
1662
	/**
1663
	 * Validates that the parameter has enough information to build a custom sharing button.
1664
	 *
1665
	 * @since 4.3.0
1666
	 *
1667
	 * @param string|bool $value Value to check.
1668
	 * @param WP_REST_Request $request
1669
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1670
	 *
1671
	 * @return bool
1672
	 */
1673
	public static function validate_custom_service( $value, $request, $param ) {
1674 View Code Duplication
		if ( ! is_array( $value ) || ! isset( $value['sharing_name'] ) || ! isset( $value['sharing_url'] ) || ! isset( $value['sharing_icon'] ) ) {
1675
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array with sharing name, url and icon.', 'jetpack' ), $param ) );
1676
		}
1677
1678
		// Allow to clear everything.
1679
		if ( empty( $value['sharing_name'] ) && empty( $value['sharing_url'] ) && empty( $value['sharing_icon'] ) ) {
1680
			return true;
1681
		}
1682
1683 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
1684
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
1685
		}
1686
1687
		if ( ( ! empty( $value['sharing_name'] ) && ! is_string( $value['sharing_name'] ) )
1688
		|| ( ! empty( $value['sharing_url'] ) && ! is_string( $value['sharing_url'] ) )
1689
		|| ( ! empty( $value['sharing_icon'] ) && ! is_string( $value['sharing_icon'] ) ) ) {
1690
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s needs sharing name, url and icon.', 'jetpack' ), $param ) );
1691
		}
1692
		return true;
1693
	}
1694
1695
	/**
1696
	 * Validates that the parameter is a custom sharing service ID like 'custom-1461976264'.
1697
	 *
1698
	 * @since 4.3.0
1699
	 *
1700
	 * @param string $value Value to check.
1701
	 * @param WP_REST_Request $request
1702
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1703
	 *
1704
	 * @return bool
1705
	 */
1706
	public static function validate_custom_service_id( $value = '', $request, $param ) {
1707 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/custom\-[0-1]+/i', $value ) ) ) {
1708
			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 ) );
1709
		}
1710
1711 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
1712
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
1713
		}
1714
		$sharer = new Sharing_Service();
1715
		$services = array_keys( $sharer->get_all_services() );
1716
1717 View Code Duplication
		if ( ! empty( $value ) && ! in_array( $value, $services ) ) {
1718
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s is not a registered custom sharing service.', 'jetpack' ), $param ) );
1719
		}
1720
1721
		return true;
1722
	}
1723
1724
	/**
1725
	 * Validates that the parameter is a Twitter username or empty string (to be able to clear the field).
1726
	 *
1727
	 * @since 4.3.0
1728
	 *
1729
	 * @param string $value Value to check.
1730
	 * @param WP_REST_Request $request
1731
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1732
	 *
1733
	 * @return bool
1734
	 */
1735
	public static function validate_twitter_username( $value = '', $request, $param ) {
1736 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/^@?\w{1,15}$/i', $value ) ) ) {
1737
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a Twitter username.', 'jetpack' ), $param ) );
1738
		}
1739
		return true;
1740
	}
1741
1742
	/**
1743
	 * Validates that the parameter is a string.
1744
	 *
1745
	 * @since 4.3.0
1746
	 *
1747
	 * @param string $value Value to check.
1748
	 * @param WP_REST_Request $request
1749
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1750
	 *
1751
	 * @return bool
1752
	 */
1753
	public static function validate_string( $value = '', $request, $param ) {
1754 View Code Duplication
		if ( ! is_string( $value ) ) {
1755
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a string.', 'jetpack' ), $param ) );
1756
		}
1757
		return true;
1758
	}
1759
1760
	/**
1761
	 * If for some reason the roles allowed to see Stats are empty (for example, user tampering with checkboxes),
1762
	 * return an array with only 'administrator' as the allowed role and save it for 'roles' option.
1763
	 *
1764
	 * @since 4.3.0
1765
	 *
1766
	 * @param string|bool $value Value to check.
1767
	 *
1768
	 * @return bool
1769
	 */
1770
	public static function sanitize_stats_allowed_roles( $value ) {
1771
		if ( empty( $value ) ) {
1772
			return array( 'administrator' );
1773
		}
1774
		return $value;
1775
	}
1776
1777
	/**
1778
	 * Get the currently accessed route and return the module slug in it.
1779
	 *
1780
	 * @since 4.3.0
1781
	 *
1782
	 * @param string $route Regular expression for the endpoint with the module slug to return.
1783
	 *
1784
	 * @return array
1785
	 */
1786
	public static function get_module_requested( $route = '/module/(?P<slug>[a-z\-]+)' ) {
1787
1788
		if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
1789
			return '';
1790
		}
1791
1792
		preg_match( "#$route#", $GLOBALS['wp']->query_vars['rest_route'], $module );
1793
1794
		if ( empty( $module['slug'] ) ) {
1795
			return '';
1796
		}
1797
1798
		return $module['slug'];
1799
	}
1800
1801
	/**
1802
	 * Adds extra information for modules.
1803
	 *
1804
	 * @since 4.3.0
1805
	 *
1806
	 * @param string      $modules Can be a single module or a list of modules.
1807
	 * @param null|string $slug    Slug of the module in the first parameter.
1808
	 *
1809
	 * @return array
1810
	 */
1811
	public static function prepare_modules_for_response( $modules = '', $slug = null ) {
1812
		if ( get_option( 'permalink_structure' ) ) {
1813
			$sitemap_url = home_url( '/sitemap.xml' );
1814
			$news_sitemap_url = home_url( '/news-sitemap.xml' );
1815
		} else {
1816
			$sitemap_url = home_url( '/?jetpack-sitemap=true' );
1817
			$news_sitemap_url = home_url( '/?jetpack-news-sitemap=true' );
1818
		}
1819
		/** This filter is documented in modules/sitemaps/sitemaps.php */
1820
		$sitemap_url = apply_filters( 'jetpack_sitemap_location', $sitemap_url );
1821
		/** This filter is documented in modules/sitemaps/sitemaps.php */
1822
		$news_sitemap_url = apply_filters( 'jetpack_news_sitemap_location', $news_sitemap_url );
1823
1824
		if ( is_null( $slug ) && isset( $modules['sitemaps'] ) ) {
1825
			// Is a list of modules
1826
			$modules['sitemaps']['extra']['sitemap_url'] = $sitemap_url;
1827
			$modules['sitemaps']['extra']['news_sitemap_url'] = $news_sitemap_url;
1828
		} elseif ( 'sitemaps' == $slug ) {
1829
			// It's a single module
1830
			$modules['extra']['sitemap_url'] = $sitemap_url;
1831
			$modules['extra']['news_sitemap_url'] = $news_sitemap_url;
1832
		}
1833
		return $modules;
1834
	}
1835
1836
	/**
1837
	 * Remove 'validate_callback' item from options available for module.
1838
	 * Fetch current option value and add to array of module options.
1839
	 * Prepare values of module options that need special handling, like those saved in wpcom.
1840
	 *
1841
	 * @since 4.3.0
1842
	 *
1843
	 * @param string $module Module slug.
1844
	 * @return array
1845
	 */
1846
	public static function prepare_options_for_response( $module = '' ) {
1847
		$options = self::get_module_available_options( $module );
1848
1849
		if ( ! is_array( $options ) || empty( $options ) ) {
1850
			return $options;
1851
		}
1852
1853
		foreach ( $options as $key => $value ) {
1854
1855
			if ( isset( $options[ $key ]['validate_callback'] ) ) {
1856
				unset( $options[ $key ]['validate_callback'] );
1857
			}
1858
1859
			$default_value = isset( $options[ $key ]['default'] ) ? $options[ $key ]['default'] : '';
1860
1861
			$current_value = get_option( $key, $default_value );
1862
1863
			$options[ $key ]['current_value'] = self::cast_value( $current_value, $options[ $key ] );
1864
		}
1865
1866
		// Some modules need special treatment.
1867
		switch ( $module ) {
1868
1869
			case 'monitor':
1870
				// Status of user notifications
1871
				$options['monitor_receive_notifications']['current_value'] = self::cast_value( self::get_remote_value( 'monitor', 'monitor_receive_notifications' ), $options['monitor_receive_notifications'] );
1872
				break;
1873
1874
			case 'post-by-email':
1875
				// Email address
1876
				$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'] );
1877
				break;
1878
1879
			case 'protect':
1880
				// Protect
1881
				$options['jetpack_protect_key']['current_value'] = get_site_option( 'jetpack_protect_key', false );
1882
				if ( ! function_exists( 'jetpack_protect_format_whitelist' ) ) {
1883
					@include( JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php' );
1884
				}
1885
				$options['jetpack_protect_global_whitelist']['current_value'] = jetpack_protect_format_whitelist();
1886
				break;
1887
1888
			case 'related-posts':
1889
				// It's local, but it must be broken apart since it's saved as an array.
1890
				$options = self::split_options( $options, Jetpack_Options::get_option( 'relatedposts' ) );
1891
				break;
1892
1893
			case 'verification-tools':
1894
				// It's local, but it must be broken apart since it's saved as an array.
1895
				$options = self::split_options( $options, get_option( 'verification_services_codes' ) );
1896
				break;
1897
1898
			case 'sharedaddy':
1899
				// It's local, but it must be broken apart since it's saved as an array.
1900
				if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
1901
					break;
1902
				}
1903
				$sharer = new Sharing_Service();
1904
				$options = self::split_options( $options, $sharer->get_global_options() );
1905
				$options['sharing_services']['current_value'] = $sharer->get_blog_services();
1906
				break;
1907
1908
			case 'site-icon':
1909
				// Return site icon ID and URL to make it more complete.
1910
				$options['site_icon_id']['current_value'] = Jetpack_Options::get_option( 'site_icon_id' );
1911
				if ( ! function_exists( 'jetpack_site_icon_url' ) ) {
1912
					@include( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
1913
				}
1914
				$options['site_icon_url']['current_value'] = jetpack_site_icon_url();
1915
				break;
1916
1917
			case 'after-the-deadline':
1918
				if ( ! function_exists( 'AtD_get_options' ) ) {
1919
					@include( JETPACK__PLUGIN_DIR . 'modules/after-the-deadline.php' );
1920
				}
1921
				$atd_options = array_merge( AtD_get_options( get_current_user_id(), 'AtD_options' ), AtD_get_options( get_current_user_id(), 'AtD_check_when' ) );
1922
				unset( $atd_options['name'] );
1923
				foreach ( $atd_options as $key => $value ) {
1924
					$options[ $key ]['current_value'] = self::cast_value( $value, $options[ $key ] );
1925
				}
1926
				$atd_options = AtD_get_options( get_current_user_id(), 'AtD_guess_lang' );
1927
				$options['guess_lang']['current_value'] = self::cast_value( isset( $atd_options['true'] ), $options[ 'guess_lang' ] );
1928
				$options['ignored_phrases']['current_value'] = AtD_get_setting( get_current_user_id(), 'AtD_ignored_phrases' );
1929
				unset( $options['unignore_phrase'] );
1930
				break;
1931
1932
			case 'minileven':
1933
				$options['wp_mobile_excerpt']['current_value'] =
1934
					1 === intval( $options['wp_mobile_excerpt']['current_value'] ) ?
1935
					'enabled' : 'disabled';
1936
1937
				$options['wp_mobile_featured_images']['current_value'] =
1938
					1 === intval( $options['wp_mobile_featured_images']['current_value'] ) ?
1939
					'enabled' : 'disabled';
1940
				break;
1941
1942
			case 'stats':
1943
				// It's local, but it must be broken apart since it's saved as an array.
1944
				if ( ! function_exists( 'stats_get_options' ) ) {
1945
					@include( JETPACK__PLUGIN_DIR . 'modules/stats.php' );
1946
				}
1947
				$options = self::split_options( $options, stats_get_options() );
1948
				break;
1949
		}
1950
1951
		return $options;
1952
	}
1953
1954
	/**
1955
	 * Splits module options saved as arrays like relatedposts or verification_services_codes into separate options to be returned in the response.
1956
	 *
1957
	 * @since 4.3.0
1958
	 *
1959
	 * @param array  $separate_options Array of options admitted by the module.
1960
	 * @param array  $grouped_options Option saved as array to be splitted.
1961
	 * @param string $prefix Optional prefix for the separate option keys.
1962
	 *
1963
	 * @return array
1964
	 */
1965
	public static function split_options( $separate_options, $grouped_options, $prefix = '' ) {
1966
		if ( is_array( $grouped_options ) ) {
1967
			foreach ( $grouped_options as $key => $value ) {
1968
				$option_key = $prefix . $key;
1969
				if ( isset( $separate_options[ $option_key ] ) ) {
1970
					$separate_options[ $option_key ]['current_value'] = self::cast_value( $grouped_options[ $key ], $separate_options[ $option_key ] );
1971
				}
1972
			}
1973
		}
1974
		return $separate_options;
1975
	}
1976
1977
	/**
1978
	 * Perform a casting to the value specified in the option definition.
1979
	 *
1980
	 * @since 4.3.0
1981
	 *
1982
	 * @param mixed $value Value to cast to the proper type.
1983
	 * @param array $definition Type to cast the value to.
1984
	 *
1985
	 * @return bool|float|int|string
1986
	 */
1987
	public static function cast_value( $value, $definition ) {
1988
		if ( $value === 'NULL' ) {
1989
			return null;
1990
		}
1991
1992
		if ( isset( $definition['type'] ) ) {
1993
			switch ( $definition['type'] ) {
1994
				case 'boolean':
1995
					if ( 'true' === $value ) {
1996
						return true;
1997
					} elseif ( 'false' === $value ) {
1998
						return false;
1999
					}
2000
					return (bool) $value;
2001
					break;
0 ignored issues
show
break is not strictly necessary here and could be removed.

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

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

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

Loading history...
2002
2003
				case 'integer':
2004
					return (int) $value;
2005
					break;
0 ignored issues
show
break is not strictly necessary here and could be removed.

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

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

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

Loading history...
2006
2007
				case 'float':
2008
					return (float) $value;
2009
					break;
0 ignored issues
show
break is not strictly necessary here and could be removed.

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

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

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

Loading history...
2010
2011
				case 'string':
2012
					return (string) $value;
2013
					break;
0 ignored issues
show
break is not strictly necessary here and could be removed.

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

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

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

Loading history...
2014
			}
2015
		}
2016
		return $value;
2017
	}
2018
2019
	/**
2020
	 * Get a value not saved locally.
2021
	 *
2022
	 * @since 4.3.0
2023
	 *
2024
	 * @param string $module Module slug.
2025
	 * @param string $option Option name.
2026
	 *
2027
	 * @return bool Whether user is receiving notifications or not.
2028
	 */
2029
	public static function get_remote_value( $module, $option ) {
2030
2031
		if ( in_array( $module, array( 'post-by-email' ), true ) ) {
2032
			$option .= get_current_user_id();
2033
		}
2034
2035
		// If option doesn't exist, 'does_not_exist' will be returned.
2036
		$value = get_option( $option, 'does_not_exist' );
2037
2038
		// If option exists, just return it.
2039
		if ( 'does_not_exist' !== $value ) {
2040
			return $value;
2041
		}
2042
2043
		// Only check a remote option if Jetpack is connected.
2044
		if ( ! Jetpack::is_active() ) {
2045
			return false;
2046
		}
2047
2048
		// If the module is inactive, load the class to use the method.
2049
		if ( ! did_action( 'jetpack_module_loaded_' . $module ) ) {
2050
			// Class can't be found so do nothing.
2051
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
2052
				return false;
2053
			}
2054
		}
2055
2056
		// Do what is necessary for each module.
2057
		switch ( $module ) {
2058
			case 'monitor':
2059
				$monitor = new Jetpack_Monitor();
2060
				$value = $monitor->user_receives_notifications( false );
2061
				break;
2062
2063
			case 'post-by-email':
2064
				$post_by_email = new Jetpack_Post_By_Email();
2065
				$value = $post_by_email->get_post_by_email_address();
2066
				if ( $value === null ) {
2067
					$value = 'NULL'; // sentinel value so it actually gets set
2068
				}
2069
				break;
2070
		}
2071
2072
		// Normalize value to boolean.
2073
		if ( is_wp_error( $value ) || is_null( $value ) ) {
2074
			$value = false;
2075
		}
2076
2077
		// Save option to use it next time.
2078
		update_option( $option, $value );
2079
2080
		return $value;
2081
	}
2082
2083
	/**
2084
	 * Get number of plugin updates available.
2085
	 *
2086
	 * @since 4.3.0
2087
	 *
2088
	 * @return mixed|WP_Error Number of plugin updates available. Otherwise, a WP_Error instance with the corresponding error.
2089
	 */
2090
	public static function get_plugin_update_count() {
2091
		$updates = wp_get_update_data();
2092
		if ( isset( $updates['counts'] ) && isset( $updates['counts']['plugins'] ) ) {
2093
			$count = $updates['counts']['plugins'];
2094
			if ( 0 == $count ) {
2095
				$response = array(
2096
					'code'    => 'success',
2097
					'message' => esc_html__( 'All plugins are up-to-date. Keep up the good work!', 'jetpack' ),
2098
					'count'   => 0,
2099
				);
2100
			} else {
2101
				$response = array(
2102
					'code'    => 'updates-available',
2103
					'message' => esc_html( sprintf( _n( '%s plugin need updating.', '%s plugins need updating.', $count, 'jetpack' ), $count ) ),
2104
					'count'   => $count,
2105
				);
2106
			}
2107
			return rest_ensure_response( $response );
2108
		}
2109
2110
		return new WP_Error( 'not_found', esc_html__( 'Could not check updates for plugins on this site.', 'jetpack' ), array( 'status' => 404 ) );
2111
	}
2112
2113
2114
	/**
2115
	 * Returns a list of all plugins in the site.
2116
	 *
2117
	 * @since 4.2.0
2118
	 * @uses get_plugins()
2119
	 *
2120
	 * @return array
2121
	 */
2122
	private static function core_get_plugins() {
2123
		if ( ! function_exists( 'get_plugins' ) ) {
2124
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2125
		}
2126
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2127
		$plugins = apply_filters( 'all_plugins', get_plugins() );
2128
2129
		if ( is_array( $plugins ) && ! empty( $plugins ) ) {
2130
			foreach ( $plugins as $plugin_slug => $plugin_data ) {
2131
				$plugins[ $plugin_slug ]['active'] = self::core_is_plugin_active( $plugin_slug );
2132
			}
2133
			return $plugins;
2134
		}
2135
2136
		return array();
2137
	}
2138
2139
	/**
2140
	 * Checks if the queried plugin is active.
2141
	 *
2142
	 * @since 4.2.0
2143
	 * @uses is_plugin_active()
2144
	 *
2145
	 * @return bool
2146
	 */
2147
	private static function core_is_plugin_active( $plugin ) {
2148
		if ( ! function_exists( 'get_plugins' ) ) {
2149
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2150
		}
2151
2152
		return is_plugin_active( $plugin );
2153
	}
2154
2155
	/**
2156
	 * Get plugins data in site.
2157
	 *
2158
	 * @since 4.2.0
2159
	 *
2160
	 * @return WP_REST_Response|WP_Error List of plugins in the site. Otherwise, a WP_Error instance with the corresponding error.
2161
	 */
2162
	public static function get_plugins() {
2163
		$plugins = self::core_get_plugins();
2164
2165
		if ( ! empty( $plugins ) ) {
2166
			return rest_ensure_response( $plugins );
2167
		}
2168
2169
		return new WP_Error( 'not_found', esc_html__( 'Unable to list plugins.', 'jetpack' ), array( 'status' => 404 ) );
2170
	}
2171
2172
	/**
2173
	 * Get data about the queried plugin. Currently it only returns whether the plugin is active or not.
2174
	 *
2175
	 * @since 4.2.0
2176
	 *
2177
	 * @param WP_REST_Request $data {
2178
	 *     Array of parameters received by request.
2179
	 *
2180
	 *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
2181
	 * }
2182
	 *
2183
	 * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
2184
	 */
2185
	public static function get_plugin( $data ) {
2186
2187
		$plugins = self::core_get_plugins();
2188
2189
		if ( empty( $plugins ) ) {
2190
			return new WP_Error( 'no_plugins_found', esc_html__( 'This site has no plugins.', 'jetpack' ), array( 'status' => 404 ) );
2191
		}
2192
2193
		$plugin = stripslashes( $data['plugin'] );
2194
2195
		if ( ! in_array( $plugin, array_keys( $plugins ) ) ) {
2196
			return new WP_Error( 'plugin_not_found', esc_html( sprintf( __( 'Plugin %s is not installed.', 'jetpack' ), $plugin ) ), array( 'status' => 404 ) );
2197
		}
2198
2199
		$plugin_data = $plugins[ $plugin ];
2200
2201
		$plugin_data['active'] = self::core_is_plugin_active( $plugin );
2202
2203
		return rest_ensure_response( array(
2204
			'code'    => 'success',
2205
			'message' => esc_html__( 'Plugin found.', 'jetpack' ),
2206
			'data'    => $plugin_data
2207
		) );
2208
	}
2209
2210
} // class end
2211