Completed
Push — fix/inline-docs-410 ( f96891...63b75c )
by
unknown
43:24 queued 33:40
created

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

Upgrade to new PHP Analysis Engine

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

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

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

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

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

Loading history...
837
838
				case 'modules':
839
					$default_modules = Jetpack::get_default_modules();
840
					Jetpack_Options::update_option( 'active_modules', $default_modules );
841
842
					return rest_ensure_response( array(
843
						'code' 	  => 'success',
844
						'message' => esc_html__( 'Modules reset to default.', 'jetpack' ),
845
					) );
846
					break;
0 ignored issues
show
break is not strictly necessary here and could be removed.

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

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

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

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

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

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

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

Loading history...
2259
			}
2260
		}
2261
		return $value;
2262
	}
2263
2264
	/**
2265
	 * Get a value not saved locally.
2266
	 *
2267
	 * @since 4.1.0
2268
	 *
2269
	 * @param string $module Module slug.
2270
	 * @param string $option Option name.
2271
	 *
2272
	 * @return bool Whether user is receiving notifications or not.
2273
	 */
2274
	public static function get_remote_value( $module, $option ) {
2275
2276
		// If option doesn't exist, 'does_not_exist' will be returned.
2277
		$value = get_option( $option, 'does_not_exist' );
2278
2279
		// If option exists, just return it.
2280
		if ( 'does_not_exist' !== $value ) {
2281
			return $value;
2282
		}
2283
2284
		// Only check a remote option if Jetpack is connected.
2285
		if ( ! Jetpack::is_active() ) {
2286
			return false;
2287
		}
2288
2289
		// If the module is inactive, load the class to use the method.
2290
		if ( ! did_action( 'jetpack_module_loaded_' . $module ) ) {
2291
			// Class can't be found so do nothing.
2292
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
2293
				return false;
2294
			}
2295
		}
2296
2297
		// Do what is necessary for each module.
2298
		switch ( $module ) {
2299
			case 'monitor':
2300
				$monitor = new Jetpack_Monitor();
2301
				$value = $monitor->user_receives_notifications( false );
2302
				break;
2303
2304
			case 'post-by-email':
2305
				$post_by_email = new Jetpack_Post_By_Email();
2306
				$value = $post_by_email->get_post_by_email_address();
2307
				break;
2308
		}
2309
2310
		// Normalize value to boolean.
2311
		if ( is_wp_error( $value ) || is_null( $value ) ) {
2312
			$value = false;
2313
		}
2314
2315
		// Save option to use it next time.
2316
		update_option( $option, $value );
2317
2318
		return $value;
2319
	}
2320
2321
	/**
2322
	 * Get number of blocked intrusion attempts.
2323
	 *
2324
	 * @since 4.1.0
2325
	 *
2326
	 * @return mixed|WP_Error Number of blocked attempts if protection is enabled. Otherwise, a WP_Error instance with the corresponding error.
2327
	 */
2328
	public static function protect_get_blocked_count() {
2329
		if ( Jetpack::is_module_active( 'protect' ) ) {
2330
			return get_site_option( 'jetpack_protect_blocked_attempts' );
2331
		}
2332
2333
		return new WP_Error( 'not_active', esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ), array( 'status' => 404 ) );
2334
	}
2335
2336
	/**
2337
	 * Get number of spam messages blocked by Akismet.
2338
	 *
2339
	 * @since 4.1.0
2340
	 *
2341
	 * @param WP_REST_Request $data {
2342
	 *     Array of parameters received by request.
2343
	 *
2344
	 *     @type string $date Date range to restrict results to.
2345
	 * }
2346
	 *
2347
	 * @return int|string Number of spam blocked by Akismet. Otherwise, an error message.
2348
	 */
2349
	public static function akismet_get_stats_data( WP_REST_Request $data ) {
2350
		if ( ! is_wp_error( $status = self::akismet_is_active_and_registered() ) ) {
2351
			return rest_ensure_response( Akismet_Admin::get_stats( Akismet::get_api_key() ) );
2352
		} else {
2353
			return $status->get_error_code();
2354
		}
2355
	}
2356
2357
	/**
2358
	 * Get date of last downtime.
2359
	 *
2360
	 * @since 4.1.0
2361
	 *
2362
	 * @return mixed|WP_Error Number of days since last downtime. Otherwise, a WP_Error instance with the corresponding error.
2363
	 */
2364
	public static function monitor_get_last_downtime() {
2365
		if ( Jetpack::is_module_active( 'monitor' ) ) {
2366
			$monitor       = new Jetpack_Monitor();
2367
			$last_downtime = $monitor->monitor_get_last_downtime();
2368
			if ( is_wp_error( $last_downtime ) ) {
2369
				return $last_downtime;
2370
			} else {
2371
				return rest_ensure_response( array(
2372
					'code' => 'success',
2373
					'date' => human_time_diff( strtotime( $last_downtime ), strtotime( 'now' ) ),
2374
				) );
2375
			}
2376
		}
2377
2378
		return new WP_Error( 'not_active', esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ), array( 'status' => 404 ) );
2379
	}
2380
2381
	/**
2382
	 * Get number of plugin updates available.
2383
	 *
2384
	 * @since 4.1.0
2385
	 *
2386
	 * @return mixed|WP_Error Number of plugin updates available. Otherwise, a WP_Error instance with the corresponding error.
2387
	 */
2388
	public static function get_plugin_update_count() {
2389
		$updates = wp_get_update_data();
2390
		if ( isset( $updates['counts'] ) && isset( $updates['counts']['plugins'] ) ) {
2391
			$count = $updates['counts']['plugins'];
2392
			if ( 0 == $count ) {
2393
				$response = array(
2394
					'code'    => 'success',
2395
					'message' => esc_html__( 'All plugins are up-to-date. Keep up the good work!', 'jetpack' ),
2396
					'count'   => 0,
2397
				);
2398
			} else {
2399
				$response = array(
2400
					'code'    => 'updates-available',
2401
					'message' => esc_html( sprintf( _n( '%s plugin need updating.', '%s plugins need updating.', $count, 'jetpack' ), $count ) ),
2402
					'count'   => $count,
2403
				);
2404
			}
2405
			return rest_ensure_response( $response );
2406
		}
2407
2408
		return new WP_Error( 'not_found', esc_html__( 'Could not check updates for plugins on this site.', 'jetpack' ), array( 'status' => 404 ) );
2409
	}
2410
2411
	/**
2412
	 * Get services that this site is verified with.
2413
	 *
2414
	 * @since 4.1.0
2415
	 *
2416
	 * @return mixed|WP_Error List of services that verified this site. Otherwise, a WP_Error instance with the corresponding error.
2417
	 */
2418
	public static function get_verified_services() {
2419
		if ( Jetpack::is_module_active( 'verification-tools' ) ) {
2420
			$verification_services_codes = get_option( 'verification_services_codes' );
2421
			if ( is_array( $verification_services_codes ) && ! empty( $verification_services_codes ) ) {
2422
				$services = array();
2423
				foreach ( jetpack_verification_services() as $name => $service ) {
2424
					if ( is_array( $service ) && ! empty( $verification_services_codes[ $name ] ) ) {
2425
						switch ( $name ) {
2426
							case 'google':
2427
								$services[] = 'Google';
2428
								break;
2429
							case 'bing':
2430
								$services[] = 'Bing';
2431
								break;
2432
							case 'pinterest':
2433
								$services[] = 'Pinterest';
2434
								break;
2435
						}
2436
					}
2437
				}
2438
				if ( ! empty( $services ) ) {
2439
					if ( 2 > count( $services ) ) {
2440
						$message = esc_html( sprintf( __( 'Your site is verified with %s.', 'jetpack' ), $services[0] ) );
2441
					} else {
2442
						$copy_services = $services;
2443
						$last = count( $copy_services ) - 1;
2444
						$last_service = $copy_services[ $last ];
2445
						unset( $copy_services[ $last ] );
2446
						$message = esc_html( sprintf( __( 'Your site is verified with %s and %s.', 'jetpack' ), join( ', ', $copy_services ), $last_service ) );
2447
					}
2448
					return rest_ensure_response( array(
2449
						'code'     => 'success',
2450
						'message'  => $message,
2451
						'services' => $services,
2452
					) );
2453
				}
2454
			}
2455
			return new WP_Error( 'empty', esc_html__( 'Site not verified with any service.', 'jetpack' ), array( 'status' => 404 ) );
2456
		}
2457
2458
		return new WP_Error( 'not_active', esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ), array( 'status' => 404 ) );
2459
	}
2460
2461
	/**
2462
	 * Get VaultPress site data including, among other things, the date of tge last backup if it was completed.
2463
	 *
2464
	 * @since 4.1.0
2465
	 *
2466
	 * @return mixed|WP_Error VaultPress site data. Otherwise, a WP_Error instance with the corresponding error.
2467
	 */
2468
	public static function vaultpress_get_site_data() {
2469
		if ( class_exists( 'VaultPress' ) ) {
2470
			$vaultpress = new VaultPress();
2471
			if ( ! $vaultpress->is_registered() ) {
2472
				return rest_ensure_response( array(
2473
					'code'    => 'not_registered',
2474
					'message' => esc_html( __( 'You need to register for VaultPress.', 'jetpack' ) )
2475
				) );
2476
			}
2477
			$data = json_decode( base64_decode( $vaultpress->contact_service( 'plugin_data' ) ) );
2478
			if ( is_wp_error( $data ) ) {
2479
				return $data;
2480
			} else {
2481
				return rest_ensure_response( array(
2482
					'code'    => 'success',
2483
					'message' => esc_html( sprintf( __( 'Your site was successfully backed-up %s ago.', 'jetpack' ), human_time_diff( $data->backups->last_backup, current_time( 'timestamp' ) ) ) ),
2484
					'data'    => $data,
2485
				) );
2486
			}
2487
		}
2488
2489
		return new WP_Error( 'not_active', esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ), array( 'status' => 404 ) );
2490
	}
2491
2492
	/**
2493
	 * Returns a list of all plugins in the site.
2494
	 *
2495
	 * @since 4.2.0
2496
	 * @uses get_plugins()
2497
	 *
2498
	 * @return array
2499
	 */
2500
	private static function core_get_plugins() {
2501
		if ( ! function_exists( 'get_plugins' ) ) {
2502
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2503
		}
2504
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2505
		$plugins = apply_filters( 'all_plugins', get_plugins() );
2506
2507
		if ( is_array( $plugins ) && ! empty( $plugins ) ) {
2508
			foreach ( $plugins as $plugin_slug => $plugin_data ) {
2509
				$plugins[ $plugin_slug ]['active'] = self::core_is_plugin_active( $plugin_slug );
2510
			}
2511
			return $plugins;
2512
		}
2513
2514
		return array();
2515
	}
2516
2517
	/**
2518
	 * Checks if the queried plugin is active.
2519
	 *
2520
	 * @since 4.2.0
2521
	 * @uses is_plugin_active()
2522
	 *
2523
	 * @return bool
2524
	 */
2525
	private static function core_is_plugin_active( $plugin ) {
2526
		if ( ! function_exists( 'get_plugins' ) ) {
2527
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2528
		}
2529
2530
		return is_plugin_active( $plugin );
2531
	}
2532
2533
	/**
2534
	 * Get plugins data in site.
2535
	 *
2536
	 * @since 4.2.0
2537
	 *
2538
	 * @return WP_REST_Response|WP_Error List of plugins in the site. Otherwise, a WP_Error instance with the corresponding error.
2539
	 */
2540
	public static function get_plugins() {
2541
		$plugins = self::core_get_plugins();
2542
2543
		if ( ! empty( $plugins ) ) {
2544
			return rest_ensure_response( $plugins );
2545
		}
2546
2547
		return new WP_Error( 'not_found', esc_html__( 'Unable to list plugins.', 'jetpack' ), array( 'status' => 404 ) );
2548
	}
2549
2550
	/**
2551
	 * Get data about the queried plugin. Currently it only returns whether the plugin is active or not.
2552
	 *
2553
	 * @since 4.2.0
2554
	 *
2555
	 * @param WP_REST_Request $data {
2556
	 *     Array of parameters received by request.
2557
	 *
2558
	 *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
2559
	 * }
2560
	 *
2561
	 * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
2562
	 */
2563
	public static function get_plugin( $data ) {
2564
2565
		$plugins = self::core_get_plugins();
2566
2567
		if ( empty( $plugins ) ) {
2568
			return new WP_Error( 'no_plugins_found', esc_html__( 'This site has no plugins.', 'jetpack' ), array( 'status' => 404 ) );
2569
		}
2570
2571
		$plugin = stripslashes( $data['plugin'] );
2572
2573 View Code Duplication
		if ( ! in_array( $plugin, array_keys( $plugins ) ) ) {
2574
			return new WP_Error( 'plugin_not_found', esc_html( sprintf( __( 'Plugin %s is not installed.', 'jetpack' ), $plugin ) ), array( 'status' => 404 ) );
2575
		}
2576
2577
		$plugin_data = $plugins[ $plugin ];
2578
2579
		$plugin_data['active'] = self::core_is_plugin_active( $plugin );
2580
2581
		return rest_ensure_response( array(
2582
			'code'    => 'success',
2583
			'message' => esc_html__( 'Plugin found.', 'jetpack' ),
2584
			'data'    => $plugin_data
2585
		) );
2586
	}
2587
2588
} // class end
2589