Completed
Push — update/batch-update-anything ( 323868...1290e5 )
by
unknown
501:05 queued 491:51
created

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

Upgrade to new PHP Analysis Engine

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

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