Completed
Push — update/rest-api-use-register-r... ( beaa11...d5393b )
by
unknown
31:19 queued 14:38
created

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

Severity

Upgrade to new PHP Analysis Engine

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

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