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