Completed
Push — update/videopress-transcode-al... ( ffe79d...2d3973 )
by Kirk
13:06 queued 05:54
created

_inc/lib/class.core-rest-api-endpoints.php (1 issue)

Severity

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
use Automattic\Jetpack\Connection\Client;
4
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
5
use Automattic\Jetpack\JITM;
6
use Automattic\Jetpack\Tracking;
7
8
/**
9
 * Register WP REST API endpoints for Jetpack.
10
 *
11
 * @author Automattic
12
 */
13
14
/**
15
 * Disable direct access.
16
 */
17
if ( ! defined( 'ABSPATH' ) ) {
18
	exit;
19
}
20
21
// Load WP_Error for error messages.
22
require_once ABSPATH . '/wp-includes/class-wp-error.php';
23
24
// Register endpoints when WP REST API is initialized.
25
add_action( 'rest_api_init', array( 'Jetpack_Core_Json_Api_Endpoints', 'register_endpoints' ) );
26
// Load API endpoints that are synced with WP.com
27
// Each of these is a class that will register its own routes on 'rest_api_init'.
28
require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/load-wpcom-endpoints.php';
29
30
/**
31
 * Class Jetpack_Core_Json_Api_Endpoints
32
 *
33
 * @since 4.3.0
34
 */
35
class Jetpack_Core_Json_Api_Endpoints {
36
37
	/**
38
	 * @var string Generic error message when user is not allowed to perform an action.
39
	 */
40
	public static $user_permissions_error_msg;
41
42
	/**
43
	 * @var array Roles that can access Stats once they're granted access.
44
	 */
45
	public static $stats_roles;
46
47
	/**
48
	 * Declare the Jetpack REST API endpoints.
49
	 *
50
	 * @since 4.3.0
51
	 */
52
	public static function register_endpoints() {
53
54
		// Load API endpoint base classes
55
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-xmlrpc-consumer-endpoint.php';
56
57
		// Load API endpoints
58
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-module-endpoints.php';
59
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-site-endpoints.php';
60
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-widgets-endpoints.php';
61
62
		self::$user_permissions_error_msg = esc_html__(
63
			'You do not have the correct user permissions to perform this action.
64
			Please contact your site admin if you think this is a mistake.',
65
			'jetpack'
66
		);
67
68
		self::$stats_roles = array( 'administrator', 'editor', 'author', 'contributor', 'subscriber' );
69
70
		$ixr_client = new Jetpack_IXR_Client( array( 'user_id' => get_current_user_id() ) );
71
		$core_api_endpoint = new Jetpack_Core_API_Data( $ixr_client );
72
		$module_list_endpoint = new Jetpack_Core_API_Module_List_Endpoint();
73
		$module_data_endpoint = new Jetpack_Core_API_Module_Data_Endpoint();
74
		$module_toggle_endpoint = new Jetpack_Core_API_Module_Toggle_Endpoint( new Jetpack_IXR_Client() );
75
		$site_endpoint = new Jetpack_Core_API_Site_Endpoint();
76
		$widget_endpoint = new Jetpack_Core_API_Widget_Endpoint();
77
78
		register_rest_route( 'jetpack/v4', 'plans', array(
79
			'methods'             => WP_REST_Server::READABLE,
80
			'callback'            => __CLASS__ . '::get_plans',
81
			'permission_callback' => __CLASS__ . '::connect_url_permission_callback',
82
83
		) );
84
85
		register_rest_route( 'jetpack/v4', 'marketing/survey', array(
86
			'methods'             => WP_REST_Server::CREATABLE,
87
			'callback'            => __CLASS__ . '::submit_survey',
88
			'permission_callback' => __CLASS__ . '::disconnect_site_permission_callback',
89
90
		) );
91
92
		register_rest_route( 'jetpack/v4', '/jitm', array(
93
			'methods'  => WP_REST_Server::READABLE,
94
			'callback' => __CLASS__ . '::get_jitm_message',
95
		) );
96
97
		register_rest_route( 'jetpack/v4', '/jitm', array(
98
			'methods'  => WP_REST_Server::CREATABLE,
99
			'callback' => __CLASS__ . '::delete_jitm_message'
100
		) );
101
102
		// Authorize a remote user
103
		register_rest_route( 'jetpack/v4', '/remote_authorize', array(
104
			'methods' => WP_REST_Server::EDITABLE,
105
			'callback' => __CLASS__ . '::remote_authorize',
106
		) );
107
108
		// Get current connection status of Jetpack
109
		register_rest_route( 'jetpack/v4', '/connection', array(
110
			'methods' => WP_REST_Server::READABLE,
111
			'callback' => __CLASS__ . '::jetpack_connection_status',
112
		) );
113
114
		// Test current connection status of Jetpack
115
		register_rest_route( 'jetpack/v4', '/connection/test', array(
116
			'methods' => WP_REST_Server::READABLE,
117
			'callback' => __CLASS__ . '::jetpack_connection_test',
118
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
119
		) );
120
121
		// Endpoint specific for privileged servers to request detailed debug information.
122
		register_rest_route( 'jetpack/v4', '/connection/test-wpcom/', array(
123
			'methods' => WP_REST_Server::READABLE,
124
			'callback' => __CLASS__ . '::jetpack_connection_test_for_external',
125
			'permission_callback' => __CLASS__ . '::view_jetpack_connection_test_check',
126
		) );
127
128
		register_rest_route( 'jetpack/v4', '/rewind', array(
129
			'methods' => WP_REST_Server::READABLE,
130
			'callback' => __CLASS__ . '::get_rewind_data',
131
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
132
		) );
133
134
		// Fetches a fresh connect URL
135
		register_rest_route( 'jetpack/v4', '/connection/url', array(
136
			'methods' => WP_REST_Server::READABLE,
137
			'callback' => __CLASS__ . '::build_connect_url',
138
			'permission_callback' => __CLASS__ . '::connect_url_permission_callback',
139
		) );
140
141
		// Get current user connection data
142
		register_rest_route( 'jetpack/v4', '/connection/data', array(
143
			'methods' => WP_REST_Server::READABLE,
144
			'callback' => __CLASS__ . '::get_user_connection_data',
145
			'permission_callback' => __CLASS__ . '::get_user_connection_data_permission_callback',
146
		) );
147
148
		// Start the connection process by registering the site on WordPress.com servers.
149
		register_rest_route( 'jetpack/v4', '/connection/register', array(
150
			'methods'             => WP_REST_Server::EDITABLE,
151
			'callback'            => __CLASS__ . '::register_site',
152
			'permission_callback' => __CLASS__ . '::connect_url_permission_callback',
153
			'args'                => array(
154
				'registration_nonce' => array( 'type' => 'string' ),
155
			),
156
		) );
157
158
		// Set the connection owner
159
		register_rest_route( 'jetpack/v4', '/connection/owner', array(
160
			'methods' => WP_REST_Server::EDITABLE,
161
			'callback' => __CLASS__ . '::set_connection_owner',
162
			'permission_callback' => __CLASS__ . '::set_connection_owner_permission_callback',
163
		) );
164
165
		// Current user: get or set tracking settings.
166
		register_rest_route( 'jetpack/v4', '/tracking/settings', array(
167
			array(
168
				'methods'             => WP_REST_Server::READABLE,
169
				'callback'            => __CLASS__ . '::get_user_tracking_settings',
170
				'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
171
			),
172
			array(
173
				'methods'             => WP_REST_Server::EDITABLE,
174
				'callback'            => __CLASS__ . '::update_user_tracking_settings',
175
				'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
176
				'args'                => array(
177
					'tracks_opt_out' => array( 'type' => 'boolean' ),
178
				),
179
			),
180
		) );
181
182
		// Disconnect site from WordPress.com servers
183
		register_rest_route( 'jetpack/v4', '/connection', array(
184
			'methods' => WP_REST_Server::EDITABLE,
185
			'callback' => __CLASS__ . '::disconnect_site',
186
			'permission_callback' => __CLASS__ . '::disconnect_site_permission_callback',
187
		) );
188
189
		// Disconnect/unlink user from WordPress.com servers
190
		register_rest_route( 'jetpack/v4', '/connection/user', array(
191
			'methods' => WP_REST_Server::EDITABLE,
192
			'callback' => __CLASS__ . '::unlink_user',
193
			'permission_callback' => __CLASS__ . '::unlink_user_permission_callback',
194
		) );
195
196
		// Get current site data
197
		register_rest_route( 'jetpack/v4', '/site', array(
198
			'methods' => WP_REST_Server::READABLE,
199
			'callback' => __CLASS__ . '::get_site_data',
200
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
201
		) );
202
203
		// Get current site data
204
		register_rest_route( 'jetpack/v4', '/site/features', array(
205
			'methods' => WP_REST_Server::READABLE,
206
			'callback' => array( $site_endpoint, 'get_features' ),
207
			'permission_callback' => array( $site_endpoint , 'can_request' ),
208
		) );
209
210
		// Get current site benefits
211
		register_rest_route( 'jetpack/v4', '/site/benefits', array(
212
			'methods'             => WP_REST_Server::READABLE,
213
			'callback'            => array( $site_endpoint, 'get_benefits' ),
214
			'permission_callback' => array( $site_endpoint, 'can_request' ),
215
		) );
216
217
		// Get Activity Log data for this site.
218
		register_rest_route( 'jetpack/v4', '/site/activity', array(
219
			'methods' => WP_REST_Server::READABLE,
220
			'callback' => __CLASS__ . '::get_site_activity',
221
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
222
		) );
223
224
		// Confirm that a site in identity crisis should be in staging mode
225
		register_rest_route( 'jetpack/v4', '/identity-crisis/confirm-safe-mode', array(
226
			'methods' => WP_REST_Server::EDITABLE,
227
			'callback' => __CLASS__ . '::confirm_safe_mode',
228
			'permission_callback' => __CLASS__ . '::identity_crisis_mitigation_permission_check',
229
		) );
230
231
		// IDC resolve: create an entirely new shadow site for this URL.
232
		register_rest_route( 'jetpack/v4', '/identity-crisis/start-fresh', array(
233
			'methods' => WP_REST_Server::EDITABLE,
234
			'callback' => __CLASS__ . '::start_fresh_connection',
235
			'permission_callback' => __CLASS__ . '::identity_crisis_mitigation_permission_check',
236
		) );
237
238
		// Handles the request to migrate stats and subscribers during an identity crisis.
239
		register_rest_route( 'jetpack/v4', 'identity-crisis/migrate', array(
240
			'methods' => WP_REST_Server::EDITABLE,
241
			'callback' => __CLASS__ . '::migrate_stats_and_subscribers',
242
			'permissison_callback' => __CLASS__ . '::identity_crisis_mitigation_permission_check',
243
		) );
244
245
		// Return all modules
246
		register_rest_route( 'jetpack/v4', '/module/all', array(
247
			'methods' => WP_REST_Server::READABLE,
248
			'callback' => array( $module_list_endpoint, 'process' ),
249
			'permission_callback' => array( $module_list_endpoint, 'can_request' ),
250
		) );
251
252
		// Activate many modules
253
		register_rest_route( 'jetpack/v4', '/module/all/active', array(
254
			'methods' => WP_REST_Server::EDITABLE,
255
			'callback' => array( $module_list_endpoint, 'process' ),
256
			'permission_callback' => array( $module_list_endpoint, 'can_request' ),
257
			'args' => array(
258
				'modules' => array(
259
					'default'           => '',
260
					'type'              => 'array',
261
					'items'             => array(
262
						'type'          => 'string',
263
					),
264
					'required'          => true,
265
					'validate_callback' => __CLASS__ . '::validate_module_list',
266
				),
267
				'active' => array(
268
					'default'           => true,
269
					'type'              => 'boolean',
270
					'required'          => false,
271
					'validate_callback' => __CLASS__ . '::validate_boolean',
272
				),
273
			)
274
		) );
275
276
		// Return a single module and update it when needed
277
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)', array(
278
			'methods' => WP_REST_Server::READABLE,
279
			'callback' => array( $core_api_endpoint, 'process' ),
280
			'permission_callback' => array( $core_api_endpoint, 'can_request' ),
281
		) );
282
283
		// Activate and deactivate a module
284
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)/active', array(
285
			'methods' => WP_REST_Server::EDITABLE,
286
			'callback' => array( $module_toggle_endpoint, 'process' ),
287
			'permission_callback' => array( $module_toggle_endpoint, 'can_request' ),
288
			'args' => array(
289
				'active' => array(
290
					'default'           => true,
291
					'type'              => 'boolean',
292
					'required'          => true,
293
					'validate_callback' => __CLASS__ . '::validate_boolean',
294
				),
295
			)
296
		) );
297
298
		// Update a module
299
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)', array(
300
			'methods' => WP_REST_Server::EDITABLE,
301
			'callback' => array( $core_api_endpoint, 'process' ),
302
			'permission_callback' => array( $core_api_endpoint, 'can_request' ),
303
			'args' => self::get_updateable_parameters( 'any' )
304
		) );
305
306
		// Get data for a specific module, i.e. Protect block count, WPCOM stats,
307
		// Akismet spam count, etc.
308
		register_rest_route( 'jetpack/v4', '/module/(?P<slug>[a-z\-]+)/data', array(
309
			'methods' => WP_REST_Server::READABLE,
310
			'callback' => array( $module_data_endpoint, 'process' ),
311
			'permission_callback' => array( $module_data_endpoint, 'can_request' ),
312
			'args' => array(
313
				'range' => array(
314
					'default'           => 'day',
315
					'type'              => 'string',
316
					'required'          => false,
317
					'validate_callback' => __CLASS__ . '::validate_string',
318
				),
319
			)
320
		) );
321
322
		// Check if the API key for a specific service is valid or not
323
		register_rest_route( 'jetpack/v4', '/module/(?P<service>[a-z\-]+)/key/check', array(
324
			'methods' => WP_REST_Server::READABLE,
325
			'callback' => array( $module_data_endpoint, 'key_check' ),
326
			'permission_callback' => __CLASS__ . '::update_settings_permission_check',
327
			'sanitize_callback' => 'sanitize_text_field',
328
		) );
329
330
		register_rest_route( 'jetpack/v4', '/module/(?P<service>[a-z\-]+)/key/check', array(
331
			'methods' => WP_REST_Server::EDITABLE,
332
			'callback' => array( $module_data_endpoint, 'key_check' ),
333
			'permission_callback' => __CLASS__ . '::update_settings_permission_check',
334
			'sanitize_callback' => 'sanitize_text_field',
335
			'args' => array(
336
				'api_key' => array(
337
					'default'           => '',
338
					'type'              => 'string',
339
					'validate_callback' => __CLASS__ . '::validate_alphanum',
340
				),
341
			)
342
		) );
343
344
		// Update any Jetpack module option or setting
345
		register_rest_route( 'jetpack/v4', '/settings', array(
346
			'methods' => WP_REST_Server::EDITABLE,
347
			'callback' => array( $core_api_endpoint, 'process' ),
348
			'permission_callback' => array( $core_api_endpoint, 'can_request' ),
349
			'args' => self::get_updateable_parameters( 'any' )
350
		) );
351
352
		// Update a module
353
		register_rest_route( 'jetpack/v4', '/settings/(?P<slug>[a-z\-]+)', array(
354
			'methods' => WP_REST_Server::EDITABLE,
355
			'callback' => array( $core_api_endpoint, 'process' ),
356
			'permission_callback' => array( $core_api_endpoint, 'can_request' ),
357
			'args' => self::get_updateable_parameters()
358
		) );
359
360
		// Return all module settings
361
		register_rest_route( 'jetpack/v4', '/settings/', array(
362
			'methods' => WP_REST_Server::READABLE,
363
			'callback' => array( $core_api_endpoint, 'process' ),
364
			'permission_callback' => array( $core_api_endpoint, 'can_request' ),
365
		) );
366
367
		// Reset all Jetpack options
368
		register_rest_route( 'jetpack/v4', '/options/(?P<options>[a-z\-]+)', array(
369
			'methods' => WP_REST_Server::EDITABLE,
370
			'callback' => __CLASS__ . '::reset_jetpack_options',
371
			'permission_callback' => __CLASS__ . '::manage_modules_permission_check',
372
		) );
373
374
		// Updates: get number of plugin updates available
375
		register_rest_route( 'jetpack/v4', '/updates/plugins', array(
376
			'methods' => WP_REST_Server::READABLE,
377
			'callback' => __CLASS__ . '::get_plugin_update_count',
378
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
379
		) );
380
381
		// Dismiss Jetpack Notices
382
		register_rest_route( 'jetpack/v4', '/notice/(?P<notice>[a-z\-_]+)', array(
383
			'methods' => WP_REST_Server::EDITABLE,
384
			'callback' => __CLASS__ . '::dismiss_notice',
385
			'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
386
		) );
387
388
		// Plugins: get list of all plugins.
389
		register_rest_route( 'jetpack/v4', '/plugins', array(
390
			'methods' => WP_REST_Server::READABLE,
391
			'callback' => __CLASS__ . '::get_plugins',
392
			'permission_callback' => __CLASS__ . '::activate_plugins_permission_check',
393
		) );
394
395
		register_rest_route( 'jetpack/v4', '/plugins/akismet/activate', array(
396
			'methods' => WP_REST_Server::EDITABLE,
397
			'callback' => __CLASS__ . '::activate_akismet',
398
			'permission_callback' => __CLASS__ . '::activate_plugins_permission_check',
399
		) );
400
401
		// Plugins: check if the plugin is active.
402
		register_rest_route( 'jetpack/v4', '/plugin/(?P<plugin>[a-z\/\.\-_]+)', array(
403
			'methods' => WP_REST_Server::READABLE,
404
			'callback' => __CLASS__ . '::get_plugin',
405
			'permission_callback' => __CLASS__ . '::activate_plugins_permission_check',
406
		) );
407
408
		// Widgets: get information about a widget that supports it.
409
		register_rest_route( 'jetpack/v4', '/widgets/(?P<id>[0-9a-z\-_]+)', array(
410
			'methods' => WP_REST_Server::READABLE,
411
			'callback' => array( $widget_endpoint, 'process' ),
412
			'permission_callback' => array( $widget_endpoint, 'can_request' ),
413
		) );
414
415
		// Site Verify: check if the site is verified, and a get verification token if not
416
		register_rest_route( 'jetpack/v4', '/verify-site/(?P<service>[a-z\-_]+)', array(
417
			'methods' => WP_REST_Server::READABLE,
418
			'callback' => __CLASS__ . '::is_site_verified_and_token',
419
			'permission_callback' => __CLASS__ . '::update_settings_permission_check',
420
		) );
421
422
		register_rest_route( 'jetpack/v4', '/verify-site/(?P<service>[a-z\-_]+)/(?<keyring_id>[0-9]+)', array(
423
			'methods' => WP_REST_Server::READABLE,
424
			'callback' => __CLASS__ . '::is_site_verified_and_token',
425
			'permission_callback' => __CLASS__ . '::update_settings_permission_check',
426
		) );
427
428
		// Site Verify: tell a service to verify the site
429
		register_rest_route( 'jetpack/v4', '/verify-site/(?P<service>[a-z\-_]+)', array(
430
			'methods' => WP_REST_Server::EDITABLE,
431
			'callback' => __CLASS__ . '::verify_site',
432
			'permission_callback' => __CLASS__ . '::update_settings_permission_check',
433
			'args' => array(
434
				'keyring_id' => array(
435
					'required'          => true,
436
					'type'              => 'integer',
437
					'validate_callback' => __CLASS__  . '::validate_posint',
438
				),
439
			)
440
		) );
441
442
		// Get and set API keys.
443
		// Note: permission_callback intentionally omitted from the GET method.
444
		// Map block requires open access to API keys on the front end.
445
		register_rest_route(
446
			'jetpack/v4',
447
			'/service-api-keys/(?P<service>[a-z\-_]+)',
448
			array(
449
				array(
450
					'methods'             => WP_REST_Server::READABLE,
451
					'callback'            => __CLASS__ . '::get_service_api_key',
452
				),
453
				array(
454
					'methods'             => WP_REST_Server::EDITABLE,
455
					'callback'            => __CLASS__ . '::update_service_api_key',
456
					'permission_callback' => array( 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys','edit_others_posts_check' ),
457
					'args'                => array(
458
						'service_api_key' => array(
459
							'required' => true,
460
							'type'     => 'text',
461
						),
462
					),
463
				),
464
				array(
465
					'methods'             => WP_REST_Server::DELETABLE,
466
					'callback'            => __CLASS__ . '::delete_service_api_key',
467
					'permission_callback' => array( 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys','edit_others_posts_check' ),
468
				),
469
			)
470
		);
471
472
		register_rest_route(
473
			'jetpack/v4',
474
			'/mobile/send-login-email',
475
			array(
476
				'methods'             => WP_REST_Server::EDITABLE,
477
				'callback'            => __CLASS__ . '::send_mobile_magic_link',
478
				'permission_callback' => __CLASS__ . '::view_admin_page_permission_check',
479
			)
480
		);
481
	}
482
483 View Code Duplication
	public static function get_plans( $request ) {
484
		$request = Client::wpcom_json_api_request_as_user(
485
			'/plans?_locale=' . get_user_locale(),
486
			'2',
487
			array(
488
				'method'  => 'GET',
489
				'headers' => array(
490
					'X-Forwarded-For' => Jetpack::current_user_ip( true ),
491
				),
492
			)
493
		);
494
495
		$body = wp_remote_retrieve_body( $request );
496
		if ( 200 === wp_remote_retrieve_response_code( $request ) ) {
497
			$data = $body;
498
		} else {
499
			// something went wrong so we'll just return the response without caching
500
			return $body;
501
		}
502
503
		return $data;
504
	}
505
506 View Code Duplication
	public static function submit_survey( $request ) {
507
508
		$wpcom_request = Client::wpcom_json_api_request_as_user(
509
			'/marketing/survey',
510
			'v2',
511
			array(
512
				'method'  => 'POST',
513
				'headers' => array(
514
					'Content-Type'    => 'application/json',
515
					'X-Forwarded-For' => Jetpack::current_user_ip( true ),
516
				),
517
			),
518
			$request->get_json_params()
519
		);
520
521
		$wpcom_request_body = json_decode( wp_remote_retrieve_body( $wpcom_request ) );
522
		if ( 200 === wp_remote_retrieve_response_code( $wpcom_request ) ) {
523
			$data = $wpcom_request_body;
524
		} else {
525
			// something went wrong so we'll just return the response without caching
526
			return $wpcom_request_body;
527
		}
528
529
		return $data;
530
	}
531
532
	/**
533
	 * Asks for a jitm, unless they've been disabled, in which case it returns an empty array
534
	 *
535
	 * @param $request WP_REST_Request
536
	 *
537
	 * @return array An array of jitms
538
	 */
539
	public static function get_jitm_message( $request ) {
540
		$jitm = new JITM();
541
542
		if ( ! $jitm->register() ) {
543
			return array();
544
		}
545
546
		return $jitm->get_messages( $request['message_path'], urldecode_deep( $request['query'] ) );
547
	}
548
549
	/**
550
	 * Dismisses a jitm
551
	 * @param $request WP_REST_Request The request
552
	 *
553
	 * @return bool Always True
554
	 */
555
	public static function delete_jitm_message( $request ) {
556
		$jitm = new JITM();
557
558
		if ( ! $jitm->register() ) {
559
			return true;
560
		}
561
562
		return $jitm->dismiss( $request['id'], $request['feature_class'] );
563
	}
564
565
	/**
566
	 * Checks if this site has been verified using a service - only 'google' supported at present - and a specfic
567
	 *  keyring to use to get the token if it is not
568
	 *
569
	 * Returns 'verified' = true/false, and a token if 'verified' is false and site is ready for verification
570
	 *
571
	 * @since 6.6.0
572
	 *
573
	 * @param WP_REST_Request $request The request sent to the WP REST API.
574
	 *
575
	 * @return array|wp-error
576
	 */
577
	public static function is_site_verified_and_token( $request ) {
578
		/**
579
		 * Return an error if the site uses a Maintenance / Coming Soon plugin
580
		 * and if the plugin is configured to make the site private.
581
		 *
582
		 * We currently handle the following plugins:
583
		 * - https://github.com/mojoness/mojo-marketplace-wp-plugin (used by bluehost)
584
		 * - https://wordpress.org/plugins/mojo-under-construction
585
		 * - https://wordpress.org/plugins/under-construction-page
586
		 * - https://wordpress.org/plugins/ultimate-under-construction
587
		 * - https://wordpress.org/plugins/coming-soon
588
		 *
589
		 * You can handle this in your own plugin thanks to the `jetpack_is_under_construction_plugin` filter.
590
		 * If the filter returns true, we will consider the site as under construction.
591
		 */
592
		$mm_coming_soon                       = get_option( 'mm_coming_soon', null );
593
		$under_construction_activation_status = get_option( 'underConstructionActivationStatus', null );
594
		$ucp_options                          = get_option( 'ucp_options', array() );
595
		$uuc_settings                         = get_option( 'uuc_settings', array() );
596
		$csp4                                 = get_option( 'seed_csp4_settings_content', array() );
597
		if (
598
			( Jetpack::is_plugin_active( 'mojo-marketplace-wp-plugin/mojo-marketplace.php' ) && 'true' === $mm_coming_soon )
599
			|| Jetpack::is_plugin_active( 'mojo-under-construction/mojo-contruction.php' ) && 1 == $under_construction_activation_status // WPCS: loose comparison ok.
600
			|| ( Jetpack::is_plugin_active( 'under-construction-page/under-construction.php' ) && isset( $ucp_options['status'] ) && 1 == $ucp_options['status'] ) // WPCS: loose comparison ok.
601
			|| ( Jetpack::is_plugin_active( 'ultimate-under-construction/ultimate-under-construction.php' ) && isset( $uuc_settings['enable'] ) && 1 == $uuc_settings['enable'] ) // WPCS: loose comparison ok.
602
			|| ( Jetpack::is_plugin_active( 'coming-soon/coming-soon.php' ) &&  isset( $csp4['status'] ) && ( 1 == $csp4['status'] || 2 == $csp4['status'] ) ) // WPCS: loose comparison ok.
603
			/**
604
			 * Allow plugins to mark a site as "under construction".
605
			 *
606
			 * @since 6.7.0
607
			 *
608
			 * @param false bool Is the site under construction? Default to false.
609
			 */
610
			|| true === apply_filters( 'jetpack_is_under_construction_plugin', false )
611
		) {
612
			return new WP_Error( 'forbidden', __( 'Site is under construction and cannot be verified', 'jetpack' ) );
613
		}
614
615
 		$xml = new Jetpack_IXR_Client( array(
616
 			'user_id' => get_current_user_id(),
617
		) );
618
619
		$args = array(
620
			'user_id' => get_current_user_id(),
621
			'service' => $request[ 'service' ],
622
		);
623
624
		if ( isset( $request[ 'keyring_id' ] ) ) {
625
			$args[ 'keyring_id' ] = $request[ 'keyring_id' ];
626
		}
627
628
		$xml->query( 'jetpack.isSiteVerified', $args );
629
630
		if ( $xml->isError() ) {
631
			return new WP_Error( 'error_checking_if_site_verified_google', sprintf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() ) );
632
		} else {
633
			return $xml->getResponse();
634
		}
635
	}
636
637
638
639
	public static function verify_site( $request ) {
640
		$xml = new Jetpack_IXR_Client( array(
641
			'user_id' => get_current_user_id(),
642
		) );
643
644
		$params = $request->get_json_params();
645
646
		$xml->query( 'jetpack.verifySite', array(
647
				'user_id' => get_current_user_id(),
648
				'service' => $request[ 'service' ],
649
				'keyring_id' => $params[ 'keyring_id' ],
650
			)
651
		);
652
653
		if ( $xml->isError() ) {
654
			return new WP_Error( 'error_verifying_site_google', sprintf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() ) );
655
		} else {
656
			$response = $xml->getResponse();
657
658
			if ( ! empty( $response['errors'] ) ) {
659
				$error = new WP_Error;
660
				$error->errors = $response['errors'];
661
				return $error;
662
			}
663
664
			return $response;
665
		}
666
	}
667
668
	/**
669
	 * Handles verification that a site is registered
670
	 *
671
	 * @since 5.4.0
672
	 *
673
	 * @param WP_REST_Request $request The request sent to the WP REST API.
674
	 *
675
	 * @return array|wp-error
676
	 */
677
	 public static function remote_authorize( $request ) {
678
		$xmlrpc_server = new Jetpack_XMLRPC_Server();
679
		$result = $xmlrpc_server->remote_authorize( $request );
680
681
		if ( is_a( $result, 'IXR_Error' ) ) {
682
			$result = new WP_Error( $result->code, $result->message );
683
		}
684
685
		return $result;
686
	 }
687
688
	/**
689
	 * Handles dismissing of Jetpack Notices
690
	 *
691
	 * @since 4.3.0
692
	 *
693
	 * @param WP_REST_Request $request The request sent to the WP REST API.
694
	 *
695
	 * @return array|wp-error
696
	 */
697
	public static function dismiss_notice( $request ) {
698
		$notice = $request['notice'];
699
700
		if ( ! isset( $request['dismissed'] ) || $request['dismissed'] !== true ) {
701
			return new WP_Error( 'invalid_param', esc_html__( 'Invalid parameter "dismissed".', 'jetpack' ), array( 'status' => 404 ) );
702
		}
703
704
		if ( isset( $notice ) && ! empty( $notice ) ) {
705
			switch( $notice ) {
706
				case 'feedback_dash_request':
707
				case 'welcome':
708
					$notices = get_option( 'jetpack_dismissed_notices', array() );
709
					$notices[ $notice ] = true;
710
					update_option( 'jetpack_dismissed_notices', $notices );
711
					return rest_ensure_response( get_option( 'jetpack_dismissed_notices', array() ) );
712
713
				default:
714
					return new WP_Error( 'invalid_param', esc_html__( 'Invalid parameter "notice".', 'jetpack' ), array( 'status' => 404 ) );
715
			}
716
		}
717
718
		return new WP_Error( 'required_param', esc_html__( 'Missing parameter "notice".', 'jetpack' ), array( 'status' => 404 ) );
719
	}
720
721
	/**
722
	 * Verify that the user can disconnect the site.
723
	 *
724
	 * @since 4.3.0
725
	 *
726
	 * @return bool|WP_Error True if user is able to disconnect the site.
727
	 */
728 View Code Duplication
	public static function disconnect_site_permission_callback() {
729
		if ( current_user_can( 'jetpack_disconnect' ) ) {
730
			return true;
731
		}
732
733
		return new WP_Error( 'invalid_user_permission_jetpack_disconnect', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
734
735
	}
736
737
	/**
738
	 * Verify that the user can get a connect/link URL
739
	 *
740
	 * @since 4.3.0
741
	 *
742
	 * @return bool|WP_Error True if user is able to disconnect the site.
743
	 */
744 View Code Duplication
	public static function connect_url_permission_callback() {
745
		if ( current_user_can( 'jetpack_connect_user' ) ) {
746
			return true;
747
		}
748
749
		return new WP_Error( 'invalid_user_permission_jetpack_disconnect', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
750
751
	}
752
753
	/**
754
	 * Verify that a user can get the data about the current user.
755
	 * Only those who can connect.
756
	 *
757
	 * @since 4.3.0
758
	 *
759
	 * @uses Jetpack::is_user_connected();
760
	 *
761
	 * @return bool|WP_Error True if user is able to unlink.
762
	 */
763 View Code Duplication
	public static function get_user_connection_data_permission_callback() {
764
		if ( current_user_can( 'jetpack_connect_user' ) ) {
765
			return true;
766
		}
767
768
		return new WP_Error( 'invalid_user_permission_user_connection_data', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
769
	}
770
771
	/**
772
	 * Check that user has permission to change the master user.
773
	 *
774
	 * @since 6.2.0
775
	 * @since 7.7.0 Update so that any user with jetpack_disconnect privs can set owner.
776
	 *
777
	 * @return bool|WP_Error True if user is able to change master user.
778
	 */
779 View Code Duplication
	public static function set_connection_owner_permission_callback() {
780
		if ( current_user_can( 'jetpack_disconnect' ) ) {
781
			return true;
782
		}
783
784
		return new WP_Error( 'invalid_user_permission_set_connection_owner', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
785
	}
786
787
	/**
788
	 * Verify that a user can use the /connection/user endpoint. Has to be a registered user and be currently linked.
789
	 *
790
	 * @since 4.3.0
791
	 *
792
	 * @uses Jetpack::is_user_connected();
793
	 *
794
	 * @return bool|WP_Error True if user is able to unlink.
795
	 */
796
	public static function unlink_user_permission_callback() {
797
		if ( current_user_can( 'jetpack_connect_user' ) && Jetpack::is_user_connected( get_current_user_id() ) ) {
798
			return true;
799
		}
800
801
		return new WP_Error( 'invalid_user_permission_unlink_user', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
802
	}
803
804
	/**
805
	 * Verify that user can manage Jetpack modules.
806
	 *
807
	 * @since 4.3.0
808
	 *
809
	 * @return bool Whether user has the capability 'jetpack_manage_modules'.
810
	 */
811
	public static function manage_modules_permission_check() {
812
		if ( current_user_can( 'jetpack_manage_modules' ) ) {
813
			return true;
814
		}
815
816
		return new WP_Error( 'invalid_user_permission_manage_modules', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
817
	}
818
819
	/**
820
	 * Verify that user can update Jetpack modules.
821
	 *
822
	 * @since 4.3.0
823
	 *
824
	 * @return bool Whether user has the capability 'jetpack_configure_modules'.
825
	 */
826 View Code Duplication
	public static function configure_modules_permission_check() {
827
		if ( current_user_can( 'jetpack_configure_modules' ) ) {
828
			return true;
829
		}
830
831
		return new WP_Error( 'invalid_user_permission_configure_modules', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
832
	}
833
834
	/**
835
	 * Verify that user can view Jetpack admin page.
836
	 *
837
	 * @since 4.3.0
838
	 *
839
	 * @return bool Whether user has the capability 'jetpack_admin_page'.
840
	 */
841 View Code Duplication
	public static function view_admin_page_permission_check() {
842
		if ( current_user_can( 'jetpack_admin_page' ) ) {
843
			return true;
844
		}
845
846
		return new WP_Error( 'invalid_user_permission_view_admin', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
847
	}
848
849
	/**
850
	 * Verify that user can mitigate an identity crisis.
851
	 *
852
	 * @since 4.4.0
853
	 *
854
	 * @return bool Whether user has capability 'jetpack_disconnect'.
855
	 */
856 View Code Duplication
	public static function identity_crisis_mitigation_permission_check() {
857
		if ( current_user_can( 'jetpack_disconnect' ) ) {
858
			return true;
859
		}
860
861
		return new WP_Error( 'invalid_user_permission_identity_crisis', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
862
	}
863
864
	/**
865
	 * Verify that user can update Jetpack general settings.
866
	 *
867
	 * @since 4.3.0
868
	 *
869
	 * @return bool Whether user has the capability 'update_settings_permission_check'.
870
	 */
871 View Code Duplication
	public static function update_settings_permission_check() {
872
		if ( current_user_can( 'jetpack_configure_modules' ) ) {
873
			return true;
874
		}
875
876
		return new WP_Error( 'invalid_user_permission_manage_settings', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
877
	}
878
879
	/**
880
	 * Verify that user can view Jetpack admin page and can activate plugins.
881
	 *
882
	 * @since 4.3.0
883
	 *
884
	 * @return bool Whether user has the capability 'jetpack_admin_page' and 'activate_plugins'.
885
	 */
886 View Code Duplication
	public static function activate_plugins_permission_check() {
887
		if ( current_user_can( 'jetpack_admin_page' ) && current_user_can( 'activate_plugins' ) ) {
888
			return true;
889
		}
890
891
		return new WP_Error( 'invalid_user_permission_activate_plugins', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
892
	}
893
894
	/**
895
	 * Verify that user can edit other's posts (Editors and Administrators).
896
	 *
897
	 * @return bool Whether user has the capability 'edit_others_posts'.
898
	 */
899
	public static function edit_others_posts_check() {
900
		if ( current_user_can( 'edit_others_posts' ) ) {
901
			return true;
902
		}
903
904
		return new WP_Error( 'invalid_user_permission_edit_others_posts', self::$user_permissions_error_msg, array( 'status' => self::rest_authorization_required_code() ) );
905
	}
906
907
	/**
908
	 * Contextual HTTP error code for authorization failure.
909
	 *
910
	 * Taken from rest_authorization_required_code() in WP-API plugin until is added to core.
911
	 * @see https://github.com/WP-API/WP-API/commit/7ba0ae6fe4f605d5ffe4ee85b1cd5f9fb46900a6
912
	 *
913
	 * @since 4.3.0
914
	 *
915
	 * @return int
916
	 */
917
	public static function rest_authorization_required_code() {
918
		return is_user_logged_in() ? 403 : 401;
919
	}
920
921
	/**
922
	 * Get connection status for this Jetpack site.
923
	 *
924
	 * @since 4.3.0
925
	 *
926
	 * @return bool True if site is connected
927
	 */
928
	public static function jetpack_connection_status() {
929
		return rest_ensure_response( array(
930
				'isActive'     => Jetpack::is_active(),
931
				'isStaging'    => Jetpack::is_staging_site(),
932
				'isRegistered' => Jetpack::connection()->is_registered(),
933
				'devMode'      => array(
934
					'isActive' => Jetpack::is_development_mode(),
935
					'constant' => defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG,
936
					'url'      => site_url() && false === strpos( site_url(), '.' ),
937
					'filter'   => apply_filters( 'jetpack_development_mode', false ),
938
				),
939
			)
940
		);
941
	}
942
943
	/**
944
	 * Test connection status for this Jetpack site.
945
	 *
946
	 * @since 6.8.0
947
	 *
948
	 * @return array|WP_Error WP_Error returned if connection test does not succeed.
949
	 */
950
	public static function jetpack_connection_test() {
951
		jetpack_require_lib( 'debugger' );
952
		$cxntests = new Jetpack_Cxn_Tests();
953
954
		if ( $cxntests->pass() ) {
955
			return rest_ensure_response(
956
				array(
957
					'code'    => 'success',
958
					'message' => __( 'All connection tests passed.', 'jetpack' ),
959
				)
960
			);
961
		} else {
962
			return $cxntests->output_fails_as_wp_error();
963
		}
964
	}
965
966
	/**
967
	 * Test connection permission check method.
968
	 *
969
	 * @since 7.1.0
970
	 *
971
	 * @return bool
972
	 */
973
	public static function view_jetpack_connection_test_check() {
974
		if ( ! isset( $_GET['signature'], $_GET['timestamp'], $_GET['url'] ) ) {
975
			return false;
976
		}
977
		$signature = base64_decode( $_GET['signature'] );
978
979
		$signature_data = wp_json_encode(
980
			array(
981
				'rest_route' => $_GET['rest_route'],
982
				'timestamp' => intval( $_GET['timestamp'] ),
983
				'url' => wp_unslash( $_GET['url'] ),
984
			)
985
		);
986
987
		if (
988
			! function_exists( 'openssl_verify' )
989
			|| ! openssl_verify(
990
				$signature_data,
991
				$signature,
992
				JETPACK__DEBUGGER_PUBLIC_KEY
993
			)
994
		) {
995
			return false;
996
		}
997
998
		// signature timestamp must be within 5min of current time
999
		if ( abs( time() - intval( $_GET['timestamp'] ) ) > 300 ) {
1000
			return false;
1001
		}
1002
1003
		return true;
1004
	}
1005
1006
	/**
1007
	 * Test connection status for this Jetpack site, encrypt the results for decryption by a third-party.
1008
	 *
1009
	 * @since 7.1.0
1010
	 *
1011
	 * @return array|mixed|object|WP_Error
1012
	 */
1013
	public static function jetpack_connection_test_for_external() {
1014
		// Since we are running this test for inclusion in the WP.com testing suite, let's not try to run them as part of these results.
1015
		add_filter( 'jetpack_debugger_run_self_test', '__return_false' );
1016
		jetpack_require_lib( 'debugger' );
1017
		$cxntests = new Jetpack_Cxn_Tests();
1018
1019
		if ( $cxntests->pass() ) {
1020
			$result = array(
1021
				'code'    => 'success',
1022
				'message' => __( 'All connection tests passed.', 'jetpack' ),
1023
			);
1024
		} else {
1025
			$error  = $cxntests->output_fails_as_wp_error(); // Using this so the output is similar both ways.
1026
			$errors = array();
1027
1028
			// Borrowed from WP_REST_Server::error_to_response().
1029
			foreach ( (array) $error->errors as $code => $messages ) {
1030
				foreach ( (array) $messages as $message ) {
1031
					$errors[] = array(
1032
						'code'    => $code,
1033
						'message' => $message,
1034
						'data'    => $error->get_error_data( $code ),
1035
					);
1036
				}
1037
			}
1038
1039
			$result = $errors[0];
1040
			if ( count( $errors ) > 1 ) {
1041
				// Remove the primary error.
1042
				array_shift( $errors );
1043
				$result['additional_errors'] = $errors;
1044
			}
1045
		}
1046
1047
		$result = wp_json_encode( $result );
1048
1049
		$encrypted = $cxntests->encrypt_string_for_wpcom( $result );
1050
1051
		if ( ! $encrypted || ! is_array( $encrypted ) ) {
1052
			return rest_ensure_response(
1053
				array(
1054
					'code'    => 'action_required',
1055
					'message' => 'Please request results from the in-plugin debugger',
1056
				)
1057
			);
1058
		}
1059
1060
		return rest_ensure_response(
1061
			array(
1062
				'code'  => 'response',
1063
				'debug' => array(
1064
					'data' => $encrypted['data'],
1065
					'key'  => $encrypted['key'],
1066
				),
1067
			)
1068
		);
1069
	}
1070
1071
	public static function rewind_data() {
1072
		$site_id = Jetpack_Options::get_option( 'id' );
1073
1074
		if ( ! $site_id ) {
1075
			return new WP_Error( 'site_id_missing' );
1076
		}
1077
1078
		$response = Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d/rewind', $site_id ) .'?force=wpcom', '2', array(), null, 'wpcom' );
1079
1080
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
1081
			return new WP_Error( 'rewind_data_fetch_failed' );
1082
		}
1083
1084
		$body = wp_remote_retrieve_body( $response );
1085
1086
		return json_decode( $body );
1087
	}
1088
1089
	/**
1090
	 * Get rewind data
1091
	 *
1092
	 * @since 5.7.0
1093
	 *
1094
	 * @return array Array of rewind properties.
1095
	 */
1096
	public static function get_rewind_data() {
1097
		$rewind_data = self::rewind_data();
1098
1099 View Code Duplication
		if ( ! is_wp_error( $rewind_data ) ) {
1100
			return rest_ensure_response( array(
1101
					'code' => 'success',
1102
					'message' => esc_html__( 'Backup & Scan data correctly received.', 'jetpack' ),
1103
					'data' => wp_json_encode( $rewind_data ),
1104
				)
1105
			);
1106
		}
1107
1108 View Code Duplication
		if ( $rewind_data->get_error_code() === 'rewind_data_fetch_failed' ) {
1109
			return new WP_Error( 'rewind_data_fetch_failed', esc_html__( 'Failed fetching rewind data. Try again later.', 'jetpack' ), array( 'status' => 400 ) );
1110
		}
1111
1112 View Code Duplication
		if ( $rewind_data->get_error_code() === 'site_id_missing' ) {
1113
			return new WP_Error( 'site_id_missing', esc_html__( 'The ID of this site does not exist.', 'jetpack' ), array( 'status' => 404 ) );
1114
		}
1115
1116
		return new WP_Error(
1117
			'error_get_rewind_data',
1118
			esc_html__( 'Could not retrieve Backup & Scan data.', 'jetpack' ),
1119
			array( 'status' => 500 )
1120
		);
1121
	}
1122
1123
	/**
1124
	 * Disconnects Jetpack from the WordPress.com Servers
1125
	 *
1126
	 * @uses Jetpack::disconnect();
1127
	 * @since 4.3.0
1128
	 *
1129
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1130
	 *
1131
	 * @return bool|WP_Error True if Jetpack successfully disconnected.
1132
	 */
1133 View Code Duplication
	public static function disconnect_site( $request ) {
1134
1135
		if ( ! isset( $request['isActive'] ) || $request['isActive'] !== false ) {
1136
			return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
1137
		}
1138
1139
		if ( Jetpack::is_active() ) {
1140
			Jetpack::disconnect();
1141
			return rest_ensure_response( array( 'code' => 'success' ) );
1142
		}
1143
1144
		return new WP_Error( 'disconnect_failed', esc_html__( 'Was not able to disconnect the site.  Please try again.', 'jetpack' ), array( 'status' => 400 ) );
1145
	}
1146
1147
	/**
1148
	 * Registers the Jetpack site
1149
	 *
1150
	 * @uses Jetpack::try_registration();
1151
	 * @since 7.7.0
1152
	 *
1153
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1154
	 *
1155
	 * @return bool|WP_Error True if Jetpack successfully registered
1156
	 */
1157
	public static function register_site( $request ) {
1158
		if ( ! wp_verify_nonce( $request->get_param( 'registration_nonce' ), 'jetpack-registration-nonce' ) ) {
1159
			return new WP_Error( 'invalid_nonce', __( 'Unable to verify your request.', 'jetpack' ), array( 'status' => 403 ) );
1160
		}
1161
1162
		$response = Jetpack::try_registration();
1163
1164
		if ( is_wp_error( $response ) ) {
1165
			return $response;
1166
		}
1167
1168
		return rest_ensure_response(
1169
			array(
1170
				'authorizeUrl' => Jetpack::build_authorize_url( false, true )
1171
			) );
1172
	}
1173
1174
	/**
1175
	 * Gets a new connect raw URL with fresh nonce.
1176
	 *
1177
	 * @uses Jetpack::disconnect();
1178
	 * @since 4.3.0
1179
	 *
1180
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1181
	 *
1182
	 * @return string|WP_Error A raw URL if the connection URL could be built; error message otherwise.
1183
	 */
1184
	public static function build_connect_url() {
1185
		$url = Jetpack::init()->build_connect_url( true, false, false );
1186
		if ( $url ) {
1187
			return rest_ensure_response( $url );
1188
		}
1189
1190
		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 ) );
1191
	}
1192
1193
	/**
1194
	 * Get miscellaneous user data related to the connection. Similar data available in old "My Jetpack".
1195
	 * Information about the master/primary user.
1196
	 * Information about the current user.
1197
	 *
1198
	 * @since 4.3.0
1199
	 *
1200
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1201
	 *
1202
	 * @return object
1203
	 */
1204
	public static function get_user_connection_data() {
1205
		require_once( JETPACK__PLUGIN_DIR . '_inc/lib/admin-pages/class.jetpack-react-page.php' );
1206
1207
		$response = array(
1208
//			'othersLinked' => Jetpack::get_other_linked_admins(),
1209
			'currentUser'  => jetpack_current_user_data(),
1210
		);
1211
		return rest_ensure_response( $response );
1212
	}
1213
1214
	/**
1215
	 * Change the master user.
1216
	 *
1217
	 * @since 6.2.0
1218
	 *
1219
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1220
	 *
1221
	 * @return bool|WP_Error True if owner successfully changed.
1222
	 */
1223
	public static function set_connection_owner( $request ) {
1224
		if ( ! isset( $request['owner'] ) ) {
1225
			return new WP_Error(
1226
				'invalid_param',
1227
				esc_html__( 'Invalid Parameter', 'jetpack' ),
1228
				array( 'status' => 400 )
1229
			);
1230
		}
1231
1232
		$new_owner_id = $request['owner'];
1233
		if ( ! user_can( $new_owner_id, 'administrator' ) ) {
1234
			return new WP_Error(
1235
				'new_owner_not_admin',
1236
				esc_html__( 'New owner is not admin', 'jetpack' ),
1237
				array( 'status' => 400 )
1238
			);
1239
		}
1240
1241
		if ( $new_owner_id === get_current_user_id() ) {
1242
			return new WP_Error(
1243
				'new_owner_is_current_user',
1244
				esc_html__( 'New owner is same as current user', 'jetpack' ),
1245
				array( 'status' => 400 )
1246
			);
1247
		}
1248
1249
		if ( ! Jetpack::is_user_connected( $new_owner_id ) ) {
1250
			return new WP_Error(
1251
				'new_owner_not_connected',
1252
				esc_html__( 'New owner is not connected', 'jetpack' ),
1253
				array( 'status' => 400 )
1254
			);
1255
		}
1256
1257
		// Update the master user in Jetpack
1258
		$updated = Jetpack_Options::update_option( 'master_user', $new_owner_id );
1259
1260
		// Notify WPCOM about the master user change
1261
		$xml = new Jetpack_IXR_Client( array(
1262
			'user_id' => get_current_user_id(),
1263
		) );
1264
		$xml->query( 'jetpack.switchBlogOwner', array(
1265
			'new_blog_owner' => $new_owner_id,
1266
		) );
1267
1268
		if ( $updated && ! $xml->isError() ) {
1269
1270
			// Track it
1271
			if ( class_exists( 'Automattic\Jetpack\Tracking' ) ) {
1272
				$tracking = new Tracking();
1273
				$tracking->record_user_event( 'set_connection_owner_success' );
1274
			}
1275
1276
			return rest_ensure_response(
1277
				array(
1278
					'code' => 'success',
1279
				)
1280
			);
1281
		}
1282
		return new WP_Error(
1283
			'error_setting_new_owner',
1284
			esc_html__( 'Could not confirm new owner.', 'jetpack' ),
1285
			array( 'status' => 500 )
1286
		);
1287
	}
1288
1289
	/**
1290
	 * Unlinks current user from the WordPress.com Servers.
1291
	 *
1292
	 * @since 4.3.0
1293
	 * @uses  Automattic\Jetpack\Connection\Manager::disconnect_user
1294
	 *
1295
	 * @param WP_REST_Request $request The request sent to the WP REST API.
1296
	 *
1297
	 * @return bool|WP_Error True if user successfully unlinked.
1298
	 */
1299 View Code Duplication
	public static function unlink_user( $request ) {
1300
1301
		if ( ! isset( $request['linked'] ) || $request['linked'] !== false ) {
1302
			return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
1303
		}
1304
1305
		if ( Connection_Manager::disconnect_user() ) {
1306
			return rest_ensure_response(
1307
				array(
1308
					'code' => 'success'
1309
				)
1310
			);
1311
		}
1312
1313
		return new WP_Error( 'unlink_user_failed', esc_html__( 'Was not able to unlink the user.  Please try again.', 'jetpack' ), array( 'status' => 400 ) );
1314
	}
1315
1316
	/**
1317
	 * Gets current user's tracking settings.
1318
	 *
1319
	 * @since 6.0.0
1320
	 *
1321
	 * @param  WP_REST_Request $request The request sent to the WP REST API.
1322
	 *
1323
	 * @return WP_REST_Response|WP_Error Response, else error.
1324
	 */
1325 View Code Duplication
	public static function get_user_tracking_settings( $request ) {
1326
		if ( ! Jetpack::is_user_connected() ) {
1327
			$response = array(
1328
				'tracks_opt_out' => true, // Default to opt-out if not connected to wp.com.
1329
			);
1330
		} else {
1331
			$response = Client::wpcom_json_api_request_as_user(
1332
				'/jetpack-user-tracking',
1333
				'v2',
1334
				array(
1335
					'method'  => 'GET',
1336
					'headers' => array(
1337
						'X-Forwarded-For' => Jetpack::current_user_ip( true ),
1338
					),
1339
				)
1340
			);
1341
			if ( ! is_wp_error( $response ) ) {
1342
				$response = json_decode( wp_remote_retrieve_body( $response ), true );
1343
			}
1344
		}
1345
1346
		return rest_ensure_response( $response );
1347
	}
1348
1349
	/**
1350
	 * Updates current user's tracking settings.
1351
	 *
1352
	 * @since 6.0.0
1353
	 *
1354
	 * @param  WP_REST_Request $request The request sent to the WP REST API.
1355
	 *
1356
	 * @return WP_REST_Response|WP_Error Response, else error.
1357
	 */
1358 View Code Duplication
	public static function update_user_tracking_settings( $request ) {
1359
		if ( ! Jetpack::is_user_connected() ) {
1360
			$response = array(
1361
				'tracks_opt_out' => true, // Default to opt-out if not connected to wp.com.
1362
			);
1363
		} else {
1364
			$response = Client::wpcom_json_api_request_as_user(
1365
				'/jetpack-user-tracking',
1366
				'v2',
1367
				array(
1368
					'method'  => 'PUT',
1369
					'headers' => array(
1370
						'Content-Type'    => 'application/json',
1371
						'X-Forwarded-For' => Jetpack::current_user_ip( true ),
1372
					),
1373
				),
1374
				wp_json_encode( $request->get_params() )
1375
			);
1376
			if ( ! is_wp_error( $response ) ) {
1377
				$response = json_decode( wp_remote_retrieve_body( $response ), true );
1378
			}
1379
		}
1380
1381
		return rest_ensure_response( $response );
1382
	}
1383
1384
	/**
1385
	 * Fetch site data from .com including the site's current plan.
1386
	 *
1387
	 * @since 5.5.0
1388
	 *
1389
	 * @return array Array of site properties.
1390
	 */
1391
	public static function site_data() {
1392
		$site_id = Jetpack_Options::get_option( 'id' );
1393
1394
		if ( ! $site_id ) {
1395
			new WP_Error( 'site_id_missing' );
1396
		}
1397
1398
		$args = array( 'headers' => array() );
1399
1400
		// Allow use a store sandbox. Internal ref: PCYsg-IA-p2.
1401
		if ( isset( $_COOKIE ) && isset( $_COOKIE['store_sandbox'] ) ) {
1402
			$secret                    = $_COOKIE['store_sandbox'];
1403
			$args['headers']['Cookie'] = "store_sandbox=$secret;";
1404
		}
1405
1406
		$response = Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d', $site_id ) .'?force=wpcom', '1.1', $args );
1407
1408
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
1409
			return new WP_Error( 'site_data_fetch_failed' );
1410
		}
1411
1412
		Jetpack_Plan::update_from_sites_response( $response );
1413
1414
		$body = wp_remote_retrieve_body( $response );
1415
1416
		return json_decode( $body );
1417
	}
1418
	/**
1419
	 * Get site data, including for example, the site's current plan.
1420
	 *
1421
	 * @since 4.3.0
1422
	 *
1423
	 * @return array Array of site properties.
1424
	 */
1425
	public static function get_site_data() {
1426
		$site_data = self::site_data();
1427
1428 View Code Duplication
		if ( ! is_wp_error( $site_data ) ) {
1429
			return rest_ensure_response( array(
1430
					'code' => 'success',
1431
					'message' => esc_html__( 'Site data correctly received.', 'jetpack' ),
1432
					'data' => json_encode( $site_data ),
1433
				)
1434
			);
1435
		}
1436 View Code Duplication
		if ( $site_data->get_error_code() === 'site_data_fetch_failed' ) {
1437
			return new WP_Error( 'site_data_fetch_failed', esc_html__( 'Failed fetching site data. Try again later.', 'jetpack' ), array( 'status' => 400 ) );
1438
		}
1439
1440 View Code Duplication
		if ( $site_data->get_error_code() === 'site_id_missing' ) {
1441
			return new WP_Error( 'site_id_missing', esc_html__( 'The ID of this site does not exist.', 'jetpack' ), array( 'status' => 404 ) );
1442
		}
1443
	}
1444
1445
	/**
1446
	 * Fetch AL data for this site and return it.
1447
	 *
1448
	 * @since 7.4
1449
	 *
1450
	 * @return array|WP_Error
1451
	 */
1452
	public static function get_site_activity() {
1453
		$site_id = Jetpack_Options::get_option( 'id' );
1454
1455
		if ( ! $site_id ) {
1456
			return new WP_Error(
1457
				'site_id_missing',
1458
				esc_html__( 'Site ID is missing.', 'jetpack' ),
1459
				array( 'status' => 400 )
1460
			);
1461
		}
1462
1463
		$response = Client::wpcom_json_api_request_as_user( "/sites/$site_id/activity", '2', array(
1464
			'method'  => 'GET',
1465
			'headers' => array(
1466
				'X-Forwarded-For' => Jetpack::current_user_ip( true ),
1467
			),
1468
		), null, 'wpcom' );
1469
		$response_code = wp_remote_retrieve_response_code( $response );
1470
1471 View Code Duplication
		if ( 200 !== $response_code ) {
1472
			return new WP_Error(
1473
				'activity_fetch_failed',
1474
				esc_html__( 'Could not retrieve site activity.', 'jetpack' ),
1475
				array( 'status' => $response_code )
1476
			);
1477
		}
1478
1479
		$data = json_decode( wp_remote_retrieve_body( $response ) );
1480
1481
		if ( ! isset( $data->current->orderedItems ) ) {
1482
			return new WP_Error(
1483
				'activity_not_found',
1484
				esc_html__( 'No activity found', 'jetpack' ),
1485
				array( 'status' => 204 ) // no content
1486
			);
1487
		}
1488
1489
		return rest_ensure_response( array(
1490
				'code' => 'success',
1491
				'data' => $data->current->orderedItems,
1492
			)
1493
		);
1494
	}
1495
1496
	/**
1497
	 * Handles identity crisis mitigation, confirming safe mode for this site.
1498
	 *
1499
	 * @since 4.4.0
1500
	 *
1501
	 * @return bool | WP_Error True if option is properly set.
1502
	 */
1503
	public static function confirm_safe_mode() {
1504
		$updated = Jetpack_Options::update_option( 'safe_mode_confirmed', true );
1505
		if ( $updated ) {
1506
			return rest_ensure_response(
1507
				array(
1508
					'code' => 'success'
1509
				)
1510
			);
1511
		}
1512
		return new WP_Error(
1513
			'error_setting_jetpack_safe_mode',
1514
			esc_html__( 'Could not confirm safe mode.', 'jetpack' ),
1515
			array( 'status' => 500 )
1516
		);
1517
	}
1518
1519
	/**
1520
	 * Handles identity crisis mitigation, migrating stats and subscribers from old url to this, new url.
1521
	 *
1522
	 * @since 4.4.0
1523
	 *
1524
	 * @return bool | WP_Error True if option is properly set.
1525
	 */
1526
	public static function migrate_stats_and_subscribers() {
1527
		if ( Jetpack_Options::get_option( 'sync_error_idc' ) && ! Jetpack_Options::delete_option( 'sync_error_idc' ) ) {
1528
			return new WP_Error(
1529
				'error_deleting_sync_error_idc',
1530
				esc_html__( 'Could not delete sync error option.', 'jetpack' ),
1531
				array( 'status' => 500 )
1532
			);
1533
		}
1534
1535
		if ( Jetpack_Options::get_option( 'migrate_for_idc' ) || Jetpack_Options::update_option( 'migrate_for_idc', true ) ) {
1536
			return rest_ensure_response(
1537
				array(
1538
					'code' => 'success'
1539
				)
1540
			);
1541
		}
1542
		return new WP_Error(
1543
			'error_setting_jetpack_migrate',
1544
			esc_html__( 'Could not confirm migration.', 'jetpack' ),
1545
			array( 'status' => 500 )
1546
		);
1547
	}
1548
1549
	/**
1550
	 * This IDC resolution will disconnect the site and re-connect to a completely new
1551
	 * and separate shadow site than the original.
1552
	 *
1553
	 * It will first will disconnect the site without phoning home as to not disturb the production site.
1554
	 * It then builds a fresh connection URL and sends it back along with the response.
1555
	 *
1556
	 * @since 4.4.0
1557
	 * @return bool|WP_Error
1558
	 */
1559
	public static function start_fresh_connection() {
1560
		// First clear the options / disconnect.
1561
		Jetpack::disconnect();
1562
		return self::build_connect_url();
1563
	}
1564
1565
	/**
1566
	 * Reset Jetpack options
1567
	 *
1568
	 * @since 4.3.0
1569
	 *
1570
	 * @param WP_REST_Request $request {
1571
	 *     Array of parameters received by request.
1572
	 *
1573
	 *     @type string $options Available options to reset are options|modules
1574
	 * }
1575
	 *
1576
	 * @return bool|WP_Error True if options were reset. Otherwise, a WP_Error instance with the corresponding error.
1577
	 */
1578
	public static function reset_jetpack_options( $request ) {
1579
1580
		if ( ! isset( $request['reset'] ) || $request['reset'] !== true ) {
1581
			return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
1582
		}
1583
1584
		if ( isset( $request['options'] ) ) {
1585
			$data = $request['options'];
1586
1587
			switch( $data ) {
1588
				case ( 'options' ) :
1589
					$options_to_reset = Jetpack::get_jetpack_options_for_reset();
1590
1591
					// Reset the Jetpack options
1592
					foreach ( $options_to_reset['jp_options'] as $option_to_reset ) {
1593
						Jetpack_Options::delete_option( $option_to_reset );
1594
					}
1595
1596
					foreach ( $options_to_reset['wp_options'] as $option_to_reset ) {
1597
						delete_option( $option_to_reset );
1598
					}
1599
1600
					// Reset to default modules
1601
					$default_modules = Jetpack::get_default_modules();
1602
					Jetpack::update_active_modules( $default_modules );
1603
1604
					return rest_ensure_response( array(
1605
						'code' 	  => 'success',
1606
						'message' => esc_html__( 'Jetpack options reset.', 'jetpack' ),
1607
					) );
1608
					break;
1609
1610
				case 'modules':
1611
					$default_modules = Jetpack::get_default_modules();
1612
					Jetpack::update_active_modules( $default_modules );
1613
					return rest_ensure_response( array(
1614
						'code' 	  => 'success',
1615
						'message' => esc_html__( 'Modules reset to default.', 'jetpack' ),
1616
					) );
1617
					break;
1618
1619
				default:
1620
					return new WP_Error( 'invalid_param', esc_html__( 'Invalid Parameter', 'jetpack' ), array( 'status' => 404 ) );
1621
			}
1622
		}
1623
1624
		return new WP_Error( 'required_param', esc_html__( 'Missing parameter "type".', 'jetpack' ), array( 'status' => 404 ) );
1625
	}
1626
1627
	/**
1628
	 * Get the query parameters to update module options or general settings.
1629
	 *
1630
	 * @since 4.3.0
1631
	 * @since 4.4.0 Accepts a $selector parameter.
1632
	 *
1633
	 * @param string $selector Selects a set of options to update, Can be empty, a module slug or 'any'.
1634
	 *
1635
	 * @return array
1636
	 */
1637
	public static function get_updateable_parameters( $selector = '' ) {
1638
		$parameters = array(
1639
			'context'     => array(
1640
				'default' => 'edit',
1641
			),
1642
		);
1643
1644
		return array_merge( $parameters, self::get_updateable_data_list( $selector ) );
1645
	}
1646
1647
	/**
1648
	 * Returns a list of module options or general settings that can be updated.
1649
	 *
1650
	 * @since 4.3.0
1651
	 * @since 4.4.0 Accepts 'any' as a parameter which will make it return the entire list.
1652
	 *
1653
	 * @param string|array $selector Module slug, 'any', or an array of parameters.
1654
	 *                               If empty, it's assumed we're updating a module and we'll try to get its slug.
1655
	 *                               If 'any' the full list is returned.
1656
	 *                               If it's an array of parameters, includes the elements by matching keys.
1657
	 *
1658
	 * @return array
1659
	 */
1660
	public static function get_updateable_data_list( $selector = '' ) {
1661
1662
		$options = array(
1663
1664
			// Carousel
1665
			'carousel_background_color' => array(
1666
				'description'       => esc_html__( 'Color scheme.', 'jetpack' ),
1667
				'type'              => 'string',
1668
				'default'           => 'black',
1669
				'enum'              => array(
1670
					'black',
1671
					'white',
1672
				),
1673
				'enum_labels' => array(
1674
					'black' => esc_html__( 'Black', 'jetpack' ),
1675
					'white' => esc_html__( 'White', 'jetpack' ),
1676
				),
1677
				'validate_callback' => __CLASS__ . '::validate_list_item',
1678
				'jp_group'          => 'carousel',
1679
			),
1680
			'carousel_display_exif' => array(
1681
				'description'       => wp_kses( sprintf( __( 'Show photo metadata (<a href="https://en.wikipedia.org/wiki/Exchangeable_image_file_format" target="_blank">Exif</a>) in carousel, when available.', 'jetpack' ) ), array( 'a' => array( 'href' => true, 'target' => true ) ) ),
1682
				'type'              => 'boolean',
1683
				'default'           => 0,
1684
				'validate_callback' => __CLASS__ . '::validate_boolean',
1685
				'jp_group'          => 'carousel',
1686
			),
1687
1688
			// Comments
1689
			'highlander_comment_form_prompt' => array(
1690
				'description'       => esc_html__( 'Greeting Text', 'jetpack' ),
1691
				'type'              => 'string',
1692
				'default'           => esc_html__( 'Leave a Reply', 'jetpack' ),
1693
				'sanitize_callback' => 'sanitize_text_field',
1694
				'jp_group'          => 'comments',
1695
			),
1696
			'jetpack_comment_form_color_scheme' => array(
1697
				'description'       => esc_html__( "Color scheme", 'jetpack' ),
1698
				'type'              => 'string',
1699
				'default'           => 'light',
1700
				'enum'              => array(
1701
					'light',
1702
					'dark',
1703
					'transparent',
1704
				),
1705
				'enum_labels' => array(
1706
					'light'       => esc_html__( 'Light', 'jetpack' ),
1707
					'dark'        => esc_html__( 'Dark', 'jetpack' ),
1708
					'transparent' => esc_html__( 'Transparent', 'jetpack' ),
1709
				),
1710
				'validate_callback' => __CLASS__ . '::validate_list_item',
1711
				'jp_group'          => 'comments',
1712
			),
1713
1714
			// Custom Content Types
1715
			'jetpack_portfolio' => array(
1716
				'description'       => esc_html__( 'Enable or disable Jetpack portfolio post type.', 'jetpack' ),
1717
				'type'              => 'boolean',
1718
				'default'           => 0,
1719
				'validate_callback' => __CLASS__ . '::validate_boolean',
1720
				'jp_group'          => 'custom-content-types',
1721
			),
1722
			'jetpack_portfolio_posts_per_page' => array(
1723
				'description'       => esc_html__( 'Number of entries to show at most in Portfolio pages.', 'jetpack' ),
1724
				'type'              => 'integer',
1725
				'default'           => 10,
1726
				'validate_callback' => __CLASS__ . '::validate_posint',
1727
				'jp_group'          => 'custom-content-types',
1728
			),
1729
			'jetpack_testimonial' => array(
1730
				'description'       => esc_html__( 'Enable or disable Jetpack testimonial post type.', 'jetpack' ),
1731
				'type'              => 'boolean',
1732
				'default'           => 0,
1733
				'validate_callback' => __CLASS__ . '::validate_boolean',
1734
				'jp_group'          => 'custom-content-types',
1735
			),
1736
			'jetpack_testimonial_posts_per_page' => array(
1737
				'description'       => esc_html__( 'Number of entries to show at most in Testimonial pages.', 'jetpack' ),
1738
				'type'              => 'integer',
1739
				'default'           => 10,
1740
				'validate_callback' => __CLASS__ . '::validate_posint',
1741
				'jp_group'          => 'custom-content-types',
1742
			),
1743
1744
			// Galleries
1745
			'tiled_galleries' => array(
1746
				'description'       => esc_html__( 'Display all your gallery pictures in a cool mosaic.', 'jetpack' ),
1747
				'type'              => 'boolean',
1748
				'default'           => 0,
1749
				'validate_callback' => __CLASS__ . '::validate_boolean',
1750
				'jp_group'          => 'tiled-gallery',
1751
			),
1752
1753
			'gravatar_disable_hovercards' => array(
1754
				'description'       => esc_html__( "View people's profiles when you mouse over their Gravatars", 'jetpack' ),
1755
				'type'              => 'string',
1756
				'default'           => 'enabled',
1757
				// Not visible. This is used as the checkbox value.
1758
				'enum'              => array(
1759
					'enabled',
1760
					'disabled',
1761
				),
1762
				'enum_labels' => array(
1763
					'enabled'  => esc_html__( 'Enabled', 'jetpack' ),
1764
					'disabled' => esc_html__( 'Disabled', 'jetpack' ),
1765
				),
1766
				'validate_callback' => __CLASS__ . '::validate_list_item',
1767
				'jp_group'          => 'gravatar-hovercards',
1768
			),
1769
1770
			// Infinite Scroll
1771
			'infinite_scroll' => array(
1772
				'description'       => esc_html__( 'To infinity and beyond', 'jetpack' ),
1773
				'type'              => 'boolean',
1774
				'default'           => 1,
1775
				'validate_callback' => __CLASS__ . '::validate_boolean',
1776
				'jp_group'          => 'infinite-scroll',
1777
			),
1778
			'infinite_scroll_google_analytics' => array(
1779
				'description'       => esc_html__( 'Use Google Analytics with Infinite Scroll', 'jetpack' ),
1780
				'type'              => 'boolean',
1781
				'default'           => 0,
1782
				'validate_callback' => __CLASS__ . '::validate_boolean',
1783
				'jp_group'          => 'infinite-scroll',
1784
			),
1785
1786
			// Likes
1787
			'wpl_default' => array(
1788
				'description'       => esc_html__( 'WordPress.com Likes are', 'jetpack' ),
1789
				'type'              => 'string',
1790
				'default'           => 'on',
1791
				'enum'              => array(
1792
					'on',
1793
					'off',
1794
				),
1795
				'enum_labels' => array(
1796
					'on'  => esc_html__( 'On for all posts', 'jetpack' ),
1797
					'off' => esc_html__( 'Turned on per post', 'jetpack' ),
1798
				),
1799
				'validate_callback' => __CLASS__ . '::validate_list_item',
1800
				'jp_group'          => 'likes',
1801
			),
1802
			'social_notifications_like' => array(
1803
				'description'       => esc_html__( 'Send email notification when someone likes a post', 'jetpack' ),
1804
				'type'              => 'boolean',
1805
				'default'           => 1,
1806
				'validate_callback' => __CLASS__ . '::validate_boolean',
1807
				'jp_group'          => 'likes',
1808
			),
1809
1810
			// Markdown
1811
			'wpcom_publish_comments_with_markdown' => array(
1812
				'description'       => esc_html__( 'Use Markdown for comments.', 'jetpack' ),
1813
				'type'              => 'boolean',
1814
				'default'           => 0,
1815
				'validate_callback' => __CLASS__ . '::validate_boolean',
1816
				'jp_group'          => 'markdown',
1817
			),
1818
			'wpcom_publish_posts_with_markdown' => array(
1819
				'description'       => esc_html__( 'Use Markdown for posts.', 'jetpack' ),
1820
				'type'              => 'boolean',
1821
				'default'           => 0,
1822
				'validate_callback' => __CLASS__ . '::validate_boolean',
1823
				'jp_group'          => 'markdown',
1824
			),
1825
1826
			// Mobile Theme
1827
			'wp_mobile_excerpt' => array(
1828
				'description'       => esc_html__( 'Excerpts', 'jetpack' ),
1829
				'type'              => 'boolean',
1830
				'default'           => 0,
1831
				'validate_callback' => __CLASS__ . '::validate_boolean',
1832
				'jp_group'          => 'minileven',
1833
			),
1834
			'wp_mobile_featured_images' => array(
1835
				'description'       => esc_html__( 'Featured Images', 'jetpack' ),
1836
				'type'              => 'boolean',
1837
				'default'           => 0,
1838
				'validate_callback' => __CLASS__ . '::validate_boolean',
1839
				'jp_group'          => 'minileven',
1840
			),
1841
			'wp_mobile_app_promos' => array(
1842
				'description'       => esc_html__( 'Show a promo for the WordPress mobile apps in the footer of the mobile theme.', 'jetpack' ),
1843
				'type'              => 'boolean',
1844
				'default'           => 0,
1845
				'validate_callback' => __CLASS__ . '::validate_boolean',
1846
				'jp_group'          => 'minileven',
1847
			),
1848
1849
			// Monitor
1850
			'monitor_receive_notifications' => array(
1851
				'description'       => esc_html__( 'Receive Monitor Email Notifications.', 'jetpack' ),
1852
				'type'              => 'boolean',
1853
				'default'           => 0,
1854
				'validate_callback' => __CLASS__ . '::validate_boolean',
1855
				'jp_group'          => 'monitor',
1856
			),
1857
1858
			// Post by Email
1859
			'post_by_email_address' => array(
1860
				'description'       => esc_html__( 'Email Address', 'jetpack' ),
1861
				'type'              => 'string',
1862
				'default'           => 'noop',
1863
				'enum'              => array(
1864
					'noop',
1865
					'create',
1866
					'regenerate',
1867
					'delete',
1868
				),
1869
				'enum_labels' => array(
1870
					'noop'       => '',
1871
					'create'     => esc_html__( 'Create Post by Email address', 'jetpack' ),
1872
					'regenerate' => esc_html__( 'Regenerate Post by Email address', 'jetpack' ),
1873
					'delete'     => esc_html__( 'Delete Post by Email address', 'jetpack' ),
1874
				),
1875
				'validate_callback' => __CLASS__ . '::validate_list_item',
1876
				'jp_group'          => 'post-by-email',
1877
			),
1878
1879
			// Protect
1880
			'jetpack_protect_key' => array(
1881
				'description'       => esc_html__( 'Protect API key', 'jetpack' ),
1882
				'type'              => 'string',
1883
				'default'           => '',
1884
				'validate_callback' => __CLASS__ . '::validate_alphanum',
1885
				'jp_group'          => 'protect',
1886
			),
1887
			'jetpack_protect_global_whitelist' => array(
1888
				'description'       => esc_html__( 'Protect global whitelist', 'jetpack' ),
1889
				'type'              => 'string',
1890
				'default'           => '',
1891
				'validate_callback' => __CLASS__ . '::validate_string',
1892
				'sanitize_callback' => 'esc_textarea',
1893
				'jp_group'          => 'protect',
1894
			),
1895
1896
			// Sharing
1897
			'sharing_services' => array(
1898
				'description'       => esc_html__( 'Enabled Services and those hidden behind a button', 'jetpack' ),
1899
				'type'              => 'object',
1900
				'default'           => array(
1901
					'visible' => array( 'twitter', 'facebook', 'google-plus-1' ),
1902
					'hidden'  => array(),
1903
				),
1904
				'validate_callback' => __CLASS__ . '::validate_services',
1905
				'jp_group'          => 'sharedaddy',
1906
			),
1907
			'button_style' => array(
1908
				'description'       => esc_html__( 'Button Style', 'jetpack' ),
1909
				'type'              => 'string',
1910
				'default'           => 'icon',
1911
				'enum'              => array(
1912
					'icon-text',
1913
					'icon',
1914
					'text',
1915
					'official',
1916
				),
1917
				'enum_labels' => array(
1918
					'icon-text' => esc_html__( 'Icon + text', 'jetpack' ),
1919
					'icon'      => esc_html__( 'Icon only', 'jetpack' ),
1920
					'text'      => esc_html__( 'Text only', 'jetpack' ),
1921
					'official'  => esc_html__( 'Official buttons', 'jetpack' ),
1922
				),
1923
				'validate_callback' => __CLASS__ . '::validate_list_item',
1924
				'jp_group'          => 'sharedaddy',
1925
			),
1926
			'sharing_label' => array(
1927
				'description'       => esc_html__( 'Sharing Label', 'jetpack' ),
1928
				'type'              => 'string',
1929
				'default'           => '',
1930
				'validate_callback' => __CLASS__ . '::validate_string',
1931
				'sanitize_callback' => 'esc_html',
1932
				'jp_group'          => 'sharedaddy',
1933
			),
1934
			'show' => array(
1935
				'description'       => esc_html__( 'Views where buttons are shown', 'jetpack' ),
1936
				'type'              => 'array',
1937
				'items'             => array(
1938
					'type' => 'string'
1939
				),
1940
				'default'           => array( 'post' ),
1941
				'validate_callback' => __CLASS__ . '::validate_sharing_show',
1942
				'jp_group'          => 'sharedaddy',
1943
			),
1944
			'jetpack-twitter-cards-site-tag' => array(
1945
				'description'       => esc_html__( "The Twitter username of the owner of this site's domain.", 'jetpack' ),
1946
				'type'              => 'string',
1947
				'default'           => '',
1948
				'validate_callback' => __CLASS__ . '::validate_twitter_username',
1949
				'sanitize_callback' => 'esc_html',
1950
				'jp_group'          => 'sharedaddy',
1951
			),
1952
			'sharedaddy_disable_resources' => array(
1953
				'description'       => esc_html__( 'Disable CSS and JS', 'jetpack' ),
1954
				'type'              => 'boolean',
1955
				'default'           => 0,
1956
				'validate_callback' => __CLASS__ . '::validate_boolean',
1957
				'jp_group'          => 'sharedaddy',
1958
			),
1959
			'custom' => array(
1960
				'description'       => esc_html__( 'Custom sharing services added by user.', 'jetpack' ),
1961
				'type'              => 'object',
1962
				'default'           => array(
1963
					'sharing_name' => '',
1964
					'sharing_url'  => '',
1965
					'sharing_icon' => '',
1966
				),
1967
				'validate_callback' => __CLASS__ . '::validate_custom_service',
1968
				'jp_group'          => 'sharedaddy',
1969
			),
1970
			// Not an option, but an action that can be perfomed on the list of custom services passing the service ID.
1971
			'sharing_delete_service' => array(
1972
				'description'       => esc_html__( 'Delete custom sharing service.', 'jetpack' ),
1973
				'type'              => 'string',
1974
				'default'           => '',
1975
				'validate_callback' => __CLASS__ . '::validate_custom_service_id',
1976
				'jp_group'          => 'sharedaddy',
1977
			),
1978
1979
			// SSO
1980
			'jetpack_sso_require_two_step' => array(
1981
				'description'       => esc_html__( 'Require Two-Step Authentication', 'jetpack' ),
1982
				'type'              => 'boolean',
1983
				'default'           => 0,
1984
				'validate_callback' => __CLASS__ . '::validate_boolean',
1985
				'jp_group'          => 'sso',
1986
			),
1987
			'jetpack_sso_match_by_email' => array(
1988
				'description'       => esc_html__( 'Match by Email', 'jetpack' ),
1989
				'type'              => 'boolean',
1990
				'default'           => 0,
1991
				'validate_callback' => __CLASS__ . '::validate_boolean',
1992
				'jp_group'          => 'sso',
1993
			),
1994
1995
			// Subscriptions
1996
			'stb_enabled' => array(
1997
				'description'       => esc_html__( "Show a <em>'follow blog'</em> option in the comment form", 'jetpack' ),
1998
				'type'              => 'boolean',
1999
				'default'           => 1,
2000
				'validate_callback' => __CLASS__ . '::validate_boolean',
2001
				'jp_group'          => 'subscriptions',
2002
			),
2003
			'stc_enabled' => array(
2004
				'description'       => esc_html__( "Show a <em>'follow comments'</em> option in the comment form", 'jetpack' ),
2005
				'type'              => 'boolean',
2006
				'default'           => 1,
2007
				'validate_callback' => __CLASS__ . '::validate_boolean',
2008
				'jp_group'          => 'subscriptions',
2009
			),
2010
2011
			// Related Posts
2012
			'show_headline' => array(
2013
				'description'       => esc_html__( 'Highlight related content with a heading', 'jetpack' ),
2014
				'type'              => 'boolean',
2015
				'default'           => 1,
2016
				'validate_callback' => __CLASS__ . '::validate_boolean',
2017
				'jp_group'          => 'related-posts',
2018
			),
2019
			'show_thumbnails' => array(
2020
				'description'       => esc_html__( 'Show a thumbnail image where available', 'jetpack' ),
2021
				'type'              => 'boolean',
2022
				'default'           => 0,
2023
				'validate_callback' => __CLASS__ . '::validate_boolean',
2024
				'jp_group'          => 'related-posts',
2025
			),
2026
2027
			// Verification Tools
2028
			'google' => array(
2029
				'description'       => esc_html__( 'Google Search Console', 'jetpack' ),
2030
				'type'              => 'string',
2031
				'default'           => '',
2032
				'validate_callback' => __CLASS__ . '::validate_verification_service',
2033
				'jp_group'          => 'verification-tools',
2034
			),
2035
			'bing' => array(
2036
				'description'       => esc_html__( 'Bing Webmaster Center', 'jetpack' ),
2037
				'type'              => 'string',
2038
				'default'           => '',
2039
				'validate_callback' => __CLASS__ . '::validate_verification_service',
2040
				'jp_group'          => 'verification-tools',
2041
			),
2042
			'pinterest' => array(
2043
				'description'       => esc_html__( 'Pinterest Site Verification', 'jetpack' ),
2044
				'type'              => 'string',
2045
				'default'           => '',
2046
				'validate_callback' => __CLASS__ . '::validate_verification_service',
2047
				'jp_group'          => 'verification-tools',
2048
			),
2049
			'yandex' => array(
2050
				'description'       => esc_html__( 'Yandex Site Verification', 'jetpack' ),
2051
				'type'              => 'string',
2052
				'default'           => '',
2053
				'validate_callback' => __CLASS__ . '::validate_verification_service',
2054
				'jp_group'          => 'verification-tools',
2055
			),
2056
			'enable_header_ad' => array(
2057
				'description'        => esc_html__( 'Display an ad unit at the top of each page.', 'jetpack' ),
2058
				'type'               => 'boolean',
2059
				'default'            => 1,
2060
				'validate_callback'  => __CLASS__ . '::validate_boolean',
2061
				'jp_group'           => 'wordads',
2062
			),
2063
			'wordads_approved' => array(
2064
				'description'        => esc_html__( 'Is site approved for WordAds?', 'jetpack' ),
2065
				'type'               => 'boolean',
2066
				'default'            => 0,
2067
				'validate_callback'  => __CLASS__ . '::validate_boolean',
2068
				'jp_group'           => 'wordads',
2069
			),
2070
			'wordads_second_belowpost' => array(
2071
				'description'        => esc_html__( 'Display second ad below post?', 'jetpack' ),
2072
				'type'               => 'boolean',
2073
				'default'            => 1,
2074
				'validate_callback'  => __CLASS__ . '::validate_boolean',
2075
				'jp_group'           => 'wordads',
2076
			),
2077
			'wordads_display_front_page' => array(
2078
				'description'        => esc_html__( 'Display ads on the front page?', 'jetpack' ),
2079
				'type'               => 'boolean',
2080
				'default'            => 1,
2081
				'validate_callback'  => __CLASS__ . '::validate_boolean',
2082
				'jp_group'           => 'wordads',
2083
			),
2084
			'wordads_display_post' => array(
2085
				'description'        => esc_html__( 'Display ads on posts?', 'jetpack' ),
2086
				'type'               => 'boolean',
2087
				'default'            => 1,
2088
				'validate_callback'  => __CLASS__ . '::validate_boolean',
2089
				'jp_group'           => 'wordads',
2090
			),
2091
			'wordads_display_page' => array(
2092
				'description'        => esc_html__( 'Display ads on pages?', 'jetpack' ),
2093
				'type'               => 'boolean',
2094
				'default'            => 1,
2095
				'validate_callback'  => __CLASS__ . '::validate_boolean',
2096
				'jp_group'           => 'wordads',
2097
			),
2098
			'wordads_display_archive' => array(
2099
				'description'        => esc_html__( 'Display ads on archive pages?', 'jetpack' ),
2100
				'type'               => 'boolean',
2101
				'default'            => 1,
2102
				'validate_callback'  => __CLASS__ . '::validate_boolean',
2103
				'jp_group'           => 'wordads',
2104
			),
2105
			'wordads_custom_adstxt' => array(
2106
				'description'        => esc_html__( 'Custom ads.txt entries', 'jetpack' ),
2107
				'type'               => 'string',
2108
				'default'            => '',
2109
				'validate_callback'  => __CLASS__ . '::validate_string',
2110
				'sanitize_callback'  => 'sanitize_textarea_field',
2111
				'jp_group'           => 'wordads',
2112
			),
2113
2114
			// Google Analytics
2115
			'google_analytics_tracking_id' => array(
2116
				'description'        => esc_html__( 'Google Analytics', 'jetpack' ),
2117
				'type'               => 'string',
2118
				'default'            => '',
2119
				'validate_callback'  => __CLASS__ . '::validate_alphanum',
2120
				'jp_group'           => 'google-analytics',
2121
			),
2122
2123
			// Stats
2124
			'admin_bar' => array(
2125
				'description'       => esc_html__( 'Include a small chart in your admin bar with a 48-hour traffic snapshot.', 'jetpack' ),
2126
				'type'              => 'boolean',
2127
				'default'           => 1,
2128
				'validate_callback' => __CLASS__ . '::validate_boolean',
2129
				'jp_group'          => 'stats',
2130
			),
2131
			'roles' => array(
2132
				'description'       => esc_html__( 'Select the roles that will be able to view stats reports.', 'jetpack' ),
2133
				'type'              => 'array',
2134
				'items'             => array(
2135
					'type' => 'string'
2136
				),
2137
				'default'           => array( 'administrator' ),
2138
				'validate_callback' => __CLASS__ . '::validate_stats_roles',
2139
				'sanitize_callback' => __CLASS__ . '::sanitize_stats_allowed_roles',
2140
				'jp_group'          => 'stats',
2141
			),
2142
			'count_roles' => array(
2143
				'description'       => esc_html__( 'Count the page views of registered users who are logged in.', 'jetpack' ),
2144
				'type'              => 'array',
2145
				'items'             => array(
2146
					'type' => 'string'
2147
				),
2148
				'default'           => array( 'administrator' ),
2149
				'validate_callback' => __CLASS__ . '::validate_stats_roles',
2150
				'jp_group'          => 'stats',
2151
			),
2152
			'blog_id' => array(
2153
				'description'       => esc_html__( 'Blog ID.', 'jetpack' ),
2154
				'type'              => 'boolean',
2155
				'default'           => 0,
2156
				'validate_callback' => __CLASS__ . '::validate_boolean',
2157
				'jp_group'          => 'stats',
2158
			),
2159
			'do_not_track' => array(
2160
				'description'       => esc_html__( 'Do not track.', 'jetpack' ),
2161
				'type'              => 'boolean',
2162
				'default'           => 1,
2163
				'validate_callback' => __CLASS__ . '::validate_boolean',
2164
				'jp_group'          => 'stats',
2165
			),
2166
			'hide_smile' => array(
2167
				'description'       => esc_html__( 'Hide the stats smiley face image.', 'jetpack' ),
2168
				'type'              => 'boolean',
2169
				'default'           => 1,
2170
				'validate_callback' => __CLASS__ . '::validate_boolean',
2171
				'jp_group'          => 'stats',
2172
			),
2173
			'version' => array(
2174
				'description'       => esc_html__( 'Version.', 'jetpack' ),
2175
				'type'              => 'integer',
2176
				'default'           => 9,
2177
				'validate_callback' => __CLASS__ . '::validate_posint',
2178
				'jp_group'          => 'stats',
2179
			),
2180
2181
			// Akismet - Not a module, but a plugin. The options can be passed and handled differently.
2182
			'akismet_show_user_comments_approved' => array(
2183
				'description'       => '',
2184
				'type'              => 'boolean',
2185
				'default'           => 0,
2186
				'validate_callback' => __CLASS__ . '::validate_boolean',
2187
				'jp_group'          => 'settings',
2188
			),
2189
2190
			'wordpress_api_key' => array(
2191
				'description'       => '',
2192
				'type'              => 'string',
2193
				'default'           => '',
2194
				'validate_callback' => __CLASS__ . '::validate_alphanum',
2195
				'jp_group'          => 'settings',
2196
			),
2197
2198
			// Apps card on dashboard
2199
			'dismiss_dash_app_card' => array(
2200
				'description'       => '',
2201
				'type'              => 'boolean',
2202
				'default'           => 0,
2203
				'validate_callback' => __CLASS__ . '::validate_boolean',
2204
				'jp_group'          => 'settings',
2205
			),
2206
2207
			// Empty stats card dismiss
2208
			'dismiss_empty_stats_card' => array(
2209
				'description'       => '',
2210
				'type'              => 'boolean',
2211
				'default'           => 0,
2212
				'validate_callback' => __CLASS__ . '::validate_boolean',
2213
				'jp_group'          => 'settings',
2214
			),
2215
2216
			'lang_id' => array(
2217
				'description' => esc_html__( 'Primary language for the site.', 'jetpack' ),
2218
				'type' => 'string',
2219
				'default' => 'en_US',
2220
				'jp_group' => 'settings',
2221
			),
2222
2223
			'onboarding' => array(
2224
				'description'       => '',
2225
				'type'              => 'object',
2226
				'default'           => array(
2227
					'siteTitle'          => '',
2228
					'siteDescription'    => '',
2229
					'siteType'           => 'personal',
2230
					'homepageFormat'     => 'posts',
2231
					'addContactForm'     => 0,
2232
					'businessAddress'    => array(
2233
						'name'   => '',
2234
						'street' => '',
2235
						'city'   => '',
2236
						'state'  => '',
2237
						'zip'    => '',
2238
					),
2239
					'installWooCommerce' => false,
2240
				),
2241
				'validate_callback' => __CLASS__ . '::validate_onboarding',
2242
				'jp_group'          => 'settings',
2243
			),
2244
2245
		);
2246
2247
		// Add modules to list so they can be toggled
2248
		$modules = Jetpack::get_available_modules();
2249
		if ( is_array( $modules ) && ! empty( $modules ) ) {
2250
			$module_args = array(
2251
				'description'       => '',
2252
				'type'              => 'boolean',
2253
				'default'           => 0,
2254
				'validate_callback' => __CLASS__ . '::validate_boolean',
2255
				'jp_group'          => 'modules',
2256
			);
2257
			foreach( $modules as $module ) {
2258
				$options[ $module ] = $module_args;
2259
			}
2260
		}
2261
2262
		if ( is_array( $selector ) ) {
2263
2264
			// Return only those options whose keys match $selector keys
2265
			return array_intersect_key( $options, $selector );
2266
		}
2267
2268
		if ( 'any' === $selector ) {
2269
2270
			// Toggle module or update any module option or any general setting
2271
			return $options;
2272
		}
2273
2274
		// We're updating the options for a single module.
2275
		if ( empty( $selector ) ) {
2276
			$selector = self::get_module_requested();
2277
		}
2278
		$selected = array();
2279
		foreach ( $options as $option => $attributes ) {
2280
2281
			// Not adding an isset( $attributes['jp_group'] ) because if it's not set, it must be fixed, otherwise options will fail.
2282
			if ( $selector === $attributes['jp_group'] ) {
2283
				$selected[ $option ] = $attributes;
2284
			}
2285
		}
2286
		return $selected;
2287
	}
2288
2289
	/**
2290
	 * Validates that the parameters are proper values that can be set during Jetpack onboarding.
2291
	 *
2292
	 * @since 5.4.0
2293
	 *
2294
	 * @param array           $onboarding_data Values to check.
2295
	 * @param WP_REST_Request $request         The request sent to the WP REST API.
2296
	 * @param string          $param           Name of the parameter passed to endpoint holding $value.
2297
	 *
2298
	 * @return bool|WP_Error
2299
	 */
2300
	public static function validate_onboarding( $onboarding_data, $request, $param ) {
2301
		if ( ! is_array( $onboarding_data ) ) {
2302
			return new WP_Error( 'invalid_param', esc_html__( 'Not valid onboarding data.', 'jetpack' ) );
2303
		}
2304
		foreach ( $onboarding_data as $value ) {
2305
			if ( is_string( $value ) ) {
2306
				$onboarding_choice = self::validate_string( $value, $request, $param );
2307
			} elseif ( is_array( $value ) ) {
2308
				$onboarding_choice = self::validate_onboarding( $value, $request, $param );
2309
			} else {
2310
				$onboarding_choice = self::validate_boolean( $value, $request, $param );
2311
			}
2312
			if ( is_wp_error( $onboarding_choice ) ) {
2313
				return $onboarding_choice;
2314
			}
2315
		}
2316
		return true;
2317
	}
2318
2319
	/**
2320
	 * Validates that the parameter is either a pure boolean or a numeric string that can be mapped to a boolean.
2321
	 *
2322
	 * @since 4.3.0
2323
	 *
2324
	 * @param string|bool $value Value to check.
2325
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2326
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2327
	 *
2328
	 * @return bool|WP_Error
2329
	 */
2330
	public static function validate_boolean( $value, $request, $param ) {
2331
		if ( ! is_bool( $value ) && ! ( ( ctype_digit( $value ) || is_numeric( $value ) ) && in_array( $value, array( 0, 1 ) ) ) ) {
2332
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be true, false, 0 or 1.', 'jetpack' ), $param ) );
2333
		}
2334
		return true;
2335
	}
2336
2337
	/**
2338
	 * Validates that the parameter is a positive integer.
2339
	 *
2340
	 * @since 4.3.0
2341
	 *
2342
	 * @param int $value Value to check.
2343
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2344
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2345
	 *
2346
	 * @return bool|WP_Error
2347
	 */
2348
	public static function validate_posint( $value = 0, $request, $param ) {
2349
		if ( ! is_numeric( $value ) || $value <= 0 ) {
2350
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a positive integer.', 'jetpack' ), $param ) );
2351
		}
2352
		return true;
2353
	}
2354
2355
	/**
2356
	 * Validates that the parameter belongs to a list of admitted values.
2357
	 *
2358
	 * @since 4.3.0
2359
	 *
2360
	 * @param string $value Value to check.
2361
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2362
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2363
	 *
2364
	 * @return bool|WP_Error
2365
	 */
2366
	public static function validate_list_item( $value = '', $request, $param ) {
2367
		$attributes = $request->get_attributes();
2368
		if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
2369
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s not recognized', 'jetpack' ), $param ) );
2370
		}
2371
		$args = $attributes['args'][ $param ];
2372
		if ( ! empty( $args['enum'] ) ) {
2373
2374
			// If it's an associative array, use the keys to check that the value is among those admitted.
2375
			$enum = ( count( array_filter( array_keys( $args['enum'] ), 'is_string' ) ) > 0 ) ? array_keys( $args['enum'] ) : $args['enum'];
2376 View Code Duplication
			if ( ! in_array( $value, $enum ) ) {
2377
				return new WP_Error( 'invalid_param_value', sprintf(
2378
					/* Translators: first variable is the parameter passed to endpoint that holds the list item, the second is a list of admitted values. */
2379
					esc_html__( '%1$s must be one of %2$s', 'jetpack' ), $param, implode( ', ', $enum )
2380
				) );
2381
			}
2382
		}
2383
		return true;
2384
	}
2385
2386
	/**
2387
	 * Validates that the parameter belongs to a list of admitted values.
2388
	 *
2389
	 * @since 4.3.0
2390
	 *
2391
	 * @param string $value Value to check.
2392
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2393
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2394
	 *
2395
	 * @return bool|WP_Error
2396
	 */
2397
	public static function validate_module_list( $value = '', $request, $param ) {
2398 View Code Duplication
		if ( ! is_array( $value ) ) {
2399
			return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be an array', 'jetpack' ), $param ) );
2400
		}
2401
2402
		$modules = Jetpack::get_available_modules();
2403
2404 View Code Duplication
		if ( count( array_intersect( $value, $modules ) ) != count( $value ) ) {
2405
			return new WP_Error( 'invalid_param_value', sprintf( esc_html__( '%s must be a list of valid modules', 'jetpack' ), $param ) );
2406
		}
2407
2408
		return true;
2409
	}
2410
2411
	/**
2412
	 * Validates that the parameter is an alphanumeric or empty string (to be able to clear the field).
2413
	 *
2414
	 * @since 4.3.0
2415
	 *
2416
	 * @param string $value Value to check.
2417
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2418
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2419
	 *
2420
	 * @return bool|WP_Error
2421
	 */
2422
	public static function validate_alphanum( $value = '', $request, $param ) {
2423 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/^[a-z0-9]+$/i', $value ) ) ) {
2424
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an alphanumeric string.', 'jetpack' ), $param ) );
2425
		}
2426
		return true;
2427
	}
2428
2429
	/**
2430
	 * Validates that the parameter is a tag or id for a verification service, or an empty string (to be able to clear the field).
2431
	 *
2432
	 * @since 4.6.0
2433
	 *
2434
	 * @param string $value Value to check.
2435
	 * @param WP_REST_Request $request
2436
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2437
	 *
2438
	 * @return bool|WP_Error
2439
	 */
2440
	public static function validate_verification_service( $value = '', $request, $param ) {
2441
		if ( ! empty( $value ) && ! ( is_string( $value ) && ( preg_match( '/^[a-z0-9_-]+$/i', $value ) || jetpack_verification_get_code( $value ) !== false ) ) ) {
2442
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an alphanumeric string or a verification tag.', 'jetpack' ), $param ) );
2443
		}
2444
		return true;
2445
	}
2446
2447
	/**
2448
	 * Validates that the parameter is among the roles allowed for Stats.
2449
	 *
2450
	 * @since 4.3.0
2451
	 *
2452
	 * @param string|bool $value Value to check.
2453
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2454
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2455
	 *
2456
	 * @return bool|WP_Error
2457
	 */
2458
	public static function validate_stats_roles( $value, $request, $param ) {
2459
		if ( ! empty( $value ) && ! array_intersect( self::$stats_roles, $value ) ) {
2460
			return new WP_Error( 'invalid_param', sprintf(
2461
				/* Translators: first variable is the name of a parameter passed to endpoint holding the role that will be checked, the second is a list of roles allowed to see stats. The parameter is checked against this list. */
2462
				esc_html__( '%1$s must be %2$s.', 'jetpack' ), $param, join( ', ', self::$stats_roles )
2463
			) );
2464
		}
2465
		return true;
2466
	}
2467
2468
	/**
2469
	 * Validates that the parameter is among the views where the Sharing can be displayed.
2470
	 *
2471
	 * @since 4.3.0
2472
	 *
2473
	 * @param string|bool $value Value to check.
2474
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2475
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2476
	 *
2477
	 * @return bool|WP_Error
2478
	 */
2479
	public static function validate_sharing_show( $value, $request, $param ) {
2480
		$views = array( 'index', 'post', 'page', 'attachment', 'jetpack-portfolio' );
2481 View Code Duplication
		if ( ! is_array( $value ) ) {
2482
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array of post types.', 'jetpack' ), $param ) );
2483
		}
2484
		if ( ! array_intersect( $views, $value ) ) {
2485
			return new WP_Error( 'invalid_param', sprintf(
2486
				/* Translators: first variable is the name of a parameter passed to endpoint holding the post type where Sharing will be displayed, the second is a list of post types where Sharing can be displayed */
2487
				esc_html__( '%1$s must be %2$s.', 'jetpack' ), $param, join( ', ', $views )
2488
			) );
2489
		}
2490
		return true;
2491
	}
2492
2493
	/**
2494
	 * Validates that the parameter is among the views where the Sharing can be displayed.
2495
	 *
2496
	 * @since 4.3.0
2497
	 *
2498
	 * @param string|bool $value {
2499
	 *     Value to check received by request.
2500
	 *
2501
	 *     @type array $visible List of slug of services to share to that are displayed directly in the page.
2502
	 *     @type array $hidden  List of slug of services to share to that are concealed in a folding menu.
2503
	 * }
2504
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2505
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2506
	 *
2507
	 * @return bool|WP_Error
2508
	 */
2509
	public static function validate_services( $value, $request, $param ) {
2510 View Code Duplication
		if ( ! is_array( $value ) || ! isset( $value['visible'] ) || ! isset( $value['hidden'] ) ) {
2511
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array with visible and hidden items.', 'jetpack' ), $param ) );
2512
		}
2513
2514
		// Allow to clear everything.
2515
		if ( empty( $value['visible'] ) && empty( $value['hidden'] ) ) {
2516
			return true;
2517
		}
2518
2519 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! include_once( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
2520
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
2521
		}
2522
		$sharer = new Sharing_Service();
2523
		$services = array_keys( $sharer->get_all_services() );
2524
2525
		if (
2526
			( ! empty( $value['visible'] ) && ! array_intersect( $value['visible'], $services ) )
2527
			||
2528
			( ! empty( $value['hidden'] ) && ! array_intersect( $value['hidden'], $services ) ) )
2529
		{
2530
			return new WP_Error( 'invalid_param', sprintf(
2531
				/* Translators: placeholder 1 is a parameter holding the services passed to endpoint, placeholder 2 is a list of all Jetpack Sharing services */
2532
				esc_html__( '%1$s visible and hidden items must be a list of %2$s.', 'jetpack' ), $param, join( ', ', $services )
2533
			) );
2534
		}
2535
		return true;
2536
	}
2537
2538
	/**
2539
	 * Validates that the parameter has enough information to build a custom sharing button.
2540
	 *
2541
	 * @since 4.3.0
2542
	 *
2543
	 * @param string|bool $value Value to check.
2544
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2545
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2546
	 *
2547
	 * @return bool|WP_Error
2548
	 */
2549
	public static function validate_custom_service( $value, $request, $param ) {
2550
		if ( ! is_array( $value ) || ! isset( $value['sharing_name'] ) || ! isset( $value['sharing_url'] ) || ! isset( $value['sharing_icon'] ) ) {
2551
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an array with sharing name, url and icon.', 'jetpack' ), $param ) );
2552
		}
2553
2554
		// Allow to clear everything.
2555
		if ( empty( $value['sharing_name'] ) && empty( $value['sharing_url'] ) && empty( $value['sharing_icon'] ) ) {
2556
			return true;
2557
		}
2558
2559 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! include_once( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
2560
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
2561
		}
2562
2563
		if ( ( ! empty( $value['sharing_name'] ) && ! is_string( $value['sharing_name'] ) )
2564
		|| ( ! empty( $value['sharing_url'] ) && ! is_string( $value['sharing_url'] ) )
2565
		|| ( ! empty( $value['sharing_icon'] ) && ! is_string( $value['sharing_icon'] ) ) ) {
2566
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s needs sharing name, url and icon.', 'jetpack' ), $param ) );
2567
		}
2568
		return true;
2569
	}
2570
2571
	/**
2572
	 * Validates that the parameter is a custom sharing service ID like 'custom-1461976264'.
2573
	 *
2574
	 * @since 4.3.0
2575
	 *
2576
	 * @param string $value Value to check.
2577
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2578
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2579
	 *
2580
	 * @return bool|WP_Error
2581
	 */
2582
	public static function validate_custom_service_id( $value = '', $request, $param ) {
2583 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/custom\-[0-1]+/i', $value ) ) ) {
2584
			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 ) );
2585
		}
2586
2587 View Code Duplication
		if ( ! class_exists( 'Sharing_Service' ) && ! include_once( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
2588
			return new WP_Error( 'invalid_param', esc_html__( 'Failed loading required dependency Sharing_Service.', 'jetpack' ) );
2589
		}
2590
		$sharer = new Sharing_Service();
2591
		$services = array_keys( $sharer->get_all_services() );
2592
2593 View Code Duplication
		if ( ! empty( $value ) && ! in_array( $value, $services ) ) {
2594
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s is not a registered custom sharing service.', 'jetpack' ), $param ) );
2595
		}
2596
2597
		return true;
2598
	}
2599
2600
	/**
2601
	 * Validates that the parameter is a Twitter username or empty string (to be able to clear the field).
2602
	 *
2603
	 * @since 4.3.0
2604
	 *
2605
	 * @param string $value Value to check.
2606
	 * @param WP_REST_Request $request
2607
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2608
	 *
2609
	 * @return bool|WP_Error
2610
	 */
2611
	public static function validate_twitter_username( $value = '', $request, $param ) {
2612 View Code Duplication
		if ( ! empty( $value ) && ( ! is_string( $value ) || ! preg_match( '/^@?\w{1,15}$/i', $value ) ) ) {
2613
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a Twitter username.', 'jetpack' ), $param ) );
2614
		}
2615
		return true;
2616
	}
2617
2618
	/**
2619
	 * Validates that the parameter is a string.
2620
	 *
2621
	 * @since 4.3.0
2622
	 *
2623
	 * @param string $value Value to check.
2624
	 * @param WP_REST_Request $request The request sent to the WP REST API.
2625
	 * @param string $param Name of the parameter passed to endpoint holding $value.
2626
	 *
2627
	 * @return bool|WP_Error
2628
	 */
2629
	public static function validate_string( $value = '', $request, $param ) {
2630
		if ( ! is_string( $value ) ) {
2631
			return new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be a string.', 'jetpack' ), $param ) );
2632
		}
2633
		return true;
2634
	}
2635
2636
	/**
2637
	 * If for some reason the roles allowed to see Stats are empty (for example, user tampering with checkboxes),
2638
	 * return an array with only 'administrator' as the allowed role and save it for 'roles' option.
2639
	 *
2640
	 * @since 4.3.0
2641
	 *
2642
	 * @param string|bool $value Value to check.
2643
	 *
2644
	 * @return bool|array
2645
	 */
2646
	public static function sanitize_stats_allowed_roles( $value ) {
2647
		if ( empty( $value ) ) {
2648
			return array( 'administrator' );
2649
		}
2650
		return $value;
2651
	}
2652
2653
	/**
2654
	 * Get the currently accessed route and return the module slug in it.
2655
	 *
2656
	 * @since 4.3.0
2657
	 *
2658
	 * @param string $route Regular expression for the endpoint with the module slug to return.
2659
	 *
2660
	 * @return array|string
2661
	 */
2662
	public static function get_module_requested( $route = '/module/(?P<slug>[a-z\-]+)' ) {
2663
2664
		if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
2665
			return '';
2666
		}
2667
2668
		preg_match( "#$route#", $GLOBALS['wp']->query_vars['rest_route'], $module );
2669
2670
		if ( empty( $module['slug'] ) ) {
2671
			return '';
2672
		}
2673
2674
		return $module['slug'];
2675
	}
2676
2677
	/**
2678
	 * Adds extra information for modules.
2679
	 *
2680
	 * @since 4.3.0
2681
	 *
2682
	 * @param string|array $modules Can be a single module or a list of modules.
2683
	 * @param null|string  $slug    Slug of the module in the first parameter.
2684
	 *
2685
	 * @return array|string
2686
	 */
2687
	public static function prepare_modules_for_response( $modules = '', $slug = null ) {
2688
		global $wp_rewrite;
2689
2690
		/** This filter is documented in modules/sitemaps/sitemaps.php */
2691
		$location = apply_filters( 'jetpack_sitemap_location', '' );
2692
2693
		if ( $wp_rewrite->using_index_permalinks() ) {
2694
			$sitemap_url = home_url( '/index.php' . $location . '/sitemap.xml' );
2695
			$news_sitemap_url = home_url( '/index.php' . $location . '/news-sitemap.xml' );
2696
		} else if ( $wp_rewrite->using_permalinks() ) {
2697
			$sitemap_url = home_url( $location . '/sitemap.xml' );
2698
			$news_sitemap_url = home_url( $location . '/news-sitemap.xml' );
2699
		} else {
2700
			$sitemap_url = home_url( $location . '/?jetpack-sitemap=sitemap.xml' );
2701
			$news_sitemap_url = home_url( $location . '/?jetpack-sitemap=news-sitemap.xml' );
2702
		}
2703
2704
		if ( is_null( $slug ) && isset( $modules['sitemaps'] ) ) {
2705
			// Is a list of modules
2706
			$modules['sitemaps']['extra']['sitemap_url'] = $sitemap_url;
2707
			$modules['sitemaps']['extra']['news_sitemap_url'] = $news_sitemap_url;
2708
		} elseif ( 'sitemaps' == $slug ) {
2709
			// It's a single module
2710
			$modules['extra']['sitemap_url'] = $sitemap_url;
2711
			$modules['extra']['news_sitemap_url'] = $news_sitemap_url;
2712
		}
2713
		return $modules;
2714
	}
2715
2716
	/**
2717
	 * Remove 'validate_callback' item from options available for module.
2718
	 * Fetch current option value and add to array of module options.
2719
	 * Prepare values of module options that need special handling, like those saved in wpcom.
2720
	 *
2721
	 * @since 4.3.0
2722
	 *
2723
	 * @param string $module Module slug.
2724
	 * @return array
2725
	 */
2726
	public static function prepare_options_for_response( $module = '' ) {
2727
		$options = self::get_updateable_data_list( $module );
2728
2729
		if ( ! is_array( $options ) || empty( $options ) ) {
2730
			return $options;
2731
		}
2732
2733
		// Some modules need special treatment.
2734
		switch ( $module ) {
2735
2736
			case 'monitor':
2737
				// Status of user notifications
2738
				$options['monitor_receive_notifications']['current_value'] = self::cast_value( self::get_remote_value( 'monitor', 'monitor_receive_notifications' ), $options['monitor_receive_notifications'] );
2739
				break;
2740
2741
			case 'post-by-email':
2742
				// Email address
2743
				$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'] );
2744
				break;
2745
2746
			case 'protect':
2747
				// Protect
2748
				$options['jetpack_protect_key']['current_value'] = get_site_option( 'jetpack_protect_key', false );
2749
				if ( ! function_exists( 'jetpack_protect_format_whitelist' ) ) {
2750
					include_once( JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php' );
2751
				}
2752
				$options['jetpack_protect_global_whitelist']['current_value'] = jetpack_protect_format_whitelist();
2753
				break;
2754
2755
			case 'related-posts':
2756
				// It's local, but it must be broken apart since it's saved as an array.
2757
				$options = self::split_options( $options, Jetpack_Options::get_option( 'relatedposts' ) );
2758
				break;
2759
2760
			case 'verification-tools':
2761
				// It's local, but it must be broken apart since it's saved as an array.
2762
				$options = self::split_options( $options, get_option( 'verification_services_codes' ) );
2763
				break;
2764
2765
			case 'google-analytics':
2766
				$wga = get_option( 'jetpack_wga' );
2767
				$code = '';
2768
				if ( is_array( $wga ) && array_key_exists( 'code', $wga ) ) {
2769
					 $code = $wga[ 'code' ];
2770
				}
2771
				$options[ 'google_analytics_tracking_id' ][ 'current_value' ] = $code;
2772
				break;
2773
2774
			case 'sharedaddy':
2775
				// It's local, but it must be broken apart since it's saved as an array.
2776
				if ( ! class_exists( 'Sharing_Service' ) && ! include_once( JETPACK__PLUGIN_DIR . 'modules/sharedaddy/sharing-service.php' ) ) {
2777
					break;
2778
				}
2779
				$sharer = new Sharing_Service();
2780
				$options = self::split_options( $options, $sharer->get_global_options() );
2781
				$options['sharing_services']['current_value'] = $sharer->get_blog_services();
2782
				$other_sharedaddy_options = array( 'jetpack-twitter-cards-site-tag', 'sharedaddy_disable_resources', 'sharing_delete_service' );
2783 View Code Duplication
				foreach ( $other_sharedaddy_options as $key ) {
2784
					$default_value = isset( $options[ $key ]['default'] ) ? $options[ $key ]['default'] : '';
2785
					$current_value = get_option( $key, $default_value );
2786
					$options[ $key ]['current_value'] = self::cast_value( $current_value, $options[ $key ] );
2787
				}
2788
				break;
2789
2790
			case 'stats':
2791
				// It's local, but it must be broken apart since it's saved as an array.
2792
				if ( ! function_exists( 'stats_get_options' ) ) {
2793
					include_once( JETPACK__PLUGIN_DIR . 'modules/stats.php' );
2794
				}
2795
				$options = self::split_options( $options, stats_get_options() );
2796
				break;
2797
			default:
2798
				// These option are just stored as plain WordPress options.
2799 View Code Duplication
				foreach ( $options as $key => $value ) {
2800
					$default_value = isset( $options[ $key ]['default'] ) ? $options[ $key ]['default'] : '';
2801
					$current_value = get_option( $key, $default_value );
2802
					$options[ $key ]['current_value'] = self::cast_value( $current_value, $options[ $key ] );
2803
				}
2804
		}
2805
		// At this point some options have current_value not set because they're options
2806
		// that only get written on update, so we set current_value to the default one.
2807
		foreach ( $options as $key => $value ) {
2808
			// We don't need validate_callback in the response
2809
			if ( isset( $options[ $key ]['validate_callback'] ) ) {
2810
				unset( $options[ $key ]['validate_callback'] );
2811
			}
2812
			$default_value = isset( $options[ $key ]['default'] ) ? $options[ $key ]['default'] : '';
2813
			if ( ! array_key_exists( 'current_value', $options[ $key ] ) ) {
2814
				$options[ $key ]['current_value'] = self::cast_value( $default_value, $options[ $key ] );
2815
			}
2816
		}
2817
		return $options;
2818
	}
2819
2820
	/**
2821
	 * Splits module options saved as arrays like relatedposts or verification_services_codes into separate options to be returned in the response.
2822
	 *
2823
	 * @since 4.3.0
2824
	 *
2825
	 * @param array  $separate_options Array of options admitted by the module.
2826
	 * @param array  $grouped_options Option saved as array to be splitted.
2827
	 * @param string $prefix Optional prefix for the separate option keys.
2828
	 *
2829
	 * @return array
2830
	 */
2831
	public static function split_options( $separate_options, $grouped_options, $prefix = '' ) {
2832
		if ( is_array( $grouped_options ) ) {
2833
			foreach ( $grouped_options as $key => $value ) {
2834
				$option_key = $prefix . $key;
2835
				if ( isset( $separate_options[ $option_key ] ) ) {
2836
					$separate_options[ $option_key ]['current_value'] = self::cast_value( $grouped_options[ $key ], $separate_options[ $option_key ] );
2837
				}
2838
			}
2839
		}
2840
		return $separate_options;
2841
	}
2842
2843
	/**
2844
	 * Perform a casting to the value specified in the option definition.
2845
	 *
2846
	 * @since 4.3.0
2847
	 *
2848
	 * @param mixed $value Value to cast to the proper type.
2849
	 * @param array $definition Type to cast the value to.
2850
	 *
2851
	 * @return bool|float|int|string
2852
	 */
2853
	public static function cast_value( $value, $definition ) {
2854
		if ( $value === 'NULL' ) {
2855
			return null;
2856
		}
2857
2858
		if ( isset( $definition['type'] ) ) {
2859
			switch ( $definition['type'] ) {
2860
				case 'boolean':
2861
					if ( 'true' === $value ) {
2862
						return true;
2863
					} elseif ( 'false' === $value ) {
2864
						return false;
2865
					}
2866
					return (bool) $value;
2867
					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...
2868
2869
				case 'integer':
2870
					return (int) $value;
2871
					break;
2872
2873
				case 'float':
2874
					return (float) $value;
2875
					break;
2876
2877
				case 'string':
2878
					return (string) $value;
2879
					break;
2880
			}
2881
		}
2882
		return $value;
2883
	}
2884
2885
	/**
2886
	 * Get a value not saved locally.
2887
	 *
2888
	 * @since 4.3.0
2889
	 *
2890
	 * @param string $module Module slug.
2891
	 * @param string $option Option name.
2892
	 *
2893
	 * @return bool Whether user is receiving notifications or not.
2894
	 */
2895
	public static function get_remote_value( $module, $option ) {
2896
2897
		if ( in_array( $module, array( 'post-by-email' ), true ) ) {
2898
			$option .= get_current_user_id();
2899
		}
2900
2901
		// If option doesn't exist, 'does_not_exist' will be returned.
2902
		$value = get_option( $option, 'does_not_exist' );
2903
2904
		// If option exists, just return it.
2905
		if ( 'does_not_exist' !== $value ) {
2906
			return $value;
2907
		}
2908
2909
		// Only check a remote option if Jetpack is connected.
2910
		if ( ! Jetpack::is_active() ) {
2911
			return false;
2912
		}
2913
2914
		// Do what is necessary for each module.
2915
		switch ( $module ) {
2916
			case 'monitor':
2917
				// Load the class to use the method. If class can't be found, do nothing.
2918
				if ( ! class_exists( 'Jetpack_Monitor' ) && ! include_once( Jetpack::get_module_path( $module ) ) ) {
2919
					return false;
2920
				}
2921
				$value = Jetpack_Monitor::user_receives_notifications( false );
2922
				break;
2923
2924
			case 'post-by-email':
2925
				// Load the class to use the method. If class can't be found, do nothing.
2926
				if ( ! class_exists( 'Jetpack_Post_By_Email' ) && ! include_once( Jetpack::get_module_path( $module ) ) ) {
2927
					return false;
2928
				}
2929
				$post_by_email = new Jetpack_Post_By_Email();
2930
				$value = $post_by_email->get_post_by_email_address();
2931
				if ( $value === null ) {
2932
					$value = 'NULL'; // sentinel value so it actually gets set
2933
				}
2934
				break;
2935
		}
2936
2937
		// Normalize value to boolean.
2938
		if ( is_wp_error( $value ) || is_null( $value ) ) {
2939
			$value = false;
2940
		}
2941
2942
		// Save option to use it next time.
2943
		update_option( $option, $value );
2944
2945
		return $value;
2946
	}
2947
2948
	/**
2949
	 * Get number of plugin updates available.
2950
	 *
2951
	 * @since 4.3.0
2952
	 *
2953
	 * @return mixed|WP_Error Number of plugin updates available. Otherwise, a WP_Error instance with the corresponding error.
2954
	 */
2955
	public static function get_plugin_update_count() {
2956
		$updates = wp_get_update_data();
2957
		if ( isset( $updates['counts'] ) && isset( $updates['counts']['plugins'] ) ) {
2958
			$count = $updates['counts']['plugins'];
2959
			if ( 0 == $count ) {
2960
				$response = array(
2961
					'code'    => 'success',
2962
					'message' => esc_html__( 'All plugins are up-to-date. Keep up the good work!', 'jetpack' ),
2963
					'count'   => 0,
2964
				);
2965
			} else {
2966
				$response = array(
2967
					'code'    => 'updates-available',
2968
					'message' => esc_html( sprintf( _n( '%s plugin need updating.', '%s plugins need updating.', $count, 'jetpack' ), $count ) ),
2969
					'count'   => $count,
2970
				);
2971
			}
2972
			return rest_ensure_response( $response );
2973
		}
2974
2975
		return new WP_Error( 'not_found', esc_html__( 'Could not check updates for plugins on this site.', 'jetpack' ), array( 'status' => 404 ) );
2976
	}
2977
2978
2979
	/**
2980
	 * Returns a list of all plugins in the site.
2981
	 *
2982
	 * @since 4.2.0
2983
	 * @uses get_plugins()
2984
	 *
2985
	 * @return array
2986
	 */
2987
	private static function core_get_plugins() {
2988
		if ( ! function_exists( 'get_plugins' ) ) {
2989
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2990
		}
2991
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2992
		$plugins = apply_filters( 'all_plugins', get_plugins() );
2993
2994
		if ( is_array( $plugins ) && ! empty( $plugins ) ) {
2995
			foreach ( $plugins as $plugin_slug => $plugin_data ) {
2996
				$plugins[ $plugin_slug ]['active'] = self::core_is_plugin_active( $plugin_slug );
2997
			}
2998
			return $plugins;
2999
		}
3000
3001
		return array();
3002
	}
3003
3004
	/**
3005
	 * Deprecated - Get third party plugin API keys.
3006
	 * @deprecated
3007
	 *
3008
	 * @param WP_REST_Request $request {
3009
	 *     Array of parameters received by request.
3010
	 *
3011
	 *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
3012
	 * }
3013
	 */
3014
	public static function get_service_api_key( $request ) {
3015
		_deprecated_function( __METHOD__, 'jetpack-6.9.0', 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys::get_service_api_key' );
3016
		return WPCOM_REST_API_V2_Endpoint_Service_API_Keys::get_service_api_key( $request );
3017
	}
3018
3019
	/**
3020
	 * Deprecated - Update third party plugin API keys.
3021
	 * @deprecated
3022
	 *
3023
	 * @param WP_REST_Request $request {
3024
	 *     Array of parameters received by request.
3025
	 *
3026
	 *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
3027
	 * }
3028
	 */
3029
	public static function update_service_api_key( $request ) {
3030
		_deprecated_function( __METHOD__, 'jetpack-6.9.0', 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys::update_service_api_key' );
3031
		return WPCOM_REST_API_V2_Endpoint_Service_API_Keys::update_service_api_key( $request ) ;
3032
	}
3033
3034
	/**
3035
	 * Deprecated - Delete a third party plugin API key.
3036
	 * @deprecated
3037
	 *
3038
	 * @param WP_REST_Request $request {
3039
	 *     Array of parameters received by request.
3040
	 *
3041
	 *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
3042
	 * }
3043
	 */
3044
	public static function delete_service_api_key( $request ) {
3045
		_deprecated_function( __METHOD__, 'jetpack-6.9.0', 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys::delete_service_api_key' );
3046
		return WPCOM_REST_API_V2_Endpoint_Service_API_Keys::delete_service_api_key( $request );
3047
	}
3048
3049
	/**
3050
	 * Deprecated - Validate the service provided in /service-api-keys/ endpoints.
3051
	 * To add a service to these endpoints, add the service name to $valid_services
3052
	 * and add '{service name}_api_key' to the non-compact return array in get_option_names(),
3053
	 * in class-jetpack-options.php
3054
	 * @deprecated
3055
	 *
3056
	 * @param string $service The service the API key is for.
3057
	 * @return string Returns the service name if valid, null if invalid.
3058
	 */
3059
	public static function validate_service_api_service( $service = null ) {
3060
		_deprecated_function( __METHOD__, 'jetpack-6.9.0', 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys::validate_service_api_service' );
3061
		return WPCOM_REST_API_V2_Endpoint_Service_API_Keys::validate_service_api_service( $service );
3062
	}
3063
3064
	/**
3065
	 * Error response for invalid service API key requests with an invalid service.
3066
	 */
3067
	public static function service_api_invalid_service_response() {
3068
		_deprecated_function( __METHOD__, 'jetpack-6.9.0', 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys::service_api_invalid_service_response' );
3069
		return WPCOM_REST_API_V2_Endpoint_Service_API_Keys::service_api_invalid_service_response();
3070
	}
3071
3072
	/**
3073
	 * Deprecated - Validate API Key
3074
	 * @deprecated
3075
	 *
3076
	 * @param string $key The API key to be validated.
3077
	 * @param string $service The service the API key is for.
3078
	 *
3079
	 */
3080
	public static function validate_service_api_key( $key = null, $service = null ) {
3081
		_deprecated_function( __METHOD__, 'jetpack-6.9.0', 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys::validate_service_api_key' );
3082
		return WPCOM_REST_API_V2_Endpoint_Service_API_Keys::validate_service_api_key( $key , $service  );
3083
	}
3084
3085
	/**
3086
	 * Deprecated - Validate Mapbox API key
3087
	 * Based loosely on https://github.com/mapbox/geocoding-example/blob/master/php/MapboxTest.php
3088
	 * @deprecated
3089
	 *
3090
	 * @param string $key The API key to be validated.
3091
	 */
3092
	public static function validate_service_api_key_mapbox( $key ) {
3093
		_deprecated_function( __METHOD__, 'jetpack-6.9.0', 'WPCOM_REST_API_V2_Endpoint_Service_API_Keys::validate_service_api_key' );
3094
		return WPCOM_REST_API_V2_Endpoint_Service_API_Keys::validate_service_api_key_mapbox( $key );
3095
3096
	}
3097
3098
	/**
3099
	 * Checks if the queried plugin is active.
3100
	 *
3101
	 * @since 4.2.0
3102
	 * @uses is_plugin_active()
3103
	 *
3104
	 * @return bool
3105
	 */
3106
	private static function core_is_plugin_active( $plugin ) {
3107
		if ( ! function_exists( 'is_plugin_active' ) ) {
3108
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
3109
		}
3110
3111
		return is_plugin_active( $plugin );
3112
	}
3113
3114
	/**
3115
	 * Get plugins data in site.
3116
	 *
3117
	 * @since 4.2.0
3118
	 *
3119
	 * @return WP_REST_Response|WP_Error List of plugins in the site. Otherwise, a WP_Error instance with the corresponding error.
3120
	 */
3121
	public static function get_plugins() {
3122
		$plugins = self::core_get_plugins();
3123
3124
		if ( ! empty( $plugins ) ) {
3125
			return rest_ensure_response( $plugins );
3126
		}
3127
3128
		return new WP_Error( 'not_found', esc_html__( 'Unable to list plugins.', 'jetpack' ), array( 'status' => 404 ) );
3129
	}
3130
3131
	/**
3132
	 * Ensures that Akismet is installed and activated.
3133
	 *
3134
	 * @since 7.7
3135
	 *
3136
	 * @return WP_REST_Response A response indicating whether or not the installation was successful.
3137
	 */
3138
	public static function activate_akismet() {
3139
		jetpack_require_lib( 'plugins' );
3140
		$result = Jetpack_Plugins::install_and_activate_plugin('akismet');
3141
3142
		if ( is_wp_error( $result ) ) {
3143
			return rest_ensure_response( array(
3144
				'code'    => 'failure',
3145
				'message' => esc_html__( 'Unable to activate Akismet', 'jetpack' )
3146
			) );
3147
		} else {
3148
			return rest_ensure_response( array(
3149
				'code'    => 'success',
3150
				'message' => esc_html__( 'Activated Akismet', 'jetpack' )
3151
			) );
3152
		}
3153
	}
3154
3155
	/**
3156
	 * Get data about the queried plugin. Currently it only returns whether the plugin is active or not.
3157
	 *
3158
	 * @since 4.2.0
3159
	 *
3160
	 * @param WP_REST_Request $request {
3161
	 *     Array of parameters received by request.
3162
	 *
3163
	 *     @type string $slug Plugin slug with the syntax 'plugin-directory/plugin-main-file.php'.
3164
	 * }
3165
	 *
3166
	 * @return bool|WP_Error True if module was activated. Otherwise, a WP_Error instance with the corresponding error.
3167
	 */
3168
	public static function get_plugin( $request ) {
3169
3170
		$plugins = self::core_get_plugins();
3171
3172
		if ( empty( $plugins ) ) {
3173
			return new WP_Error( 'no_plugins_found', esc_html__( 'This site has no plugins.', 'jetpack' ), array( 'status' => 404 ) );
3174
		}
3175
3176
		$plugin = stripslashes( $request['plugin'] );
3177
3178
		if ( ! in_array( $plugin, array_keys( $plugins ) ) ) {
3179
			return new WP_Error( 'plugin_not_found', esc_html( sprintf( __( 'Plugin %s is not installed.', 'jetpack' ), $plugin ) ), array( 'status' => 404 ) );
3180
		}
3181
3182
		$plugin_data = $plugins[ $plugin ];
3183
3184
		$plugin_data['active'] = self::core_is_plugin_active( $plugin );
3185
3186
		return rest_ensure_response( array(
3187
			'code'    => 'success',
3188
			'message' => esc_html__( 'Plugin found.', 'jetpack' ),
3189
			'data'    => $plugin_data
3190
		) );
3191
	}
3192
3193
	/**
3194
	 * Proxies a request to WordPress.com to request that a magic link be sent to the current user
3195
	 * to log this user in to the mobile app via email.
3196
	 *
3197
	 * @param WP_REST_REQUEST $request The request parameters.
3198
	 * @return bool|WP_Error
3199
	 */
3200
	public static function send_mobile_magic_link( $request ) {
3201
		$xml = new Jetpack_IXR_Client(
3202
			array(
3203
				'user_id' => get_current_user_id(),
3204
			)
3205
		);
3206
3207
		$xml->query( 'jetpack.sendMobileMagicLink', array() );
3208
		if ( $xml->isError() ) {
3209
			return new WP_Error(
3210
				'error_sending_mobile_magic_link',
3211
				sprintf(
3212
					'%s: %s',
3213
					$xml->getErrorCode(),
3214
					$xml->getErrorMessage()
3215
				)
3216
			);
3217
		}
3218
3219
		$response = $xml->getResponse();
3220
3221
		return rest_ensure_response(
3222
			array(
3223
				'code' => 'success',
3224
			)
3225
		);
3226
	}
3227
} // class end
3228