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