Completed
Push — fix/issue-5159 ( e5f9c0...935047 )
by
unknown
55:37 queued 42:38
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
885
			// Carousel
886
			case 'carousel':
887
				$options = array(
888
					'carousel_background_color' => array(
889
						'description'        => esc_html__( 'Background color.', 'jetpack' ),
890
						'type'               => 'string',
891
						'default'            => 'black',
892
						'enum'				 => array(
893
							'black' => esc_html__( 'Black', 'jetpack' ),
894
							'white' => esc_html__( 'White', 'jetpack' ),
895
						),
896
						'validate_callback'  => __CLASS__ . '::validate_list_item',
897
					),
898
					'carousel_display_exif' => array(
899
						'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 ) )  ),
900
						'type'               => 'boolean',
901
						'default'            => 0,
902
						'validate_callback'  => __CLASS__ . '::validate_boolean',
903
					),
904
				);
905
				break;
906
907
			// Comments
908
			case 'comments':
909
				$options = array(
910
					'highlander_comment_form_prompt' => array(
911
						'description'        => esc_html__( 'Greeting Text', 'jetpack' ),
912
						'type'               => 'string',
913
						'default'            => esc_html__( 'Leave a Reply', 'jetpack' ),
914
						'sanitize_callback'  => 'sanitize_text_field',
915
					),
916
					'jetpack_comment_form_color_scheme' => array(
917
						'description'        => esc_html__( "Color Scheme", 'jetpack' ),
918
						'type'               => 'string',
919
						'default'            => 'light',
920
						'enum'				 => array(
921
							'light'       => esc_html__( 'Light', 'jetpack' ),
922
							'dark'        => esc_html__( 'Dark', 'jetpack' ),
923
							'transparent' => esc_html__( 'Transparent', 'jetpack' ),
924
						),
925
						'validate_callback'  => __CLASS__ . '::validate_list_item',
926
					),
927
				);
928
				break;
929
930
			// Custom Content Types
931
			case 'custom-content-types':
932
				$options = array(
933
					'jetpack_portfolio' => array(
934
						'description'        => esc_html__( 'Enable or disable Jetpack portfolio post type.', 'jetpack' ),
935
						'type'               => 'boolean',
936
						'default'            => 0,
937
						'validate_callback'  => __CLASS__ . '::validate_boolean',
938
					),
939
					'jetpack_portfolio_posts_per_page' => array(
940
						'description'        => esc_html__( 'Number of entries to show at most in Portfolio pages.', 'jetpack' ),
941
						'type'               => 'integer',
942
						'default'            => 10,
943
						'validate_callback'  => __CLASS__ . '::validate_posint',
944
					),
945
					'jetpack_testimonial' => array(
946
						'description'        => esc_html__( 'Enable or disable Jetpack testimonial post type.', 'jetpack' ),
947
						'type'               => 'boolean',
948
						'default'            => 0,
949
						'validate_callback'  => __CLASS__ . '::validate_boolean',
950
					),
951
					'jetpack_testimonial_posts_per_page' => array(
952
						'description'        => esc_html__( 'Number of entries to show at most in Testimonial pages.', 'jetpack' ),
953
						'type'               => 'integer',
954
						'default'            => 10,
955
						'validate_callback'  => __CLASS__ . '::validate_posint',
956
					),
957
				);
958
				break;
959
960
			// Galleries
961 View Code Duplication
			case 'tiled-gallery':
962
				$options = array(
963
					'tiled_galleries' => array(
964
						'description'        => esc_html__( 'Display all your gallery pictures in a cool mosaic.', 'jetpack' ),
965
						'type'               => 'boolean',
966
						'default'            => 0,
967
						'validate_callback'  => __CLASS__ . '::validate_boolean',
968
					),
969
				);
970
				break;
971
972
			// Gravatar Hovercards
973
			case 'gravatar-hovercards':
974
				$options = array(
975
					'gravatar_disable_hovercards' => array(
976
						'description'        => esc_html__( "View people's profiles when you mouse over their Gravatars", 'jetpack' ),
977
						'type'               => 'string',
978
						'default'            => 'enabled',
979
						// Not visible. This is used as the checkbox value.
980
						'enum'				 => array(
981
							'enabled' => esc_html__( 'Enabled', 'jetpack' ),
982
							'disabled' => esc_html__( 'Disabled', 'jetpack' ),
983
						),
984
						'validate_callback'  => __CLASS__ . '::validate_list_item',
985
					),
986
				);
987
				break;
988
989
			// Infinite Scroll
990
			case 'infinite-scroll':
991
				$options = array(
992
					'infinite_scroll' => array(
993
						'description'        => esc_html__( 'To infinity and beyond', 'jetpack' ),
994
						'type'               => 'boolean',
995
						'default'            => 1,
996
						'validate_callback'  => __CLASS__ . '::validate_boolean',
997
					),
998
					'infinite_scroll_google_analytics' => array(
999
						'description'        => esc_html__( 'Use Google Analytics with Infinite Scroll', 'jetpack' ),
1000
						'type'               => 'boolean',
1001
						'default'            => 0,
1002
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1003
					),
1004
				);
1005
				break;
1006
1007
			// Likes
1008
			case 'likes':
1009
				$options = array(
1010
					'wpl_default' => array(
1011
						'description'        => esc_html__( 'WordPress.com Likes are', 'jetpack' ),
1012
						'type'               => 'string',
1013
						'default'            => 'on',
1014
						'enum'				 => array(
1015
							'on'  => esc_html__( 'On for all posts', 'jetpack' ),
1016
							'off' => esc_html__( 'Turned on per post', 'jetpack' ),
1017
						),
1018
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1019
					),
1020
					'social_notifications_like' => array(
1021
						'description'        => esc_html__( 'Send email notification when someone likes a post', 'jetpack' ),
1022
						'type'               => 'boolean',
1023
						'default'            => 1,
1024
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1025
					),
1026
				);
1027
				break;
1028
1029
			// Markdown
1030 View Code Duplication
			case 'markdown':
1031
				$options = array(
1032
					'wpcom_publish_comments_with_markdown' => array(
1033
						'description'        => esc_html__( 'Use Markdown for comments.', 'jetpack' ),
1034
						'type'               => 'boolean',
1035
						'default'            => 0,
1036
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1037
					),
1038
				);
1039
				break;
1040
1041
			// Mobile Theme
1042
			case 'minileven':
1043
				$options = array(
1044
					'wp_mobile_excerpt' => array(
1045
						'description'        => esc_html__( 'Excerpts', 'jetpack' ),
1046
						'type'               => 'string',
1047
						'default'            => 'disabled',
1048
						'enum'				 => array(
1049
							'enabled'  => esc_html__( 'Enable excerpts on front page and on archive pages', 'jetpack' ),
1050
							'disabled' => esc_html__( 'Show full posts on front page and on archive pages', 'jetpack' ),
1051
						),
1052
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1053
					),
1054
					'wp_mobile_featured_images' => array(
1055
						'description'        => esc_html__( 'Featured Images', 'jetpack' ),
1056
						'type'               => 'string',
1057
						'default'            => 'disabled',
1058
						'enum'				 => array(
1059
							'enabled' => esc_html__( 'Display featured images', 'jetpack' ),
1060
							'disabled'  => esc_html__( 'Hide all featured images', 'jetpack' ),
1061
						),
1062
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1063
					),
1064
					'wp_mobile_app_promos' => array(
1065
						'description'        => esc_html__( 'Show a promo for the WordPress mobile apps in the footer of the mobile theme.', 'jetpack' ),
1066
						'type'               => 'boolean',
1067
						'default'            => 0,
1068
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1069
					),
1070
				);
1071
				break;
1072
1073
			// Monitor
1074 View Code Duplication
			case 'monitor':
1075
				$options = array(
1076
					'monitor_receive_notifications' => array(
1077
						'description'        => esc_html__( 'Receive Monitor Email Notifications.', 'jetpack' ),
1078
						'type'               => 'boolean',
1079
						'default'            => 0,
1080
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1081
					),
1082
				);
1083
				break;
1084
1085
			// Post by Email
1086 View Code Duplication
			case 'post-by-email':
1087
				$options = array(
1088
					'post_by_email_address' => array(
1089
						'description'       => esc_html__( 'Email Address', 'jetpack' ),
1090
						'type'              => 'string',
1091
						'default'           => '',
1092
						'enum'              => array(
1093
							'create'     => esc_html__( 'Create Post by Email address', 'jetpack' ),
1094
							'regenerate' => esc_html__( 'Regenerate Post by Email address', 'jetpack' ),
1095
							'delete'     => esc_html__( 'Delete Post by Email address', 'jetpack' ),
1096
						),
1097
						'validate_callback' => __CLASS__ . '::validate_list_item',
1098
					),
1099
				);
1100
				break;
1101
1102
			// Protect
1103 View Code Duplication
			case 'protect':
1104
				$options = array(
1105
					'jetpack_protect_key' => array(
1106
						'description'        => esc_html__( 'Protect API key', 'jetpack' ),
1107
						'type'               => 'string',
1108
						'default'            => '',
1109
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1110
					),
1111
					'jetpack_protect_global_whitelist' => array(
1112
						'description'        => esc_html__( 'Protect global whitelist', 'jetpack' ),
1113
						'type'               => 'string',
1114
						'default'            => '',
1115
						'validate_callback'  => __CLASS__ . '::validate_string',
1116
						'sanitize_callback'  => 'esc_textarea',
1117
					),
1118
				);
1119
				break;
1120
1121
			// Sharing
1122
			case 'sharedaddy':
1123
				$options = array(
1124
					'sharing_services' => array(
1125
						'description'        => esc_html__( 'Enabled Services and those hidden behind a button', 'jetpack' ),
1126
						'type'               => 'array',
1127
						'default'            => array(
1128
							'visible' => array( 'twitter', 'facebook', 'google-plus-1' ),
1129
							'hidden'  => array(),
1130
						),
1131
						'validate_callback'  => __CLASS__ . '::validate_services',
1132
					),
1133
					'button_style' => array(
1134
						'description'       => esc_html__( 'Button Style', 'jetpack' ),
1135
						'type'              => 'string',
1136
						'default'           => 'icon',
1137
						'enum'              => array(
1138
							'icon-text' => esc_html__( 'Icon + text', 'jetpack' ),
1139
							'icon'      => esc_html__( 'Icon only', 'jetpack' ),
1140
							'text'      => esc_html__( 'Text only', 'jetpack' ),
1141
							'official'  => esc_html__( 'Official buttons', 'jetpack' ),
1142
						),
1143
						'validate_callback' => __CLASS__ . '::validate_list_item',
1144
					),
1145
					'sharing_label' => array(
1146
						'description'        => esc_html__( 'Sharing Label', 'jetpack' ),
1147
						'type'               => 'string',
1148
						'default'            => '',
1149
						'validate_callback'  => __CLASS__ . '::validate_string',
1150
						'sanitize_callback'  => 'esc_html',
1151
					),
1152
					'show' => array(
1153
						'description'        => esc_html__( 'Views where buttons are shown', 'jetpack' ),
1154
						'type'               => 'array',
1155
						'default'            => array( 'post' ),
1156
						'validate_callback'  => __CLASS__ . '::validate_sharing_show',
1157
					),
1158
					'jetpack-twitter-cards-site-tag' => array(
1159
						'description'        => esc_html__( "The Twitter username of the owner of this site's domain.", 'jetpack' ),
1160
						'type'               => 'string',
1161
						'default'            => '',
1162
						'validate_callback'  => __CLASS__ . '::validate_twitter_username',
1163
						'sanitize_callback'  => 'esc_html',
1164
					),
1165
					'sharedaddy_disable_resources' => array(
1166
						'description'        => esc_html__( 'Disable CSS and JS', 'jetpack' ),
1167
						'type'               => 'boolean',
1168
						'default'            => 0,
1169
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1170
					),
1171
					'custom' => array(
1172
						'description'        => esc_html__( 'Custom sharing services added by user.', 'jetpack' ),
1173
						'type'               => 'array',
1174
						'default'            => array(
1175
							'sharing_name' => '',
1176
							'sharing_url'  => '',
1177
							'sharing_icon' => '',
1178
						),
1179
						'validate_callback'  => __CLASS__ . '::validate_custom_service',
1180
					),
1181
					// Not an option, but an action that can be perfomed on the list of custom services passing the service ID.
1182
					'sharing_delete_service' => array(
1183
						'description'        => esc_html__( 'Delete custom sharing service.', 'jetpack' ),
1184
						'type'               => 'string',
1185
						'default'            => '',
1186
						'validate_callback'  => __CLASS__ . '::validate_custom_service_id',
1187
					),
1188
				);
1189
				break;
1190
1191
			// SSO
1192 View Code Duplication
			case 'sso':
1193
				$options = array(
1194
					'jetpack_sso_require_two_step' => array(
1195
						'description'        => esc_html__( 'Require Two-Step Authentication', 'jetpack' ),
1196
						'type'               => 'boolean',
1197
						'default'            => 0,
1198
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1199
					),
1200
					'jetpack_sso_match_by_email' => array(
1201
						'description'        => esc_html__( 'Match by Email', 'jetpack' ),
1202
						'type'               => 'boolean',
1203
						'default'            => 0,
1204
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1205
					),
1206
				);
1207
				break;
1208
1209
			// Site Icon
1210 View Code Duplication
			case 'site-icon':
1211
				$options = array(
1212
					'site_icon_id' => array(
1213
						'description'        => esc_html__( 'Site Icon ID', 'jetpack' ),
1214
						'type'               => 'integer',
1215
						'default'            => 0,
1216
						'validate_callback'  => __CLASS__ . '::validate_posint',
1217
					),
1218
					'site_icon_url' => array(
1219
						'description'        => esc_html__( 'Site Icon URL', 'jetpack' ),
1220
						'type'               => 'string',
1221
						'default'            => '',
1222
						'sanitize_callback'  => 'esc_url',
1223
					),
1224
				);
1225
				break;
1226
1227
			// Subscriptions
1228
			case 'subscriptions':
1229
				$options = array(
1230
					'stb_enabled' => array(
1231
						'description'        => esc_html__( "Show a <em>'follow blog'</em> option in the comment form", 'jetpack' ),
1232
						'type'               => 'boolean',
1233
						'default'            => 1,
1234
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1235
					),
1236
					'stc_enabled' => array(
1237
						'description'        => esc_html__( "Show a <em>'follow comments'</em> option in the comment form", 'jetpack' ),
1238
						'type'               => 'boolean',
1239
						'default'            => 1,
1240
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1241
					),
1242
				);
1243
				break;
1244
1245
			// Related Posts
1246
			case 'related-posts':
1247
				$options = array(
1248
					'show_headline' => array(
1249
						'description'        => esc_html__( 'Show a "Related" header to more clearly separate the related section from posts', 'jetpack' ),
1250
						'type'               => 'boolean',
1251
						'default'            => 1,
1252
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1253
					),
1254
					'show_thumbnails' => array(
1255
						'description'        => esc_html__( 'Use a large and visually striking layout', 'jetpack' ),
1256
						'type'               => 'boolean',
1257
						'default'            => 0,
1258
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1259
					),
1260
				);
1261
				break;
1262
1263
			// Spelling and Grammar - After the Deadline
1264
			case 'after-the-deadline':
1265
				$options = array(
1266
					'onpublish' => array(
1267
						'description'        => esc_html__( 'Proofread when a post or page is first published.', 'jetpack' ),
1268
						'type'               => 'boolean',
1269
						'default'            => 0,
1270
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1271
					),
1272
					'onupdate' => array(
1273
						'description'        => esc_html__( 'Proofread when a post or page is updated.', 'jetpack' ),
1274
						'type'               => 'boolean',
1275
						'default'            => 0,
1276
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1277
					),
1278
					'Bias Language' => array(
1279
						'description'        => esc_html__( 'Bias Language', 'jetpack' ),
1280
						'type'               => 'boolean',
1281
						'default'            => 0,
1282
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1283
					),
1284
					'Cliches' => array(
1285
						'description'        => esc_html__( 'Clichés', 'jetpack' ),
1286
						'type'               => 'boolean',
1287
						'default'            => 0,
1288
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1289
					),
1290
					'Complex Expression' => array(
1291
						'description'        => esc_html__( 'Complex Phrases', 'jetpack' ),
1292
						'type'               => 'boolean',
1293
						'default'            => 0,
1294
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1295
					),
1296
					'Diacritical Marks' => array(
1297
						'description'        => esc_html__( 'Diacritical Marks', 'jetpack' ),
1298
						'type'               => 'boolean',
1299
						'default'            => 0,
1300
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1301
					),
1302
					'Double Negative' => array(
1303
						'description'        => esc_html__( 'Double Negatives', 'jetpack' ),
1304
						'type'               => 'boolean',
1305
						'default'            => 0,
1306
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1307
					),
1308
					'Hidden Verbs' => array(
1309
						'description'        => esc_html__( 'Hidden Verbs', 'jetpack' ),
1310
						'type'               => 'boolean',
1311
						'default'            => 0,
1312
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1313
					),
1314
					'Jargon Language' => array(
1315
						'description'        => esc_html__( 'Jargon', 'jetpack' ),
1316
						'type'               => 'boolean',
1317
						'default'            => 0,
1318
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1319
					),
1320
					'Passive voice' => array(
1321
						'description'        => esc_html__( 'Passive Voice', 'jetpack' ),
1322
						'type'               => 'boolean',
1323
						'default'            => 0,
1324
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1325
					),
1326
					'Phrases to Avoid' => array(
1327
						'description'        => esc_html__( 'Phrases to Avoid', 'jetpack' ),
1328
						'type'               => 'boolean',
1329
						'default'            => 0,
1330
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1331
					),
1332
					'Redundant Expression' => array(
1333
						'description'        => esc_html__( 'Redundant Phrases', 'jetpack' ),
1334
						'type'               => 'boolean',
1335
						'default'            => 0,
1336
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1337
					),
1338
					'guess_lang' => array(
1339
						'description'        => esc_html__( 'Use automatically detected language to proofread posts and pages', 'jetpack' ),
1340
						'type'               => 'boolean',
1341
						'default'            => 0,
1342
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1343
					),
1344
					'ignored_phrases' => array(
1345
						'description'        => esc_html__( 'Add Phrase to be ignored', 'jetpack' ),
1346
						'type'               => 'string',
1347
						'default'            => '',
1348
						'sanitize_callback'  => 'esc_html',
1349
					),
1350
					'unignore_phrase' => array(
1351
						'description'        => esc_html__( 'Remove Phrase from being ignored', 'jetpack' ),
1352
						'type'               => 'string',
1353
						'default'            => '',
1354
						'sanitize_callback'  => 'esc_html',
1355
					),
1356
				);
1357
				break;
1358
1359
			// Verification Tools
1360
			case 'verification-tools':
1361
				$options = array(
1362
					'google' => array(
1363
						'description'        => esc_html__( 'Google Search Console', 'jetpack' ),
1364
						'type'               => 'string',
1365
						'default'            => '',
1366
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1367
					),
1368
					'bing' => array(
1369
						'description'        => esc_html__( 'Bing Webmaster Center', 'jetpack' ),
1370
						'type'               => 'string',
1371
						'default'            => '',
1372
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1373
					),
1374
					'pinterest' => array(
1375
						'description'        => esc_html__( 'Pinterest Site Verification', 'jetpack' ),
1376
						'type'               => 'string',
1377
						'default'            => '',
1378
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1379
					),
1380
				);
1381
				break;
1382
1383
			// Stats
1384
			/*
1385
				Example:
1386
				'admin_bar' => true
1387
				'roles' => array ( 'administrator', 'editor' )
1388
				'count_roles' => array ( 'editor' )
1389
				'blog_id' => false
1390
				'do_not_track' => true
1391
				'hide_smile' => true
1392
				'version' => '9'
1393
			*/
1394
			case 'stats':
1395
				$options = array(
1396
					'admin_bar' => array(
1397
						'description'        => esc_html__( 'Put a chart showing 48 hours of views in the admin bar.', 'jetpack' ),
1398
						'type'               => 'boolean',
1399
						'default'            => 1,
1400
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1401
					),
1402
					'roles' => array(
1403
						'description'       => esc_html__( 'Select the roles that will be able to view stats reports.', 'jetpack' ),
1404
						'type'              => 'array',
1405
						'default'           => array( 'administrator' ),
1406
						'validate_callback' => __CLASS__ . '::validate_stats_roles',
1407
						'sanitize_callback' => __CLASS__ . '::sanitize_stats_allowed_roles',
1408
					),
1409
					'count_roles' => array(
1410
						'description'       => esc_html__( 'Count the page views of registered users who are logged in.', 'jetpack' ),
1411
						'type'              => 'array',
1412
						'default'           => array( 'administrator' ),
1413
						'validate_callback' => __CLASS__ . '::validate_stats_roles',
1414
					),
1415
					'blog_id' => array(
1416
						'description'        => esc_html__( 'Blog ID.', 'jetpack' ),
1417
						'type'               => 'boolean',
1418
						'default'            => 0,
1419
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1420
					),
1421
					'do_not_track' => array(
1422
						'description'        => esc_html__( 'Do not track.', 'jetpack' ),
1423
						'type'               => 'boolean',
1424
						'default'            => 1,
1425
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1426
					),
1427
					'hide_smile' => array(
1428
						'description'        => esc_html__( 'Hide the stats smiley face image.', 'jetpack' ),
1429
						'type'               => 'boolean',
1430
						'default'            => 1,
1431
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1432
					),
1433
					'version' => array(
1434
						'description'        => esc_html__( 'Version.', 'jetpack' ),
1435
						'type'               => 'integer',
1436
						'default'            => 9,
1437
						'validate_callback'  => __CLASS__ . '::validate_posint',
1438
					),
1439
				);
1440
				break;
1441
		}
1442
1443
		return $options;
1444
	}
1445
1446
	/**
1447
	 * Validates that the parameter is either a pure boolean or a numeric string that can be mapped to a boolean.
1448
	 *
1449
	 * @since 4.3.0
1450
	 *
1451
	 * @param string|bool $value Value to check.
1452
	 * @param WP_REST_Request $request
1453
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1454
	 *
1455
	 * @return bool
1456
	 */
1457
	public static function validate_boolean( $value, $request, $param ) {
1458
		if ( ! is_bool( $value ) && ! ( ( ctype_digit( $value ) || is_numeric( $value ) ) && in_array( $value, array( 0, 1 ) ) ) ) {
1459
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be true, false, 0 or 1.', 'jetpack' ), $param ) );
1460
		}
1461
		return true;
1462
	}
1463
1464
	/**
1465
	 * Validates that the parameter is a positive integer.
1466
	 *
1467
	 * @since 4.3.0
1468
	 *
1469
	 * @param int $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_posint( $value = 0, $request, $param ) {
1476 View Code Duplication
		if ( ! is_numeric( $value ) || $value <= 0 ) {
1477
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a positive integer.', 'jetpack' ), $param ) );
1478
		}
1479
		return true;
1480
	}
1481
1482
	/**
1483
	 * Validates that the parameter belongs to a list of admitted values.
1484
	 *
1485
	 * @since 4.3.0
1486
	 *
1487
	 * @param string $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_list_item( $value = '', $request, $param ) {
1494
		$attributes = $request->get_attributes();
1495
		if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
1496
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s not recognized', 'jetpack' ), $param ) );
1497
		}
1498
		$args = $attributes['args'][ $param ];
1499
		if ( ! empty( $args['enum'] ) ) {
1500
1501
			// If it's an associative array, use the keys to check that the value is among those admitted.
1502
			$enum = ( count( array_filter( array_keys( $args['enum'] ), 'is_string' ) ) > 0 ) ? array_keys( $args['enum'] ) : $args['enum'];
1503 View Code Duplication
			if ( ! in_array( $value, $enum ) ) {
1504
				return new WP_Error( 'invalid_param_value', sprintf(
1505
					/* Translators: first variable is the parameter passed to endpoint that holds the list item, the second is a list of admitted values. */
1506
					esc_html__( '%1$s must be one of %2$s', 'jetpack' ), $param, implode( ', ', $enum )
1507
				) );
1508
			}
1509
		}
1510
		return true;
1511
	}
1512
1513
	/**
1514
	 * Validates that the parameter belongs to a list of admitted values.
1515
	 *
1516
	 * @since 4.3.0
1517
	 *
1518
	 * @param string $value Value to check.
1519
	 * @param WP_REST_Request $request
1520
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1521
	 *
1522
	 * @return bool
1523
	 */
1524
	public static function validate_module_list( $value = '', $request, $param ) {
1525
		if ( ! is_array( $value ) ) {
1526
			return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be an array', 'jetpack' ), $param ) );
1527
		}
1528
1529
		$modules = Jetpack::get_available_modules();
1530
1531 View Code Duplication
		if ( count( array_intersect( $value, $modules ) ) != count( $value ) ) {
1532
			return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be a list of valid modules', 'jetpack' ), $param ) );
1533
		}
1534
1535
		return true;
1536
	}
1537
1538
	/**
1539
	 * Validates that the parameter is an alphanumeric or empty string (to be able to clear the field).
1540
	 *
1541
	 * @since 4.3.0
1542
	 *
1543
	 * @param string $value Value to check.
1544
	 * @param WP_REST_Request $request
1545
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1546
	 *
1547
	 * @return bool
1548
	 */
1549
	public static function validate_alphanum( $value = '', $request, $param ) {
1550 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/[a-z0-9]+/i', $value ) ) ) {
1551
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an alphanumeric string.', 'jetpack' ), $param ) );
1552
		}
1553
		return true;
1554
	}
1555
1556
	/**
1557
	 * Validates that the parameter is among the roles allowed for Stats.
1558
	 *
1559
	 * @since 4.3.0
1560
	 *
1561
	 * @param string|bool $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_stats_roles( $value, $request, $param ) {
1568
		if ( ! empty( $value ) && ! array_intersect( self::$stats_roles, $value ) ) {
1569
			return new WP_Error( 'invalid_param', sprintf(
1570
				/* 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. */
1571
				esc_html__( '%1$s must be %2$s.', 'jetpack' ), $param, join( ', ', self::$stats_roles )
1572
			) );
1573
		}
1574
		return true;
1575
	}
1576
1577
	/**
1578
	 * Validates that the parameter is among the views where the Sharing can be displayed.
1579
	 *
1580
	 * @since 4.3.0
1581
	 *
1582
	 * @param string|bool $value Value to check.
1583
	 * @param WP_REST_Request $request
1584
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1585
	 *
1586
	 * @return bool
1587
	 */
1588
	public static function validate_sharing_show( $value, $request, $param ) {
1589
		$views = array( 'index', 'post', 'page', 'attachment', 'jetpack-portfolio' );
1590 View Code Duplication
		if ( ! array_intersect( $views, $value ) ) {
1591
			return new WP_Error( 'invalid_param', sprintf(
1592
				/* 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 */
1593
				esc_html__( '%1$s must be %2$s.', 'jetpack' ), $param, join( ', ', $views )
1594
			) );
1595
		}
1596
		return true;
1597
	}
1598
1599
	/**
1600
	 * Validates that the parameter is among the views where the Sharing can be displayed.
1601
	 *
1602
	 * @since 4.3.0
1603
	 *
1604
	 * @param string|bool $value {
1605
	 *     Value to check received by request.
1606
	 *
1607
	 *     @type array $visible List of slug of services to share to that are displayed directly in the page.
1608
	 *     @type array $hidden  List of slug of services to share to that are concealed in a folding menu.
1609
	 * }
1610
	 * @param WP_REST_Request $request
1611
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1612
	 *
1613
	 * @return bool
1614
	 */
1615
	public static function validate_services( $value, $request, $param ) {
1616 View Code Duplication
		if ( ! is_array( $value ) || ! isset( $value['visible'] ) || ! isset( $value['hidden'] ) ) {
1617
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array with visible and hidden items.', 'jetpack' ), $param ) );
1618
		}
1619
1620
		// Allow to clear everything.
1621
		if ( empty( $value['visible'] ) && empty( $value['hidden'] ) ) {
1622
			return true;
1623
		}
1624
1625 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
1626
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
1627
		}
1628
		$sharer = new Sharing_Service();
1629
		$services = array_keys( $sharer->get_all_services() );
1630
1631
		if (
1632
			( ! empty( $value['visible'] ) && ! array_intersect( $value['visible'], $services ) )
1633
			||
1634
			( ! empty( $value['hidden'] ) && ! array_intersect( $value['hidden'], $services ) ) )
1635
		{
1636
			return new WP_Error( 'invalid_param', sprintf(
1637
				/* Translators: placeholder 1 is a parameter holding the services passed to endpoint, placeholder 2 is a list of all Jetpack Sharing services */
1638
				esc_html__( '%1$s visible and hidden items must be a list of %2$s.', 'jetpack' ), $param, join( ', ', $services )
1639
			) );
1640
		}
1641
		return true;
1642
	}
1643
1644
	/**
1645
	 * Validates that the parameter has enough information to build a custom sharing button.
1646
	 *
1647
	 * @since 4.3.0
1648
	 *
1649
	 * @param string|bool $value Value to check.
1650
	 * @param WP_REST_Request $request
1651
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1652
	 *
1653
	 * @return bool
1654
	 */
1655
	public static function validate_custom_service( $value, $request, $param ) {
1656 View Code Duplication
		if ( ! is_array( $value ) || ! isset( $value['sharing_name'] ) || ! isset( $value['sharing_url'] ) || ! isset( $value['sharing_icon'] ) ) {
1657
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array with sharing name, url and icon.', 'jetpack' ), $param ) );
1658
		}
1659
1660
		// Allow to clear everything.
1661
		if ( empty( $value['sharing_name'] ) && empty( $value['sharing_url'] ) && empty( $value['sharing_icon'] ) ) {
1662
			return true;
1663
		}
1664
1665 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
1666
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
1667
		}
1668
1669
		if ( ( ! empty( $value['sharing_name'] ) && ! is_string( $value['sharing_name'] ) )
1670
		|| ( ! empty( $value['sharing_url'] ) && ! is_string( $value['sharing_url'] ) )
1671
		|| ( ! empty( $value['sharing_icon'] ) && ! is_string( $value['sharing_icon'] ) ) ) {
1672
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s needs sharing name, url and icon.', 'jetpack' ), $param ) );
1673
		}
1674
		return true;
1675
	}
1676
1677
	/**
1678
	 * Validates that the parameter is a custom sharing service ID like 'custom-1461976264'.
1679
	 *
1680
	 * @since 4.3.0
1681
	 *
1682
	 * @param string $value Value to check.
1683
	 * @param WP_REST_Request $request
1684
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1685
	 *
1686
	 * @return bool
1687
	 */
1688
	public static function validate_custom_service_id( $value = '', $request, $param ) {
1689 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/custom\-[0-1]+/i', $value ) ) ) {
1690
			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 ) );
1691
		}
1692
1693 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
1694
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
1695
		}
1696
		$sharer = new Sharing_Service();
1697
		$services = array_keys( $sharer->get_all_services() );
1698
1699 View Code Duplication
		if ( ! empty( $value ) && ! in_array( $value, $services ) ) {
1700
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s is not a registered custom sharing service.', 'jetpack' ), $param ) );
1701
		}
1702
1703
		return true;
1704
	}
1705
1706
	/**
1707
	 * Validates that the parameter is a Twitter username or empty string (to be able to clear the field).
1708
	 *
1709
	 * @since 4.3.0
1710
	 *
1711
	 * @param string $value Value to check.
1712
	 * @param WP_REST_Request $request
1713
	 * @param string $param Name of the parameter passed to endpoint holding $value.
1714
	 *
1715
	 * @return bool
1716
	 */
1717
	public static function validate_twitter_username( $value = '', $request, $param ) {
1718 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/^@?\w{1,15}$/i', $value ) ) ) {
1719
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a Twitter username.', 'jetpack' ), $param ) );
1720
		}
1721
		return true;
1722
	}
1723
1724
	/**
1725
	 * Validates that the parameter is a string.
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_string( $value = '', $request, $param ) {
1736 View Code Duplication
		if ( ! is_string( $value ) ) {
1737
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a string.', 'jetpack' ), $param ) );
1738
		}
1739
		return true;
1740
	}
1741
1742
	/**
1743
	 * If for some reason the roles allowed to see Stats are empty (for example, user tampering with checkboxes),
1744
	 * return an array with only 'administrator' as the allowed role and save it for 'roles' option.
1745
	 *
1746
	 * @since 4.3.0
1747
	 *
1748
	 * @param string|bool $value Value to check.
1749
	 *
1750
	 * @return bool
1751
	 */
1752
	public static function sanitize_stats_allowed_roles( $value ) {
1753
		if ( empty( $value ) ) {
1754
			return array( 'administrator' );
1755
		}
1756
		return $value;
1757
	}
1758
1759
	/**
1760
	 * Get the currently accessed route and return the module slug in it.
1761
	 *
1762
	 * @since 4.3.0
1763
	 *
1764
	 * @param string $route Regular expression for the endpoint with the module slug to return.
1765
	 *
1766
	 * @return array
1767
	 */
1768
	public static function get_module_requested( $route = '/module/(?P<slug>[a-z\-]+)' ) {
1769
1770
		if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
1771
			return '';
1772
		}
1773
1774
		preg_match( "#$route#", $GLOBALS['wp']->query_vars['rest_route'], $module );
1775
1776
		if ( empty( $module['slug'] ) ) {
1777
			return '';
1778
		}
1779
1780
		return $module['slug'];
1781
	}
1782
1783
	/**
1784
	 * Adds extra information for modules.
1785
	 *
1786
	 * @since 4.3.0
1787
	 *
1788
	 * @param string      $modules Can be a single module or a list of modules.
1789
	 * @param null|string $slug    Slug of the module in the first parameter.
1790
	 *
1791
	 * @return array
1792
	 */
1793
	public static function prepare_modules_for_response( $modules = '', $slug = null ) {
1794
		if ( get_option( 'permalink_structure' ) ) {
1795
			$sitemap_url = home_url( '/sitemap.xml' );
1796
			$news_sitemap_url = home_url( '/news-sitemap.xml' );
1797
		} else {
1798
			$sitemap_url = home_url( '/?jetpack-sitemap=true' );
1799
			$news_sitemap_url = home_url( '/?jetpack-news-sitemap=true' );
1800
		}
1801
		/** This filter is documented in modules/sitemaps/sitemaps.php */
1802
		$sitemap_url = apply_filters( 'jetpack_sitemap_location', $sitemap_url );
1803
		/** This filter is documented in modules/sitemaps/sitemaps.php */
1804
		$news_sitemap_url = apply_filters( 'jetpack_news_sitemap_location', $news_sitemap_url );
1805
1806
		if ( is_null( $slug ) && isset( $modules['sitemaps'] ) ) {
1807
			// Is a list of modules
1808
			$modules['sitemaps']['extra']['sitemap_url'] = $sitemap_url;
1809
			$modules['sitemaps']['extra']['news_sitemap_url'] = $news_sitemap_url;
1810
		} elseif ( 'sitemaps' == $slug ) {
1811
			// It's a single module
1812
			$modules['extra']['sitemap_url'] = $sitemap_url;
1813
			$modules['extra']['news_sitemap_url'] = $news_sitemap_url;
1814
		}
1815
		return $modules;
1816
	}
1817
1818
	/**
1819
	 * Remove 'validate_callback' item from options available for module.
1820
	 * Fetch current option value and add to array of module options.
1821
	 * Prepare values of module options that need special handling, like those saved in wpcom.
1822
	 *
1823
	 * @since 4.3.0
1824
	 *
1825
	 * @param string $module Module slug.
1826
	 * @return array
1827
	 */
1828
	public static function prepare_options_for_response( $module = '' ) {
1829
		$options = self::get_module_available_options( $module );
1830
1831
		if ( ! is_array( $options ) || empty( $options ) ) {
1832
			return $options;
1833
		}
1834
1835
		foreach ( $options as $key => $value ) {
1836
1837
			if ( isset( $options[ $key ]['validate_callback'] ) ) {
1838
				unset( $options[ $key ]['validate_callback'] );
1839
			}
1840
1841
			$default_value = isset( $options[ $key ]['default'] ) ? $options[ $key ]['default'] : '';
1842
1843
			$current_value = get_option( $key, $default_value );
1844
1845
			$options[ $key ]['current_value'] = self::cast_value( $current_value, $options[ $key ] );
1846
		}
1847
1848
		// Some modules need special treatment.
1849
		switch ( $module ) {
1850
1851
			case 'monitor':
1852
				// Status of user notifications
1853
				$options['monitor_receive_notifications']['current_value'] = self::cast_value( self::get_remote_value( 'monitor', 'monitor_receive_notifications' ), $options['monitor_receive_notifications'] );
1854
				break;
1855
1856
			case 'post-by-email':
1857
				// Email address
1858
				$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'] );
1859
				break;
1860
1861
			case 'protect':
1862
				// Protect
1863
				$options['jetpack_protect_key']['current_value'] = get_site_option( 'jetpack_protect_key', false );
1864
				if ( ! function_exists( 'jetpack_protect_format_whitelist' ) ) {
1865
					@include( JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php' );
1866
				}
1867
				$options['jetpack_protect_global_whitelist']['current_value'] = jetpack_protect_format_whitelist();
1868
				break;
1869
1870
			case 'related-posts':
1871
				// It's local, but it must be broken apart since it's saved as an array.
1872
				$options = self::split_options( $options, Jetpack_Options::get_option( 'relatedposts' ) );
1873
				break;
1874
1875
			case 'verification-tools':
1876
				// It's local, but it must be broken apart since it's saved as an array.
1877
				$options = self::split_options( $options, get_option( 'verification_services_codes' ) );
1878
				break;
1879
1880
			case 'sharedaddy':
1881
				// It's local, but it must be broken apart since it's saved as an array.
1882
				if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
1883
					break;
1884
				}
1885
				$sharer = new Sharing_Service();
1886
				$options = self::split_options( $options, $sharer->get_global_options() );
1887
				$options['sharing_services']['current_value'] = $sharer->get_blog_services();
1888
				break;
1889
1890
			case 'site-icon':
1891
				// Return site icon ID and URL to make it more complete.
1892
				$options['site_icon_id']['current_value'] = Jetpack_Options::get_option( 'site_icon_id' );
1893
				if ( ! function_exists( 'jetpack_site_icon_url' ) ) {
1894
					@include( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
1895
				}
1896
				$options['site_icon_url']['current_value'] = jetpack_site_icon_url();
1897
				break;
1898
1899
			case 'after-the-deadline':
1900
				if ( ! function_exists( 'AtD_get_options' ) ) {
1901
					@include( JETPACK__PLUGIN_DIR . 'modules/after-the-deadline.php' );
1902
				}
1903
				$atd_options = array_merge( AtD_get_options( get_current_user_id(), 'AtD_options' ), AtD_get_options( get_current_user_id(), 'AtD_check_when' ) );
1904
				unset( $atd_options['name'] );
1905
				foreach ( $atd_options as $key => $value ) {
1906
					$options[ $key ]['current_value'] = self::cast_value( $value, $options[ $key ] );
1907
				}
1908
				$atd_options = AtD_get_options( get_current_user_id(), 'AtD_guess_lang' );
1909
				$options['guess_lang']['current_value'] = self::cast_value( isset( $atd_options['true'] ), $options[ 'guess_lang' ] );
1910
				$options['ignored_phrases']['current_value'] = AtD_get_setting( get_current_user_id(), 'AtD_ignored_phrases' );
1911
				unset( $options['unignore_phrase'] );
1912
				break;
1913
1914
			case 'minileven':
1915
				$options['wp_mobile_excerpt']['current_value'] =
1916
					1 === intval( $options['wp_mobile_excerpt']['current_value'] ) ?
1917
					'enabled' : 'disabled';
1918
1919
				$options['wp_mobile_featured_images']['current_value'] =
1920
					1 === intval( $options['wp_mobile_featured_images']['current_value'] ) ?
1921
					'enabled' : 'disabled';
1922
				break;
1923
1924
			case 'stats':
1925
				// It's local, but it must be broken apart since it's saved as an array.
1926
				if ( ! function_exists( 'stats_get_options' ) ) {
1927
					@include( JETPACK__PLUGIN_DIR . 'modules/stats.php' );
1928
				}
1929
				$options = self::split_options( $options, stats_get_options() );
1930
				break;
1931
		}
1932
1933
		return $options;
1934
	}
1935
1936
	/**
1937
	 * Splits module options saved as arrays like relatedposts or verification_services_codes into separate options to be returned in the response.
1938
	 *
1939
	 * @since 4.3.0
1940
	 *
1941
	 * @param array  $separate_options Array of options admitted by the module.
1942
	 * @param array  $grouped_options Option saved as array to be splitted.
1943
	 * @param string $prefix Optional prefix for the separate option keys.
1944
	 *
1945
	 * @return array
1946
	 */
1947
	public static function split_options( $separate_options, $grouped_options, $prefix = '' ) {
1948
		if ( is_array( $grouped_options ) ) {
1949
			foreach ( $grouped_options as $key => $value ) {
1950
				$option_key = $prefix . $key;
1951
				if ( isset( $separate_options[ $option_key ] ) ) {
1952
					$separate_options[ $option_key ]['current_value'] = self::cast_value( $grouped_options[ $key ], $separate_options[ $option_key ] );
1953
				}
1954
			}
1955
		}
1956
		return $separate_options;
1957
	}
1958
1959
	/**
1960
	 * Perform a casting to the value specified in the option definition.
1961
	 *
1962
	 * @since 4.3.0
1963
	 *
1964
	 * @param mixed $value Value to cast to the proper type.
1965
	 * @param array $definition Type to cast the value to.
1966
	 *
1967
	 * @return bool|float|int|string
1968
	 */
1969
	public static function cast_value( $value, $definition ) {
1970
		if ( $value === 'NULL' ) {
1971
			return null;
1972
		}
1973
1974
		if ( isset( $definition['type'] ) ) {
1975
			switch ( $definition['type'] ) {
1976
				case 'boolean':
1977
					if ( 'true' === $value ) {
1978
						return true;
1979
					} elseif ( 'false' === $value ) {
1980
						return false;
1981
					}
1982
					return (bool) $value;
1983
					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...
1984
1985
				case 'integer':
1986
					return (int) $value;
1987
					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...
1988
1989
				case 'float':
1990
					return (float) $value;
1991
					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...
1992
1993
				case 'string':
1994
					return (string) $value;
1995
					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...
1996
			}
1997
		}
1998
		return $value;
1999
	}
2000
2001
	/**
2002
	 * Get a value not saved locally.
2003
	 *
2004
	 * @since 4.3.0
2005
	 *
2006
	 * @param string $module Module slug.
2007
	 * @param string $option Option name.
2008
	 *
2009
	 * @return bool Whether user is receiving notifications or not.
2010
	 */
2011
	public static function get_remote_value( $module, $option ) {
2012
2013
		if ( in_array( $module, array( 'post-by-email' ), true ) ) {
2014
			$option .= get_current_user_id();
2015
		}
2016
2017
		// If option doesn't exist, 'does_not_exist' will be returned.
2018
		$value = get_option( $option, 'does_not_exist' );
2019
2020
		// If option exists, just return it.
2021
		if ( 'does_not_exist' !== $value ) {
2022
			return $value;
2023
		}
2024
2025
		// Only check a remote option if Jetpack is connected.
2026
		if ( ! Jetpack::is_active() ) {
2027
			return false;
2028
		}
2029
2030
		// If the module is inactive, load the class to use the method.
2031
		if ( ! did_action( 'jetpack_module_loaded_' . $module ) ) {
2032
			// Class can't be found so do nothing.
2033
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
2034
				return false;
2035
			}
2036
		}
2037
2038
		// Do what is necessary for each module.
2039
		switch ( $module ) {
2040
			case 'monitor':
2041
				$monitor = new Jetpack_Monitor();
2042
				$value = $monitor->user_receives_notifications( false );
2043
				break;
2044
2045
			case 'post-by-email':
2046
				$post_by_email = new Jetpack_Post_By_Email();
2047
				$value = $post_by_email->get_post_by_email_address();
2048
				if ( $value === null ) {
2049
					$value = 'NULL'; // sentinel value so it actually gets set
2050
				}
2051
				break;
2052
		}
2053
2054
		// Normalize value to boolean.
2055
		if ( is_wp_error( $value ) || is_null( $value ) ) {
2056
			$value = false;
2057
		}
2058
2059
		// Save option to use it next time.
2060
		update_option( $option, $value );
2061
2062
		return $value;
2063
	}
2064
2065
	/**
2066
	 * Get number of plugin updates available.
2067
	 *
2068
	 * @since 4.3.0
2069
	 *
2070
	 * @return mixed|WP_Error Number of plugin updates available. Otherwise, a WP_Error instance with the corresponding error.
2071
	 */
2072
	public static function get_plugin_update_count() {
2073
		$updates = wp_get_update_data();
2074
		if ( isset( $updates['counts'] ) && isset( $updates['counts']['plugins'] ) ) {
2075
			$count = $updates['counts']['plugins'];
2076
			if ( 0 == $count ) {
2077
				$response = array(
2078
					'code'    => 'success',
2079
					'message' => esc_html__( 'All plugins are up-to-date. Keep up the good work!', 'jetpack' ),
2080
					'count'   => 0,
2081
				);
2082
			} else {
2083
				$response = array(
2084
					'code'    => 'updates-available',
2085
					'message' => esc_html( sprintf( _n( '%s plugin need updating.', '%s plugins need updating.', $count, 'jetpack' ), $count ) ),
2086
					'count'   => $count,
2087
				);
2088
			}
2089
			return rest_ensure_response( $response );
2090
		}
2091
2092
		return new WP_Error( 'not_found', esc_html__( 'Could not check updates for plugins on this site.', 'jetpack' ), array( 'status' => 404 ) );
2093
	}
2094
2095
2096
	/**
2097
	 * Returns a list of all plugins in the site.
2098
	 *
2099
	 * @since 4.2.0
2100
	 * @uses get_plugins()
2101
	 *
2102
	 * @return array
2103
	 */
2104
	private static function core_get_plugins() {
2105
		if ( ! function_exists( 'get_plugins' ) ) {
2106
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2107
		}
2108
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2109
		$plugins = apply_filters( 'all_plugins', get_plugins() );
2110
2111
		if ( is_array( $plugins ) && ! empty( $plugins ) ) {
2112
			foreach ( $plugins as $plugin_slug => $plugin_data ) {
2113
				$plugins[ $plugin_slug ]['active'] = self::core_is_plugin_active( $plugin_slug );
2114
			}
2115
			return $plugins;
2116
		}
2117
2118
		return array();
2119
	}
2120
2121
	/**
2122
	 * Checks if the queried plugin is active.
2123
	 *
2124
	 * @since 4.2.0
2125
	 * @uses is_plugin_active()
2126
	 *
2127
	 * @return bool
2128
	 */
2129
	private static function core_is_plugin_active( $plugin ) {
2130
		if ( ! function_exists( 'get_plugins' ) ) {
2131
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2132
		}
2133
2134
		return is_plugin_active( $plugin );
2135
	}
2136
2137
	/**
2138
	 * Get plugins data in site.
2139
	 *
2140
	 * @since 4.2.0
2141
	 *
2142
	 * @return WP_REST_Response|WP_Error List of plugins in the site. Otherwise, a WP_Error instance with the corresponding error.
2143
	 */
2144
	public static function get_plugins() {
2145
		$plugins = self::core_get_plugins();
2146
2147
		if ( ! empty( $plugins ) ) {
2148
			return rest_ensure_response( $plugins );
2149
		}
2150
2151
		return new WP_Error( 'not_found', esc_html__( 'Unable to list plugins.', 'jetpack' ), array( 'status' => 404 ) );
2152
	}
2153
2154
	/**
2155
	 * Get data about the queried plugin. Currently it only returns whether the plugin is active or not.
2156
	 *
2157
	 * @since 4.2.0
2158
	 *
2159
	 * @param WP_REST_Request $data {
2160
	 *     Array of parameters received by request.
2161
	 *
2162
	 *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
2163
	 * }
2164
	 *
2165
	 * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
2166
	 */
2167
	public static function get_plugin( $data ) {
2168
2169
		$plugins = self::core_get_plugins();
2170
2171
		if ( empty( $plugins ) ) {
2172
			return new WP_Error( 'no_plugins_found', esc_html__( 'This site has no plugins.', 'jetpack' ), array( 'status' => 404 ) );
2173
		}
2174
2175
		$plugin = stripslashes( $data['plugin'] );
2176
2177
		if ( ! in_array( $plugin, array_keys( $plugins ) ) ) {
2178
			return new WP_Error( 'plugin_not_found', esc_html( sprintf( __( 'Plugin %s is not installed.', 'jetpack' ), $plugin ) ), array( 'status' => 404 ) );
2179
		}
2180
2181
		$plugin_data = $plugins[ $plugin ];
2182
2183
		$plugin_data['active'] = self::core_is_plugin_active( $plugin );
2184
2185
		return rest_ensure_response( array(
2186
			'code'    => 'success',
2187
			'message' => esc_html__( 'Plugin found.', 'jetpack' ),
2188
			'data'    => $plugin_data
2189
		) );
2190
	}
2191
2192
} // class end
2193