Completed
Push — feature/videopress-uploader ( 58b703...e9e1f9 )
by
unknown
104:20 queued 95:05
created

_inc/lib/class.core-rest-api-endpoints.php (7 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
		register_rest_route( 'jetpack/v4', '/recheck-ssl', array(
85
			'methods' => WP_REST_Server::EDITABLE,
86
			'callback' => __CLASS__ . '::recheck_ssl',
87
		) );
88
89
		// Get current site data
90
		register_rest_route( 'jetpack/v4', '/site', array(
91
			'methods' => WP_REST_Server::READABLE,
92
			'callback' => __CLASS__ . '::get_site_data',
93
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
94
		) );
95
96
		// Return all modules
97
		register_rest_route( 'jetpack/v4', '/modules', array(
98
			'methods' => WP_REST_Server::READABLE,
99
			'callback' => __CLASS__ . '::get_modules',
100
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
101
		) );
102
103
		// Return a single module
104
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)', array(
105
			'methods' => WP_REST_Server::READABLE,
106
			'callback' => __CLASS__ . '::get_module',
107
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
108
		) );
109
110
		// Activate a module
111
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)/activate', array(
112
			'methods' => WP_REST_Server::EDITABLE,
113
			'callback' => __CLASS__ . '::activate_module',
114
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
115
		) );
116
117
		// Deactivate a module
118
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)/deactivate', array(
119
			'methods' => WP_REST_Server::EDITABLE,
120
			'callback' => __CLASS__ . '::deactivate_module',
121
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
122
		) );
123
124
		// Update a module
125
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)/update', array(
126
			'methods' => WP_REST_Server::EDITABLE,
127
			'callback' => __CLASS__ . '::update_module',
128
			'permission_callback' => __CLASS__ . '::configure_modules_permission_check',
129
			'args' => self::get_module_updating_parameters(),
130
		) );
131
132
		// Activate many modules
133
		register_rest_route( 'jetpack/v4', '/modules/activate', array(
134
			'methods' => WP_REST_Server::EDITABLE,
135
			'callback' => __CLASS__ . '::activate_modules',
136
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
137
			'args' => array(
138
				'modules' => array(
139
					'default'           => '',
140
					'type'              => 'array',
141
					'required'          => true,
142
					'validate_callback' => __CLASS__ . '::validate_module_list',
143
				),
144
			),
145
		) );
146
147
		// Reset all Jetpack options
148
		register_rest_route( 'jetpack/v4', '/reset/(?P<options>[a-z\-]+)', array(
149
			'methods' => WP_REST_Server::EDITABLE,
150
			'callback' => __CLASS__ . '::reset_jetpack_options',
151
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
152
		) );
153
154
		// Return miscellaneous settings
155
		register_rest_route( 'jetpack/v4', '/settings', array(
156
			'methods' => WP_REST_Server::READABLE,
157
			'callback' => __CLASS__ . '::get_settings',
158
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
159
		) );
160
161
		// Update miscellaneous setting
162
		register_rest_route( 'jetpack/v4', '/setting/update', array(
163
			'methods' => WP_REST_Server::EDITABLE,
164
			'callback' => __CLASS__ . '::update_setting',
165
			'permission_callback' => __CLASS__ . '::update_settings',
166
		) );
167
168
		// Jumpstart
169
		register_rest_route( 'jetpack/v4', '/jumpstart/activate', array(
170
			'methods' => WP_REST_Server::EDITABLE,
171
			'callback' => __CLASS__ . '::jumpstart_activate',
172
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
173
		) );
174
175
		register_rest_route( 'jetpack/v4', '/jumpstart/deactivate', array(
176
			'methods' => WP_REST_Server::EDITABLE,
177
			'callback' => __CLASS__ . '::jumpstart_deactivate',
178
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
179
		) );
180
181
		// Protect: get blocked count
182
		register_rest_route( 'jetpack/v4', '/module/protect/count/get', array(
183
			'methods' => WP_REST_Server::READABLE,
184
			'callback' => __CLASS__ . '::protect_get_blocked_count',
185
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
186
		) );
187
188
		// Akismet: get spam count
189
		register_rest_route( 'jetpack/v4', '/akismet/stats/get', array(
190
			'methods'  => WP_REST_Server::READABLE,
191
			'callback' => __CLASS__ . '::akismet_get_stats_data',
192
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
193
		) );
194
195
		// Monitor: get last downtime
196
		register_rest_route( 'jetpack/v4', '/module/monitor/downtime/last', array(
197
			'methods' => WP_REST_Server::READABLE,
198
			'callback' => __CLASS__ . '::monitor_get_last_downtime',
199
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
200
		) );
201
202
		// Updates: get number of plugin updates available
203
		register_rest_route( 'jetpack/v4', '/updates/plugins', array(
204
			'methods' => WP_REST_Server::READABLE,
205
			'callback' => __CLASS__ . '::get_plugin_update_count',
206
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
207
		) );
208
209
		// Verification: get services that this site is verified with
210
		register_rest_route( 'jetpack/v4', '/module/verification-tools/services', array(
211
			'methods' => WP_REST_Server::READABLE,
212
			'callback' => __CLASS__ . '::get_verified_services',
213
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
214
		) );
215
216
		// VaultPress: get date last backup or status and actions for user to take
217
		register_rest_route( 'jetpack/v4', '/module/vaultpress/data', array(
218
			'methods' => WP_REST_Server::READABLE,
219
			'callback' => __CLASS__ . '::vaultpress_get_site_data',
220
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
221
		) );
222
223
		// Dismiss Jetpack Notices
224
		register_rest_route( 'jetpack/v4', '/dismiss-jetpack-notice/(?P<notice>[a-z\-_]+)', array(
225
			'methods' => WP_REST_Server::EDITABLE,
226
			'callback' => __CLASS__ . '::dismiss_jetpack_notice',
227
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
228
		) );
229
	}
230
231
	/**
232
	 * Handles dismissing of Jetpack Notices
233
	 *
234
	 * @since 4.1.0
235
	 *
236
	 * @return array|wp-error
0 ignored issues
show
The doc-type array|wp-error could not be parsed: Unknown type name "wp-error" at position 6. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
237
	 */
238
	public static function dismiss_jetpack_notice( $data ) {
239
		$notice = $data['notice'];
240
		if ( isset( $notice ) && ! empty( $notice ) ) {
241
			switch( $notice ) {
242
				case 'feedback_dash_request':
243
				case 'welcome':
244
					$notices = get_option( 'jetpack_dismissed_notices', array() );
245
					$notices[ $notice ] = true;
246
					update_option( 'jetpack_dismissed_notices', $notices );
247
					return rest_ensure_response( get_option( 'jetpack_dismissed_notices', array() ) );
248
249
				default:
250
					return new WP_Error( 'invalid_param', esc_html__( 'Invalid parameter "notice".', 'jetpack' ), array( 'status' => 404 ) );
251
			}
252
		}
253
254
		return new WP_Error( 'required_param', esc_html__( 'Missing parameter "notice".', 'jetpack' ), array( 'status' => 404 ) );
255
	}
256
257
	/**
258
	 * Verify that the user can disconnect the site.
259
	 *
260
	 * @since 4.1.0
261
	 *
262
	 * @return bool|WP_Error True if user is able to disconnect the site.
263
	 */
264
	public static function disconnect_site_permission_callback() {
265
		if ( current_user_can( 'jetpack_disconnect' ) ) {
266
			return true;
267
		}
268
269
		return new WP_Error( 'invalid_user_permission_jetpack_disconnect', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
270
271
	}
272
273
	/**
274
	 * Verify that the user can get a connect/link URL
275
	 *
276
	 * @since 4.1.0
277
	 *
278
	 * @return bool|WP_Error True if user is able to disconnect the site.
279
	 */
280 View Code Duplication
	public static function connect_url_permission_callback() {
281
		if ( current_user_can( 'jetpack_connect_user' ) ) {
282
			return true;
283
		}
284
285
		return new WP_Error( 'invalid_user_permission_jetpack_disconnect', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
286
287
	}
288
289
	/**
290
	 * Verify that a user can use the link endpoint.
291
	 *
292
	 * @since 4.1.0
293
	 *
294
	 * @return bool|WP_Error True if user is able to link to WordPress.com
295
	 */
296 View Code Duplication
	public static function link_user_permission_callback() {
297
		if ( current_user_can( 'jetpack_connect_user' ) ) {
298
			return true;
299
		}
300
301
		return new WP_Error( 'invalid_user_permission_link_user', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
302
	}
303
304
	/**
305
	 * Verify that a user can get the data about the current user.
306
	 * Only those who can connect.
307
	 *
308
	 * @since 4.1.0
309
	 *
310
	 * @uses Jetpack::is_user_connected();
311
	 *
312
	 * @return bool|WP_Error True if user is able to unlink.
313
	 */
314 View Code Duplication
	public static function get_user_connection_data_permission_callback() {
315
		if ( current_user_can( 'jetpack_connect_user' ) ) {
316
			return true;
317
		}
318
319
		return new WP_Error( 'invalid_user_permission_unlink_user', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
320
	}
321
322
	/**
323
	 * Verify that a user can use the unlink endpoint.
324
	 * Either needs to be an admin of the site, or for them to be currently linked.
325
	 *
326
	 * @since 4.1.0
327
	 *
328
	 * @uses Jetpack::is_user_connected();
329
	 *
330
	 * @return bool|WP_Error True if user is able to unlink.
331
	 */
332
	public static function unlink_user_permission_callback() {
333
		if ( current_user_can( 'jetpack_connect' ) || Jetpack::is_user_connected( get_current_user_id() ) ) {
334
			return true;
335
		}
336
337
		return new WP_Error( 'invalid_user_permission_unlink_user', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
338
	}
339
340
	/**
341
	 * Verify that user can manage Jetpack modules.
342
	 *
343
	 * @since 4.1.0
344
	 *
345
	 * @return bool Whether user has the capability 'jetpack_manage_modules'.
346
	 */
347
	public static function manage_modules_permission_check() {
348
		if ( current_user_can( 'jetpack_manage_modules' ) ) {
349
			return true;
350
		}
351
352
		return new WP_Error( 'invalid_user_permission_manage_modules', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
353
	}
354
355
	/**
356
	 * Verify that user can update Jetpack modules.
357
	 *
358
	 * @since 4.1.0
359
	 *
360
	 * @return bool Whether user has the capability 'jetpack_configure_modules'.
361
	 */
362
	public static function configure_modules_permission_check() {
363
		if ( current_user_can( 'jetpack_configure_modules' ) ) {
364
			return true;
365
		}
366
367
		return new WP_Error( 'invalid_user_permission_configure_modules', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
368
	}
369
370
	/**
371
	 * Verify that user can view Jetpack admin page.
372
	 *
373
	 * @since 4.1.0
374
	 *
375
	 * @return bool Whether user has the capability 'jetpack_admin_page'.
376
	 */
377
	public static function view_admin_page_permission_check() {
378
		if ( current_user_can( 'jetpack_admin_page' ) ) {
379
			return true;
380
		}
381
382
		return new WP_Error( 'invalid_user_permission_view_admin', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
383
	}
384
385
	/**
386
	 * Verify that user can update Jetpack options.
387
	 *
388
	 * @since 4.1.0
389
	 *
390
	 * @return bool Whether user has the capability 'jetpack_admin_page'.
391
	 */
392
	public static function update_settings() {
393
		if ( current_user_can( 'manage_options' ) ) {
394
			return true;
395
		}
396
397
		return new WP_Error( 'invalid_user_permission_manage_settings', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
398
	}
399
400
	/**
401
	 * Contextual HTTP error code for authorization failure.
402
	 *
403
	 * Taken from rest_authorization_required_code() in WP-API plugin until is added to core.
404
	 * @see https://github.com/WP-API/WP-API/commit/7ba0ae6fe4f605d5ffe4ee85b1cd5f9fb46900a6
405
	 *
406
	 * @since 4.1.0
407
	 *
408
	 * @return int
409
	 */
410
	public static function rest_authorization_required_code() {
411
		return is_user_logged_in() ? 403 : 401;
412
	}
413
414
	/**
415
	 * Get connection status for this Jetpack site.
416
	 *
417
	 * @since 4.1.0
418
	 *
419
	 * @return bool True if site is connected
420
	 */
421
	public static function jetpack_connection_status() {
422
		return rest_ensure_response( array(
423
				'isActive'  => Jetpack::is_active(),
424
				'isStaging' => Jetpack::is_staging_site(),
425
				'devMode'   => array(
426
					'isActive' => Jetpack::is_development_mode(),
427
					'constant' => defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG,
428
					'url'      => site_url() && false === strpos( site_url(), '.' ),
429
					'filter'   => apply_filters( 'jetpack_development_mode', false ),
430
				),
431
			)
432
		);
433
	}
434
435
	public static function recheck_ssl() {
436
		$result = Jetpack::permit_ssl( true );
437
		return array(
438
			'enabled' => $result,
439
			'message' => get_transient( 'jetpack_https_test_message' )
440
		);
441
	}
442
443
	/**
444
	 * Disconnects Jetpack from the WordPress.com Servers
445
	 *
446
	 * @uses Jetpack::disconnect();
447
	 * @since 4.1.0
448
	 * @return bool|WP_Error True if Jetpack successfully disconnected.
449
	 */
450
	public static function disconnect_site() {
451
		if ( Jetpack::is_active() ) {
452
			Jetpack::disconnect();
453
			return rest_ensure_response( array( 'code' => 'success' ) );
454
		}
455
456
		return new WP_Error( 'disconnect_failed', esc_html__( 'Was not able to disconnect the site.  Please try again.', 'jetpack' ), array( 'status' => 400 ) );
457
	}
458
459
	/**
460
	 * Gets a new connect URL with fresh nonce
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 build_connect_url() {
467
		if ( require_once( ABSPATH . 'wp-admin/includes/plugin.php' ) ) {
468
			$url = Jetpack::init()->build_connect_url( true, false, false );
469
			return rest_ensure_response( $url );
470
		}
471
472
		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 ) );
473
	}
474
475
	/**
476
	 * Get miscellaneous settings for this Jetpack installation, like Holiday Snow.
477
	 *
478
	 * @since 4.1.0
479
	 *
480
	 * @return object $response {
481
	 *     Array of miscellaneous settings.
482
	 *
483
	 *     @type bool $holiday-snow Did Jack steal Christmas?
484
	 * }
485
	 */
486
	public static function get_settings() {
487
		$response = array(
488
			jetpack_holiday_snow_option_name() => get_option( jetpack_holiday_snow_option_name() ) == 'letitsnow',
489
		);
490
		return rest_ensure_response( $response );
491
	}
492
493
	/**
494
	 * Get miscellaneous user data related to the connection. Similar data available in old "My Jetpack".
495
	 * Information about the master/primary user.
496
	 * Information about the current user.
497
	 *
498
	 * @since 4.1.0
499
	 *
500
	 * @return object
501
	 */
502
	public static function get_user_connection_data() {
503
		require_once( JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class.jetpack-react-page.php' );
504
505
		$response = array(
506
			'othersLinked' => jetpack_get_other_linked_users(),
507
			'currentUser'  => jetpack_current_user_data(),
508
		);
509
		return rest_ensure_response( $response );
510
	}
511
512
513
514
	/**
515
	 * Update a single miscellaneous setting for this Jetpack installation, like Holiday Snow.
516
	 *
517
	 * @since 4.1.0
518
	 *
519
	 * @param WP_REST_Request $data
520
	 *
521
	 * @return object Jetpack miscellaneous settings.
522
	 */
523
	public static function update_setting( $data ) {
524
		// Get parameters to update the module.
525
		$param = $data->get_json_params();
526
527
		// Exit if no parameters were passed.
528 View Code Duplication
		if ( ! is_array( $param ) ) {
529
			return new WP_Error( 'missing_setting', esc_html__( 'Missing setting.', 'jetpack' ), array( 'status' => 404 ) );
530
		}
531
532
		// Get option name and value.
533
		$option = key( $param );
534
		$value  = current( $param );
535
536
		// Log success or not
537
		$updated = false;
538
539
		switch ( $option ) {
540
			case jetpack_holiday_snow_option_name():
541
				$updated = update_option( $option, ( true == (bool) $value ) ? 'letitsnow' : '' );
542
				break;
543
		}
544
545
		if ( $updated ) {
546
			return rest_ensure_response( array(
547
				'code' 	  => 'success',
548
				'message' => esc_html__( 'Setting updated.', 'jetpack' ),
549
				'value'   => $value,
550
			) );
551
		}
552
553
		return new WP_Error( 'setting_not_updated', esc_html__( 'The setting was not updated.', 'jetpack' ), array( 'status' => 400 ) );
554
	}
555
556
	/**
557
	 * Unlinks a user from the WordPress.com Servers.
558
	 * Default $data['id'] will default to current_user_id if no value is given.
559
	 *
560
	 * Example: '/unlink?id=1234'
561
	 *
562
	 * @since 4.1.0
563
	 * @uses  Jetpack::unlink_user
564
	 *
565
	 * @param WP_REST_Request $data {
566
	 *     Array of parameters received by request.
567
	 *
568
	 *     @type int $id ID of user to unlink.
569
	 * }
570
	 *
571
	 * @return bool|WP_Error True if user successfully unlinked.
572
	 */
573
	public static function unlink_user( $data ) {
574
		if ( isset( $data['id'] ) && Jetpack::unlink_user( $data['id'] ) ) {
575
			return rest_ensure_response(
576
				array(
577
					'code' => 'success'
578
				)
579
			);
580
		}
581
582
		return new WP_Error( 'unlink_user_failed', esc_html__( 'Was not able to unlink the user.  Please try again.', 'jetpack' ), array( 'status' => 400 ) );
583
	}
584
585
	/**
586
	 * Get site data, including for example, the site's current plan.
587
	 *
588
	 * @since 4.1.0
589
	 *
590
	 * @return array Array of Jetpack modules.
591
	 */
592
	public static function get_site_data() {
593
594
		if ( $site_id = Jetpack_Options::get_option( 'id' ) ) {
595
			$response = Jetpack_Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d', $site_id ), '1.1' );
596
597
			if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
598
				return new WP_Error( 'site_data_fetch_failed', esc_html__( 'Failed fetching site data. Try again later.', 'jetpack' ), array( 'status' => 400 ) );
599
			}
600
601
			return rest_ensure_response( array(
602
					'code' => 'success',
603
					'message' => esc_html__( 'Site data correctly received.', 'jetpack' ),
604
					'data' => wp_remote_retrieve_body( $response ),
605
				)
606
			);
607
		}
608
609
		return new WP_Error( 'site_id_missing', esc_html__( 'The ID of this site does not exist.', 'jetpack' ), array( 'status' => 404 ) );
610
	}
611
612
	/**
613
	 * Is Akismet registered and active?
614
	 *
615
	 * @since 4.1.0
616
	 *
617
	 * @return bool|WP_Error True if Akismet is active and registered. Otherwise, a WP_Error instance with the corresponding error.
618
	 */
619
	public static function akismet_is_active_and_registered() {
620
		if ( ! file_exists( WP_PLUGIN_DIR . '/akismet/class.akismet.php' ) ) {
621
			return new WP_Error( 'not_installed', esc_html__( 'Please install Akismet.', 'jetpack' ), array( 'status' => 400 ) );
622
		}
623
624
		if ( ! class_exists( 'Akismet' ) ) {
625
			return new WP_Error( 'not_active', esc_html__( 'Please activate Akismet.', 'jetpack' ), array( 'status' => 400 ) );
626
		}
627
628
		// What about if Akismet is put in a sub-directory or maybe in mu-plugins?
629
		require_once WP_PLUGIN_DIR . '/akismet/class.akismet.php';
630
		require_once WP_PLUGIN_DIR . '/akismet/class.akismet-admin.php';
631
		$akismet_key = Akismet::verify_key( Akismet::get_api_key() );
632
633
		if ( ! $akismet_key || 'invalid' === $akismet_key || 'failed' === $akismet_key ) {
634
			return new WP_Error( 'invalid_key', esc_html__( 'Invalid Akismet key. Please contact support.', 'jetpack' ), array( 'status' => 400 ) );
635
		}
636
637
		return true;
638
	}
639
640
	/**
641
	 * Get a list of all Jetpack modules and their information.
642
	 *
643
	 * @since 4.1.0
644
	 *
645
	 * @return array Array of Jetpack modules.
646
	 */
647
	public static function get_modules() {
648
		require_once( JETPACK__PLUGIN_DIR . 'class.jetpack-admin.php' );
649
650
		$modules = Jetpack_Admin::init()->get_modules();
651
		foreach ( $modules as $slug => $properties ) {
652
			$modules[ $slug ]['options'] = self::prepare_options_for_response( $slug );
653
		}
654
655
		return $modules;
656
	}
657
658
	/**
659
	 * Get information about a specific and valid Jetpack module.
660
	 *
661
	 * @since 4.1.0
662
	 *
663
	 * @param WP_REST_Request $data {
664
	 *     Array of parameters received by request.
665
	 *
666
	 *     @type string $slug Module slug.
667
	 * }
668
	 *
669
	 * @return mixed|void|WP_Error
670
	 */
671
	public static function get_module( $data ) {
672
		if ( Jetpack::is_module( $data['slug'] ) ) {
673
674
			$module = Jetpack::get_module( $data['slug'] );
675
676
			$module['options'] = self::prepare_options_for_response( $data['slug'] );
677
678
			return $module;
679
		}
680
681
		return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
682
	}
683
684
	/**
685
	 * If it's a valid Jetpack module, activate it.
686
	 *
687
	 * @since 4.1.0
688
	 *
689
	 * @param WP_REST_Request $data {
690
	 *     Array of parameters received by request.
691
	 *
692
	 *     @type string $slug Module slug.
693
	 * }
694
	 *
695
	 * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
696
	 */
697
	public static function activate_module( $data ) {
698
		if ( Jetpack::is_module( $data['slug'] ) ) {
699 View Code Duplication
			if ( Jetpack::activate_module( $data['slug'], false, false ) ) {
700
				return rest_ensure_response( array(
701
					'code' 	  => 'success',
702
					'message' => esc_html__( 'The requested Jetpack module was activated.', 'jetpack' ),
703
				) );
704
			}
705
			return new WP_Error( 'activation_failed', esc_html__( 'The requested Jetpack module could not be activated.', 'jetpack' ), array( 'status' => 424 ) );
706
		}
707
708
		return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
709
	}
710
711
	/**
712
	 * Activate a list of valid Jetpack modules.
713
	 *
714
	 * @since 4.1.0
715
	 *
716
	 * @param WP_REST_Request $data {
717
	 *     Array of parameters received by request.
718
	 *
719
	 *     @type string $slug Module slug.
720
	 * }
721
	 *
722
	 * @return bool|WP_Error True if modules were activated. Otherwise, a WP_Error instance with the corresponding error.
723
	 */
724
	public static function activate_modules( $data ) {
725
		$params = $data->get_json_params();
726
		if ( isset( $params['modules'] ) && is_array( $params['modules'] ) ) {
727
			$activated = array();
728
			$failed = array();
729
730
			foreach ( $params['modules'] as $module ) {
731
				if ( Jetpack::activate_module( $module, false, false ) ) {
732
					$activated[] = $module;
733
				} else {
734
					$failed[] = $module;
735
				}
736
			}
737
738
			if ( empty( $failed ) ) {
739
				return rest_ensure_response( array(
740
					'code' 	  => 'success',
741
					'message' => esc_html__( 'All modules activated.', 'jetpack' ),
742
				) );
743
			} else {
744
				$error = '';
745
746
				$activated_count = count( $activated );
747 View Code Duplication
				if ( $activated_count > 0 ) {
748
					$activated_last = array_pop( $activated );
749
					$activated_text = $activated_count > 1 ? sprintf(
750
						/* Translators: first variable is a list followed by a last item. Example: dog, cat and bird. */
751
						__( '%s and %s', 'jetpack' ),
752
						join( ', ', $activated ), $activated_last ) : $activated_last;
753
754
					$error = sprintf(
755
						/* Translators: the plural variable is a list followed by a last item. Example: dog, cat and bird. */
756
						_n( 'The module %s was activated.', 'The modules %s were activated.', $activated_count, 'jetpack' ),
757
						$activated_text ) . ' ';
758
				}
759
760
				$failed_count = count( $failed );
761 View Code Duplication
				if ( count( $failed ) > 0 ) {
762
					$failed_last = array_pop( $failed );
763
					$failed_text = $failed_count > 1 ? sprintf(
764
						/* Translators: first variable is a list followed by a last item. Example: dog, cat and bird. */
765
						__( '%s and %s', 'jetpack' ),
766
						join( ', ', $failed ), $failed_last ) : $failed_last;
767
768
					$error = sprintf(
769
						/* Translators: the plural variable is a list followed by a last item. Example: dog, cat and bird. */
770
						_n( 'The module %s failed to be activated.', 'The modules %s failed to be activated.', $failed_count, 'jetpack' ),
771
						$failed_text ) . ' ';
772
				}
773
			}
774
			return new WP_Error( 'activation_failed', esc_html( $error ), array( 'status' => 424 ) );
775
		}
776
777
		return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
778
	}
779
780
	/**
781
	 * Reset Jetpack options
782
	 *
783
	 * @since 4.1.0
784
	 *
785
	 * @param WP_REST_Request $data {
786
	 *     Array of parameters received by request.
787
	 *
788
	 *     @type string $options Available options to reset are options|modules
789
	 * }
790
	 *
791
	 * @return bool|WP_Error True if options were reset. Otherwise, a WP_Error instance with the corresponding error.
792
	 */
793
	public static function reset_jetpack_options( $data ) {
794
		if ( isset( $data['options'] ) ) {
795
			$data = $data['options'];
796
797
			switch( $data ) {
798
				case ( 'options' ) :
799
					$options_to_reset = Jetpack::get_jetpack_options_for_reset();
800
801
					// Reset the Jetpack options
802
					foreach ( $options_to_reset['jp_options'] as $option_to_reset ) {
803
						Jetpack_Options::delete_option( $option_to_reset );
804
					}
805
806
					foreach ( $options_to_reset['wp_options'] as $option_to_reset ) {
807
						delete_option( $option_to_reset );
808
					}
809
810
					// Reset to default modules
811
					$default_modules = Jetpack::get_default_modules();
812
					Jetpack_Options::update_option( 'active_modules', $default_modules );
813
814
					// Jumpstart option is special
815
					Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
816
					return rest_ensure_response( array(
817
						'code' 	  => 'success',
818
						'message' => esc_html__( 'Jetpack options reset.', 'jetpack' ),
819
					) );
820
					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...
821
822
				case 'modules':
823
					$default_modules = Jetpack::get_default_modules();
824
					Jetpack_Options::update_option( 'active_modules', $default_modules );
825
826
					return rest_ensure_response( array(
827
						'code' 	  => 'success',
828
						'message' => esc_html__( 'Modules reset to default.', 'jetpack' ),
829
					) );
830
					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...
831
832
				default:
833
					return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
834
			}
835
		}
836
837
		return new WP_Error( 'required_param', esc_html__( 'Missing parameter "type".', 'jetpack' ), array( 'status' => 404 ) );
838
	}
839
840
	/**
841
	 * Activates a series of valid Jetpack modules and initializes some options.
842
	 *
843
	 * @since 4.1.0
844
	 *
845
	 * @param WP_REST_Request $data {
846
	 *     Array of parameters received by request.
847
	 * }
848
	 *
849
	 * @return bool|WP_Error True if Jumpstart succeeded. Otherwise, a WP_Error instance with the corresponding error.
850
	 */
851
	public static function jumpstart_activate( $data ) {
852
		$modules = Jetpack::get_available_modules();
853
		$activate_modules = array();
854
		foreach ( $modules as $module ) {
855
			$module_info = Jetpack::get_module( $module );
856
			if ( isset( $module_info['feature'] ) && is_array( $module_info['feature'] ) && in_array( 'Jumpstart', $module_info['feature'] ) ) {
857
				$activate_modules[] = $module;
858
			}
859
		}
860
861
		// Collect success/error messages like modules that are properly activated.
862
		$result = array(
863
			'activated_modules' => array(),
864
			'failed_modules'    => array(),
865
		);
866
867
		// Update the jumpstart option
868
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
869
			$result['jumpstart_activated'] = Jetpack_Options::update_option( 'jumpstart', 'jumpstart_activated' );
870
		}
871
872
		// Check for possible conflicting plugins
873
		$module_slugs_filtered = Jetpack::init()->filter_default_modules( $activate_modules );
874
875
		foreach ( $module_slugs_filtered as $module_slug ) {
876
			Jetpack::log( 'activate', $module_slug );
877
			if ( Jetpack::activate_module( $module_slug, false, false ) ) {
878
				$result['activated_modules'][] = $module_slug;
879
			} else {
880
				$result['failed_modules'][] = $module_slug;
881
			}
882
			Jetpack::state( 'message', 'no_message' );
883
		}
884
885
		// Set the default sharing buttons and set to display on posts if none have been set.
886
		$sharing_services = get_option( 'sharing-services' );
887
		$sharing_options  = get_option( 'sharing-options' );
888
		if ( empty( $sharing_services['visible'] ) ) {
889
			// Default buttons to set
890
			$visible = array(
891
				'twitter',
892
				'facebook',
893
				'google-plus-1',
894
			);
895
			$hidden = array();
896
897
			// Set some sharing settings
898
			$sharing = new Sharing_Service();
899
			$sharing_options['global'] = array(
900
				'button_style'  => 'icon',
901
				'sharing_label' => $sharing->default_sharing_label,
902
				'open_links'    => 'same',
903
				'show'          => array( 'post' ),
904
				'custom'        => isset( $sharing_options['global']['custom'] ) ? $sharing_options['global']['custom'] : array()
905
			);
906
907
			$result['sharing_options']  = update_option( 'sharing-options', $sharing_options );
908
			$result['sharing_services'] = update_option( 'sharing-services', array( 'visible' => $visible, 'hidden' => $hidden ) );
909
		}
910
911
		// If all Jumpstart modules were activated
912
		if ( empty( $result['failed_modules'] ) ) {
913
			return rest_ensure_response( array(
914
				'code' 	  => 'success',
915
				'message' => esc_html__( 'Jumpstart done.', 'jetpack' ),
916
				'data'    => $result,
917
			) );
918
		}
919
920
		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 ) );
921
	}
922
923
	/**
924
	 * Dismisses Jumpstart so user is not prompted to go through it again.
925
	 *
926
	 * @since 4.1.0
927
	 *
928
	 * @param WP_REST_Request $data {
929
	 *     Array of parameters received by request.
930
	 * }
931
	 *
932
	 * @return bool|WP_Error True if Jumpstart was disabled or was nothing to dismiss. Otherwise, a WP_Error instance with a message.
933
	 */
934
	public static function jumpstart_deactivate( $data ) {
935
936
		// If dismissed, flag the jumpstart option as such.
937
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
938
			if ( Jetpack_Options::update_option( 'jumpstart', 'jumpstart_dismissed' ) ) {
939
				return rest_ensure_response( array(
940
					'code' 	  => 'success',
941
					'message' => esc_html__( 'Jumpstart dismissed.', 'jetpack' ),
942
				) );
943
			} else {
944
				return new WP_Error( 'jumpstart_failed_dismiss', esc_html__( 'Jumpstart could not be dismissed.', 'jetpack' ), array( 'status' => 400 ) );
945
			}
946
		}
947
948
		// If this was not a new connection and there was nothing to dismiss, don't fail.
949
		return rest_ensure_response( array(
950
			'code' 	  => 'success',
951
			'message' => esc_html__( 'Nothing to dismiss. This was not a new connection.', 'jetpack' ),
952
		) );
953
	}
954
955
	/**
956
	 * If it's a valid Jetpack module, deactivate it.
957
	 *
958
	 * @since 4.1.0
959
	 *
960
	 * @param WP_REST_Request $data {
961
	 *     Array of parameters received by request.
962
	 *
963
	 *     @type string $slug Module slug.
964
	 * }
965
	 *
966
	 * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
967
	 */
968
	public static function deactivate_module( $data ) {
969
		if ( Jetpack::is_module( $data['slug'] ) ) {
970 View Code Duplication
			if ( ! Jetpack::is_module_active( $data['slug'] ) ) {
971
				return new WP_Error( 'already_inactive', esc_html__( 'The requested Jetpack module was already inactive.', 'jetpack' ), array( 'status' => 409 ) );
972
			}
973 View Code Duplication
			if ( Jetpack::deactivate_module( $data['slug'] ) ) {
974
				return rest_ensure_response( array(
975
					'code' 	  => 'success',
976
					'message' => esc_html__( 'The requested Jetpack module was deactivated.', 'jetpack' ),
977
				) );
978
			}
979
			return new WP_Error( 'deactivation_failed', esc_html__( 'The requested Jetpack module could not be deactivated.', 'jetpack' ), array( 'status' => 400 ) );
980
		}
981
982
		return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
983
	}
984
985
	/**
986
	 * If it's a valid Jetpack module and configuration parameters have been sent, update it.
987
	 *
988
	 * @since 4.1.0
989
	 *
990
	 * @param WP_REST_Request $data {
991
	 *     Array of parameters received by request.
992
	 *
993
	 *     @type string $slug Module slug.
994
	 * }
995
	 *
996
	 * @return bool|WP_Error True if module was updated. Otherwise, a WP_Error instance with the corresponding error.
997
	 */
998
	public static function update_module( $data ) {
999
		if ( ! Jetpack::is_module( $data['slug'] ) ) {
1000
			return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
1001
		}
1002
1003 View Code Duplication
		if ( ! Jetpack::is_module_active( $data['slug'] ) ) {
1004
			return new WP_Error( 'inactive', esc_html__( 'The requested Jetpack module is inactive.', 'jetpack' ), array( 'status' => 409 ) );
1005
		}
1006
1007
		// Get parameters to update the module.
1008
		$param = $data->get_json_params();
1009
1010
		// Exit if no parameters were passed.
1011 View Code Duplication
		if ( ! is_array( $param ) ) {
1012
			return new WP_Error( 'missing_option', esc_html__( 'Missing option.', 'jetpack' ), array( 'status' => 404 ) );
1013
		}
1014
1015
		// Get option name and value.
1016
		$option = key( $param );
1017
		$value  = current( $param );
1018
1019
		// Get available module options.
1020
		$options = self::get_module_available_options();
1021
1022
		// If option is invalid, don't go any further.
1023
		if ( ! in_array( $option, array_keys( $options ) ) ) {
1024
			return new WP_Error( 'invalid_param', esc_html(	sprintf( __( 'The option %s is invalid for this module.', 'jetpack' ), $option ) ), array( 'status' => 404 ) );
1025
		}
1026
1027
		// Used if response is successful. The message can be overwritten and additional data can be added here.
1028
		$response = array(
1029
			'code' 	  => 'success',
1030
			'message' => esc_html__( 'The requested Jetpack module was updated.', 'jetpack' ),
1031
		);
1032
1033
		// Used if there was an error. Can be overwritten with specific error messages.
1034
		/* Translators: the variable is a module option name. */
1035
		$error = sprintf( __( 'The option %s was not updated.', 'jetpack' ), $option );
1036
1037
		// Set to true if the option update was successful.
1038
		$updated = false;
1039
1040
		// Properly cast value based on its type defined in endpoint accepted args.
1041
		$value = self::cast_value( $value, $options[ $option ] );
1042
1043
		switch ( $option ) {
1044
			case 'monitor_receive_notifications':
1045
				$monitor = new Jetpack_Monitor();
1046
1047
				// If we got true as response, consider it done.
1048
				$updated = true === $monitor->update_option_receive_jetpack_monitor_notification( $value );
1049
				break;
1050
1051
			case 'post_by_email_address':
1052
				if ( 'create' == $value ) {
1053
					$result = self::_process_post_by_email(
1054
						'jetpack.createPostByEmailAddress',
1055
						esc_html__( 'Unable to create the Post by Email address. Please try again later.', 'jetpack' )
1056
					);
1057
				} elseif ( 'regenerate' == $value ) {
1058
					$result = self::_process_post_by_email(
1059
						'jetpack.regeneratePostByEmailAddress',
1060
						esc_html__( 'Unable to regenerate the Post by Email address. Please try again later.', 'jetpack' )
1061
					);
1062
				} elseif ( 'delete' == $value ) {
1063
					$result = self::_process_post_by_email(
1064
						'jetpack.deletePostByEmailAddress',
1065
						esc_html__( 'Unable to delete the Post by Email address. Please try again later.', 'jetpack' )
1066
					);
1067
				} else {
1068
					$result = false;
1069
				}
1070
1071
				// If we got an email address (create or regenerate) or 1 (delete), consider it done.
1072
				if ( preg_match( '/[a-z0-9][email protected]/', $result ) ) {
1073
					$response[ $option ] = $result;
1074
					$updated = true;
1075
				} elseif ( 1 == $result ) {
1076
					$updated = true;
1077
				} elseif ( is_array( $result ) && isset( $result['message'] ) ) {
1078
					$error = $result['message'];
1079
				}
1080
				break;
1081
1082
			case 'jetpack_protect_key':
1083
				$protect = Jetpack_Protect_Module::instance();
1084
				if ( 'create' == $value ) {
1085
					$result = $protect->get_protect_key();
1086
				} else {
1087
					$result = false;
1088
				}
1089
1090
				// If we got one of Protect keys, consider it done.
1091
				if ( preg_match( '/[a-z0-9]{40,}/i', $result ) ) {
1092
					$response[ $option ] = $result;
1093
					$updated = true;
1094
				}
1095
				break;
1096
1097
			case 'jetpack_protect_global_whitelist':
1098
				$updated = jetpack_protect_save_whitelist( explode( PHP_EOL, str_replace( ' ', '', $value ) ) );
1099
				if ( is_wp_error( $updated ) ) {
1100
					$error = $updated->get_error_message();
1101
				}
1102
				break;
1103
1104
			case 'show_headline':
1105
			case 'show_thumbnails':
1106
				$grouped_options = $grouped_options_current = Jetpack_Options::get_option( 'relatedposts' );
1107
				$grouped_options[ $option ] = $value;
1108
1109
				// If option value was the same, consider it done.
1110
				$updated = $grouped_options_current != $grouped_options ? Jetpack_Options::update_option( 'relatedposts', $grouped_options ) : true;
1111
				break;
1112
1113
			case 'google':
1114
			case 'bing':
1115
			case 'pinterest':
1116
				$grouped_options = $grouped_options_current = get_option( 'verification_services_codes' );
1117
				$grouped_options[ $option ] = $value;
1118
1119
				// If option value was the same, consider it done.
1120
				$updated = $grouped_options_current != $grouped_options ? update_option( 'verification_services_codes', $grouped_options ) : true;
1121
				break;
1122
1123
			case 'sharing_services':
1124
				$sharer = new Sharing_Service();
1125
1126
				// If option value was the same, consider it done.
1127
				$updated = $value != $sharer->get_blog_services() ? $sharer->set_blog_services( $value['visible'], $value['hidden'] ) : true;
1128
				break;
1129
1130
			case 'button_style':
1131
			case 'sharing_label':
1132
			case 'show':
1133
				$sharer = new Sharing_Service();
1134
				$grouped_options = $sharer->get_global_options();
1135
				$grouped_options[ $option ] = $value;
1136
				$updated = $sharer->set_global_options( $grouped_options );
1137
				break;
1138
1139
			case 'custom':
1140
				$sharer = new Sharing_Service();
1141
				$updated = $sharer->new_service( stripslashes( $value['sharing_name'] ), stripslashes( $value['sharing_url'] ), stripslashes( $value['sharing_icon'] ) );
1142
1143
				// Return new custom service
1144
				$response[ $option ] = $updated;
1145
				break;
1146
1147
			case 'sharing_delete_service':
1148
				$sharer = new Sharing_Service();
1149
				$updated = $sharer->delete_service( $value );
1150
				break;
1151
1152
			case 'jetpack-twitter-cards-site-tag':
1153
				$value = trim( ltrim( strip_tags( $value ), '@' ) );
1154
				$updated = get_option( $option ) !== $value ? update_option( $option, $value ) : true;
1155
				break;
1156
1157
			case 'onpublish':
1158
			case 'onupdate':
1159
			case 'Bias Language':
1160
			case 'Cliches':
1161
			case 'Complex Expression':
1162
			case 'Diacritical Marks':
1163
			case 'Double Negative':
1164
			case 'Hidden Verbs':
1165
			case 'Jargon Language':
1166
			case 'Passive voice':
1167
			case 'Phrases to Avoid':
1168
			case 'Redundant Expression':
1169
			case 'guess_lang':
1170
				if ( in_array( $option, array( 'onpublish', 'onupdate' ) ) ) {
1171
					$atd_option = 'AtD_check_when';
1172
				} elseif ( 'guess_lang' == $option ) {
1173
					$atd_option = 'AtD_guess_lang';
1174
					$option = 'true';
1175
				} else {
1176
					$atd_option = 'AtD_options';
1177
				}
1178
				$user_id = get_current_user_id();
1179
				$grouped_options_current = AtD_get_options( $user_id, $atd_option );
1180
				unset( $grouped_options_current['name'] );
1181
				$grouped_options = $grouped_options_current;
1182
				if ( $value && ! isset( $grouped_options [ $option ] ) ) {
1183
					$grouped_options [ $option ] = $value;
1184
				} elseif ( ! $value && isset( $grouped_options [ $option ] ) ) {
1185
					unset( $grouped_options [ $option ] );
1186
				}
1187
				// If option value was the same, consider it done, otherwise try to update it.
1188
				$options_to_save = implode( ',', array_keys( $grouped_options ) );
1189
				$updated = $grouped_options != $grouped_options_current ? AtD_update_setting( $user_id, $atd_option, $options_to_save ) : true;
1190
				break;
1191
1192
			case 'ignored_phrases':
1193
			case 'unignore_phrase':
1194
				$user_id = get_current_user_id();
1195
				$atd_option = 'AtD_ignored_phrases';
1196
				$grouped_options = $grouped_options_current = explode( ',', AtD_get_setting( $user_id, $atd_option ) );
1197
				if ( 'ignored_phrases' == $option ) {
1198
					$grouped_options[] = $value;
1199
				} else {
1200
					$index = array_search( $value, $grouped_options );
1201
					if ( false !== $index ) {
1202
						unset( $grouped_options[ $index ] );
1203
						$grouped_options = array_values( $grouped_options );
1204
					}
1205
				}
1206
				$ignored_phrases = implode( ',', array_filter( array_map( 'strip_tags', $grouped_options ) ) );
1207
				$updated = $grouped_options != $grouped_options_current ? AtD_update_setting( $user_id, $atd_option, $ignored_phrases ) : true;
1208
				break;
1209
1210
			default:
1211
				// If option value was the same, consider it done.
1212
				$updated = get_option( $option ) != $value ? update_option( $option, $value ) : true;
1213
				break;
1214
		}
1215
1216
		// The option was not updated.
1217
		if ( ! $updated ) {
1218
			return new WP_Error( 'module_option_not_updated', esc_html( $error ), array( 'status' => 400 ) );
1219
		}
1220
1221
		// The option was updated.
1222
		return rest_ensure_response( $response );
1223
	}
1224
1225
	/**
1226
	 * Calls WPCOM through authenticated request to create, regenerate or delete the Post by Email address.
1227
	 * @todo: When all settings are updated to use endpoints, move this to the Post by Email module and replace __process_ajax_proxy_request.
0 ignored issues
show
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
1228
	 *
1229
	 * @since 4.1.0
1230
	 *
1231
	 * @param string $endpoint Process to call on WPCOM to create, regenerate or delete the Post by Email address.
1232
	 * @param string $error	   Error message to return.
1233
	 *
1234
	 * @return array
1235
	 */
1236
	private static function _process_post_by_email( $endpoint, $error ) {
1237
		if ( ! current_user_can( 'edit_posts' ) ) {
1238
			return array( 'message' => $error );
1239
		}
1240
		Jetpack::load_xml_rpc_client();
1241
		$xml = new Jetpack_IXR_Client( array(
1242
			'user_id' => get_current_user_id(),
1243
		) );
1244
		$xml->query( $endpoint );
1245
1246
		if ( $xml->isError() ) {
1247
			return array( 'message' => $error );
1248
		}
1249
1250
		$response = $xml->getResponse();
1251
		if ( empty( $response ) ) {
1252
			return array( 'message' => $error );
1253
		}
1254
1255
		// Used only in Jetpack_Core_Json_Api_Endpoints::get_remote_value.
1256
		update_option( 'post_by_email_address', $response );
1257
1258
		return $response;
1259
	}
1260
1261
	/**
1262
	 * Get the query parameters for module updating.
1263
	 *
1264
	 * @since 4.1.0
1265
	 *
1266
	 * @return array
1267
	 */
1268
	public static function get_module_updating_parameters() {
1269
		$parameters = array(
1270
			'context'     => array(
1271
				'default' => 'edit',
1272
			),
1273
		);
1274
1275
		return array_merge( $parameters, self::get_module_available_options() );
1276
	}
1277
1278
	/**
1279
	 * Returns a list of module options that can be updated.
1280
	 *
1281
	 * @since 4.1.0
1282
	 *
1283
	 * @param string $module Module slug. If empty, it's assumed we're updating a module and we'll try to get its slug.
1284
	 * @param bool $cache Whether to cache the options or return always fresh.
1285
	 *
1286
	 * @return array
1287
	 */
1288
	public static function get_module_available_options( $module = '', $cache = true ) {
1289
		if ( $cache ) {
1290
			static $options;
1291
		} else {
1292
			$options = null;
1293
		}
1294
1295
		if ( isset( $options ) ) {
1296
			return $options;
1297
		}
1298
1299
		if ( empty( $module ) ) {
1300
			$module = self::get_module_requested( '/module/(?P<slug>[a-z\-]+)/update' );
1301
			if ( empty( $module ) ) {
1302
				return array();
1303
			}
1304
		}
1305
1306
		switch ( $module ) {
1307
1308
			// Carousel
1309
			case 'carousel':
1310
				$options = array(
1311
					'carousel_background_color' => array(
1312
						'description'        => esc_html__( 'Background color.', 'jetpack' ),
1313
						'type'               => 'string',
1314
						'default'            => 'black',
1315
						'enum'				 => array(
1316
							'black' => esc_html__( 'Black', 'jetpack' ),
1317
							'white' => esc_html__( 'White', 'jetpack' ),
1318
						),
1319
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1320
					),
1321
					'carousel_display_exif' => array(
1322
						'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 ) )  ),
1323
						'type'               => 'boolean',
1324
						'default'            => 0,
1325
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1326
					),
1327
				);
1328
				break;
1329
1330
			// Comments
1331
			case 'comments':
1332
				$options = array(
1333
					'highlander_comment_form_prompt' => array(
1334
						'description'        => esc_html__( 'Greeting Text', 'jetpack' ),
1335
						'type'               => 'string',
1336
						'default'            => esc_html__( 'Leave a Reply', 'jetpack' ),
1337
						'sanitize_callback'  => 'sanitize_text_field',
1338
					),
1339
					'jetpack_comment_form_color_scheme' => array(
1340
						'description'        => esc_html__( "Color Scheme", 'jetpack' ),
1341
						'type'               => 'string',
1342
						'default'            => 'light',
1343
						'enum'				 => array(
1344
							'light'       => esc_html__( 'Light', 'jetpack' ),
1345
							'dark'        => esc_html__( 'Dark', 'jetpack' ),
1346
							'transparent' => esc_html__( 'Transparent', 'jetpack' ),
1347
						),
1348
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1349
					),
1350
				);
1351
				break;
1352
1353
			// Custom Content Types
1354
			case 'custom-content-types':
1355
				$options = array(
1356
					'jetpack_portfolio' => array(
1357
						'description'        => esc_html__( 'Enable or disable Jetpack portfolio post type.', 'jetpack' ),
1358
						'type'               => 'boolean',
1359
						'default'            => 0,
1360
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1361
					),
1362
					'jetpack_portfolio_posts_per_page' => array(
1363
						'description'        => esc_html__( 'Number of entries to show at most in Portfolio pages.', 'jetpack' ),
1364
						'type'               => 'integer',
1365
						'default'            => 10,
1366
						'validate_callback'  => __CLASS__ . '::validate_posint',
1367
					),
1368
					'jetpack_testimonial' => array(
1369
						'description'        => esc_html__( 'Enable or disable Jetpack testimonial post type.', 'jetpack' ),
1370
						'type'               => 'boolean',
1371
						'default'            => 0,
1372
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1373
					),
1374
					'jetpack_testimonial_posts_per_page' => array(
1375
						'description'        => esc_html__( 'Number of entries to show at most in Testimonial pages.', 'jetpack' ),
1376
						'type'               => 'integer',
1377
						'default'            => 10,
1378
						'validate_callback'  => __CLASS__ . '::validate_posint',
1379
					),
1380
				);
1381
				break;
1382
1383
			// Galleries
1384 View Code Duplication
			case 'tiled-gallery':
1385
				$options = array(
1386
					'tiled_galleries' => array(
1387
						'description'        => esc_html__( 'Display all your gallery pictures in a cool mosaic.', 'jetpack' ),
1388
						'type'               => 'boolean',
1389
						'default'            => 0,
1390
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1391
					),
1392
				);
1393
				break;
1394
1395
			// Gravatar Hovercards
1396
			case 'gravatar-hovercards':
1397
				$options = array(
1398
					'gravatar_disable_hovercards' => array(
1399
						'description'        => esc_html__( "View people's profiles when you mouse over their Gravatars", 'jetpack' ),
1400
						'type'               => 'string',
1401
						'default'            => 'enabled',
1402
						// Not visible. This is used as the checkbox value.
1403
						'enum'				 => array( 'enabled', 'disabled' ),
1404
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1405
					),
1406
				);
1407
				break;
1408
1409
			// Infinite Scroll
1410
			case 'infinite-scroll':
1411
				$options = array(
1412
					'infinite_scroll' => array(
1413
						'description'        => esc_html__( 'To infinity and beyond', 'jetpack' ),
1414
						'type'               => 'boolean',
1415
						'default'            => 1,
1416
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1417
					),
1418
					'infinite_scroll_google_analytics' => array(
1419
						'description'        => esc_html__( 'Use Google Analytics with Infinite Scroll', 'jetpack' ),
1420
						'type'               => 'boolean',
1421
						'default'            => 0,
1422
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1423
					),
1424
				);
1425
				break;
1426
1427
			// Likes
1428
			case 'likes':
1429
				$options = array(
1430
					'wpl_default' => array(
1431
						'description'        => esc_html__( 'WordPress.com Likes are', 'jetpack' ),
1432
						'type'               => 'string',
1433
						'default'            => 'on',
1434
						'enum'				 => array(
1435
							'on'  => esc_html__( 'On for all posts', 'jetpack' ),
1436
							'off' => esc_html__( 'Turned on per post', 'jetpack' ),
1437
						),
1438
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1439
					),
1440
					'social_notifications_like' => array(
1441
						'description'        => esc_html__( 'Send email notification when someone likes a posts', 'jetpack' ),
1442
						'type'               => 'boolean',
1443
						'default'            => 1,
1444
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1445
					),
1446
				);
1447
				break;
1448
1449
			// Markdown
1450 View Code Duplication
			case 'markdown':
1451
				$options = array(
1452
					'wpcom_publish_comments_with_markdown' => array(
1453
						'description'        => esc_html__( 'Use Markdown for comments.', 'jetpack' ),
1454
						'type'               => 'boolean',
1455
						'default'            => 0,
1456
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1457
					),
1458
				);
1459
				break;
1460
1461
			// Mobile Theme
1462
			case 'minileven':
1463
				$options = array(
1464
					'wp_mobile_excerpt' => array(
1465
						'description'        => esc_html__( 'Excerpts', 'jetpack' ),
1466
						'type'               => 'string',
1467
						'default'            => '0',
1468
						'enum'				 => array(
1469
							'1'  => esc_html__( 'Enable excerpts on front page and on archive pages', 'jetpack' ),
1470
							'0' => esc_html__( 'Show full posts on front page and on archive pages', 'jetpack' ),
1471
						),
1472
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1473
					),
1474
					'wp_mobile_featured_images' => array(
1475
						'description'        => esc_html__( 'Featured Images', 'jetpack' ),
1476
						'type'               => 'string',
1477
						'default'            => '0',
1478
						'enum'				 => array(
1479
							'0'  => esc_html__( 'Hide all featured images', 'jetpack' ),
1480
							'1' => esc_html__( 'Display featured images', 'jetpack' ),
1481
						),
1482
						'validate_callback'  => __CLASS__ . '::validate_list_item',
1483
					),
1484
					'wp_mobile_app_promos' => array(
1485
						'description'        => esc_html__( 'Show a promo for the WordPress mobile apps in the footer of the mobile theme.', 'jetpack' ),
1486
						'type'               => 'boolean',
1487
						'default'            => 0,
1488
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1489
					),
1490
				);
1491
				break;
1492
1493
			// Monitor
1494 View Code Duplication
			case 'monitor':
1495
				$options = array(
1496
					'monitor_receive_notifications' => array(
1497
						'description'        => esc_html__( 'Receive Monitor Email Notifications.', 'jetpack' ),
1498
						'type'               => 'boolean',
1499
						'default'            => 0,
1500
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1501
					),
1502
				);
1503
				break;
1504
1505
			// Post by Email
1506 View Code Duplication
			case 'post-by-email':
1507
				$options = array(
1508
					'post_by_email_address' => array(
1509
						'description'       => esc_html__( 'Email Address', 'jetpack' ),
1510
						'type'              => 'string',
1511
						'default'           => '',
1512
						'enum'              => array(
1513
							'create'     => esc_html__( 'Create Post by Email address', 'jetpack' ),
1514
							'regenerate' => esc_html__( 'Regenerate Post by Email address', 'jetpack' ),
1515
							'delete'     => esc_html__( 'Delete Post by Email address', 'jetpack' ),
1516
						),
1517
						'validate_callback' => __CLASS__ . '::validate_list_item',
1518
					),
1519
				);
1520
				break;
1521
1522
			// Protect
1523 View Code Duplication
			case 'protect':
1524
				$options = array(
1525
					'jetpack_protect_key' => array(
1526
						'description'        => esc_html__( 'Protect API key', 'jetpack' ),
1527
						'type'               => 'string',
1528
						'default'            => '',
1529
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1530
					),
1531
					'jetpack_protect_global_whitelist' => array(
1532
						'description'        => esc_html__( 'Protect global whitelist', 'jetpack' ),
1533
						'type'               => 'string',
1534
						'default'            => '',
1535
						'validate_callback'  => __CLASS__ . '::validate_string',
1536
						'sanitize_callback'  => 'esc_textarea',
1537
					),
1538
				);
1539
				break;
1540
1541
			// Sharing
1542
			case 'sharedaddy':
1543
				$options = array(
1544
					'sharing_services' => array(
1545
						'description'        => esc_html__( 'Enabled Services and those hidden behind a button', 'jetpack' ),
1546
						'type'               => 'array',
1547
						'default'            => array(
1548
							'visible' => array( 'twitter', 'facebook', 'google-plus-1' ),
1549
							'hidden'  => array(),
1550
						),
1551
						'validate_callback'  => __CLASS__ . '::validate_services',
1552
					),
1553
					'button_style' => array(
1554
						'description'       => esc_html__( 'Button Style', 'jetpack' ),
1555
						'type'              => 'string',
1556
						'default'           => 'icon',
1557
						'enum'              => array(
1558
							'icon-text' => esc_html__( 'Icon + text', 'jetpack' ),
1559
							'icon'      => esc_html__( 'Icon only', 'jetpack' ),
1560
							'text'      => esc_html__( 'Text only', 'jetpack' ),
1561
							'official'  => esc_html__( 'Official buttons', 'jetpack' ),
1562
						),
1563
						'validate_callback' => __CLASS__ . '::validate_list_item',
1564
					),
1565
					'sharing_label' => array(
1566
						'description'        => esc_html__( 'Sharing Label', 'jetpack' ),
1567
						'type'               => 'string',
1568
						'default'            => '',
1569
						'validate_callback'  => __CLASS__ . '::validate_string',
1570
						'sanitize_callback'  => 'esc_html',
1571
					),
1572
					'show' => array(
1573
						'description'        => esc_html__( 'Views where buttons are shown', 'jetpack' ),
1574
						'type'               => 'array',
1575
						'default'            => array( 'post' ),
1576
						'validate_callback'  => __CLASS__ . '::validate_sharing_show',
1577
					),
1578
					'jetpack-twitter-cards-site-tag' => array(
1579
						'description'        => esc_html__( "The Twitter username of the owner of this site's domain.", 'jetpack' ),
1580
						'type'               => 'string',
1581
						'default'            => '',
1582
						'validate_callback'  => __CLASS__ . '::validate_twitter_username',
1583
						'sanitize_callback'  => 'esc_html',
1584
					),
1585
					'sharedaddy_disable_resources' => array(
1586
						'description'        => esc_html__( 'Disable CSS and JS', 'jetpack' ),
1587
						'type'               => 'boolean',
1588
						'default'            => 0,
1589
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1590
					),
1591
					'custom' => array(
1592
						'description'        => esc_html__( 'Custom sharing services added by user.', 'jetpack' ),
1593
						'type'               => 'array',
1594
						'default'            => array(
1595
							'sharing_name' => '',
1596
							'sharing_url'  => '',
1597
							'sharing_icon' => '',
1598
						),
1599
						'validate_callback'  => __CLASS__ . '::validate_custom_service',
1600
					),
1601
					// Not an option, but an action that can be perfomed on the list of custom services passing the service ID.
1602
					'sharing_delete_service' => array(
1603
						'description'        => esc_html__( 'Delete custom sharing service.', 'jetpack' ),
1604
						'type'               => 'string',
1605
						'default'            => '',
1606
						'validate_callback'  => __CLASS__ . '::validate_custom_service_id',
1607
					),
1608
				);
1609
				break;
1610
1611
			// SSO
1612 View Code Duplication
			case 'sso':
1613
				$options = array(
1614
					'jetpack_sso_require_two_step' => array(
1615
						'description'        => esc_html__( 'Require Two-Step Authentication', 'jetpack' ),
1616
						'type'               => 'boolean',
1617
						'default'            => 0,
1618
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1619
					),
1620
					'jetpack_sso_match_by_email' => array(
1621
						'description'        => esc_html__( 'Match by Email', 'jetpack' ),
1622
						'type'               => 'boolean',
1623
						'default'            => 0,
1624
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1625
					),
1626
				);
1627
				break;
1628
1629
			// Site Icon
1630 View Code Duplication
			case 'site-icon':
1631
				$options = array(
1632
					'site_icon_id' => array(
1633
						'description'        => esc_html__( 'Site Icon ID', 'jetpack' ),
1634
						'type'               => 'integer',
1635
						'default'            => 0,
1636
						'validate_callback'  => __CLASS__ . '::validate_posint',
1637
					),
1638
					'site_icon_url' => array(
1639
						'description'        => esc_html__( 'Site Icon URL', 'jetpack' ),
1640
						'type'               => 'string',
1641
						'default'            => '',
1642
						'sanitize_callback'  => 'esc_url',
1643
					),
1644
				);
1645
				break;
1646
1647
			// Subscriptions
1648
			case 'subscriptions':
1649
				$options = array(
1650
					'stb_enabled' => array(
1651
						'description'        => esc_html__( "Show a <em>'follow blog'</em> option in the comment form", 'jetpack' ),
1652
						'type'               => 'boolean',
1653
						'default'            => 1,
1654
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1655
					),
1656
					'stc_enabled' => array(
1657
						'description'        => esc_html__( "Show a <em>'follow comments'</em> option in the comment form", 'jetpack' ),
1658
						'type'               => 'boolean',
1659
						'default'            => 1,
1660
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1661
					),
1662
				);
1663
				break;
1664
1665
			// Related Posts
1666
			case 'related-posts':
1667
				$options = array(
1668
					'show_headline' => array(
1669
						'description'        => esc_html__( 'Show a "Related" header to more clearly separate the related section from posts', 'jetpack' ),
1670
						'type'               => 'boolean',
1671
						'default'            => 1,
1672
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1673
					),
1674
					'show_thumbnails' => array(
1675
						'description'        => esc_html__( 'Use a large and visually striking layout', 'jetpack' ),
1676
						'type'               => 'boolean',
1677
						'default'            => 0,
1678
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1679
					),
1680
				);
1681
				break;
1682
1683
			// Spelling and Grammar - After the Deadline
1684
			case 'after-the-deadline':
1685
				$options = array(
1686
					'onpublish' => array(
1687
						'description'        => esc_html__( 'Proofread when a post or page is first published.', 'jetpack' ),
1688
						'type'               => 'boolean',
1689
						'default'            => 0,
1690
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1691
					),
1692
					'onupdate' => array(
1693
						'description'        => esc_html__( 'Proofread when a post or page is updated.', 'jetpack' ),
1694
						'type'               => 'boolean',
1695
						'default'            => 0,
1696
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1697
					),
1698
					'Bias Language' => array(
1699
						'description'        => esc_html__( 'Bias Language', 'jetpack' ),
1700
						'type'               => 'boolean',
1701
						'default'            => 0,
1702
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1703
					),
1704
					'Cliches' => array(
1705
						'description'        => esc_html__( 'Clichés', 'jetpack' ),
1706
						'type'               => 'boolean',
1707
						'default'            => 0,
1708
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1709
					),
1710
					'Complex Expression' => array(
1711
						'description'        => esc_html__( 'Complex Phrases', 'jetpack' ),
1712
						'type'               => 'boolean',
1713
						'default'            => 0,
1714
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1715
					),
1716
					'Diacritical Marks' => array(
1717
						'description'        => esc_html__( 'Diacritical Marks', 'jetpack' ),
1718
						'type'               => 'boolean',
1719
						'default'            => 0,
1720
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1721
					),
1722
					'Double Negative' => array(
1723
						'description'        => esc_html__( 'Double Negatives', 'jetpack' ),
1724
						'type'               => 'boolean',
1725
						'default'            => 0,
1726
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1727
					),
1728
					'Hidden Verbs' => array(
1729
						'description'        => esc_html__( 'Hidden Verbs', 'jetpack' ),
1730
						'type'               => 'boolean',
1731
						'default'            => 0,
1732
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1733
					),
1734
					'Jargon Language' => array(
1735
						'description'        => esc_html__( 'Jargon', 'jetpack' ),
1736
						'type'               => 'boolean',
1737
						'default'            => 0,
1738
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1739
					),
1740
					'Passive voice' => array(
1741
						'description'        => esc_html__( 'Passive Voice', 'jetpack' ),
1742
						'type'               => 'boolean',
1743
						'default'            => 0,
1744
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1745
					),
1746
					'Phrases to Avoid' => array(
1747
						'description'        => esc_html__( 'Phrases to Avoid', 'jetpack' ),
1748
						'type'               => 'boolean',
1749
						'default'            => 0,
1750
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1751
					),
1752
					'Redundant Expression' => array(
1753
						'description'        => esc_html__( 'Redundant Phrases', 'jetpack' ),
1754
						'type'               => 'boolean',
1755
						'default'            => 0,
1756
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1757
					),
1758
					'guess_lang' => array(
1759
						'description'        => esc_html__( 'Use automatically detected language to proofread posts and pages', 'jetpack' ),
1760
						'type'               => 'boolean',
1761
						'default'            => 0,
1762
						'validate_callback'  => __CLASS__ . '::validate_boolean',
1763
					),
1764
					'ignored_phrases' => array(
1765
						'description'        => esc_html__( 'Add Phrase to be ignored', 'jetpack' ),
1766
						'type'               => 'string',
1767
						'default'            => '',
1768
						'sanitize_callback'  => 'esc_html',
1769
					),
1770
					'unignore_phrase' => array(
1771
						'description'        => esc_html__( 'Remove Phrase from being ignored', 'jetpack' ),
1772
						'type'               => 'string',
1773
						'default'            => '',
1774
						'sanitize_callback'  => 'esc_html',
1775
					),
1776
				);
1777
				break;
1778
1779
			// Verification Tools
1780
			case 'verification-tools':
1781
				$options = array(
1782
					'google' => array(
1783
						'description'        => esc_html__( 'Google Search Console', 'jetpack' ),
1784
						'type'               => 'string',
1785
						'default'            => '',
1786
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1787
					),
1788
					'bing' => array(
1789
						'description'        => esc_html__( 'Bing Webmaster Center', 'jetpack' ),
1790
						'type'               => 'string',
1791
						'default'            => '',
1792
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1793
					),
1794
					'pinterest' => array(
1795
						'description'        => esc_html__( 'Pinterest Site Verification', 'jetpack' ),
1796
						'type'               => 'string',
1797
						'default'            => '',
1798
						'validate_callback'  => __CLASS__ . '::validate_alphanum',
1799
					),
1800
				);
1801
				break;
1802
		}
1803
1804
		return $options;
1805
	}
1806
1807
	/**
1808
	 * Validates that the parameter is either a pure boolean or a numeric string that can be mapped to a boolean.
1809
	 *
1810
	 * @since 4.1.0
1811
	 *
1812
	 * @param string|bool $value Value to check.
1813
	 * @param WP_REST_Request $request
1814
	 * @param string $param
1815
	 *
1816
	 * @return bool
1817
	 */
1818
	public static function validate_boolean( $value, $request, $param ) {
1819
		if ( ! is_bool( $value ) && ! in_array( $value, array( 0, 1 ) ) ) {
1820
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be true, false, 0 or 1.', 'jetpack' ), $param ) );
1821
		}
1822
		return true;
1823
	}
1824
1825
	/**
1826
	 * Validates that the parameter is a positive integer.
1827
	 *
1828
	 * @since 4.1.0
1829
	 *
1830
	 * @param int $value Value to check.
1831
	 * @param WP_REST_Request $request
1832
	 * @param string $param
1833
	 *
1834
	 * @return bool
1835
	 */
1836
	public static function validate_posint( $value = 0, $request, $param ) {
1837
		if ( ! is_numeric( $value ) || $value <= 0 ) {
1838
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a positive integer.', 'jetpack' ), $param ) );
1839
		}
1840
		return true;
1841
	}
1842
1843
	/**
1844
	 * Validates that the parameter belongs to a list of admitted values.
1845
	 *
1846
	 * @since 4.1.0
1847
	 *
1848
	 * @param string $value Value to check.
1849
	 * @param WP_REST_Request $request
1850
	 * @param string $param
1851
	 *
1852
	 * @return bool
1853
	 */
1854
	public static function validate_list_item( $value = '', $request, $param ) {
1855
		$attributes = $request->get_attributes();
1856
		if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
1857
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s not recognized', 'jetpack' ), $param ) );
1858
		}
1859
		$args = $attributes['args'][ $param ];
1860
		if ( ! empty( $args['enum'] ) ) {
1861
1862
			// If it's an associative array, use the keys to check that the value is among those admitted.
1863
			$enum = ( count( array_filter( array_keys( $args['enum'] ), 'is_string' ) ) > 0 ) ? array_keys( $args['enum'] ) : $args['enum'];
1864 View Code Duplication
			if ( ! in_array( $value, $enum ) ) {
1865
				return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be one of %s', 'jetpack' ), $param, implode( ', ', $enum ) ) );
1866
			}
1867
		}
1868
		return true;
1869
	}
1870
1871
	/**
1872
	 * Validates that the parameter belongs to a list of admitted values.
1873
	 *
1874
	 * @since 4.1.0
1875
	 *
1876
	 * @param string $value Value to check.
1877
	 * @param WP_REST_Request $request
1878
	 * @param string $param
1879
	 *
1880
	 * @return bool
1881
	 */
1882
	public static function validate_module_list( $value = '', $request, $param ) {
1883
		if ( ! is_array( $value ) ) {
1884
			return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be an array', 'jetpack' ), $param ) );
1885
		}
1886
1887
		$modules = Jetpack::get_available_modules();
1888
1889
		if ( count( array_intersect( $value, $modules ) ) != count( $value ) ) {
1890
			return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be a list of valid modules', 'jetpack' ), $param ) );
1891
		}
1892
1893
		return true;
1894
	}
1895
1896
	/**
1897
	 * Validates that the parameter is an alphanumeric or empty string (to be able to clear the field).
1898
	 *
1899
	 * @since 4.1.0
1900
	 *
1901
	 * @param string $value Value to check.
1902
	 * @param WP_REST_Request $request
1903
	 * @param string $param
1904
	 *
1905
	 * @return bool
1906
	 */
1907
	public static function validate_alphanum( $value = '', $request, $param ) {
1908 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/[a-z0-9]+/i', $value ) ) ) {
1909
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an alphanumeric string.', 'jetpack' ), $param ) );
1910
		}
1911
		return true;
1912
	}
1913
1914
	/**
1915
	 * Validates that the parameter is among the views where the Sharing can be displayed.
1916
	 *
1917
	 * @since 4.1.0
1918
	 *
1919
	 * @param string|bool $value Value to check.
1920
	 * @param WP_REST_Request $request
1921
	 * @param string $param
1922
	 *
1923
	 * @return bool
1924
	 */
1925
	public static function validate_sharing_show( $value, $request, $param ) {
1926
		$views = array( 'index', 'post', 'page', 'attachment', 'jetpack-portfolio' );
1927 View Code Duplication
		if ( ! array_intersect( $views, $value ) ) {
1928
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be %s.', 'jetpack' ), $param, join( ', ', $views ) ) );
1929
		}
1930
		return true;
1931
	}
1932
1933
	/**
1934
	 * Validates that the parameter is among the views where the Sharing can be displayed.
1935
	 *
1936
	 * @since 4.1.0
1937
	 *
1938
	 * @param string|bool $value Value to check.
1939
	 * @param WP_REST_Request $request
1940
	 * @param string $param
1941
	 *
1942
	 * @return bool
1943
	 */
1944
	public static function validate_services( $value, $request, $param ) {
1945 View Code Duplication
		if ( ! is_array( $value ) || ! isset( $value['visible'] ) || ! isset( $value['hidden'] ) ) {
1946
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array with visible and hidden items.', 'jetpack' ), $param ) );
1947
		}
1948
1949
		// Allow to clear everything.
1950
		if ( empty( $value['visible'] ) && empty( $value['hidden'] ) ) {
1951
			return true;
1952
		}
1953
1954 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharing/sharing-service.php' ) ) {
1955
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
1956
		}
1957
		$sharer = new Sharing_Service();
1958
		$services = array_keys( $sharer->get_all_services() );
1959
1960
		if (
1961
			( ! empty( $value['visible'] ) && ! array_intersect( $value['visible'], $services ) )
1962
			||
1963
			( ! empty( $value['hidden'] ) && ! array_intersect( $value['hidden'], $services ) ) )
1964
		{
1965
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s visible and hidden items must be a list of %s.', 'jetpack' ), $param, join( ', ', $services ) ) );
1966
		}
1967
		return true;
1968
	}
1969
1970
	/**
1971
	 * Validates that the parameter has enough information to build a custom sharing button.
1972
	 *
1973
	 * @since 4.1.0
1974
	 *
1975
	 * @param string|bool $value Value to check.
1976
	 * @param WP_REST_Request $request
1977
	 * @param string $param
1978
	 *
1979
	 * @return bool
1980
	 */
1981
	public static function validate_custom_service( $value, $request, $param ) {
1982 View Code Duplication
		if ( ! is_array( $value ) || ! isset( $value['sharing_name'] ) || ! isset( $value['sharing_url'] ) || ! isset( $value['sharing_icon'] ) ) {
1983
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array with sharing name, url and icon.', 'jetpack' ), $param ) );
1984
		}
1985
1986
		// Allow to clear everything.
1987
		if ( empty( $value['sharing_name'] ) && empty( $value['sharing_url'] ) && empty( $value['sharing_icon'] ) ) {
1988
			return true;
1989
		}
1990
1991 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharing/sharing-service.php' ) ) {
1992
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
1993
		}
1994
1995
		if ( ( ! empty( $value['sharing_name'] ) && ! is_string( $value['sharing_name'] ) )
1996
		|| ( ! empty( $value['sharing_url'] ) && ! is_string( $value['sharing_url'] ) )
1997
		|| ( ! empty( $value['sharing_icon'] ) && ! is_string( $value['sharing_icon'] ) ) ) {
1998
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s needs sharing name, url and icon.', 'jetpack' ), $param ) );
1999
		}
2000
		return true;
2001
	}
2002
2003
	/**
2004
	 * Validates that the parameter is a custom sharing service ID like 'custom-1461976264'.
2005
	 *
2006
	 * @since 4.1.0
2007
	 *
2008
	 * @param string $value Value to check.
2009
	 * @param WP_REST_Request $request
2010
	 * @param string $param
2011
	 *
2012
	 * @return bool
2013
	 */
2014
	public static function validate_custom_service_id( $value = '', $request, $param ) {
2015 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/custom\-[0-1]+/i', $value ) ) ) {
2016
			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 ) );
2017
		}
2018
2019 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharing/sharing-service.php' ) ) {
2020
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
2021
		}
2022
		$sharer = new Sharing_Service();
2023
		$services = array_keys( $sharer->get_all_services() );
2024
2025 View Code Duplication
		if ( ! empty( $value ) && ! in_array( $value, $services ) ) {
2026
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s is not a registered custom sharing service.', 'jetpack' ), $param ) );
2027
		}
2028
2029
		return true;
2030
	}
2031
2032
	/**
2033
	 * Validates that the parameter is a Twitter username or empty string (to be able to clear the field).
2034
	 *
2035
	 * @since 4.1.0
2036
	 *
2037
	 * @param string $value Value to check.
2038
	 * @param WP_REST_Request $request
2039
	 * @param string $param
2040
	 *
2041
	 * @return bool
2042
	 */
2043
	public static function validate_twitter_username( $value = '', $request, $param ) {
2044 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/^@?\w{1,15}$/i', $value ) ) ) {
2045
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a Twitter username.', 'jetpack' ), $param ) );
2046
		}
2047
		return true;
2048
	}
2049
2050
	/**
2051
	 * Validates that the parameter is a string.
2052
	 *
2053
	 * @since 4.1.0
2054
	 *
2055
	 * @param string $value Value to check.
2056
	 * @param WP_REST_Request $request
2057
	 * @param string $param
2058
	 *
2059
	 * @return bool
2060
	 */
2061
	public static function validate_string( $value = '', $request, $param ) {
2062
		if ( ! is_string( $value ) ) {
2063
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a string.', 'jetpack' ), $param ) );
2064
		}
2065
		return true;
2066
	}
2067
2068
	/**
2069
	 * Get the currently accessed route and return the module slug in it.
2070
	 *
2071
	 * @since 4.1.0
2072
	 *
2073
	 * @param string $route Regular expression for the endpoint with the module slug to return.
2074
	 *
2075
	 * @return array
2076
	 */
2077
	public static function get_module_requested( $route ) {
2078
2079
		if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
2080
			return '';
2081
		}
2082
2083
		preg_match( "#$route#", $GLOBALS['wp']->query_vars['rest_route'], $module );
2084
2085
		if ( empty( $module['slug'] ) ) {
2086
			return '';
2087
		}
2088
2089
		return $module['slug'];
2090
	}
2091
2092
	/**
2093
	 * Remove 'validate_callback' item from options available for module.
2094
	 * Fetch current option value and add to array of module options.
2095
	 * Prepare values of module options that need special handling, like those saved in wpcom.
2096
	 *
2097
	 * @since 4.1.0
2098
	 *
2099
	 * @param string $module Module slug.
2100
	 * @return array
2101
	 */
2102
	public static function prepare_options_for_response( $module = '' ) {
2103
		$options = self::get_module_available_options( $module, false );
2104
2105
		if ( ! is_array( $options ) || empty( $options ) ) {
2106
			return $options;
2107
		}
2108
2109
		foreach ( $options as $key => $value ) {
2110
2111
			if ( isset( $options[ $key ]['validate_callback'] ) ) {
2112
				unset( $options[ $key ]['validate_callback'] );
2113
			}
2114
2115
			$default_value = isset( $options[ $key ]['default'] ) ? $options[ $key ]['default'] : '';
2116
2117
			$current_value = get_option( $key, $default_value );
2118
2119
			$options[ $key ]['current_value'] = self::cast_value( $current_value, $options[ $key ] );
2120
		}
2121
2122
		// Some modules need special treatment.
2123
		switch ( $module ) {
2124
2125
			case 'monitor':
2126
				// Status of user notifications
2127
				$options['monitor_receive_notifications']['current_value'] = self::cast_value( self::get_remote_value( 'monitor', 'monitor_receive_notifications' ), $options['monitor_receive_notifications'] );
2128
				break;
2129
2130
			case 'post-by-email':
2131
				// Email address
2132
				$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'] );
2133
				break;
2134
2135
			case 'protect':
2136
				// Protect
2137
				$options['jetpack_protect_key']['current_value'] = get_site_option( 'jetpack_protect_key', false );
2138
				if ( ! function_exists( 'jetpack_protect_format_whitelist' ) ) {
2139
					@include( JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php' );
2140
				}
2141
				$options['jetpack_protect_global_whitelist']['current_value'] = jetpack_protect_format_whitelist();
2142
				break;
2143
2144
			case 'related-posts':
2145
				// It's local, but it must be broken apart since it's saved as an array.
2146
				$options = self::split_options( $options, Jetpack_Options::get_option( 'relatedposts' ) );
2147
				break;
2148
2149
			case 'verification-tools':
2150
				// It's local, but it must be broken apart since it's saved as an array.
2151
				$options = self::split_options( $options, get_option( 'verification_services_codes' ) );
2152
				break;
2153
2154
			case 'sharedaddy':
2155
				// It's local, but it must be broken apart since it's saved as an array.
2156
				if ( ! class_exists( 'Sharing_Service' ) && ! @include( JETPACK__PLUGIN_DIR . 'modules/sharing/sharing-service.php' ) ) {
2157
					break;
2158
				}
2159
				$sharer = new Sharing_Service();
2160
				$options = self::split_options( $options, $sharer->get_global_options() );
2161
				$options['sharing_services']['current_value'] = $sharer->get_blog_services();
2162
				break;
2163
2164
			case 'site-icon':
2165
				// Return site icon ID and URL to make it more complete.
2166
				$options['site_icon_id']['current_value'] = Jetpack_Options::get_option( 'site_icon_id' );
2167
				if ( ! function_exists( 'jetpack_site_icon_url' ) ) {
2168
					@include( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
2169
				}
2170
				$options['site_icon_url']['current_value'] = jetpack_site_icon_url();
2171
				break;
2172
2173
			case 'after-the-deadline':
2174
				if ( ! function_exists( 'AtD_get_options' ) ) {
2175
					@include( JETPACK__PLUGIN_DIR . 'modules/after-the-deadline.php' );
2176
				}
2177
				$atd_options = array_merge( AtD_get_options( get_current_user_id(), 'AtD_options' ), AtD_get_options( get_current_user_id(), 'AtD_check_when' ) );
2178
				unset( $atd_options['name'] );
2179
				foreach ( $atd_options as $key => $value ) {
2180
					$options[ $key ]['current_value'] = self::cast_value( $value, $options[ $key ] );
2181
				}
2182
				$atd_options = AtD_get_options( get_current_user_id(), 'AtD_guess_lang' );
2183
				$options['guess_lang']['current_value'] = self::cast_value( isset( $atd_options['true'] ), $options[ 'guess_lang' ] );
2184
				$options['ignored_phrases']['current_value'] = AtD_get_setting( get_current_user_id(), 'AtD_ignored_phrases' );
2185
				unset( $options['unignore_phrase'] );
2186
				break;
2187
		}
2188
2189
		return $options;
2190
	}
2191
2192
	/**
2193
	 * Splits module options saved as arrays like relatedposts or verification_services_codes into separate options to be returned in the response.
2194
	 *
2195
	 * @since 4.1.0
2196
	 *
2197
	 * @param array  $separate_options Array of options admitted by the module.
2198
	 * @param array  $grouped_options Option saved as array to be splitted.
2199
	 * @param string $prefix Optional prefix for the separate option keys.
2200
	 *
2201
	 * @return array
2202
	 */
2203
	public static function split_options( $separate_options, $grouped_options, $prefix = '' ) {
2204
		if ( is_array( $grouped_options ) ) {
2205
			foreach ( $grouped_options as $key => $value ) {
2206
				$option_key = $prefix . $key;
2207
				if ( isset( $separate_options[ $option_key ] ) ) {
2208
					$separate_options[ $option_key ]['current_value'] = self::cast_value( $grouped_options[ $key ], $separate_options[ $option_key ] );
2209
				}
2210
			}
2211
		}
2212
		return $separate_options;
2213
	}
2214
2215
	/**
2216
	 * Perform a casting to the value specified in the option definition.
2217
	 *
2218
	 * @since 4.1.0
2219
	 *
2220
	 * @param mixed $value Value to cast to the proper type.
2221
	 * @param array $definition Type to cast the value to.
2222
	 *
2223
	 * @return bool|float|int|string
2224
	 */
2225
	public static function cast_value( $value, $definition ) {
2226
		if ( isset( $definition['type'] ) ) {
2227
			switch ( $definition['type'] ) {
2228
				case 'boolean':
2229
					if ( 'true' === $value ) {
2230
						return true;
2231
					} elseif ( 'false' === $value ) {
2232
						return false;
2233
					}
2234
					return (bool) $value;
2235
					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...
2236
2237
				case 'integer':
2238
					return (int) $value;
2239
					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...
2240
2241
				case 'float':
2242
					return (float) $value;
2243
					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...
2244
			}
2245
		}
2246
		return $value;
2247
	}
2248
2249
	/**
2250
	 * Get a value not saved locally.
2251
	 *
2252
	 * @since 4.1.0
2253
	 *
2254
	 * @param string $module Module slug.
2255
	 * @param string $option Option name.
2256
	 *
2257
	 * @return bool Whether user is receiving notifications or not.
2258
	 */
2259
	public static function get_remote_value( $module, $option ) {
2260
2261
		// If option doesn't exist, 'does_not_exist' will be returned.
2262
		$value = get_option( $option, 'does_not_exist' );
2263
2264
		// If option exists, just return it.
2265
		if ( 'does_not_exist' !== $value ) {
2266
			return $value;
2267
		}
2268
2269
		// Only check a remote option if Jetpack is connected.
2270
		if ( ! Jetpack::is_active() ) {
2271
			return false;
2272
		}
2273
2274
		// If the module is inactive, load the class to use the method.
2275
		if ( ! did_action( 'jetpack_module_loaded_' . $module ) ) {
2276
			// Class can't be found so do nothing.
2277
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
2278
				return false;
2279
			}
2280
		}
2281
2282
		// Do what is necessary for each module.
2283
		switch ( $module ) {
2284
			case 'monitor':
2285
				$monitor = new Jetpack_Monitor();
2286
				$value = $monitor->user_receives_notifications( false );
2287
				break;
2288
2289
			case 'post-by-email':
2290
				$post_by_email = new Jetpack_Post_By_Email();
2291
				$value = $post_by_email->get_post_by_email_address();
2292
				break;
2293
		}
2294
2295
		// Normalize value to boolean.
2296
		if ( is_wp_error( $value ) || is_null( $value ) ) {
2297
			$value = false;
2298
		}
2299
2300
		// Save option to use it next time.
2301
		update_option( $option, $value );
2302
2303
		return $value;
2304
	}
2305
2306
	/**
2307
	 * Get number of blocked intrusion attempts.
2308
	 *
2309
	 * @since 4.1.0
2310
	 *
2311
	 * @return mixed|WP_Error Number of blocked attempts if protection is enabled. Otherwise, a WP_Error instance with the corresponding error.
2312
	 */
2313
	public static function protect_get_blocked_count() {
2314
		if ( Jetpack::is_module_active( 'protect' ) ) {
2315
			return get_site_option( 'jetpack_protect_blocked_attempts' );
2316
		}
2317
2318
		return new WP_Error( 'not_active', esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ), array( 'status' => 404 ) );
2319
	}
2320
2321
	/**
2322
	 * Get number of spam messages blocked by Akismet.
2323
	 *
2324
	 * @since 4.1.0
2325
	 *
2326
	 * @param WP_REST_Request $data {
2327
	 *     Array of parameters received by request.
2328
	 *
2329
	 *     @type string $date Date range to restrict results to.
2330
	 * }
2331
	 *
2332
	 * @return int|string Number of spam blocked by Akismet. Otherwise, an error message.
2333
	 */
2334
	public static function akismet_get_stats_data( WP_REST_Request $data ) {
2335
		if ( ! is_wp_error( $status = self::akismet_is_active_and_registered() ) ) {
2336
			return rest_ensure_response( Akismet_Admin::get_stats( Akismet::get_api_key() ) );
2337
		} else {
2338
			return $status->get_error_code();
2339
		}
2340
	}
2341
2342
	/**
2343
	 * Get date of last downtime.
2344
	 *
2345
	 * @since 4.1.0
2346
	 *
2347
	 * @return mixed|WP_Error Number of days since last downtime. Otherwise, a WP_Error instance with the corresponding error.
2348
	 */
2349
	public static function monitor_get_last_downtime() {
2350
		if ( Jetpack::is_module_active( 'monitor' ) ) {
2351
			$monitor       = new Jetpack_Monitor();
2352
			$last_downtime = $monitor->monitor_get_last_downtime();
2353
			if ( is_wp_error( $last_downtime ) ) {
2354
				return $last_downtime;
2355
			} else {
2356
				return rest_ensure_response( array(
2357
					'code' => 'success',
2358
					'date' => human_time_diff( strtotime( $last_downtime ), strtotime( 'now' ) ),
2359
				) );
2360
			}
2361
		}
2362
2363
		return new WP_Error( 'not_active', esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ), array( 'status' => 404 ) );
2364
	}
2365
2366
	/**
2367
	 * Get number of plugin updates available.
2368
	 *
2369
	 * @since 4.1.0
2370
	 *
2371
	 * @return mixed|WP_Error Number of plugin updates available. Otherwise, a WP_Error instance with the corresponding error.
2372
	 */
2373
	public static function get_plugin_update_count() {
2374
		$updates = wp_get_update_data();
2375
		if ( isset( $updates['counts'] ) && isset( $updates['counts']['plugins'] ) ) {
2376
			$count = $updates['counts']['plugins'];
2377
			if ( 0 == $count ) {
2378
				$response = array(
2379
					'code'    => 'success',
2380
					'message' => esc_html__( 'All plugins are up-to-date. Keep up the good work!', 'jetpack' ),
2381
					'count'   => 0,
2382
				);
2383
			} else {
2384
				$response = array(
2385
					'code'    => 'updates-available',
2386
					'message' => esc_html( sprintf( _n( '%s plugin need updating.', '%s plugins need updating.', $count, 'jetpack' ), $count ) ),
2387
					'count'   => $count,
2388
				);
2389
			}
2390
			return rest_ensure_response( $response );
2391
		}
2392
2393
		return new WP_Error( 'not_found', esc_html__( 'Could not check updates for plugins on this site.', 'jetpack' ), array( 'status' => 404 ) );
2394
	}
2395
2396
	/**
2397
	 * Get services that this site is verified with.
2398
	 *
2399
	 * @since 4.1.0
2400
	 *
2401
	 * @return mixed|WP_Error List of services that verified this site. Otherwise, a WP_Error instance with the corresponding error.
2402
	 */
2403
	public static function get_verified_services() {
2404
		if ( Jetpack::is_module_active( 'verification-tools' ) ) {
2405
			$verification_services_codes = get_option( 'verification_services_codes' );
2406
			if ( is_array( $verification_services_codes ) && ! empty( $verification_services_codes ) ) {
2407
				$services = array();
2408
				foreach ( jetpack_verification_services() as $name => $service ) {
2409
					if ( is_array( $service ) && ! empty( $verification_services_codes[ $name ] ) ) {
2410
						switch ( $name ) {
2411
							case 'google':
2412
								$services[] = 'Google';
2413
								break;
2414
							case 'bing':
2415
								$services[] = 'Bing';
2416
								break;
2417
							case 'pinterest':
2418
								$services[] = 'Pinterest';
2419
								break;
2420
						}
2421
					}
2422
				}
2423
				if ( ! empty( $services ) ) {
2424
					if ( 2 > count( $services ) ) {
2425
						$message = esc_html( sprintf( __( 'Your site is verified with %s.', 'jetpack' ), $services[0] ) );
2426
					} else {
2427
						$copy_services = $services;
2428
						$last = count( $copy_services ) - 1;
2429
						$last_service = $copy_services[ $last ];
2430
						unset( $copy_services[ $last ] );
2431
						$message = esc_html( sprintf( __( 'Your site is verified with %s and %s.', 'jetpack' ), join( ', ', $copy_services ), $last_service ) );
2432
					}
2433
					return rest_ensure_response( array(
2434
						'code'     => 'success',
2435
						'message'  => $message,
2436
						'services' => $services,
2437
					) );
2438
				}
2439
			}
2440
			return new WP_Error( 'empty', esc_html__( 'Site not verified with any service.', 'jetpack' ), array( 'status' => 404 ) );
2441
		}
2442
2443
		return new WP_Error( 'not_active', esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ), array( 'status' => 404 ) );
2444
	}
2445
2446
	/**
2447
	 * Get VaultPress site data including, among other things, the date of tge last backup if it was completed.
2448
	 *
2449
	 * @since 4.1.0
2450
	 *
2451
	 * @return mixed|WP_Error VaultPress site data. Otherwise, a WP_Error instance with the corresponding error.
2452
	 */
2453
	public static function vaultpress_get_site_data() {
2454
		if ( class_exists( 'VaultPress' ) ) {
2455
			$vaultpress = new VaultPress();
2456
			if ( ! $vaultpress->is_registered() ) {
2457
				return rest_ensure_response( array(
2458
					'code'    => 'not_registered',
2459
					'message' => esc_html( __( 'You need to register for VaultPress.', 'jetpack' ) )
2460
				) );
2461
			}
2462
			$data = json_decode( base64_decode( $vaultpress->contact_service( 'plugin_data' ) ) );
2463
			if ( is_wp_error( $data ) ) {
2464
				return $data;
2465
			} else {
2466
				return rest_ensure_response( array(
2467
					'code'    => 'success',
2468
					'message' => esc_html( sprintf( __( 'Your site was successfully backed-up %s ago.', 'jetpack' ), human_time_diff( $data->backups->last_backup, current_time( 'timestamp' ) ) ) ),
2469
					'data'    => $data,
2470
				) );
2471
			}
2472
		}
2473
2474
		return new WP_Error( 'not_active', esc_html__( 'The requested Jetpack module is not active.', 'jetpack' ), array( 'status' => 404 ) );
2475
	}
2476
2477
} // class end
2478