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