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