Completed
Push — fix/normalize-www-in-site-url-... ( e67e76 )
by
unknown
13:13 queued 02:59
created

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

Upgrade to new PHP Analysis Engine

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

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