Completed
Push — fix/space-twitter-4455 ( 859b70...d25e05 )
by Jeremy
20:31 queued 11:02
created

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