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