Completed
Push — add/sso-analytics ( 683a91...e67d7d )
by
unknown
162:06 queued 152:34
created

_inc/lib/class.core-rest-api-endpoints.php (8 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
		if ( Jetpack::is_development_mode() ) {
423
			return rest_ensure_response( 'dev' );
424
		}
425
		return Jetpack::is_active();
426
	}
427
428
	public static function recheck_ssl() {
429
		$result = Jetpack::permit_ssl( true );
430
		return array(
431
			'enabled' => $result,
432
			'message' => get_transient( 'jetpack_https_test_message' )
433
		);
434
	}
435
436
	/**
437
	 * Disconnects Jetpack from the WordPress.com Servers
438
	 *
439
	 * @uses Jetpack::disconnect();
440
	 * @since 4.1.0
441
	 * @return bool|WP_Error True if Jetpack successfully disconnected.
442
	 */
443
	public static function disconnect_site() {
444
		if ( Jetpack::is_active() ) {
445
			Jetpack::disconnect();
446
			return rest_ensure_response( array( 'code' => 'success' ) );
447
		}
448
449
		return new WP_Error( 'disconnect_failed', esc_html__( 'Was not able to disconnect the site.  Please try again.', 'jetpack' ), array( 'status' => 400 ) );
450
	}
451
452
	/**
453
	 * Gets a new connect URL with fresh nonce
454
	 *
455
	 * @uses Jetpack::disconnect();
456
	 * @since 4.1.0
457
	 * @return bool|WP_Error True if Jetpack successfully disconnected.
458
	 */
459
	public static function build_connect_url() {
460
		if ( require_once( ABSPATH . 'wp-admin/includes/plugin.php' ) ) {
461
			$url = Jetpack::init()->build_connect_url( true, false, false );
462
			return rest_ensure_response( $url );
463
		}
464
465
		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 ) );
466
	}
467
468
	/**
469
	 * Get miscellaneous settings for this Jetpack installation, like Holiday Snow.
470
	 *
471
	 * @since 4.1.0
472
	 *
473
	 * @return object $response {
474
	 *     Array of miscellaneous settings.
475
	 *
476
	 *     @type bool $holiday-snow Did Jack steal Christmas?
477
	 * }
478
	 */
479
	public static function get_settings() {
480
		$response = array(
481
			jetpack_holiday_snow_option_name() => get_option( jetpack_holiday_snow_option_name() ) == 'letitsnow',
482
		);
483
		return rest_ensure_response( $response );
484
	}
485
486
	/**
487
	 * Get miscellaneous user data related to the connection. Similar data available in old "My Jetpack".
488
	 * Information about the master/primary user.
489
	 * Information about the current user.
490
	 *
491
	 * @since 4.1.0
492
	 *
493
	 * @return object
494
	 */
495
	public static function get_user_connection_data() {
496
		require_once( JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class.jetpack-react-page.php' );
497
498
		$response = array(
499
			'othersLinked' => jetpack_get_other_linked_users(),
500
			'currentUser'  => jetpack_current_user_data(),
501
		);
502
		return rest_ensure_response( $response );
503
	}
504
505
506
507
	/**
508
	 * Update a single miscellaneous setting for this Jetpack installation, like Holiday Snow.
509
	 *
510
	 * @since 4.1.0
511
	 *
512
	 * @param WP_REST_Request $data
513
	 *
514
	 * @return object Jetpack miscellaneous settings.
515
	 */
516
	public static function update_setting( $data ) {
517
		// Get parameters to update the module.
518
		$param = $data->get_json_params();
519
520
		// Exit if no parameters were passed.
521 View Code Duplication
		if ( ! is_array( $param ) ) {
522
			return new WP_Error( 'missing_setting', esc_html__( 'Missing setting.', 'jetpack' ), array( 'status' => 404 ) );
523
		}
524
525
		// Get option name and value.
526
		$option = key( $param );
527
		$value  = current( $param );
528
529
		// Log success or not
530
		$updated = false;
531
532
		switch ( $option ) {
533
			case jetpack_holiday_snow_option_name():
534
				$updated = update_option( $option, ( true == (bool) $value ) ? 'letitsnow' : '' );
535
				break;
536
		}
537
538
		if ( $updated ) {
539
			return rest_ensure_response( array(
540
				'code' 	  => 'success',
541
				'message' => esc_html__( 'Setting updated.', 'jetpack' ),
542
				'value'   => $value,
543
			) );
544
		}
545
546
		return new WP_Error( 'setting_not_updated', esc_html__( 'The setting was not updated.', 'jetpack' ), array( 'status' => 400 ) );
547
	}
548
549
	/**
550
	 * Unlinks a user from the WordPress.com Servers.
551
	 * Default $data['id'] will default to current_user_id if no value is given.
552
	 *
553
	 * Example: '/unlink?id=1234'
554
	 *
555
	 * @since 4.1.0
556
	 * @uses  Jetpack::unlink_user
557
	 *
558
	 * @param WP_REST_Request $data {
559
	 *     Array of parameters received by request.
560
	 *
561
	 *     @type int $id ID of user to unlink.
562
	 * }
563
	 *
564
	 * @return bool|WP_Error True if user successfully unlinked.
565
	 */
566
	public static function unlink_user( $data ) {
567
		if ( isset( $data['id'] ) && Jetpack::unlink_user( $data['id'] ) ) {
568
			return rest_ensure_response(
569
				array(
570
					'code' => 'success'
571
				)
572
			);
573
		}
574
575
		return new WP_Error( 'unlink_user_failed', esc_html__( 'Was not able to unlink the user.  Please try again.', 'jetpack' ), array( 'status' => 400 ) );
576
	}
577
578
	/**
579
	 * Get site data, including for example, the site's current plan.
580
	 *
581
	 * @since 4.1.0
582
	 *
583
	 * @return array Array of Jetpack modules.
584
	 */
585
	public static function get_site_data() {
586
587
		if ( $site_id = Jetpack_Options::get_option( 'id' ) ) {
588
			$response = Jetpack_Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d', $site_id ), '1.1' );
589
590
			if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
591
				return new WP_Error( 'site_data_fetch_failed', esc_html__( 'Failed fetching site data. Try again later.', 'jetpack' ), array( 'status' => 400 ) );
592
			}
593
594
			return rest_ensure_response( array(
595
					'code' => 'success',
596
					'message' => esc_html__( 'Site data correctly received.', 'jetpack' ),
597
					'data' => wp_remote_retrieve_body( $response ),
598
				)
599
			);
600
		}
601
602
		return new WP_Error( 'site_id_missing', esc_html__( 'The ID of this site does not exist.', 'jetpack' ), array( 'status' => 404 ) );
603
	}
604
605
	/**
606
	 * Is Akismet registered and active?
607
	 *
608
	 * @since 4.1.0
609
	 *
610
	 * @return bool|WP_Error True if Akismet is active and registered. Otherwise, a WP_Error instance with the corresponding error.
611
	 */
612
	public static function akismet_is_active_and_registered() {
613
		if ( ! file_exists( WP_PLUGIN_DIR . '/akismet/class.akismet.php' ) ) {
614
			return new WP_Error( 'not_installed', esc_html__( 'Please install Akismet.', 'jetpack' ), array( 'status' => 400 ) );
615
		}
616
617
		if ( ! class_exists( 'Akismet' ) ) {
618
			return new WP_Error( 'not_active', esc_html__( 'Please activate Akismet.', 'jetpack' ), array( 'status' => 400 ) );
619
		}
620
621
		// What about if Akismet is put in a sub-directory or maybe in mu-plugins?
622
		require_once WP_PLUGIN_DIR . '/akismet/class.akismet.php';
623
		require_once WP_PLUGIN_DIR . '/akismet/class.akismet-admin.php';
624
		$akismet_key = Akismet::verify_key( Akismet::get_api_key() );
625
626
		if ( ! $akismet_key || 'invalid' === $akismet_key || 'failed' === $akismet_key ) {
627
			return new WP_Error( 'invalid_key', esc_html__( 'Invalid Akismet key. Please contact support.', 'jetpack' ), array( 'status' => 400 ) );
628
		}
629
630
		return true;
631
	}
632
633
	/**
634
	 * Get a list of all Jetpack modules and their information.
635
	 *
636
	 * @since 4.1.0
637
	 *
638
	 * @return array Array of Jetpack modules.
639
	 */
640
	public static function get_modules() {
641
		require_once( JETPACK__PLUGIN_DIR . 'class.jetpack-admin.php' );
642
643
		$modules = Jetpack_Admin::init()->get_modules();
644
		foreach ( $modules as $slug => $properties ) {
645
			$modules[ $slug ]['options'] = self::prepare_options_for_response( $slug );
646
		}
647
648
		return $modules;
649
	}
650
651
	/**
652
	 * Get information about a specific and valid Jetpack module.
653
	 *
654
	 * @since 4.1.0
655
	 *
656
	 * @param WP_REST_Request $data {
657
	 *     Array of parameters received by request.
658
	 *
659
	 *     @type string $slug Module slug.
660
	 * }
661
	 *
662
	 * @return mixed|void|WP_Error
663
	 */
664
	public static function get_module( $data ) {
665
		if ( Jetpack::is_module( $data['slug'] ) ) {
666
667
			$module = Jetpack::get_module( $data['slug'] );
668
669
			$module['options'] = self::prepare_options_for_response( $data['slug'] );
670
671
			return $module;
672
		}
673
674
		return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
675
	}
676
677
	/**
678
	 * If it's a valid Jetpack module, activate it.
679
	 *
680
	 * @since 4.1.0
681
	 *
682
	 * @param WP_REST_Request $data {
683
	 *     Array of parameters received by request.
684
	 *
685
	 *     @type string $slug Module slug.
686
	 * }
687
	 *
688
	 * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
689
	 */
690
	public static function activate_module( $data ) {
691
		if ( Jetpack::is_module( $data['slug'] ) ) {
692 View Code Duplication
			if ( Jetpack::activate_module( $data['slug'], false, false ) ) {
693
				return rest_ensure_response( array(
694
					'code' 	  => 'success',
695
					'message' => esc_html__( 'The requested Jetpack module was activated.', 'jetpack' ),
696
				) );
697
			}
698
			return new WP_Error( 'activation_failed', esc_html__( 'The requested Jetpack module could not be activated.', 'jetpack' ), array( 'status' => 424 ) );
699
		}
700
701
		return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
702
	}
703
704
	/**
705
	 * Activate a list of valid Jetpack modules.
706
	 *
707
	 * @since 4.1.0
708
	 *
709
	 * @param WP_REST_Request $data {
710
	 *     Array of parameters received by request.
711
	 *
712
	 *     @type string $slug Module slug.
713
	 * }
714
	 *
715
	 * @return bool|WP_Error True if modules were activated. Otherwise, a WP_Error instance with the corresponding error.
716
	 */
717
	public static function activate_modules( $data ) {
718
		$params = $data->get_json_params();
719
		if ( isset( $params['modules'] ) && is_array( $params['modules'] ) ) {
720
			$activated = array();
721
			$failed = array();
722
723
			foreach ( $params['modules'] as $module ) {
724
				if ( Jetpack::activate_module( $module, false, false ) ) {
725
					$activated[] = $module;
726
				} else {
727
					$failed[] = $module;
728
				}
729
			}
730
731
			if ( empty( $failed ) ) {
732
				return rest_ensure_response( array(
733
					'code' 	  => 'success',
734
					'message' => esc_html__( 'All modules activated.', 'jetpack' ),
735
				) );
736
			} else {
737
				$error = '';
738
739
				$activated_count = count( $activated );
740 View Code Duplication
				if ( $activated_count > 0 ) {
741
					$activated_last = array_pop( $activated );
742
					$activated_text = $activated_count > 1 ? sprintf(
743
						/* Translators: first variable is a list followed by a last item. Example: dog, cat and bird. */
744
						__( '%s and %s', 'jetpack' ),
745
						join( ', ', $activated ), $activated_last ) : $activated_last;
746
747
					$error = sprintf(
748
						/* Translators: the plural variable is a list followed by a last item. Example: dog, cat and bird. */
749
						_n( 'The module %s was activated.', 'The modules %s were activated.', $activated_count, 'jetpack' ),
750
						$activated_text ) . ' ';
751
				}
752
753
				$failed_count = count( $failed );
754 View Code Duplication
				if ( count( $failed ) > 0 ) {
755
					$failed_last = array_pop( $failed );
756
					$failed_text = $failed_count > 1 ? sprintf(
757
						/* Translators: first variable is a list followed by a last item. Example: dog, cat and bird. */
758
						__( '%s and %s', 'jetpack' ),
759
						join( ', ', $failed ), $failed_last ) : $failed_last;
760
761
					$error = sprintf(
762
						/* Translators: the plural variable is a list followed by a last item. Example: dog, cat and bird. */
763
						_n( 'The module %s failed to be activated.', 'The modules %s failed to be activated.', $failed_count, 'jetpack' ),
764
						$failed_text ) . ' ';
765
				}
766
			}
767
			return new WP_Error( 'activation_failed', esc_html( $error ), array( 'status' => 424 ) );
768
		}
769
770
		return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
771
	}
772
773
	/**
774
	 * Reset Jetpack options
775
	 *
776
	 * @since 4.1.0
777
	 *
778
	 * @param WP_REST_Request $data {
779
	 *     Array of parameters received by request.
780
	 *
781
	 *     @type string $options Available options to reset are options|modules
782
	 * }
783
	 *
784
	 * @return bool|WP_Error True if options were reset. Otherwise, a WP_Error instance with the corresponding error.
785
	 */
786
	public static function reset_jetpack_options( $data ) {
787
		if ( isset( $data['options'] ) ) {
788
			$data = $data['options'];
789
790
			switch( $data ) {
791
				case ( 'options' ) :
792
					$options_to_reset = Jetpack::get_jetpack_options_for_reset();
793
794
					// Reset the Jetpack options
795
					foreach ( $options_to_reset['jp_options'] as $option_to_reset ) {
796
						Jetpack_Options::delete_option( $option_to_reset );
797
					}
798
799
					foreach ( $options_to_reset['wp_options'] as $option_to_reset ) {
800
						delete_option( $option_to_reset );
801
					}
802
803
					// Reset to default modules
804
					$default_modules = Jetpack::get_default_modules();
805
					Jetpack_Options::update_option( 'active_modules', $default_modules );
806
807
					// Jumpstart option is special
808
					Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
809
					return rest_ensure_response( array(
810
						'code' 	  => 'success',
811
						'message' => esc_html__( 'Jetpack options reset.', 'jetpack' ),
812
					) );
813
					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...
814
815
				case 'modules':
816
					$default_modules = Jetpack::get_default_modules();
817
					Jetpack_Options::update_option( 'active_modules', $default_modules );
818
819
					return rest_ensure_response( array(
820
						'code' 	  => 'success',
821
						'message' => esc_html__( 'Modules reset to default.', 'jetpack' ),
822
					) );
823
					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...
824
825
				default:
826
					return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
827
			}
828
		}
829
830
		return new WP_Error( 'required_param', esc_html__( 'Missing parameter "type".', 'jetpack' ), array( 'status' => 404 ) );
831
	}
832
833
	/**
834
	 * Activates a series of valid Jetpack modules and initializes some options.
835
	 *
836
	 * @since 4.1.0
837
	 *
838
	 * @param WP_REST_Request $data {
839
	 *     Array of parameters received by request.
840
	 * }
841
	 *
842
	 * @return bool|WP_Error True if Jumpstart succeeded. Otherwise, a WP_Error instance with the corresponding error.
843
	 */
844
	public static function jumpstart_activate( $data ) {
845
		$modules = Jetpack::get_available_modules();
846
		$activate_modules = array();
847
		foreach ( $modules as $module ) {
848
			$module_info = Jetpack::get_module( $module );
849
			if ( isset( $module_info['feature'] ) && is_array( $module_info['feature'] ) && in_array( 'Jumpstart', $module_info['feature'] ) ) {
850
				$activate_modules[] = $module;
851
			}
852
		}
853
854
		// Collect success/error messages like modules that are properly activated.
855
		$result = array(
856
			'activated_modules' => array(),
857
			'failed_modules'    => array(),
858
		);
859
860
		// Update the jumpstart option
861
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
862
			$result['jumpstart_activated'] = Jetpack_Options::update_option( 'jumpstart', 'jumpstart_activated' );
863
		}
864
865
		// Check for possible conflicting plugins
866
		$module_slugs_filtered = Jetpack::init()->filter_default_modules( $activate_modules );
867
868
		foreach ( $module_slugs_filtered as $module_slug ) {
869
			Jetpack::log( 'activate', $module_slug );
870
			if ( Jetpack::activate_module( $module_slug, false, false ) ) {
871
				$result['activated_modules'][] = $module_slug;
872
			} else {
873
				$result['failed_modules'][] = $module_slug;
874
			}
875
			Jetpack::state( 'message', 'no_message' );
876
		}
877
878
		// Set the default sharing buttons and set to display on posts if none have been set.
879
		$sharing_services = get_option( 'sharing-services' );
880
		$sharing_options  = get_option( 'sharing-options' );
881
		if ( empty( $sharing_services['visible'] ) ) {
882
			// Default buttons to set
883
			$visible = array(
884
				'twitter',
885
				'facebook',
886
				'google-plus-1',
887
			);
888
			$hidden = array();
889
890
			// Set some sharing settings
891
			$sharing = new Sharing_Service();
892
			$sharing_options['global'] = array(
893
				'button_style'  => 'icon',
894
				'sharing_label' => $sharing->default_sharing_label,
895
				'open_links'    => 'same',
896
				'show'          => array( 'post' ),
897
				'custom'        => isset( $sharing_options['global']['custom'] ) ? $sharing_options['global']['custom'] : array()
898
			);
899
900
			$result['sharing_options']  = update_option( 'sharing-options', $sharing_options );
901
			$result['sharing_services'] = update_option( 'sharing-services', array( 'visible' => $visible, 'hidden' => $hidden ) );
902
		}
903
904
		// If all Jumpstart modules were activated
905
		if ( empty( $result['failed_modules'] ) ) {
906
			return rest_ensure_response( array(
907
				'code' 	  => 'success',
908
				'message' => esc_html__( 'Jumpstart done.', 'jetpack' ),
909
				'data'    => $result,
910
			) );
911
		}
912
913
		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 ) );
914
	}
915
916
	/**
917
	 * Dismisses Jumpstart so user is not prompted to go through it again.
918
	 *
919
	 * @since 4.1.0
920
	 *
921
	 * @param WP_REST_Request $data {
922
	 *     Array of parameters received by request.
923
	 * }
924
	 *
925
	 * @return bool|WP_Error True if Jumpstart was disabled or was nothing to dismiss. Otherwise, a WP_Error instance with a message.
926
	 */
927
	public static function jumpstart_deactivate( $data ) {
928
929
		// If dismissed, flag the jumpstart option as such.
930
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
931
			if ( Jetpack_Options::update_option( 'jumpstart', 'jumpstart_dismissed' ) ) {
932
				return rest_ensure_response( array(
933
					'code' 	  => 'success',
934
					'message' => esc_html__( 'Jumpstart dismissed.', 'jetpack' ),
935
				) );
936
			} else {
937
				return new WP_Error( 'jumpstart_failed_dismiss', esc_html__( 'Jumpstart could not be dismissed.', 'jetpack' ), array( 'status' => 400 ) );
938
			}
939
		}
940
941
		// If this was not a new connection and there was nothing to dismiss, don't fail.
942
		return rest_ensure_response( array(
943
			'code' 	  => 'success',
944
			'message' => esc_html__( 'Nothing to dismiss. This was not a new connection.', 'jetpack' ),
945
		) );
946
	}
947
948
	/**
949
	 * If it's a valid Jetpack module, deactivate it.
950
	 *
951
	 * @since 4.1.0
952
	 *
953
	 * @param WP_REST_Request $data {
954
	 *     Array of parameters received by request.
955
	 *
956
	 *     @type string $slug Module slug.
957
	 * }
958
	 *
959
	 * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
960
	 */
961
	public static function deactivate_module( $data ) {
962
		if ( Jetpack::is_module( $data['slug'] ) ) {
963 View Code Duplication
			if ( ! Jetpack::is_module_active( $data['slug'] ) ) {
964
				return new WP_Error( 'already_inactive', esc_html__( 'The requested Jetpack module was already inactive.', 'jetpack' ), array( 'status' => 409 ) );
965
			}
966 View Code Duplication
			if ( Jetpack::deactivate_module( $data['slug'] ) ) {
967
				return rest_ensure_response( array(
968
					'code' 	  => 'success',
969
					'message' => esc_html__( 'The requested Jetpack module was deactivated.', 'jetpack' ),
970
				) );
971
			}
972
			return new WP_Error( 'deactivation_failed', esc_html__( 'The requested Jetpack module could not be deactivated.', 'jetpack' ), array( 'status' => 400 ) );
973
		}
974
975
		return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
976
	}
977
978
	/**
979
	 * If it's a valid Jetpack module and configuration parameters have been sent, update it.
980
	 *
981
	 * @since 4.1.0
982
	 *
983
	 * @param WP_REST_Request $data {
984
	 *     Array of parameters received by request.
985
	 *
986
	 *     @type string $slug Module slug.
987
	 * }
988
	 *
989
	 * @return bool|WP_Error True if module was updated. Otherwise, a WP_Error instance with the corresponding error.
990
	 */
991
	public static function update_module( $data ) {
992
		if ( ! Jetpack::is_module( $data['slug'] ) ) {
993
			return new WP_Error( 'not_found', esc_html__( 'The requested Jetpack module was not found.', 'jetpack' ), array( 'status' => 404 ) );
994
		}
995
996 View Code Duplication
		if ( ! Jetpack::is_module_active( $data['slug'] ) ) {
997
			return new WP_Error( 'inactive', esc_html__( 'The requested Jetpack module is inactive.', 'jetpack' ), array( 'status' => 409 ) );
998
		}
999
1000
		// Get parameters to update the module.
1001
		$param = $data->get_json_params();
1002
1003
		// Exit if no parameters were passed.
1004 View Code Duplication
		if ( ! is_array( $param ) ) {
1005
			return new WP_Error( 'missing_option', esc_html__( 'Missing option.', 'jetpack' ), array( 'status' => 404 ) );
1006
		}
1007
1008
		// Get option name and value.
1009
		$option = key( $param );
1010
		$value  = current( $param );
1011
1012
		// Get available module options.
1013
		$options = self::get_module_available_options();
1014
1015
		// If option is invalid, don't go any further.
1016
		if ( ! in_array( $option, array_keys( $options ) ) ) {
1017
			return new WP_Error( 'invalid_param', esc_html(	sprintf( __( 'The option %s is invalid for this module.', 'jetpack' ), $option ) ), array( 'status' => 404 ) );
1018
		}
1019
1020
		// Used if response is successful. The message can be overwritten and additional data can be added here.
1021
		$response = array(
1022
			'code' 	  => 'success',
1023
			'message' => esc_html__( 'The requested Jetpack module was updated.', 'jetpack' ),
1024
		);
1025
1026
		// Used if there was an error. Can be overwritten with specific error messages.
1027
		/* Translators: the variable is a module option name. */
1028
		$error = sprintf( __( 'The option %s was not updated.', 'jetpack' ), $option );
1029
1030
		// Set to true if the option update was successful.
1031
		$updated = false;
1032
1033
		// Properly cast value based on its type defined in endpoint accepted args.
1034
		$value = self::cast_value( $value, $options[ $option ] );
1035
1036
		switch ( $option ) {
1037
			case 'monitor_receive_notifications':
1038
				$monitor = new Jetpack_Monitor();
1039
1040
				// If we got true as response, consider it done.
1041
				$updated = true === $monitor->update_option_receive_jetpack_monitor_notification( $value );
1042
				break;
1043
1044
			case 'post_by_email_address':
1045
				$post_by_email = new Jetpack_Post_By_Email();
0 ignored issues
show
$post_by_email is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

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