Completed
Push — feature/videopress-uploader ( 46da43...bb1f5c )
by
unknown
22:02 queued 10:48
created

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

Severity

Upgrade to new PHP Analysis Engine

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

1
<?php
2
/**
3
 * Register WP REST API endpoints for Jetpack.
4
 *
5
 * @author Automattic
6
 */
7
8
/**
9
 * Disable direct access.
10
 */
11
if ( ! defined( 'ABSPATH' ) ) {
12
	exit;
13
}
14
15
// Load WP_Error for error messages.
16
require_once ABSPATH . '/wp-includes/class-wp-error.php';
17
18
// Register endpoints when WP REST API is initialized.
19
add_action( 'rest_api_init', array( 'Jetpack_Core_Json_Api_Endpoints', 'register_endpoints' ) );
20
21
/**
22
 * Class Jetpack_Core_Json_Api_Endpoints
23
 *
24
 * @since 4.1.0
25
 */
26
class Jetpack_Core_Json_Api_Endpoints {
27
28
	public static $user_permissions_error_msg;
29
30
	function __construct() {
31
		self::$user_permissions_error_msg = esc_html__(
32
			'You do not have the correct user permissions to perform this action.
33
			Please contact your site admin if you think this is a mistake.',
34
			'jetpack'
35
		);
36
	}
37
38
	/**
39
	 * Declare the Jetpack REST API endpoints.
40
	 *
41
	 * @since 4.1.0
42
	 */
43
	public static function register_endpoints() {
44
		// Get current connection status of Jetpack
45
		register_rest_route( 'jetpack/v4', '/connection-status', array(
46
			'methods' => WP_REST_Server::READABLE,
47
			'callback' => __CLASS__ . '::jetpack_connection_status',
48
		) );
49
50
		// Fetches a fresh connect URL
51
		register_rest_route( 'jetpack/v4', '/connect-url', array(
52
			'methods' => WP_REST_Server::READABLE,
53
			'callback' => __CLASS__ . '::build_connect_url',
54
			'permission_callback' => __CLASS__ . '::connect_url_permission_callback',
55
		) );
56
57
		// Get current user connection data
58
		register_rest_route( 'jetpack/v4', '/user-connection-data', array(
59
			'methods' => WP_REST_Server::READABLE,
60
			'callback' => __CLASS__ . '::get_user_connection_data',
61
			'permission_callback' => __CLASS__ . '::get_user_connection_data_permission_callback',
62
		) );
63
64
		// Disconnect site from WordPress.com servers
65
		register_rest_route( 'jetpack/v4', '/disconnect/site', array(
66
			'methods' => WP_REST_Server::EDITABLE,
67
			'callback' => __CLASS__ . '::disconnect_site',
68
			'permission_callback' => __CLASS__ . '::disconnect_site_permission_callback',
69
		) );
70
71
		// Disconnect/unlink user from WordPress.com servers
72
		register_rest_route( 'jetpack/v4', '/unlink', array(
73
			'methods' => WP_REST_Server::EDITABLE,
74
			'callback' => __CLASS__ . '::unlink_user',
75
			'permission_callback' => __CLASS__ . '::link_user_permission_callback',
76
			'args' => array(
77
				'id' => array(
78
					'default' => get_current_user_id(),
79
					'validate_callback' => __CLASS__  . '::validate_posint',
80
				),
81
			),
82
		) );
83
84
		register_rest_route( 'jetpack/v4', '/recheck-ssl', array(
85
			'methods' => WP_REST_Server::EDITABLE,
86
			'callback' => __CLASS__ . '::recheck_ssl',
87
		) );
88
89
		// Get current site data
90
		register_rest_route( 'jetpack/v4', '/site', array(
91
			'methods' => WP_REST_Server::READABLE,
92
			'callback' => __CLASS__ . '::get_site_data',
93
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
94
		) );
95
96
		// Return all modules
97
		register_rest_route( 'jetpack/v4', '/modules', array(
98
			'methods' => WP_REST_Server::READABLE,
99
			'callback' => __CLASS__ . '::get_modules',
100
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
101
		) );
102
103
		// Return a single module
104
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)', array(
105
			'methods' => WP_REST_Server::READABLE,
106
			'callback' => __CLASS__ . '::get_module',
107
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
108
		) );
109
110
		// Activate a module
111
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)/activate', array(
112
			'methods' => WP_REST_Server::EDITABLE,
113
			'callback' => __CLASS__ . '::activate_module',
114
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
115
		) );
116
117
		// Deactivate a module
118
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)/deactivate', array(
119
			'methods' => WP_REST_Server::EDITABLE,
120
			'callback' => __CLASS__ . '::deactivate_module',
121
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
122
		) );
123
124
		// Update a module
125
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)/update', array(
126
			'methods' => WP_REST_Server::EDITABLE,
127
			'callback' => __CLASS__ . '::update_module',
128
			'permission_callback' => __CLASS__ . '::configure_modules_permission_check',
129
			'args' => self::get_module_updating_parameters(),
130
		) );
131
132
		// Activate many modules
133
		register_rest_route( 'jetpack/v4', '/modules/activate', array(
134
			'methods' => WP_REST_Server::EDITABLE,
135
			'callback' => __CLASS__ . '::activate_modules',
136
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
137
			'args' => array(
138
				'modules' => array(
139
					'default'           => '',
140
					'type'              => 'array',
141
					'required'          => true,
142
					'validate_callback' => __CLASS__ . '::validate_module_list',
143
				),
144
			),
145
		) );
146
147
		// Reset all Jetpack options
148
		register_rest_route( 'jetpack/v4', '/reset/(?P<options>[a-z\-]+)', array(
149
			'methods' => WP_REST_Server::EDITABLE,
150
			'callback' => __CLASS__ . '::reset_jetpack_options',
151
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
152
		) );
153
154
		// Return miscellaneous settings
155
		register_rest_route( 'jetpack/v4', '/settings', array(
156
			'methods' => WP_REST_Server::READABLE,
157
			'callback' => __CLASS__ . '::get_settings',
158
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
159
		) );
160
161
		// Update miscellaneous setting
162
		register_rest_route( 'jetpack/v4', '/setting/update', array(
163
			'methods' => WP_REST_Server::EDITABLE,
164
			'callback' => __CLASS__ . '::update_setting',
165
			'permission_callback' => __CLASS__ . '::update_settings_permission_check',
166
		) );
167
168
		// Jumpstart
169
		register_rest_route( 'jetpack/v4', '/jumpstart/activate', array(
170
			'methods' => WP_REST_Server::EDITABLE,
171
			'callback' => __CLASS__ . '::jumpstart_activate',
172
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
173
		) );
174
175
		register_rest_route( 'jetpack/v4', '/jumpstart/deactivate', array(
176
			'methods' => WP_REST_Server::EDITABLE,
177
			'callback' => __CLASS__ . '::jumpstart_deactivate',
178
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
179
		) );
180
181
		// Protect: get blocked count
182
		register_rest_route( 'jetpack/v4', '/module/protect/count/get', array(
183
			'methods' => WP_REST_Server::READABLE,
184
			'callback' => __CLASS__ . '::protect_get_blocked_count',
185
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
186
		) );
187
188
		// Akismet: get spam count
189
		register_rest_route( 'jetpack/v4', '/akismet/stats/get', array(
190
			'methods'  => WP_REST_Server::READABLE,
191
			'callback' => __CLASS__ . '::akismet_get_stats_data',
192
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
193
		) );
194
195
		// Monitor: get last downtime
196
		register_rest_route( 'jetpack/v4', '/module/monitor/downtime/last', array(
197
			'methods' => WP_REST_Server::READABLE,
198
			'callback' => __CLASS__ . '::monitor_get_last_downtime',
199
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
200
		) );
201
202
		// Updates: get number of plugin updates available
203
		register_rest_route( 'jetpack/v4', '/updates/plugins', array(
204
			'methods' => WP_REST_Server::READABLE,
205
			'callback' => __CLASS__ . '::get_plugin_update_count',
206
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
207
		) );
208
209
		// Verification: get services that this site is verified with
210
		register_rest_route( 'jetpack/v4', '/module/verification-tools/services', array(
211
			'methods' => WP_REST_Server::READABLE,
212
			'callback' => __CLASS__ . '::get_verified_services',
213
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
214
		) );
215
216
		// VaultPress: get date last backup or status and actions for user to take
217
		register_rest_route( 'jetpack/v4', '/module/vaultpress/data', array(
218
			'methods' => WP_REST_Server::READABLE,
219
			'callback' => __CLASS__ . '::vaultpress_get_site_data',
220
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
221
		) );
222
223
		// Dismiss Jetpack Notices
224
		register_rest_route( 'jetpack/v4', '/notice/(?P<notice>[a-z\-_]+)/dismiss', array(
225
			'methods' => WP_REST_Server::EDITABLE,
226
			'callback' => __CLASS__ . '::dismiss_notice',
227
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
228
		) );
229
230
		// Plugins: get list of all plugins.
231
		register_rest_route( 'jetpack/v4', '/plugins', array(
232
			'methods' => WP_REST_Server::READABLE,
233
			'callback' => __CLASS__ . '::get_plugins',
234
			'permission_callback' => __CLASS__ . '::activate_plugins_permission_check',
235
		) );
236
237
		// Plugins: check if the plugin is active.
238
		register_rest_route( 'jetpack/v4', '/plugin/(?P<plugin>[a-z\/\.\-_]+)', array(
239
			'methods' => WP_REST_Server::READABLE,
240
			'callback' => __CLASS__ . '::get_plugin',
241
			'permission_callback' => __CLASS__ . '::activate_plugins_permission_check',
242
		) );
243
	}
244
245
	/**
246
	 * Handles dismissing of Jetpack Notices
247
	 *
248
	 * @since 4.1.0
249
	 *
250
	 * @return array|wp-error
251
	 */
252
	public static function dismiss_notice( $data ) {
253
		$notice = $data['notice'];
254
		if ( isset( $notice ) && ! empty( $notice ) ) {
255
			switch( $notice ) {
256
				case 'feedback_dash_request':
257
				case 'welcome':
258
					$notices = get_option( 'jetpack_dismissed_notices', array() );
259
					$notices[ $notice ] = true;
260
					update_option( 'jetpack_dismissed_notices', $notices );
261
					return rest_ensure_response( get_option( 'jetpack_dismissed_notices', array() ) );
262
263
				default:
264
					return new WP_Error( 'invalid_param', esc_html__( 'Invalid parameter "notice".', 'jetpack' ), array( 'status' => 404 ) );
265
			}
266
		}
267
268
		return new WP_Error( 'required_param', esc_html__( 'Missing parameter "notice".', 'jetpack' ), array( 'status' => 404 ) );
269
	}
270
271
	/**
272
	 * Verify that the user can disconnect the site.
273
	 *
274
	 * @since 4.1.0
275
	 *
276
	 * @return bool|WP_Error True if user is able to disconnect the site.
277
	 */
278
	public static function disconnect_site_permission_callback() {
279
		if ( current_user_can( 'jetpack_disconnect' ) ) {
280
			return true;
281
		}
282
283
		return new WP_Error( 'invalid_user_permission_jetpack_disconnect', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
284
285
	}
286
287
	/**
288
	 * Verify that the user can get a connect/link URL
289
	 *
290
	 * @since 4.1.0
291
	 *
292
	 * @return bool|WP_Error True if user is able to disconnect the site.
293
	 */
294 View Code Duplication
	public static function connect_url_permission_callback() {
295
		if ( current_user_can( 'jetpack_connect_user' ) ) {
296
			return true;
297
		}
298
299
		return new WP_Error( 'invalid_user_permission_jetpack_disconnect', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
300
301
	}
302
303
	/**
304
	 * Verify that a user can use the link endpoint.
305
	 *
306
	 * @since 4.1.0
307
	 *
308
	 * @return bool|WP_Error True if user is able to link to WordPress.com
309
	 */
310 View Code Duplication
	public static function link_user_permission_callback() {
311
		if ( current_user_can( 'jetpack_connect_user' ) ) {
312
			return true;
313
		}
314
315
		return new WP_Error( 'invalid_user_permission_link_user', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
316
	}
317
318
	/**
319
	 * Verify that a user can get the data about the current user.
320
	 * Only those who can connect.
321
	 *
322
	 * @since 4.1.0
323
	 *
324
	 * @uses Jetpack::is_user_connected();
325
	 *
326
	 * @return bool|WP_Error True if user is able to unlink.
327
	 */
328 View Code Duplication
	public static function get_user_connection_data_permission_callback() {
329
		if ( current_user_can( 'jetpack_connect_user' ) ) {
330
			return true;
331
		}
332
333
		return new WP_Error( 'invalid_user_permission_unlink_user', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
334
	}
335
336
	/**
337
	 * Verify that a user can use the unlink endpoint.
338
	 * Either needs to be an admin of the site, or for them to be currently linked.
339
	 *
340
	 * @since 4.1.0
341
	 *
342
	 * @uses Jetpack::is_user_connected();
343
	 *
344
	 * @return bool|WP_Error True if user is able to unlink.
345
	 */
346
	public static function unlink_user_permission_callback() {
347
		if ( current_user_can( 'jetpack_connect' ) || Jetpack::is_user_connected( get_current_user_id() ) ) {
348
			return true;
349
		}
350
351
		return new WP_Error( 'invalid_user_permission_unlink_user', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
352
	}
353
354
	/**
355
	 * Verify that user can manage Jetpack modules.
356
	 *
357
	 * @since 4.1.0
358
	 *
359
	 * @return bool Whether user has the capability 'jetpack_manage_modules'.
360
	 */
361
	public static function manage_modules_permission_check() {
362
		if ( current_user_can( 'jetpack_manage_modules' ) ) {
363
			return true;
364
		}
365
366
		return new WP_Error( 'invalid_user_permission_manage_modules', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
367
	}
368
369
	/**
370
	 * Verify that user can update Jetpack modules.
371
	 *
372
	 * @since 4.1.0
373
	 *
374
	 * @return bool Whether user has the capability 'jetpack_configure_modules'.
375
	 */
376
	public static function configure_modules_permission_check() {
377
		if ( current_user_can( 'jetpack_configure_modules' ) ) {
378
			return true;
379
		}
380
381
		return new WP_Error( 'invalid_user_permission_configure_modules', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
382
	}
383
384
	/**
385
	 * Verify that user can view Jetpack admin page.
386
	 *
387
	 * @since 4.1.0
388
	 *
389
	 * @return bool Whether user has the capability 'jetpack_admin_page'.
390
	 */
391 View Code Duplication
	public static function view_admin_page_permission_check() {
392
		if ( current_user_can( 'jetpack_admin_page' ) ) {
393
			return true;
394
		}
395
396
		return new WP_Error( 'invalid_user_permission_view_admin', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
397
	}
398
399
	/**
400
	 * Verify that user can update Jetpack options.
401
	 *
402
	 * @since 4.1.0
403
	 *
404
	 * @return bool Whether user has the capability 'jetpack_admin_page'.
405
	 */
406
	public static function update_settings_permission_check() {
407
		if ( current_user_can( 'manage_options' ) ) {
408
			return true;
409
		}
410
411
		return new WP_Error( 'invalid_user_permission_manage_settings', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
412
	}
413
414
	/**
415
	 * Verify that user can view Jetpack admin page and can activate plugins.
416
	 *
417
	 * @since 4.1.0
418
	 *
419
	 * @return bool Whether user has the capability 'jetpack_admin_page' and 'activate_plugins'.
420
	 */
421 View Code Duplication
	public static function activate_plugins_permission_check() {
422
		if ( current_user_can( 'jetpack_admin_page', 'activate_plugins' ) ) {
423
			return true;
424
		}
425
426
		return new WP_Error( 'invalid_user_permission_activate_plugins', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
427
	}
428
429
	/**
430
	 * Contextual HTTP error code for authorization failure.
431
	 *
432
	 * Taken from rest_authorization_required_code() in WP-API plugin until is added to core.
433
	 * @see https://github.com/WP-API/WP-API/commit/7ba0ae6fe4f605d5ffe4ee85b1cd5f9fb46900a6
434
	 *
435
	 * @since 4.1.0
436
	 *
437
	 * @return int
438
	 */
439
	public static function rest_authorization_required_code() {
440
		return is_user_logged_in() ? 403 : 401;
441
	}
442
443
	/**
444
	 * Get connection status for this Jetpack site.
445
	 *
446
	 * @since 4.1.0
447
	 *
448
	 * @return bool True if site is connected
449
	 */
450
	public static function jetpack_connection_status() {
451
		return rest_ensure_response( array(
452
				'isActive'  => Jetpack::is_active(),
453
				'isStaging' => Jetpack::is_staging_site(),
454
				'devMode'   => array(
455
					'isActive' => Jetpack::is_development_mode(),
456
					'constant' => defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG,
457
					'url'      => site_url() && false === strpos( site_url(), '.' ),
458
					'filter'   => apply_filters( 'jetpack_development_mode', false ),
459
				),
460
			)
461
		);
462
	}
463
464
	public static function recheck_ssl() {
465
		$result = Jetpack::permit_ssl( true );
466
		return array(
467
			'enabled' => $result,
468
			'message' => get_transient( 'jetpack_https_test_message' )
469
		);
470
	}
471
472
	/**
473
	 * Disconnects Jetpack from the WordPress.com Servers
474
	 *
475
	 * @uses Jetpack::disconnect();
476
	 * @since 4.1.0
477
	 * @return bool|WP_Error True if Jetpack successfully disconnected.
478
	 */
479
	public static function disconnect_site() {
480
		if ( Jetpack::is_active() ) {
481
			Jetpack::disconnect();
482
			return rest_ensure_response( array( 'code' => 'success' ) );
483
		}
484
485
		return new WP_Error( 'disconnect_failed', esc_html__( 'Was not able to disconnect the site.  Please try again.', 'jetpack' ), array( 'status' => 400 ) );
486
	}
487
488
	/**
489
	 * Gets a new connect URL with fresh nonce
490
	 *
491
	 * @uses Jetpack::disconnect();
492
	 * @since 4.1.0
493
	 * @return bool|WP_Error True if Jetpack successfully disconnected.
494
	 */
495
	public static function build_connect_url() {
496
		if ( require_once( ABSPATH . 'wp-admin/includes/plugin.php' ) ) {
497
			$url = Jetpack::init()->build_connect_url( true, false, false );
498
			return rest_ensure_response( $url );
499
		}
500
501
		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 ) );
502
	}
503
504
	/**
505
	 * Get miscellaneous settings for this Jetpack installation, like Holiday Snow.
506
	 *
507
	 * @since 4.1.0
508
	 *
509
	 * @return object $response {
510
	 *     Array of miscellaneous settings.
511
	 *
512
	 *     @type bool $holiday-snow Did Jack steal Christmas?
513
	 * }
514
	 */
515
	public static function get_settings() {
516
		$response = array(
517
			jetpack_holiday_snow_option_name() => get_option( jetpack_holiday_snow_option_name() ) == 'letitsnow',
518
		);
519
		return rest_ensure_response( $response );
520
	}
521
522
	/**
523
	 * Get miscellaneous user data related to the connection. Similar data available in old "My Jetpack".
524
	 * Information about the master/primary user.
525
	 * Information about the current user.
526
	 *
527
	 * @since 4.1.0
528
	 *
529
	 * @return object
530
	 */
531
	public static function get_user_connection_data() {
532
		require_once( JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class.jetpack-react-page.php' );
533
534
		$response = array(
535
			'othersLinked' => jetpack_get_other_linked_users(),
536
			'currentUser'  => jetpack_current_user_data(),
537
		);
538
		return rest_ensure_response( $response );
539
	}
540
541
542
543
	/**
544
	 * Update a single miscellaneous setting for this Jetpack installation, like Holiday Snow.
545
	 *
546
	 * @since 4.1.0
547
	 *
548
	 * @param WP_REST_Request $data
549
	 *
550
	 * @return object Jetpack miscellaneous settings.
551
	 */
552
	public static function update_setting( $data ) {
553
		// Get parameters to update the module.
554
		$param = $data->get_json_params();
555
556
		// Exit if no parameters were passed.
557 View Code Duplication
		if ( ! is_array( $param ) ) {
558
			return new WP_Error( 'missing_setting', esc_html__( 'Missing setting.', 'jetpack' ), array( 'status' => 404 ) );
559
		}
560
561
		// Get option name and value.
562
		$option = key( $param );
563
		$value  = current( $param );
564
565
		// Log success or not
566
		$updated = false;
567
568
		switch ( $option ) {
569
			case jetpack_holiday_snow_option_name():
570
				$updated = update_option( $option, ( true == (bool) $value ) ? 'letitsnow' : '' );
571
				break;
572
		}
573
574
		if ( $updated ) {
575
			return rest_ensure_response( array(
576
				'code' 	  => 'success',
577
				'message' => esc_html__( 'Setting updated.', 'jetpack' ),
578
				'value'   => $value,
579
			) );
580
		}
581
582
		return new WP_Error( 'setting_not_updated', esc_html__( 'The setting was not updated.', 'jetpack' ), array( 'status' => 400 ) );
583
	}
584
585
	/**
586
	 * Unlinks a user from the WordPress.com Servers.
587
	 * Default $data['id'] will default to current_user_id if no value is given.
588
	 *
589
	 * Example: '/unlink?id=1234'
590
	 *
591
	 * @since 4.1.0
592
	 * @uses  Jetpack::unlink_user
593
	 *
594
	 * @param WP_REST_Request $data {
595
	 *     Array of parameters received by request.
596
	 *
597
	 *     @type int $id ID of user to unlink.
598
	 * }
599
	 *
600
	 * @return bool|WP_Error True if user successfully unlinked.
601
	 */
602
	public static function unlink_user( $data ) {
603
		if ( isset( $data['id'] ) && Jetpack::unlink_user( $data['id'] ) ) {
604
			return rest_ensure_response(
605
				array(
606
					'code' => 'success'
607
				)
608
			);
609
		}
610
611
		return new WP_Error( 'unlink_user_failed', esc_html__( 'Was not able to unlink the user.  Please try again.', 'jetpack' ), array( 'status' => 400 ) );
612
	}
613
614
	/**
615
	 * Get site data, including for example, the site's current plan.
616
	 *
617
	 * @since 4.1.0
618
	 *
619
	 * @return array Array of Jetpack modules.
620
	 */
621
	public static function get_site_data() {
622
623
		if ( $site_id = Jetpack_Options::get_option( 'id' ) ) {
624
			$response = Jetpack_Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d', $site_id ), '1.1' );
625
626
			if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
627
				return new WP_Error( 'site_data_fetch_failed', esc_html__( 'Failed fetching site data. Try again later.', 'jetpack' ), array( 'status' => 400 ) );
628
			}
629
630
			return rest_ensure_response( array(
631
					'code' => 'success',
632
					'message' => esc_html__( 'Site data correctly received.', 'jetpack' ),
633
					'data' => wp_remote_retrieve_body( $response ),
634
				)
635
			);
636
		}
637
638
		return new WP_Error( 'site_id_missing', esc_html__( 'The ID of this site does not exist.', 'jetpack' ), array( 'status' => 404 ) );
639
	}
640
641
	/**
642
	 * Is Akismet registered and active?
643
	 *
644
	 * @since 4.1.0
645
	 *
646
	 * @return bool|WP_Error True if Akismet is active and registered. Otherwise, a WP_Error instance with the corresponding error.
647
	 */
648
	public static function akismet_is_active_and_registered() {
649
		if ( ! file_exists( WP_PLUGIN_DIR . '/akismet/class.akismet.php' ) ) {
650
			return new WP_Error( 'not_installed', esc_html__( 'Please install Akismet.', 'jetpack' ), array( 'status' => 400 ) );
651
		}
652
653
		if ( ! class_exists( 'Akismet' ) ) {
654
			return new WP_Error( 'not_active', esc_html__( 'Please activate Akismet.', 'jetpack' ), array( 'status' => 400 ) );
655
		}
656
657
		// What about if Akismet is put in a sub-directory or maybe in mu-plugins?
658
		require_once WP_PLUGIN_DIR . '/akismet/class.akismet.php';
659
		require_once WP_PLUGIN_DIR . '/akismet/class.akismet-admin.php';
660
		$akismet_key = Akismet::verify_key( Akismet::get_api_key() );
661
662
		if ( ! $akismet_key || 'invalid' === $akismet_key || 'failed' === $akismet_key ) {
663
			return new WP_Error( 'invalid_key', esc_html__( 'Invalid Akismet key. Please contact support.', 'jetpack' ), array( 'status' => 400 ) );
664
		}
665
666
		return true;
667
	}
668
669
	/**
670
	 * Get a list of all Jetpack modules and their information.
671
	 *
672
	 * @since 4.1.0
673
	 *
674
	 * @return array Array of Jetpack modules.
675
	 */
676
	public static function get_modules() {
677
		require_once( JETPACK__PLUGIN_DIR . 'class.jetpack-admin.php' );
678
679
		$modules = Jetpack_Admin::init()->get_modules();
680
		foreach ( $modules as $slug => $properties ) {
681
			$modules[ $slug ]['options'] = self::prepare_options_for_response( $slug );
682
		}
683
684
		return $modules;
685
	}
686
687
	/**
688
	 * Get information about a specific and valid Jetpack module.
689
	 *
690
	 * @since 4.1.0
691
	 *
692
	 * @param WP_REST_Request $data {
693
	 *     Array of parameters received by request.
694
	 *
695
	 *     @type string $slug Module slug.
696
	 * }
697
	 *
698
	 * @return mixed|void|WP_Error
699
	 */
700
	public static function get_module( $data ) {
701
		if ( Jetpack::is_module( $data['slug'] ) ) {
702
703
			$module = Jetpack::get_module( $data['slug'] );
704
705
			$module['options'] = self::prepare_options_for_response( $data['slug'] );
706
707
			return $module;
708
		}
709
710
		return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
711
	}
712
713
	/**
714
	 * If it's a valid Jetpack module, activate it.
715
	 *
716
	 * @since 4.1.0
717
	 *
718
	 * @param WP_REST_Request $data {
719
	 *     Array of parameters received by request.
720
	 *
721
	 *     @type string $slug Module slug.
722
	 * }
723
	 *
724
	 * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
725
	 */
726
	public static function activate_module( $data ) {
727
		if ( Jetpack::is_module( $data['slug'] ) ) {
728 View Code Duplication
			if ( Jetpack::activate_module( $data['slug'], false, false ) ) {
729
				return rest_ensure_response( array(
730
					'code' 	  => 'success',
731
					'message' => esc_html__( 'The requested Jetpack module was activated.', 'jetpack' ),
732
				) );
733
			}
734
			return new WP_Error( 'activation_failed', esc_html__( 'The requested Jetpack module could not be activated.', 'jetpack' ), array( 'status' => 424 ) );
735
		}
736
737
		return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
738
	}
739
740
	/**
741
	 * Activate a list of valid Jetpack modules.
742
	 *
743
	 * @since 4.1.0
744
	 *
745
	 * @param WP_REST_Request $data {
746
	 *     Array of parameters received by request.
747
	 *
748
	 *     @type string $slug Module slug.
749
	 * }
750
	 *
751
	 * @return bool|WP_Error True if modules were activated. Otherwise, a WP_Error instance with the corresponding error.
752
	 */
753
	public static function activate_modules( $data ) {
754
		$params = $data->get_json_params();
755
		if ( isset( $params['modules'] ) && is_array( $params['modules'] ) ) {
756
			$activated = array();
757
			$failed = array();
758
759
			foreach ( $params['modules'] as $module ) {
760
				if ( Jetpack::activate_module( $module, false, false ) ) {
761
					$activated[] = $module;
762
				} else {
763
					$failed[] = $module;
764
				}
765
			}
766
767
			if ( empty( $failed ) ) {
768
				return rest_ensure_response( array(
769
					'code' 	  => 'success',
770
					'message' => esc_html__( 'All modules activated.', 'jetpack' ),
771
				) );
772
			} else {
773
				$error = '';
774
775
				$activated_count = count( $activated );
776 View Code Duplication
				if ( $activated_count > 0 ) {
777
					$activated_last = array_pop( $activated );
778
					$activated_text = $activated_count > 1 ? sprintf(
779
						/* Translators: first variable is a list followed by a last item. Example: dog, cat and bird. */
780
						__( '%s and %s', 'jetpack' ),
781
						join( ', ', $activated ), $activated_last ) : $activated_last;
782
783
					$error = sprintf(
784
						/* Translators: the plural variable is a list followed by a last item. Example: dog, cat and bird. */
785
						_n( 'The module %s was activated.', 'The modules %s were activated.', $activated_count, 'jetpack' ),
786
						$activated_text ) . ' ';
787
				}
788
789
				$failed_count = count( $failed );
790 View Code Duplication
				if ( count( $failed ) > 0 ) {
791
					$failed_last = array_pop( $failed );
792
					$failed_text = $failed_count > 1 ? sprintf(
793
						/* Translators: first variable is a list followed by a last item. Example: dog, cat and bird. */
794
						__( '%s and %s', 'jetpack' ),
795
						join( ', ', $failed ), $failed_last ) : $failed_last;
796
797
					$error = sprintf(
798
						/* Translators: the plural variable is a list followed by a last item. Example: dog, cat and bird. */
799
						_n( 'The module %s failed to be activated.', 'The modules %s failed to be activated.', $failed_count, 'jetpack' ),
800
						$failed_text ) . ' ';
801
				}
802
			}
803
			return new WP_Error( 'activation_failed', esc_html( $error ), array( 'status' => 424 ) );
804
		}
805
806
		return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
807
	}
808
809
	/**
810
	 * Reset Jetpack options
811
	 *
812
	 * @since 4.1.0
813
	 *
814
	 * @param WP_REST_Request $data {
815
	 *     Array of parameters received by request.
816
	 *
817
	 *     @type string $options Available options to reset are options|modules
818
	 * }
819
	 *
820
	 * @return bool|WP_Error True if options were reset. Otherwise, a WP_Error instance with the corresponding error.
821
	 */
822
	public static function reset_jetpack_options( $data ) {
823
		if ( isset( $data['options'] ) ) {
824
			$data = $data['options'];
825
826
			switch( $data ) {
827
				case ( 'options' ) :
828
					$options_to_reset = Jetpack::get_jetpack_options_for_reset();
829
830
					// Reset the Jetpack options
831
					foreach ( $options_to_reset['jp_options'] as $option_to_reset ) {
832
						Jetpack_Options::delete_option( $option_to_reset );
833
					}
834
835
					foreach ( $options_to_reset['wp_options'] as $option_to_reset ) {
836
						delete_option( $option_to_reset );
837
					}
838
839
					// Reset to default modules
840
					$default_modules = Jetpack::get_default_modules();
841
					Jetpack_Options::update_option( 'active_modules', $default_modules );
842
843
					// Jumpstart option is special
844
					Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
845
					return rest_ensure_response( array(
846
						'code' 	  => 'success',
847
						'message' => esc_html__( 'Jetpack options reset.', 'jetpack' ),
848
					) );
849
					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...
850
851
				case 'modules':
852
					$default_modules = Jetpack::get_default_modules();
853
					Jetpack_Options::update_option( 'active_modules', $default_modules );
854
855
					return rest_ensure_response( array(
856
						'code' 	  => 'success',
857
						'message' => esc_html__( 'Modules reset to default.', 'jetpack' ),
858
					) );
859
					break;
0 ignored issues
show
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
860
861
				default:
862
					return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
863
			}
864
		}
865
866
		return new WP_Error( 'required_param', esc_html__( 'Missing parameter "type".', 'jetpack' ), array( 'status' => 404 ) );
867
	}
868
869
	/**
870
	 * Activates a series of valid Jetpack modules and initializes some options.
871
	 *
872
	 * @since 4.1.0
873
	 *
874
	 * @param WP_REST_Request $data {
875
	 *     Array of parameters received by request.
876
	 * }
877
	 *
878
	 * @return bool|WP_Error True if Jumpstart succeeded. Otherwise, a WP_Error instance with the corresponding error.
879
	 */
880
	public static function jumpstart_activate( $data ) {
881
		$modules = Jetpack::get_available_modules();
882
		$activate_modules = array();
883
		foreach ( $modules as $module ) {
884
			$module_info = Jetpack::get_module( $module );
885
			if ( isset( $module_info['feature'] ) && is_array( $module_info['feature'] ) && in_array( 'Jumpstart', $module_info['feature'] ) ) {
886
				$activate_modules[] = $module;
887
			}
888
		}
889
890
		// Collect success/error messages like modules that are properly activated.
891
		$result = array(
892
			'activated_modules' => array(),
893
			'failed_modules'    => array(),
894
		);
895
896
		// Update the jumpstart option
897
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
898
			$result['jumpstart_activated'] = Jetpack_Options::update_option( 'jumpstart', 'jumpstart_activated' );
899
		}
900
901
		// Check for possible conflicting plugins
902
		$module_slugs_filtered = Jetpack::init()->filter_default_modules( $activate_modules );
903
904
		foreach ( $module_slugs_filtered as $module_slug ) {
905
			Jetpack::log( 'activate', $module_slug );
906
			if ( Jetpack::activate_module( $module_slug, false, false ) ) {
907
				$result['activated_modules'][] = $module_slug;
908
			} else {
909
				$result['failed_modules'][] = $module_slug;
910
			}
911
			Jetpack::state( 'message', 'no_message' );
912
		}
913
914
		// Set the default sharing buttons and set to display on posts if none have been set.
915
		$sharing_services = get_option( 'sharing-services' );
916
		$sharing_options  = get_option( 'sharing-options' );
917
		if ( empty( $sharing_services['visible'] ) ) {
918
			// Default buttons to set
919
			$visible = array(
920
				'twitter',
921
				'facebook',
922
				'google-plus-1',
923
			);
924
			$hidden = array();
925
926
			// Set some sharing settings
927
			$sharing = new Sharing_Service();
928
			$sharing_options['global'] = array(
929
				'button_style'  => 'icon',
930
				'sharing_label' => $sharing->default_sharing_label,
931
				'open_links'    => 'same',
932
				'show'          => array( 'post' ),
933
				'custom'        => isset( $sharing_options['global']['custom'] ) ? $sharing_options['global']['custom'] : array()
934
			);
935
936
			$result['sharing_options']  = update_option( 'sharing-options', $sharing_options );
937
			$result['sharing_services'] = update_option( 'sharing-services', array( 'visible' => $visible, 'hidden' => $hidden ) );
938
		}
939
940
		// If all Jumpstart modules were activated
941
		if ( empty( $result['failed_modules'] ) ) {
942
			return rest_ensure_response( array(
943
				'code' 	  => 'success',
944
				'message' => esc_html__( 'Jumpstart done.', 'jetpack' ),
945
				'data'    => $result,
946
			) );
947
		}
948
949
		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 ) );
950
	}
951
952
	/**
953
	 * Dismisses Jumpstart so user is not prompted to go through it again.
954
	 *
955
	 * @since 4.1.0
956
	 *
957
	 * @param WP_REST_Request $data {
958
	 *     Array of parameters received by request.
959
	 * }
960
	 *
961
	 * @return bool|WP_Error True if Jumpstart was disabled or was nothing to dismiss. Otherwise, a WP_Error instance with a message.
962
	 */
963
	public static function jumpstart_deactivate( $data ) {
964
965
		// If dismissed, flag the jumpstart option as such.
966
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
967
			if ( Jetpack_Options::update_option( 'jumpstart', 'jumpstart_dismissed' ) ) {
968
				return rest_ensure_response( array(
969
					'code' 	  => 'success',
970
					'message' => esc_html__( 'Jumpstart dismissed.', 'jetpack' ),
971
				) );
972
			} else {
973
				return new WP_Error( 'jumpstart_failed_dismiss', esc_html__( 'Jumpstart could not be dismissed.', 'jetpack' ), array( 'status' => 400 ) );
974
			}
975
		}
976
977
		// If this was not a new connection and there was nothing to dismiss, don't fail.
978
		return rest_ensure_response( array(
979
			'code' 	  => 'success',
980
			'message' => esc_html__( 'Nothing to dismiss. This was not a new connection.', 'jetpack' ),
981
		) );
982
	}
983
984
	/**
985
	 * If it's a valid Jetpack module, deactivate it.
986
	 *
987
	 * @since 4.1.0
988
	 *
989
	 * @param WP_REST_Request $data {
990
	 *     Array of parameters received by request.
991
	 *
992
	 *     @type string $slug Module slug.
993
	 * }
994
	 *
995
	 * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
996
	 */
997
	public static function deactivate_module( $data ) {
998
		if ( Jetpack::is_module( $data['slug'] ) ) {
999 View Code Duplication
			if ( ! Jetpack::is_module_active( $data['slug'] ) ) {
1000
				return new WP_Error( 'already_inactive', esc_html__( 'The requested Jetpack module was already inactive.', 'jetpack' ), array( 'status' => 409 ) );
1001
			}
1002 View Code Duplication
			if ( Jetpack::deactivate_module( $data['slug'] ) ) {
1003
				return rest_ensure_response( array(
1004
					'code' 	  => 'success',
1005
					'message' => esc_html__( 'The requested Jetpack module was deactivated.', 'jetpack' ),
1006
				) );
1007
			}
1008
			return new WP_Error( 'deactivation_failed', esc_html__( 'The requested Jetpack module could not be deactivated.', 'jetpack' ), array( 'status' => 400 ) );
1009
		}
1010
1011
		return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
1012
	}
1013
1014
	/**
1015
	 * If it's a valid Jetpack module and configuration parameters have been sent, update it.
1016
	 *
1017
	 * @since 4.1.0
1018
	 *
1019
	 * @param WP_REST_Request $data {
1020
	 *     Array of parameters received by request.
1021
	 *
1022
	 *     @type string $slug Module slug.
1023
	 * }
1024
	 *
1025
	 * @return bool|WP_Error True if module was updated. Otherwise, a WP_Error instance with the corresponding error.
1026
	 */
1027
	public static function update_module( $data ) {
1028
		if ( ! Jetpack::is_module( $data['slug'] ) ) {
1029
			return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
1030
		}
1031
1032 View Code Duplication
		if ( ! Jetpack::is_module_active( $data['slug'] ) ) {
1033
			return new WP_Error( 'inactive', esc_html__( 'The requested Jetpack module is inactive.', 'jetpack' ), array( 'status' => 409 ) );
1034
		}
1035
1036
		// Get parameters to update the module.
1037
		$param = $data->get_json_params();
1038
1039
		// Exit if no parameters were passed.
1040 View Code Duplication
		if ( ! is_array( $param ) ) {
1041
			return new WP_Error( 'missing_option', esc_html__( 'Missing option.', 'jetpack' ), array( 'status' => 404 ) );
1042
		}
1043
1044
		// Get option name and value.
1045
		$option = key( $param );
1046
		$value  = current( $param );
1047
1048
		// Get available module options.
1049
		$options = self::get_module_available_options();
1050
1051
		// If option is invalid, don't go any further.
1052 View Code Duplication
		if ( ! in_array( $option, array_keys( $options ) ) ) {
1053
			return new WP_Error( 'invalid_param', esc_html(	sprintf( __( 'The option %s is invalid for this module.', 'jetpack' ), $option ) ), array( 'status' => 404 ) );
1054
		}
1055
1056
		// Used if response is successful. The message can be overwritten and additional data can be added here.
1057
		$response = array(
1058
			'code' 	  => 'success',
1059
			'message' => esc_html__( 'The requested Jetpack module was updated.', 'jetpack' ),
1060
		);
1061
1062
		// Used if there was an error. Can be overwritten with specific error messages.
1063
		/* Translators: the variable is a module option name. */
1064
		$error = sprintf( __( 'The option %s was not updated.', 'jetpack' ), $option );
1065
1066
		// Set to true if the option update was successful.
1067
		$updated = false;
1068
1069
		// Properly cast value based on its type defined in endpoint accepted args.
1070
		$value = self::cast_value( $value, $options[ $option ] );
1071
1072
		switch ( $option ) {
1073
			case 'monitor_receive_notifications':
1074
				$monitor = new Jetpack_Monitor();
1075
1076
				// If we got true as response, consider it done.
1077
				$updated = true === $monitor->update_option_receive_jetpack_monitor_notification( $value );
1078
				break;
1079
1080
			case 'post_by_email_address':
1081
				if ( 'create' == $value ) {
1082
					$result = self::_process_post_by_email(
1083
						'jetpack.createPostByEmailAddress',
1084
						esc_html__( 'Unable to create the Post by Email address. Please try again later.', 'jetpack' )
1085
					);
1086
				} elseif ( 'regenerate' == $value ) {
1087
					$result = self::_process_post_by_email(
1088
						'jetpack.regeneratePostByEmailAddress',
1089
						esc_html__( 'Unable to regenerate the Post by Email address. Please try again later.', 'jetpack' )
1090
					);
1091
				} elseif ( 'delete' == $value ) {
1092
					$result = self::_process_post_by_email(
1093
						'jetpack.deletePostByEmailAddress',
1094
						esc_html__( 'Unable to delete the Post by Email address. Please try again later.', 'jetpack' )
1095
					);
1096
				} else {
1097
					$result = false;
1098
				}
1099
1100
				// If we got an email address (create or regenerate) or 1 (delete), consider it done.
1101
				if ( preg_match( '/[a-z0-9][email protected]/', $result ) ) {
1102
					$response[ $option ] = $result;
1103
					$updated = true;
1104
				} elseif ( 1 == $result ) {
1105
					$updated = true;
1106
				} elseif ( is_array( $result ) && isset( $result['message'] ) ) {
1107
					$error = $result['message'];
1108
				}
1109
				break;
1110
1111
			case 'jetpack_protect_key':
1112
				$protect = Jetpack_Protect_Module::instance();
1113
				if ( 'create' == $value ) {
1114
					$result = $protect->get_protect_key();
1115
				} else {
1116
					$result = false;
1117
				}
1118
1119
				// If we got one of Protect keys, consider it done.
1120
				if ( preg_match( '/[a-z0-9]{40,}/i', $result ) ) {
1121
					$response[ $option ] = $result;
1122
					$updated = true;
1123
				}
1124
				break;
1125
1126
			case 'jetpack_protect_global_whitelist':
1127
				$updated = jetpack_protect_save_whitelist( explode( PHP_EOL, str_replace( ' ', '', $value ) ) );
1128
				if ( is_wp_error( $updated ) ) {
1129
					$error = $updated->get_error_message();
1130
				}
1131
				break;
1132
1133
			case 'show_headline':
1134
			case 'show_thumbnails':
1135
				$grouped_options = $grouped_options_current = Jetpack_Options::get_option( 'relatedposts' );
1136
				$grouped_options[ $option ] = $value;
1137
1138
				// If option value was the same, consider it done.
1139
				$updated = $grouped_options_current != $grouped_options ? Jetpack_Options::update_option( 'relatedposts', $grouped_options ) : true;
1140
				break;
1141
1142
			case 'google':
1143
			case 'bing':
1144
			case 'pinterest':
1145
				$grouped_options = $grouped_options_current = get_option( 'verification_services_codes' );
1146
				$grouped_options[ $option ] = $value;
1147
1148
				// If option value was the same, consider it done.
1149
				$updated = $grouped_options_current != $grouped_options ? update_option( 'verification_services_codes', $grouped_options ) : true;
1150
				break;
1151
1152
			case 'sharing_services':
1153
				$sharer = new Sharing_Service();
1154
1155
				// If option value was the same, consider it done.
1156
				$updated = $value != $sharer->get_blog_services() ? $sharer->set_blog_services( $value['visible'], $value['hidden'] ) : true;
1157
				break;
1158
1159
			case 'button_style':
1160
			case 'sharing_label':
1161
			case 'show':
1162
				$sharer = new Sharing_Service();
1163
				$grouped_options = $sharer->get_global_options();
1164
				$grouped_options[ $option ] = $value;
1165
				$updated = $sharer->set_global_options( $grouped_options );
1166
				break;
1167
1168
			case 'custom':
1169
				$sharer = new Sharing_Service();
1170
				$updated = $sharer->new_service( stripslashes( $value['sharing_name'] ), stripslashes( $value['sharing_url'] ), stripslashes( $value['sharing_icon'] ) );
1171
1172
				// Return new custom service
1173
				$response[ $option ] = $updated;
1174
				break;
1175
1176
			case 'sharing_delete_service':
1177
				$sharer = new Sharing_Service();
1178
				$updated = $sharer->delete_service( $value );
1179
				break;
1180
1181
			case 'jetpack-twitter-cards-site-tag':
1182
				$value = trim( ltrim( strip_tags( $value ), '@' ) );
1183
				$updated = get_option( $option ) !== $value ? update_option( $option, $value ) : true;
1184
				break;
1185
1186
			case 'onpublish':
1187
			case 'onupdate':
1188
			case 'Bias Language':
1189
			case 'Cliches':
1190
			case 'Complex Expression':
1191
			case 'Diacritical Marks':
1192
			case 'Double Negative':
1193
			case 'Hidden Verbs':
1194
			case 'Jargon Language':
1195
			case 'Passive voice':
1196
			case 'Phrases to Avoid':
1197
			case 'Redundant Expression':
1198
			case 'guess_lang':
1199
				if ( in_array( $option, array( 'onpublish', 'onupdate' ) ) ) {
1200
					$atd_option = 'AtD_check_when';
1201
				} elseif ( 'guess_lang' == $option ) {
1202
					$atd_option = 'AtD_guess_lang';
1203
					$option = 'true';
1204
				} else {
1205
					$atd_option = 'AtD_options';
1206
				}
1207
				$user_id = get_current_user_id();
1208
				$grouped_options_current = AtD_get_options( $user_id, $atd_option );
1209
				unset( $grouped_options_current['name'] );
1210
				$grouped_options = $grouped_options_current;
1211
				if ( $value && ! isset( $grouped_options [ $option ] ) ) {
1212
					$grouped_options [ $option ] = $value;
1213
				} elseif ( ! $value && isset( $grouped_options [ $option ] ) ) {
1214
					unset( $grouped_options [ $option ] );
1215
				}
1216
				// If option value was the same, consider it done, otherwise try to update it.
1217
				$options_to_save = implode( ',', array_keys( $grouped_options ) );
1218
				$updated = $grouped_options != $grouped_options_current ? AtD_update_setting( $user_id, $atd_option, $options_to_save ) : true;
1219
				break;
1220
1221
			case 'ignored_phrases':
1222
			case 'unignore_phrase':
1223
				$user_id = get_current_user_id();
1224
				$atd_option = 'AtD_ignored_phrases';
1225
				$grouped_options = $grouped_options_current = explode( ',', AtD_get_setting( $user_id, $atd_option ) );
1226
				if ( 'ignored_phrases' == $option ) {
1227
					$grouped_options[] = $value;
1228
				} else {
1229
					$index = array_search( $value, $grouped_options );
1230
					if ( false !== $index ) {
1231
						unset( $grouped_options[ $index ] );
1232
						$grouped_options = array_values( $grouped_options );
1233
					}
1234
				}
1235
				$ignored_phrases = implode( ',', array_filter( array_map( 'strip_tags', $grouped_options ) ) );
1236
				$updated = $grouped_options != $grouped_options_current ? AtD_update_setting( $user_id, $atd_option, $ignored_phrases ) : true;
1237
				break;
1238
1239
			default:
1240
				// If option value was the same, consider it done.
1241
				$updated = get_option( $option ) != $value ? update_option( $option, $value ) : true;
1242
				break;
1243
		}
1244
1245
		// The option was not updated.
1246
		if ( ! $updated ) {
1247
			return new WP_Error( 'module_option_not_updated', esc_html( $error ), array( 'status' => 400 ) );
1248
		}
1249
1250
		// The option was updated.
1251
		return rest_ensure_response( $response );
1252
	}
1253
1254
	/**
1255
	 * Calls WPCOM through authenticated request to create, regenerate or delete the Post by Email address.
1256
	 * @todo: When all settings are updated to use endpoints, move this to the Post by Email module and replace __process_ajax_proxy_request.
1257
	 *
1258
	 * @since 4.1.0
1259
	 *
1260
	 * @param string $endpoint Process to call on WPCOM to create, regenerate or delete the Post by Email address.
1261
	 * @param string $error	   Error message to return.
1262
	 *
1263
	 * @return array
1264
	 */
1265
	private static function _process_post_by_email( $endpoint, $error ) {
1266
		if ( ! current_user_can( 'edit_posts' ) ) {
1267
			return array( 'message' => $error );
1268
		}
1269
		Jetpack::load_xml_rpc_client();
1270
		$xml = new Jetpack_IXR_Client( array(
1271
			'user_id' => get_current_user_id(),
1272
		) );
1273
		$xml->query( $endpoint );
1274
1275
		if ( $xml->isError() ) {
1276
			return array( 'message' => $error );
1277
		}
1278
1279
		$response = $xml->getResponse();
1280
		if ( empty( $response ) ) {
1281
			return array( 'message' => $error );
1282
		}
1283
1284
		// Used only in Jetpack_Core_Json_Api_Endpoints::get_remote_value.
1285
		update_option( 'post_by_email_address', $response );
1286
1287
		return $response;
1288
	}
1289
1290
	/**
1291
	 * Get the query parameters for module updating.
1292
	 *
1293
	 * @since 4.1.0
1294
	 *
1295
	 * @return array
1296
	 */
1297
	public static function get_module_updating_parameters() {
1298
		$parameters = array(
1299
			'context'     => array(
1300
				'default' => 'edit',
1301
			),
1302
		);
1303
1304
		return array_merge( $parameters, self::get_module_available_options() );
1305
	}
1306
1307
	/**
1308
	 * Returns a list of module options that can be updated.
1309
	 *
1310
	 * @since 4.1.0
1311
	 *
1312
	 * @param string $module Module slug. If empty, it's assumed we're updating a module and we'll try to get its slug.
1313
	 * @param bool $cache Whether to cache the options or return always fresh.
1314
	 *
1315
	 * @return array
1316
	 */
1317
	public static function get_module_available_options( $module = '', $cache = true ) {
1318
		if ( $cache ) {
1319
			static $options;
1320
		} else {
1321
			$options = null;
1322
		}
1323
1324
		if ( isset( $options ) ) {
1325
			return $options;
1326
		}
1327
1328
		if ( empty( $module ) ) {
1329
			$module = self::get_module_requested( '/module/(?P<slug>[a-z\-]+)/update' );
1330
			if ( empty( $module ) ) {
1331
				return array();
1332
			}
1333
		}
1334
1335
		switch ( $module ) {
1336
1337
			// Carousel
1338
			case 'carousel':
1339
				$options = array(
1340
					'carousel_background_color' => array(
1341
						'description'        => esc_html__( 'Background color.', 'jetpack' ),
1342
						'type'               => 'string',
1343
						'default'            => 'black',
1344
						'enum'				 => array(
1345
							'black' => esc_html__( 'Black', 'jetpack' ),
1346
							'white' => esc_html__( 'White', 'jetpack' ),
1347
						),
1348
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1349
					),
1350
					'carousel_display_exif' => array(
1351
						'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 ) )  ),
1352
						'type'               => 'boolean',
1353
						'default'            => 0,
1354
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1355
					),
1356
				);
1357
				break;
1358
1359
			// Comments
1360
			case 'comments':
1361
				$options = array(
1362
					'highlander_comment_form_prompt' => array(
1363
						'description'        => esc_html__( 'Greeting Text', 'jetpack' ),
1364
						'type'               => 'string',
1365
						'default'            => esc_html__( 'Leave a Reply', 'jetpack' ),
1366
						'sanitize_callback'  => 'sanitize_text_field',
1367
					),
1368
					'jetpack_comment_form_color_scheme' => array(
1369
						'description'        => esc_html__( "Color Scheme", 'jetpack' ),
1370
						'type'               => 'string',
1371
						'default'            => 'light',
1372
						'enum'				 => array(
1373
							'light'       => esc_html__( 'Light', 'jetpack' ),
1374
							'dark'        => esc_html__( 'Dark', 'jetpack' ),
1375
							'transparent' => esc_html__( 'Transparent', 'jetpack' ),
1376
						),
1377
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1378
					),
1379
				);
1380
				break;
1381
1382
			// Custom Content Types
1383
			case 'custom-content-types':
1384
				$options = array(
1385
					'jetpack_portfolio' => array(
1386
						'description'        => esc_html__( 'Enable or disable Jetpack portfolio post type.', 'jetpack' ),
1387
						'type'               => 'boolean',
1388
						'default'            => 0,
1389
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1390
					),
1391
					'jetpack_portfolio_posts_per_page' => array(
1392
						'description'        => esc_html__( 'Number of entries to show at most in Portfolio pages.', 'jetpack' ),
1393
						'type'               => 'integer',
1394
						'default'            => 10,
1395
						'validate_callback'  => __CLASS__ . '::validate_posint',
1396
					),
1397
					'jetpack_testimonial' => array(
1398
						'description'        => esc_html__( 'Enable or disable Jetpack testimonial post type.', 'jetpack' ),
1399
						'type'               => 'boolean',
1400
						'default'            => 0,
1401
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1402
					),
1403
					'jetpack_testimonial_posts_per_page' => array(
1404
						'description'        => esc_html__( 'Number of entries to show at most in Testimonial pages.', 'jetpack' ),
1405
						'type'               => 'integer',
1406
						'default'            => 10,
1407
						'validate_callback'  => __CLASS__ . '::validate_posint',
1408
					),
1409
				);
1410
				break;
1411
1412
			// Galleries
1413 View Code Duplication
			case 'tiled-gallery':
1414
				$options = array(
1415
					'tiled_galleries' => array(
1416
						'description'        => esc_html__( 'Display all your gallery pictures in a cool mosaic.', 'jetpack' ),
1417
						'type'               => 'boolean',
1418
						'default'            => 0,
1419
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1420
					),
1421
				);
1422
				break;
1423
1424
			// Gravatar Hovercards
1425
			case 'gravatar-hovercards':
1426
				$options = array(
1427
					'gravatar_disable_hovercards' => array(
1428
						'description'        => esc_html__( "View people's profiles when you mouse over their Gravatars", 'jetpack' ),
1429
						'type'               => 'string',
1430
						'default'            => 'enabled',
1431
						// Not visible. This is used as the checkbox value.
1432
						'enum'				 => array( 'enabled', 'disabled' ),
1433
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1434
					),
1435
				);
1436
				break;
1437
1438
			// Infinite Scroll
1439
			case 'infinite-scroll':
1440
				$options = array(
1441
					'infinite_scroll' => array(
1442
						'description'        => esc_html__( 'To infinity and beyond', 'jetpack' ),
1443
						'type'               => 'boolean',
1444
						'default'            => 1,
1445
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1446
					),
1447
					'infinite_scroll_google_analytics' => array(
1448
						'description'        => esc_html__( 'Use Google Analytics with Infinite Scroll', 'jetpack' ),
1449
						'type'               => 'boolean',
1450
						'default'            => 0,
1451
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1452
					),
1453
				);
1454
				break;
1455
1456
			// Likes
1457
			case 'likes':
1458
				$options = array(
1459
					'wpl_default' => array(
1460
						'description'        => esc_html__( 'WordPress.com Likes are', 'jetpack' ),
1461
						'type'               => 'string',
1462
						'default'            => 'on',
1463
						'enum'				 => array(
1464
							'on'  => esc_html__( 'On for all posts', 'jetpack' ),
1465
							'off' => esc_html__( 'Turned on per post', 'jetpack' ),
1466
						),
1467
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1468
					),
1469
					'social_notifications_like' => array(
1470
						'description'        => esc_html__( 'Send email notification when someone likes a posts', 'jetpack' ),
1471
						'type'               => 'boolean',
1472
						'default'            => 1,
1473
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1474
					),
1475
				);
1476
				break;
1477
1478
			// Markdown
1479 View Code Duplication
			case 'markdown':
1480
				$options = array(
1481
					'wpcom_publish_comments_with_markdown' => array(
1482
						'description'        => esc_html__( 'Use Markdown for comments.', 'jetpack' ),
1483
						'type'               => 'boolean',
1484
						'default'            => 0,
1485
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1486
					),
1487
				);
1488
				break;
1489
1490
			// Mobile Theme
1491
			case 'minileven':
1492
				$options = array(
1493
					'wp_mobile_excerpt' => array(
1494
						'description'        => esc_html__( 'Excerpts', 'jetpack' ),
1495
						'type'               => 'string',
1496
						'default'            => '0',
1497
						'enum'				 => array(
1498
							'1'  => esc_html__( 'Enable excerpts on front page and on archive pages', 'jetpack' ),
1499
							'0' => esc_html__( 'Show full posts on front page and on archive pages', 'jetpack' ),
1500
						),
1501
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1502
					),
1503
					'wp_mobile_featured_images' => array(
1504
						'description'        => esc_html__( 'Featured Images', 'jetpack' ),
1505
						'type'               => 'string',
1506
						'default'            => '0',
1507
						'enum'				 => array(
1508
							'0'  => esc_html__( 'Hide all featured images', 'jetpack' ),
1509
							'1' => esc_html__( 'Display featured images', 'jetpack' ),
1510
						),
1511
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1512
					),
1513
					'wp_mobile_app_promos' => array(
1514
						'description'        => esc_html__( 'Show a promo for the WordPress mobile apps in the footer of the mobile theme.', 'jetpack' ),
1515
						'type'               => 'boolean',
1516
						'default'            => 0,
1517
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1518
					),
1519
				);
1520
				break;
1521
1522
			// Monitor
1523 View Code Duplication
			case 'monitor':
1524
				$options = array(
1525
					'monitor_receive_notifications' => array(
1526
						'description'        => esc_html__( 'Receive Monitor Email Notifications.', 'jetpack' ),
1527
						'type'               => 'boolean',
1528
						'default'            => 0,
1529
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1530
					),
1531
				);
1532
				break;
1533
1534
			// Post by Email
1535 View Code Duplication
			case 'post-by-email':
1536
				$options = array(
1537
					'post_by_email_address' => array(
1538
						'description'       => esc_html__( 'Email Address', 'jetpack' ),
1539
						'type'              => 'string',
1540
						'default'           => '',
1541
						'enum'              => array(
1542
							'create'     => esc_html__( 'Create Post by Email address', 'jetpack' ),
1543
							'regenerate' => esc_html__( 'Regenerate Post by Email address', 'jetpack' ),
1544
							'delete'     => esc_html__( 'Delete Post by Email address', 'jetpack' ),
1545
						),
1546
						'validate_callback' => __CLASS__ . '::validate_list_item',
1547
					),
1548
				);
1549
				break;
1550
1551
			// Protect
1552 View Code Duplication
			case 'protect':
1553
				$options = array(
1554
					'jetpack_protect_key' => array(
1555
						'description'        => esc_html__( 'Protect API key', 'jetpack' ),
1556
						'type'               => 'string',
1557
						'default'            => '',
1558
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1559
					),
1560
					'jetpack_protect_global_whitelist' => array(
1561
						'description'        => esc_html__( 'Protect global whitelist', 'jetpack' ),
1562
						'type'               => 'string',
1563
						'default'            => '',
1564
						'validate_callback'  => __CLASS__ . '::validate_string',
1565
						'sanitize_callback'  => 'esc_textarea',
1566
					),
1567
				);
1568
				break;
1569
1570
			// Sharing
1571
			case 'sharedaddy':
1572
				$options = array(
1573
					'sharing_services' => array(
1574
						'description'        => esc_html__( 'Enabled Services and those hidden behind a button', 'jetpack' ),
1575
						'type'               => 'array',
1576
						'default'            => array(
1577
							'visible' => array( 'twitter', 'facebook', 'google-plus-1' ),
1578
							'hidden'  => array(),
1579
						),
1580
						'validate_callback'  => __CLASS__ . '::validate_services',
1581
					),
1582
					'button_style' => array(
1583
						'description'       => esc_html__( 'Button Style', 'jetpack' ),
1584
						'type'              => 'string',
1585
						'default'           => 'icon',
1586
						'enum'              => array(
1587
							'icon-text' => esc_html__( 'Icon + text', 'jetpack' ),
1588
							'icon'      => esc_html__( 'Icon only', 'jetpack' ),
1589
							'text'      => esc_html__( 'Text only', 'jetpack' ),
1590
							'official'  => esc_html__( 'Official buttons', 'jetpack' ),
1591
						),
1592
						'validate_callback' => __CLASS__ . '::validate_list_item',
1593
					),
1594
					'sharing_label' => array(
1595
						'description'        => esc_html__( 'Sharing Label', 'jetpack' ),
1596
						'type'               => 'string',
1597
						'default'            => '',
1598
						'validate_callback'  => __CLASS__ . '::validate_string',
1599
						'sanitize_callback'  => 'esc_html',
1600
					),
1601
					'show' => array(
1602
						'description'        => esc_html__( 'Views where buttons are shown', 'jetpack' ),
1603
						'type'               => 'array',
1604
						'default'            => array( 'post' ),
1605
						'validate_callback'  => __CLASS__ . '::validate_sharing_show',
1606
					),
1607
					'jetpack-twitter-cards-site-tag' => array(
1608
						'description'        => esc_html__( "The Twitter username of the owner of this site's domain.", 'jetpack' ),
1609
						'type'               => 'string',
1610
						'default'            => '',
1611
						'validate_callback'  => __CLASS__ . '::validate_twitter_username',
1612
						'sanitize_callback'  => 'esc_html',
1613
					),
1614
					'sharedaddy_disable_resources' => array(
1615
						'description'        => esc_html__( 'Disable CSS and JS', 'jetpack' ),
1616
						'type'               => 'boolean',
1617
						'default'            => 0,
1618
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1619
					),
1620
					'custom' => array(
1621
						'description'        => esc_html__( 'Custom sharing services added by user.', 'jetpack' ),
1622
						'type'               => 'array',
1623
						'default'            => array(
1624
							'sharing_name' => '',
1625
							'sharing_url'  => '',
1626
							'sharing_icon' => '',
1627
						),
1628
						'validate_callback'  => __CLASS__ . '::validate_custom_service',
1629
					),
1630
					// Not an option, but an action that can be perfomed on the list of custom services passing the service ID.
1631
					'sharing_delete_service' => array(
1632
						'description'        => esc_html__( 'Delete custom sharing service.', 'jetpack' ),
1633
						'type'               => 'string',
1634
						'default'            => '',
1635
						'validate_callback'  => __CLASS__ . '::validate_custom_service_id',
1636
					),
1637
				);
1638
				break;
1639
1640
			// SSO
1641 View Code Duplication
			case 'sso':
1642
				$options = array(
1643
					'jetpack_sso_require_two_step' => array(
1644
						'description'        => esc_html__( 'Require Two-Step Authentication', 'jetpack' ),
1645
						'type'               => 'boolean',
1646
						'default'            => 0,
1647
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1648
					),
1649
					'jetpack_sso_match_by_email' => array(
1650
						'description'        => esc_html__( 'Match by Email', 'jetpack' ),
1651
						'type'               => 'boolean',
1652
						'default'            => 0,
1653
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1654
					),
1655
				);
1656
				break;
1657
1658
			// Site Icon
1659 View Code Duplication
			case 'site-icon':
1660
				$options = array(
1661
					'site_icon_id' => array(
1662
						'description'        => esc_html__( 'Site Icon ID', 'jetpack' ),
1663
						'type'               => 'integer',
1664
						'default'            => 0,
1665
						'validate_callback'  => __CLASS__ . '::validate_posint',
1666
					),
1667
					'site_icon_url' => array(
1668
						'description'        => esc_html__( 'Site Icon URL', 'jetpack' ),
1669
						'type'               => 'string',
1670
						'default'            => '',
1671
						'sanitize_callback'  => 'esc_url',
1672
					),
1673
				);
1674
				break;
1675
1676
			// Subscriptions
1677
			case 'subscriptions':
1678
				$options = array(
1679
					'stb_enabled' => array(
1680
						'description'        => esc_html__( "Show a <em>'follow blog'</em> option in the comment form", 'jetpack' ),
1681
						'type'               => 'boolean',
1682
						'default'            => 1,
1683
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1684
					),
1685
					'stc_enabled' => array(
1686
						'description'        => esc_html__( "Show a <em>'follow comments'</em> option in the comment form", 'jetpack' ),
1687
						'type'               => 'boolean',
1688
						'default'            => 1,
1689
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1690
					),
1691
				);
1692
				break;
1693
1694
			// Related Posts
1695
			case 'related-posts':
1696
				$options = array(
1697
					'show_headline' => array(
1698
						'description'        => esc_html__( 'Show a "Related" header to more clearly separate the related section from posts', 'jetpack' ),
1699
						'type'               => 'boolean',
1700
						'default'            => 1,
1701
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1702
					),
1703
					'show_thumbnails' => array(
1704
						'description'        => esc_html__( 'Use a large and visually striking layout', 'jetpack' ),
1705
						'type'               => 'boolean',
1706
						'default'            => 0,
1707
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1708
					),
1709
				);
1710
				break;
1711
1712
			// Spelling and Grammar - After the Deadline
1713
			case 'after-the-deadline':
1714
				$options = array(
1715
					'onpublish' => array(
1716
						'description'        => esc_html__( 'Proofread when a post or page is first published.', 'jetpack' ),
1717
						'type'               => 'boolean',
1718
						'default'            => 0,
1719
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1720
					),
1721
					'onupdate' => array(
1722
						'description'        => esc_html__( 'Proofread when a post or page is updated.', 'jetpack' ),
1723
						'type'               => 'boolean',
1724
						'default'            => 0,
1725
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1726
					),
1727
					'Bias Language' => array(
1728
						'description'        => esc_html__( 'Bias Language', 'jetpack' ),
1729
						'type'               => 'boolean',
1730
						'default'            => 0,
1731
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1732
					),
1733
					'Cliches' => array(
1734
						'description'        => esc_html__( 'Clichés', 'jetpack' ),
1735
						'type'               => 'boolean',
1736
						'default'            => 0,
1737
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1738
					),
1739
					'Complex Expression' => array(
1740
						'description'        => esc_html__( 'Complex Phrases', 'jetpack' ),
1741
						'type'               => 'boolean',
1742
						'default'            => 0,
1743
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1744
					),
1745
					'Diacritical Marks' => array(
1746
						'description'        => esc_html__( 'Diacritical Marks', 'jetpack' ),
1747
						'type'               => 'boolean',
1748
						'default'            => 0,
1749
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1750
					),
1751
					'Double Negative' => array(
1752
						'description'        => esc_html__( 'Double Negatives', 'jetpack' ),
1753
						'type'               => 'boolean',
1754
						'default'            => 0,
1755
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1756
					),
1757
					'Hidden Verbs' => array(
1758
						'description'        => esc_html__( 'Hidden Verbs', 'jetpack' ),
1759
						'type'               => 'boolean',
1760
						'default'            => 0,
1761
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1762
					),
1763
					'Jargon Language' => array(
1764
						'description'        => esc_html__( 'Jargon', 'jetpack' ),
1765
						'type'               => 'boolean',
1766
						'default'            => 0,
1767
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1768
					),
1769
					'Passive voice' => array(
1770
						'description'        => esc_html__( 'Passive Voice', 'jetpack' ),
1771
						'type'               => 'boolean',
1772
						'default'            => 0,
1773
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1774
					),
1775
					'Phrases to Avoid' => array(
1776
						'description'        => esc_html__( 'Phrases to Avoid', 'jetpack' ),
1777
						'type'               => 'boolean',
1778
						'default'            => 0,
1779
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1780
					),
1781
					'Redundant Expression' => array(
1782
						'description'        => esc_html__( 'Redundant Phrases', 'jetpack' ),
1783
						'type'               => 'boolean',
1784
						'default'            => 0,
1785
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1786
					),
1787
					'guess_lang' => array(
1788
						'description'        => esc_html__( 'Use automatically detected language to proofread posts and pages', 'jetpack' ),
1789
						'type'               => 'boolean',
1790
						'default'            => 0,
1791
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1792
					),
1793
					'ignored_phrases' => array(
1794
						'description'        => esc_html__( 'Add Phrase to be ignored', 'jetpack' ),
1795
						'type'               => 'string',
1796
						'default'            => '',
1797
						'sanitize_callback'  => 'esc_html',
1798
					),
1799
					'unignore_phrase' => array(
1800
						'description'        => esc_html__( 'Remove Phrase from being ignored', 'jetpack' ),
1801
						'type'               => 'string',
1802
						'default'            => '',
1803
						'sanitize_callback'  => 'esc_html',
1804
					),
1805
				);
1806
				break;
1807
1808
			// Verification Tools
1809
			case 'verification-tools':
1810
				$options = array(
1811
					'google' => array(
1812
						'description'        => esc_html__( 'Google Search Console', 'jetpack' ),
1813
						'type'               => 'string',
1814
						'default'            => '',
1815
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1816
					),
1817
					'bing' => array(
1818
						'description'        => esc_html__( 'Bing Webmaster Center', 'jetpack' ),
1819
						'type'               => 'string',
1820
						'default'            => '',
1821
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1822
					),
1823
					'pinterest' => array(
1824
						'description'        => esc_html__( 'Pinterest Site Verification', 'jetpack' ),
1825
						'type'               => 'string',
1826
						'default'            => '',
1827
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1828
					),
1829
				);
1830
				break;
1831
		}
1832
1833
		return $options;
1834
	}
1835
1836
	/**
1837
	 * Validates that the parameter is either a pure boolean or a numeric string that can be mapped to a boolean.
1838
	 *
1839
	 * @since 4.1.0
1840
	 *
1841
	 * @param string|bool $value Value to check.
1842
	 * @param WP_REST_Request $request
1843
	 * @param string $param
1844
	 *
1845
	 * @return bool
1846
	 */
1847
	public static function validate_boolean( $value, $request, $param ) {
1848
		if ( ! is_bool( $value ) && ! in_array( $value, array( 0, 1 ) ) ) {
1849
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be true, false, 0 or 1.', 'jetpack' ), $param ) );
1850
		}
1851
		return true;
1852
	}
1853
1854
	/**
1855
	 * Validates that the parameter is a positive integer.
1856
	 *
1857
	 * @since 4.1.0
1858
	 *
1859
	 * @param int $value Value to check.
1860
	 * @param WP_REST_Request $request
1861
	 * @param string $param
1862
	 *
1863
	 * @return bool
1864
	 */
1865
	public static function validate_posint( $value = 0, $request, $param ) {
1866
		if ( ! is_numeric( $value ) || $value <= 0 ) {
1867
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a positive integer.', 'jetpack' ), $param ) );
1868
		}
1869
		return true;
1870
	}
1871
1872
	/**
1873
	 * Validates that the parameter belongs to a list of admitted values.
1874
	 *
1875
	 * @since 4.1.0
1876
	 *
1877
	 * @param string $value Value to check.
1878
	 * @param WP_REST_Request $request
1879
	 * @param string $param
1880
	 *
1881
	 * @return bool
1882
	 */
1883
	public static function validate_list_item( $value = '', $request, $param ) {
1884
		$attributes = $request->get_attributes();
1885
		if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
1886
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s not recognized', 'jetpack' ), $param ) );
1887
		}
1888
		$args = $attributes['args'][ $param ];
1889
		if ( ! empty( $args['enum'] ) ) {
1890
1891
			// If it's an associative array, use the keys to check that the value is among those admitted.
1892
			$enum = ( count( array_filter( array_keys( $args['enum'] ), 'is_string' ) ) > 0 ) ? array_keys( $args['enum'] ) : $args['enum'];
1893 View Code Duplication
			if ( ! in_array( $value, $enum ) ) {
1894
				return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be one of %s', 'jetpack' ), $param, implode( ', ', $enum ) ) );
1895
			}
1896
		}
1897
		return true;
1898
	}
1899
1900
	/**
1901
	 * Validates that the parameter belongs to a list of admitted values.
1902
	 *
1903
	 * @since 4.1.0
1904
	 *
1905
	 * @param string $value Value to check.
1906
	 * @param WP_REST_Request $request
1907
	 * @param string $param
1908
	 *
1909
	 * @return bool
1910
	 */
1911
	public static function validate_module_list( $value = '', $request, $param ) {
1912
		if ( ! is_array( $value ) ) {
1913
			return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be an array', 'jetpack' ), $param ) );
1914
		}
1915
1916
		$modules = Jetpack::get_available_modules();
1917
1918
		if ( count( array_intersect( $value, $modules ) ) != count( $value ) ) {
1919
			return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be a list of valid modules', 'jetpack' ), $param ) );
1920
		}
1921
1922
		return true;
1923
	}
1924
1925
	/**
1926
	 * Validates that the parameter is an alphanumeric or empty string (to be able to clear the field).
1927
	 *
1928
	 * @since 4.1.0
1929
	 *
1930
	 * @param string $value Value to check.
1931
	 * @param WP_REST_Request $request
1932
	 * @param string $param
1933
	 *
1934
	 * @return bool
1935
	 */
1936
	public static function validate_alphanum( $value = '', $request, $param ) {
1937 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/[a-z0-9]+/i', $value ) ) ) {
1938
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an alphanumeric string.', 'jetpack' ), $param ) );
1939
		}
1940
		return true;
1941
	}
1942
1943
	/**
1944
	 * Validates that the parameter is among the views where the Sharing can be displayed.
1945
	 *
1946
	 * @since 4.1.0
1947
	 *
1948
	 * @param string|bool $value Value to check.
1949
	 * @param WP_REST_Request $request
1950
	 * @param string $param
1951
	 *
1952
	 * @return bool
1953
	 */
1954
	public static function validate_sharing_show( $value, $request, $param ) {
1955
		$views = array( 'index', 'post', 'page', 'attachment', 'jetpack-portfolio' );
1956 View Code Duplication
		if ( ! array_intersect( $views, $value ) ) {
1957
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be %s.', 'jetpack' ), $param, join( ', ', $views ) ) );
1958
		}
1959
		return true;
1960
	}
1961
1962
	/**
1963
	 * Validates that the parameter is among the views where the Sharing can be displayed.
1964
	 *
1965
	 * @since 4.1.0
1966
	 *
1967
	 * @param string|bool $value Value to check.
1968
	 * @param WP_REST_Request $request
1969
	 * @param string $param
1970
	 *
1971
	 * @return bool
1972
	 */
1973
	public static function validate_services( $value, $request, $param ) {
1974 View Code Duplication
		if ( ! is_array( $value ) || ! isset( $value['visible'] ) || ! isset( $value['hidden'] ) ) {
1975
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array with visible and hidden items.', 'jetpack' ), $param ) );
1976
		}
1977
1978
		// Allow to clear everything.
1979
		if ( empty( $value['visible'] ) && empty( $value['hidden'] ) ) {
1980
			return true;
1981
		}
1982
1983 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharing/sharing-service.php' ) ) {
1984
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
1985
		}
1986
		$sharer = new Sharing_Service();
1987
		$services = array_keys( $sharer->get_all_services() );
1988
1989
		if (
1990
			( ! empty( $value['visible'] ) && ! array_intersect( $value['visible'], $services ) )
1991
			||
1992
			( ! empty( $value['hidden'] ) && ! array_intersect( $value['hidden'], $services ) ) )
1993
		{
1994
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s visible and hidden items must be a list of %s.', 'jetpack' ), $param, join( ', ', $services ) ) );
1995
		}
1996
		return true;
1997
	}
1998
1999
	/**
2000
	 * Validates that the parameter has enough information to build a custom sharing button.
2001
	 *
2002
	 * @since 4.1.0
2003
	 *
2004
	 * @param string|bool $value Value to check.
2005
	 * @param WP_REST_Request $request
2006
	 * @param string $param
2007
	 *
2008
	 * @return bool
2009
	 */
2010
	public static function validate_custom_service( $value, $request, $param ) {
2011 View Code Duplication
		if ( ! is_array( $value ) || ! isset( $value['sharing_name'] ) || ! isset( $value['sharing_url'] ) || ! isset( $value['sharing_icon'] ) ) {
2012
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array with sharing name, url and icon.', 'jetpack' ), $param ) );
2013
		}
2014
2015
		// Allow to clear everything.
2016
		if ( empty( $value['sharing_name'] ) && empty( $value['sharing_url'] ) && empty( $value['sharing_icon'] ) ) {
2017
			return true;
2018
		}
2019
2020 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharing/sharing-service.php' ) ) {
2021
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
2022
		}
2023
2024
		if ( ( ! empty( $value['sharing_name'] ) && ! is_string( $value['sharing_name'] ) )
2025
		|| ( ! empty( $value['sharing_url'] ) && ! is_string( $value['sharing_url'] ) )
2026
		|| ( ! empty( $value['sharing_icon'] ) && ! is_string( $value['sharing_icon'] ) ) ) {
2027
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s needs sharing name, url and icon.', 'jetpack' ), $param ) );
2028
		}
2029
		return true;
2030
	}
2031
2032
	/**
2033
	 * Validates that the parameter is a custom sharing service ID like 'custom-1461976264'.
2034
	 *
2035
	 * @since 4.1.0
2036
	 *
2037
	 * @param string $value Value to check.
2038
	 * @param WP_REST_Request $request
2039
	 * @param string $param
2040
	 *
2041
	 * @return bool
2042
	 */
2043
	public static function validate_custom_service_id( $value = '', $request, $param ) {
2044 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/custom\-[0-1]+/i', $value ) ) ) {
2045
			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 ) );
2046
		}
2047
2048 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharing/sharing-service.php' ) ) {
2049
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
2050
		}
2051
		$sharer = new Sharing_Service();
2052
		$services = array_keys( $sharer->get_all_services() );
2053
2054 View Code Duplication
		if ( ! empty( $value ) && ! in_array( $value, $services ) ) {
2055
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s is not a registered custom sharing service.', 'jetpack' ), $param ) );
2056
		}
2057
2058
		return true;
2059
	}
2060
2061
	/**
2062
	 * Validates that the parameter is a Twitter username or empty string (to be able to clear the field).
2063
	 *
2064
	 * @since 4.1.0
2065
	 *
2066
	 * @param string $value Value to check.
2067
	 * @param WP_REST_Request $request
2068
	 * @param string $param
2069
	 *
2070
	 * @return bool
2071
	 */
2072
	public static function validate_twitter_username( $value = '', $request, $param ) {
2073 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/^@?\w{1,15}$/i', $value ) ) ) {
2074
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a Twitter username.', 'jetpack' ), $param ) );
2075
		}
2076
		return true;
2077
	}
2078
2079
	/**
2080
	 * Validates that the parameter is a string.
2081
	 *
2082
	 * @since 4.1.0
2083
	 *
2084
	 * @param string $value Value to check.
2085
	 * @param WP_REST_Request $request
2086
	 * @param string $param
2087
	 *
2088
	 * @return bool
2089
	 */
2090
	public static function validate_string( $value = '', $request, $param ) {
2091
		if ( ! is_string( $value ) ) {
2092
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a string.', 'jetpack' ), $param ) );
2093
		}
2094
		return true;
2095
	}
2096
2097
	/**
2098
	 * Get the currently accessed route and return the module slug in it.
2099
	 *
2100
	 * @since 4.1.0
2101
	 *
2102
	 * @param string $route Regular expression for the endpoint with the module slug to return.
2103
	 *
2104
	 * @return array
2105
	 */
2106
	public static function get_module_requested( $route ) {
2107
2108
		if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
2109
			return '';
2110
		}
2111
2112
		preg_match( "#$route#", $GLOBALS['wp']->query_vars['rest_route'], $module );
2113
2114
		if ( empty( $module['slug'] ) ) {
2115
			return '';
2116
		}
2117
2118
		return $module['slug'];
2119
	}
2120
2121
	/**
2122
	 * Remove 'validate_callback' item from options available for module.
2123
	 * Fetch current option value and add to array of module options.
2124
	 * Prepare values of module options that need special handling, like those saved in wpcom.
2125
	 *
2126
	 * @since 4.1.0
2127
	 *
2128
	 * @param string $module Module slug.
2129
	 * @return array
2130
	 */
2131
	public static function prepare_options_for_response( $module = '' ) {
2132
		$options = self::get_module_available_options( $module, false );
2133
2134
		if ( ! is_array( $options ) || empty( $options ) ) {
2135
			return $options;
2136
		}
2137
2138
		foreach ( $options as $key => $value ) {
2139
2140
			if ( isset( $options[ $key ]['validate_callback'] ) ) {
2141
				unset( $options[ $key ]['validate_callback'] );
2142
			}
2143
2144
			$default_value = isset( $options[ $key ]['default'] ) ? $options[ $key ]['default'] : '';
2145
2146
			$current_value = get_option( $key, $default_value );
2147
2148
			$options[ $key ]['current_value'] = self::cast_value( $current_value, $options[ $key ] );
2149
		}
2150
2151
		// Some modules need special treatment.
2152
		switch ( $module ) {
2153
2154
			case 'monitor':
2155
				// Status of user notifications
2156
				$options['monitor_receive_notifications']['current_value'] = self::cast_value( self::get_remote_value( 'monitor', 'monitor_receive_notifications' ), $options['monitor_receive_notifications'] );
2157
				break;
2158
2159
			case 'post-by-email':
2160
				// Email address
2161
				$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'] );
2162
				break;
2163
2164
			case 'protect':
2165
				// Protect
2166
				$options['jetpack_protect_key']['current_value'] = get_site_option( 'jetpack_protect_key', false );
2167
				if ( ! function_exists( 'jetpack_protect_format_whitelist' ) ) {
2168
					@include( JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php' );
2169
				}
2170
				$options['jetpack_protect_global_whitelist']['current_value'] = jetpack_protect_format_whitelist();
2171
				break;
2172
2173
			case 'related-posts':
2174
				// It's local, but it must be broken apart since it's saved as an array.
2175
				$options = self::split_options( $options, Jetpack_Options::get_option( 'relatedposts' ) );
2176
				break;
2177
2178
			case 'verification-tools':
2179
				// It's local, but it must be broken apart since it's saved as an array.
2180
				$options = self::split_options( $options, get_option( 'verification_services_codes' ) );
2181
				break;
2182
2183
			case 'sharedaddy':
2184
				// It's local, but it must be broken apart since it's saved as an array.
2185
				if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharing/sharing-service.php' ) ) {
2186
					break;
2187
				}
2188
				$sharer = new Sharing_Service();
2189
				$options = self::split_options( $options, $sharer->get_global_options() );
2190
				$options['sharing_services']['current_value'] = $sharer->get_blog_services();
2191
				break;
2192
2193
			case 'site-icon':
2194
				// Return site icon ID and URL to make it more complete.
2195
				$options['site_icon_id']['current_value'] = Jetpack_Options::get_option( 'site_icon_id' );
2196
				if ( ! function_exists( 'jetpack_site_icon_url' ) ) {
2197
					@include( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
2198
				}
2199
				$options['site_icon_url']['current_value'] = jetpack_site_icon_url();
2200
				break;
2201
2202
			case 'after-the-deadline':
2203
				if ( ! function_exists( 'AtD_get_options' ) ) {
2204
					@include( JETPACK__PLUGIN_DIR . 'modules/after-the-deadline.php' );
2205
				}
2206
				$atd_options = array_merge( AtD_get_options( get_current_user_id(), 'AtD_options' ), AtD_get_options( get_current_user_id(), 'AtD_check_when' ) );
2207
				unset( $atd_options['name'] );
2208
				foreach ( $atd_options as $key => $value ) {
2209
					$options[ $key ]['current_value'] = self::cast_value( $value, $options[ $key ] );
2210
				}
2211
				$atd_options = AtD_get_options( get_current_user_id(), 'AtD_guess_lang' );
2212
				$options['guess_lang']['current_value'] = self::cast_value( isset( $atd_options['true'] ), $options[ 'guess_lang' ] );
2213
				$options['ignored_phrases']['current_value'] = AtD_get_setting( get_current_user_id(), 'AtD_ignored_phrases' );
2214
				unset( $options['unignore_phrase'] );
2215
				break;
2216
		}
2217
2218
		return $options;
2219
	}
2220
2221
	/**
2222
	 * Splits module options saved as arrays like relatedposts or verification_services_codes into separate options to be returned in the response.
2223
	 *
2224
	 * @since 4.1.0
2225
	 *
2226
	 * @param array  $separate_options Array of options admitted by the module.
2227
	 * @param array  $grouped_options Option saved as array to be splitted.
2228
	 * @param string $prefix Optional prefix for the separate option keys.
2229
	 *
2230
	 * @return array
2231
	 */
2232
	public static function split_options( $separate_options, $grouped_options, $prefix = '' ) {
2233
		if ( is_array( $grouped_options ) ) {
2234
			foreach ( $grouped_options as $key => $value ) {
2235
				$option_key = $prefix . $key;
2236
				if ( isset( $separate_options[ $option_key ] ) ) {
2237
					$separate_options[ $option_key ]['current_value'] = self::cast_value( $grouped_options[ $key ], $separate_options[ $option_key ] );
2238
				}
2239
			}
2240
		}
2241
		return $separate_options;
2242
	}
2243
2244
	/**
2245
	 * Perform a casting to the value specified in the option definition.
2246
	 *
2247
	 * @since 4.1.0
2248
	 *
2249
	 * @param mixed $value Value to cast to the proper type.
2250
	 * @param array $definition Type to cast the value to.
2251
	 *
2252
	 * @return bool|float|int|string
2253
	 */
2254
	public static function cast_value( $value, $definition ) {
2255
		if ( isset( $definition['type'] ) ) {
2256
			switch ( $definition['type'] ) {
2257
				case 'boolean':
2258
					if ( 'true' === $value ) {
2259
						return true;
2260
					} elseif ( 'false' === $value ) {
2261
						return false;
2262
					}
2263
					return (bool) $value;
2264
					break;
2265
2266
				case 'integer':
2267
					return (int) $value;
2268
					break;
2269
2270
				case 'float':
2271
					return (float) $value;
2272
					break;
2273
			}
2274
		}
2275
		return $value;
2276
	}
2277
2278
	/**
2279
	 * Get a value not saved locally.
2280
	 *
2281
	 * @since 4.1.0
2282
	 *
2283
	 * @param string $module Module slug.
2284
	 * @param string $option Option name.
2285
	 *
2286
	 * @return bool Whether user is receiving notifications or not.
2287
	 */
2288
	public static function get_remote_value( $module, $option ) {
2289
2290
		// If option doesn't exist, 'does_not_exist' will be returned.
2291
		$value = get_option( $option, 'does_not_exist' );
2292
2293
		// If option exists, just return it.
2294
		if ( 'does_not_exist' !== $value ) {
2295
			return $value;
2296
		}
2297
2298
		// Only check a remote option if Jetpack is connected.
2299
		if ( ! Jetpack::is_active() ) {
2300
			return false;
2301
		}
2302
2303
		// If the module is inactive, load the class to use the method.
2304
		if ( ! did_action( 'jetpack_module_loaded_' . $module ) ) {
2305
			// Class can't be found so do nothing.
2306
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
2307
				return false;
2308
			}
2309
		}
2310
2311
		// Do what is necessary for each module.
2312
		switch ( $module ) {
2313
			case 'monitor':
2314
				$monitor = new Jetpack_Monitor();
2315
				$value = $monitor->user_receives_notifications( false );
2316
				break;
2317
2318
			case 'post-by-email':
2319
				$post_by_email = new Jetpack_Post_By_Email();
2320
				$value = $post_by_email->get_post_by_email_address();
2321
				break;
2322
		}
2323
2324
		// Normalize value to boolean.
2325
		if ( is_wp_error( $value ) || is_null( $value ) ) {
2326
			$value = false;
2327
		}
2328
2329
		// Save option to use it next time.
2330
		update_option( $option, $value );
2331
2332
		return $value;
2333
	}
2334
2335
	/**
2336
	 * Get number of blocked intrusion attempts.
2337
	 *
2338
	 * @since 4.1.0
2339
	 *
2340
	 * @return mixed|WP_Error Number of blocked attempts if protection is enabled. Otherwise, a WP_Error instance with the corresponding error.
2341
	 */
2342
	public static function protect_get_blocked_count() {
2343
		if ( Jetpack::is_module_active( 'protect' ) ) {
2344
			return get_site_option( 'jetpack_protect_blocked_attempts' );
2345
		}
2346
2347
		return new WP_Error( 'not_active', esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ), array( 'status' => 404 ) );
2348
	}
2349
2350
	/**
2351
	 * Get number of spam messages blocked by Akismet.
2352
	 *
2353
	 * @since 4.1.0
2354
	 *
2355
	 * @param WP_REST_Request $data {
2356
	 *     Array of parameters received by request.
2357
	 *
2358
	 *     @type string $date Date range to restrict results to.
2359
	 * }
2360
	 *
2361
	 * @return int|string Number of spam blocked by Akismet. Otherwise, an error message.
2362
	 */
2363
	public static function akismet_get_stats_data( WP_REST_Request $data ) {
2364
		if ( ! is_wp_error( $status = self::akismet_is_active_and_registered() ) ) {
2365
			return rest_ensure_response( Akismet_Admin::get_stats( Akismet::get_api_key() ) );
2366
		} else {
2367
			return $status->get_error_code();
2368
		}
2369
	}
2370
2371
	/**
2372
	 * Get date of last downtime.
2373
	 *
2374
	 * @since 4.1.0
2375
	 *
2376
	 * @return mixed|WP_Error Number of days since last downtime. Otherwise, a WP_Error instance with the corresponding error.
2377
	 */
2378
	public static function monitor_get_last_downtime() {
2379
		if ( Jetpack::is_module_active( 'monitor' ) ) {
2380
			$monitor       = new Jetpack_Monitor();
2381
			$last_downtime = $monitor->monitor_get_last_downtime();
2382
			if ( is_wp_error( $last_downtime ) ) {
2383
				return $last_downtime;
2384
			} else {
2385
				return rest_ensure_response( array(
2386
					'code' => 'success',
2387
					'date' => human_time_diff( strtotime( $last_downtime ), strtotime( 'now' ) ),
2388
				) );
2389
			}
2390
		}
2391
2392
		return new WP_Error( 'not_active', esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ), array( 'status' => 404 ) );
2393
	}
2394
2395
	/**
2396
	 * Get number of plugin updates available.
2397
	 *
2398
	 * @since 4.1.0
2399
	 *
2400
	 * @return mixed|WP_Error Number of plugin updates available. Otherwise, a WP_Error instance with the corresponding error.
2401
	 */
2402
	public static function get_plugin_update_count() {
2403
		$updates = wp_get_update_data();
2404
		if ( isset( $updates['counts'] ) && isset( $updates['counts']['plugins'] ) ) {
2405
			$count = $updates['counts']['plugins'];
2406
			if ( 0 == $count ) {
2407
				$response = array(
2408
					'code'    => 'success',
2409
					'message' => esc_html__( 'All plugins are up-to-date. Keep up the good work!', 'jetpack' ),
2410
					'count'   => 0,
2411
				);
2412
			} else {
2413
				$response = array(
2414
					'code'    => 'updates-available',
2415
					'message' => esc_html( sprintf( _n( '%s plugin need updating.', '%s plugins need updating.', $count, 'jetpack' ), $count ) ),
2416
					'count'   => $count,
2417
				);
2418
			}
2419
			return rest_ensure_response( $response );
2420
		}
2421
2422
		return new WP_Error( 'not_found', esc_html__( 'Could not check updates for plugins on this site.', 'jetpack' ), array( 'status' => 404 ) );
2423
	}
2424
2425
	/**
2426
	 * Get services that this site is verified with.
2427
	 *
2428
	 * @since 4.1.0
2429
	 *
2430
	 * @return mixed|WP_Error List of services that verified this site. Otherwise, a WP_Error instance with the corresponding error.
2431
	 */
2432
	public static function get_verified_services() {
2433
		if ( Jetpack::is_module_active( 'verification-tools' ) ) {
2434
			$verification_services_codes = get_option( 'verification_services_codes' );
2435
			if ( is_array( $verification_services_codes ) && ! empty( $verification_services_codes ) ) {
2436
				$services = array();
2437
				foreach ( jetpack_verification_services() as $name => $service ) {
2438
					if ( is_array( $service ) && ! empty( $verification_services_codes[ $name ] ) ) {
2439
						switch ( $name ) {
2440
							case 'google':
2441
								$services[] = 'Google';
2442
								break;
2443
							case 'bing':
2444
								$services[] = 'Bing';
2445
								break;
2446
							case 'pinterest':
2447
								$services[] = 'Pinterest';
2448
								break;
2449
						}
2450
					}
2451
				}
2452
				if ( ! empty( $services ) ) {
2453
					if ( 2 > count( $services ) ) {
2454
						$message = esc_html( sprintf( __( 'Your site is verified with %s.', 'jetpack' ), $services[0] ) );
2455
					} else {
2456
						$copy_services = $services;
2457
						$last = count( $copy_services ) - 1;
2458
						$last_service = $copy_services[ $last ];
2459
						unset( $copy_services[ $last ] );
2460
						$message = esc_html( sprintf( __( 'Your site is verified with %s and %s.', 'jetpack' ), join( ', ', $copy_services ), $last_service ) );
2461
					}
2462
					return rest_ensure_response( array(
2463
						'code'     => 'success',
2464
						'message'  => $message,
2465
						'services' => $services,
2466
					) );
2467
				}
2468
			}
2469
			return new WP_Error( 'empty', esc_html__( 'Site not verified with any service.', 'jetpack' ), array( 'status' => 404 ) );
2470
		}
2471
2472
		return new WP_Error( 'not_active', esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ), array( 'status' => 404 ) );
2473
	}
2474
2475
	/**
2476
	 * Get VaultPress site data including, among other things, the date of tge last backup if it was completed.
2477
	 *
2478
	 * @since 4.1.0
2479
	 *
2480
	 * @return mixed|WP_Error VaultPress site data. Otherwise, a WP_Error instance with the corresponding error.
2481
	 */
2482
	public static function vaultpress_get_site_data() {
2483
		if ( class_exists( 'VaultPress' ) ) {
2484
			$vaultpress = new VaultPress();
2485
			if ( ! $vaultpress->is_registered() ) {
2486
				return rest_ensure_response( array(
2487
					'code'    => 'not_registered',
2488
					'message' => esc_html( __( 'You need to register for VaultPress.', 'jetpack' ) )
2489
				) );
2490
			}
2491
			$data = json_decode( base64_decode( $vaultpress->contact_service( 'plugin_data' ) ) );
2492
			if ( is_wp_error( $data ) ) {
2493
				return $data;
2494
			} else {
2495
				return rest_ensure_response( array(
2496
					'code'    => 'success',
2497
					'message' => esc_html( sprintf( __( 'Your site was successfully backed-up %s ago.', 'jetpack' ), human_time_diff( $data->backups->last_backup, current_time( 'timestamp' ) ) ) ),
2498
					'data'    => $data,
2499
				) );
2500
			}
2501
		}
2502
2503
		return new WP_Error( 'not_active', esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ), array( 'status' => 404 ) );
2504
	}
2505
2506
	/**
2507
	 * Returns a list of all plugins in the site.
2508
	 *
2509
	 * @since 4.2.0
2510
	 * @uses get_plugins()
2511
	 *
2512
	 * @return array
2513
	 */
2514
	private static function core_get_plugins() {
2515
		if ( ! function_exists( 'get_plugins' ) ) {
2516
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2517
		}
2518
2519
		$plugins = get_plugins();
2520
2521
		if ( is_array( $plugins ) && ! empty( $plugins ) ) {
2522
			foreach ( $plugins as $plugin_slug => $plugin_data ) {
2523
				$plugins[ $plugin_slug ]['active'] = self::core_is_plugin_active( $plugin_slug );
2524
			}
2525
			return $plugins;
2526
		}
2527
2528
		return array();
2529
	}
2530
2531
	/**
2532
	 * Checks if the queried plugin is active.
2533
	 *
2534
	 * @since 4.2.0
2535
	 * @uses is_plugin_active()
2536
	 *
2537
	 * @return bool
2538
	 */
2539
	private static function core_is_plugin_active( $plugin ) {
2540
		if ( ! function_exists( 'get_plugins' ) ) {
2541
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2542
		}
2543
2544
		return is_plugin_active( $plugin );
2545
	}
2546
2547
	/**
2548
	 * Get plugins data in site.
2549
	 *
2550
	 * @since 4.2.0
2551
	 *
2552
	 * @return WP_REST_Response|WP_Error List of plugins in the site. Otherwise, a WP_Error instance with the corresponding error.
2553
	 */
2554
	public static function get_plugins() {
2555
		$plugins = self::core_get_plugins();
2556
2557
		if ( ! empty( $plugins ) ) {
2558
			return rest_ensure_response( $plugins );
2559
		}
2560
2561
		return new WP_Error( 'not_found', esc_html__( 'Unable to list plugins.', 'jetpack' ), array( 'status' => 404 ) );
2562
	}
2563
2564
	/**
2565
	 * Get data about the queried plugin. Currently it only returns whether the plugin is active or not.
2566
	 *
2567
	 * @since 4.2.0
2568
	 *
2569
	 * @param WP_REST_Request $data {
2570
	 *     Array of parameters received by request.
2571
	 *
2572
	 *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
2573
	 * }
2574
	 *
2575
	 * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
2576
	 */
2577
	public static function get_plugin( $data ) {
2578
2579
		$plugins = self::core_get_plugins();
2580
2581
		if ( empty( $plugins ) ) {
2582
			return new WP_Error( 'no_plugins_found', esc_html__( 'This site has no plugins.', 'jetpack' ), array( 'status' => 404 ) );
2583
		}
2584
2585
		$plugin = stripslashes( $data['plugin'] );
2586
2587 View Code Duplication
		if ( ! in_array( $plugin, array_keys( $plugins ) ) ) {
2588
			return new WP_Error( 'plugin_not_found', esc_html( sprintf( __( 'Plugin %s is not installed.', 'jetpack' ), $plugin ) ), array( 'status' => 404 ) );
2589
		}
2590
2591
		$plugin_data = $plugins[ $plugin ];
2592
2593
		$plugin_data['active'] = self::core_is_plugin_active( $plugin );
2594
2595
		return rest_ensure_response( array(
2596
			'code'    => 'success',
2597
			'message' => esc_html__( 'Plugin found.', 'jetpack' ),
2598
			'data'    => $plugin_data
2599
		) );
2600
	}
2601
2602
} // class end
2603