PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 16.3-beta
Jetpack – WP Security, Backup, Speed, & Growth v16.3-beta
16.3-beta 16.3-a.5 16.3-a.7 16.3-a.3 16.3-a.1 16.2 16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 All 507 releases
← All changes | jetpack_vendor/automattic/jetpack-connection/src/class-manager.php +1699 -167 12.0.3 → 16.3-beta View file →
@@ -6,17 +6,22 @@
6 6 */
7 7
8 8 namespace Automattic\Jetpack\Connection;
9 9
10 -use Automattic\Jetpack\A8c_Mc_Stats as A8c_Mc_Stats;
10 +use Automattic\Jetpack\A8c_Mc_Stats;
11 11 use Automattic\Jetpack\Constants;
12 12 use Automattic\Jetpack\Heartbeat;
13 +use Automattic\Jetpack\Identity_Crisis;
14 +use Automattic\Jetpack\Partner;
13 15 use Automattic\Jetpack\Roles;
14 16 use Automattic\Jetpack\Status;
17 +use Automattic\Jetpack\Status\Host;
15 18 use Automattic\Jetpack\Terms_Of_Service;
16 19 use Automattic\Jetpack\Tracking;
20 +use IXR_Error;
17 21 use Jetpack_IXR_Client;
18 22 use Jetpack_Options;
23 +use Jetpack_XMLRPC_Server;
19 24 use WP_Error;
20 25 use WP_User;
21 26
22 27 /**
@@ -24,11 +29,36 @@
24 29 * and Jetpack.
25 30 */
26 31 class Manager {
27 32 /**
33 + * Prefix of the transient holding the cached WordPress.com site record. The blog ID is
34 + * appended so a reconnect to a different site cannot read the previous site's record.
35 + *
36 + * @since 9.0.0
37 + *
38 + * @var string
39 + */
40 + const SITE_DATA_TRANSIENT_PREFIX = 'jetpack_site_data_';
41 +
42 + /**
43 + * Why `has_protected_owner()` answered false, and what would change it.
44 + *
45 + * `RE_EVALUATE` is the race: the gate said false, and by the time the state was classified the
46 + * owner matched after all. It is not a problem to report, it is an instruction to ask again.
47 + *
48 + * @since 9.4.0
49 + */
50 + const PO_STATE_NOT_ELIGIBLE = 'NOT_ELIGIBLE';
51 + const PO_STATE_NEEDS_CONNECT_TO_ESTABLISH = 'NEEDS_CONNECT_TO_ESTABLISH';
52 + const PO_STATE_CAN_ESTABLISH = 'CAN_ESTABLISH';
53 + const PO_STATE_NEEDS_OWNER_RECONNECT = 'NEEDS_OWNER_RECONNECT';
54 + const PO_STATE_NEEDS_DIFFERENT_OWNER = 'NEEDS_DIFFERENT_OWNER';
55 + const PO_STATE_RE_EVALUATE = 'RE_EVALUATE';
56 +
57 + /**
28 58 * A copy of the raw POST data for signature verification purposes.
29 59 *
30 - * @var String
60 + * @var string
31 61 */
32 62 protected $raw_post_data;
33 63
34 64 /**
@@ -69,8 +99,37 @@
69 99 */
70 100 private static $extra_register_params = array();
71 101
72 102 /**
103 + * We store ID's of users already disconnected to prevent multiple disconnect requests.
104 + *
105 + * @var array
106 + */
107 + private static $disconnected_users = array();
108 +
109 + /**
110 + * Cached connection status.
111 + *
112 + * @var bool|null True if the site is connected, false if not, null if not determined yet.
113 + */
114 + private static $is_connected = null;
115 +
116 + /**
117 + * Memoized user ID of the connection owner.
118 + * If undefined or invalid, set to 0.
119 + *
120 + * @var null|int
121 + */
122 + private static $connection_owner_id = null;
123 +
124 + /**
125 + * Tracks whether connection status invalidation hooks have been added.
126 + *
127 + * @var bool
128 + */
129 + private static $connection_invalidators_added = false;
130 +
131 + /**
73 132 * Initialize the object.
74 133 * Make sure to call the "Configure" first.
75 134 *
76 135 * @param string $plugin_slug Slug of the plugin using the connection (optional, but encouraged).
@@ -99,9 +158,9 @@
99 158 2
100 159 );
101 160
102 161 $manager->setup_xmlrpc_handlers(
103 - $_GET, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
162 + null,
104 163 $manager->has_connected_owner(),
105 164 $manager->verify_xml_rpc_signature()
106 165 );
107 166
@@ -108,12 +167,14 @@
108 167 $manager->error_handler = Error_Handler::get_instance();
109 168
110 169 if ( $manager->is_connected() ) {
111 170 add_filter( 'xmlrpc_methods', array( $manager, 'public_xmlrpc_methods' ) );
112 - add_filter( 'shutdown', array( new Package_Version_Tracker(), 'maybe_update_package_versions' ) );
171 + add_filter( 'shutdown', array( Package_Version_Tracker::class, 'update_on_shutdown' ) );
113 172 }
114 173
115 - add_action( 'rest_api_init', array( $manager, 'initialize_rest_api_registration_connector' ) );
174 + // This runs on priority 11 - at least one api method in the connection package is set to override a previously
175 + // existing method from the Jetpack plugin. Running later than Jetpack's api init ensures the override is successful.
176 + add_action( 'rest_api_init', array( $manager, 'initialize_rest_api_registration_connector' ), 11 );
116 177
117 178 ( new Nonce_Handler() )->init_schedule();
118 179
119 180 add_action( 'plugins_loaded', __NAMESPACE__ . '\Plugin_Storage::configure', 100 );
@@ -121,11 +182,28 @@
121 182 add_filter( 'map_meta_cap', array( $manager, 'jetpack_connection_custom_caps' ), 1, 4 );
122 183
123 184 Heartbeat::init();
124 185 add_filter( 'jetpack_heartbeat_stats_array', array( $manager, 'add_stats_to_heartbeat' ) );
186 + add_action( 'jetpack_verify_signature_error', array( $manager, 'track_xmlrpc_error' ) );
125 187
126 188 Webhooks::init( $manager );
127 189
190 + add_action( 'pre_update_jetpack_option_user_tokens', array( $manager, 'unbind_wpcom_user_ids_for_new_tokens' ), 10, 2 );
191 + add_action( 'jetpack_user_authorized', array( $manager, 'reconcile_protected_owner' ) );
192 +
193 + // Unlink user before deleting the user from WP.com.
194 + add_action( 'deleted_user', array( $manager, 'disconnect_user_force' ), 9, 1 );
195 + add_action( 'remove_user_from_blog', array( $manager, 'disconnect_user_force' ), 9, 1 );
196 +
197 + // Add hooks for cleaning up account mismatch transients
198 + $user_account_status = new User_Account_Status();
199 + add_action( 'delete_user', array( $user_account_status, 'clean_account_mismatch_transients' ), 9, 1 );
200 + add_action( 'remove_user_from_blog', array( $user_account_status, 'clean_account_mismatch_transients' ), 9, 1 );
201 + add_action( 'user_register', array( $user_account_status, 'clean_account_mismatch_transients' ), 9, 1 );
202 + add_action( 'profile_update', array( $user_account_status, 'clean_account_mismatch_transients' ), 9, 1 );
203 +
204 + $manager->add_connection_status_invalidation_hooks();
205 +
128 206 // Set up package version hook.
129 207 add_filter( 'jetpack_package_versions', __NAMESPACE__ . '\Package_Version::send_package_version_to_tracker' );
130 208
131 209 if ( defined( 'JETPACK__SANDBOX_DOMAIN' ) && JETPACK__SANDBOX_DOMAIN ) {
@@ -133,40 +211,77 @@
133 211 }
134 212
135 213 // Initialize connection notices.
136 214 new Connection_Notice();
215 +
216 + // Initialize token locks.
217 + new Tokens_Locks();
218 +
219 + // Initial Partner management.
220 + Partner::init();
221 +
222 + // WP 7.0+ Connectors screen card.
223 + Jetpack_Connector::init();
224 +
225 + // Site Health integration.
226 + Site_Health::init();
137 227 }
138 228
139 229 /**
230 + * Adds hooks to invalidate the memoized connection status.
231 + */
232 + private function add_connection_status_invalidation_hooks() {
233 + if ( self::$connection_invalidators_added ) {
234 + return;
235 + }
236 +
237 + // Force is_connected() to recompute after important actions.
238 + add_action( 'jetpack_site_registered', array( $this, 'reset_connection_status' ) );
239 + add_action( 'jetpack_site_disconnected', array( $this, 'reset_connection_status' ) );
240 + // Deletion doesn't fire `pre_update_jetpack_option_*`; see the action's docblock in `Tokens::delete_all()`.
241 + add_action( 'jetpack_connection_tokens_deleted', array( $this, 'reset_connection_status' ) );
242 + add_action( 'jetpack_sync_register_user', array( $this, 'reset_connection_status' ) );
243 + add_action( 'pre_update_jetpack_option_id', array( $this, 'reset_connection_status' ) );
244 + add_action( 'pre_update_jetpack_option_blog_token', array( $this, 'reset_connection_status' ) );
245 + add_action( 'pre_update_jetpack_option_user_token', array( $this, 'reset_connection_status' ) );
246 + add_action( 'pre_update_jetpack_option_user_tokens', array( $this, 'reset_connection_status' ) );
247 + add_action( 'pre_update_jetpack_option_master_user', array( $this, 'reset_connection_status' ) );
248 + // phpcs:ignore WPCUT.SwitchBlog.SwitchBlog -- wpcom flags **every** use of switch_blog, apparently expecting valid instances to ignore or suppress the sniff.
249 + add_action( 'switch_blog', array( $this, 'reset_connection_status' ) );
250 + add_action( 'jetpack_external_storage_provider_registered', array( $this, 'reset_connection_status' ), 10, 0 );
251 +
252 + self::$connection_invalidators_added = true;
253 + }
254 +
255 + /**
140 256 * Sets up the XMLRPC request handlers.
141 257 *
142 258 * @since 1.25.0 Deprecate $is_active param.
259 + * @since 2.8.4 Deprecate $request_params param.
143 260 *
144 - * @param array $request_params incoming request parameters.
145 - * @param bool $has_connected_owner Whether the site has a connected owner.
146 - * @param bool $is_signed whether the signature check has been successful.
147 - * @param \Jetpack_XMLRPC_Server $xmlrpc_server (optional) an instance of the server to use instead of instantiating a new one.
261 + * @param array|null $deprecated Deprecated. Not used.
262 + * @param bool $has_connected_owner Whether the site has a connected owner.
263 + * @param bool $is_signed whether the signature check has been successful.
264 + * @param Jetpack_XMLRPC_Server $xmlrpc_server (optional) an instance of the server to use instead of instantiating a new one.
148 265 */
149 266 public function setup_xmlrpc_handlers(
150 - $request_params,
267 + $deprecated,
151 268 $has_connected_owner,
152 269 $is_signed,
153 - \Jetpack_XMLRPC_Server $xmlrpc_server = null
270 + ?Jetpack_XMLRPC_Server $xmlrpc_server = null
154 271 ) {
155 272 add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ), 1000, 2 );
156 -
157 - if (
158 - ! isset( $request_params['for'] )
159 - || 'jetpack' !== $request_params['for']
160 - ) {
273 + if ( $deprecated !== null ) {
274 + _deprecated_argument( __METHOD__, '2.8.4' );
275 + }
276 + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- We are using the 'for' request param to early return unless it's 'jetpack'.
277 + if ( ! isset( $_GET['for'] ) || 'jetpack' !== $_GET['for'] ) {
161 278 return false;
162 279 }
163 280
164 281 // Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
165 - if (
166 - isset( $request_params['jetpack'] )
167 - && 'comms' === $request_params['jetpack']
168 - ) {
282 + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This just determines whether to handle the request as an XML-RPC request. The actual XML-RPC endpoints do the appropriate nonce checking where applicable. Plus we make sure to clear all cookies via require_jetpack_authentication called later in method.
283 + if ( isset( $_GET['jetpack'] ) && 'comms' === $_GET['jetpack'] ) {
169 284 if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
170 285 // Use the real constant here for WordPress' sake.
171 286 define( 'XMLRPC_REQUEST', true );
172 287 }
@@ -178,15 +293,18 @@
178 293
179 294 if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
180 295 return false;
181 296 }
297 +
182 298 // Display errors can cause the XML to be not well formed.
299 + // This only affects Jetpack XML-RPC endpoints received from WordPress.com servers.
300 + // All other XML-RPC requests are unaffected.
183 301 @ini_set( 'display_errors', false ); // phpcs:ignore
184 302
185 303 if ( $xmlrpc_server ) {
186 304 $this->xmlrpc_server = $xmlrpc_server;
187 305 } else {
188 - $this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
306 + $this->xmlrpc_server = new Jetpack_XMLRPC_Server();
189 307 }
190 308
191 309 $this->require_jetpack_authentication();
192 310
@@ -198,13 +316,12 @@
198 316
199 317 // Hack to preserve $HTTP_RAW_POST_DATA.
200 318 add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
201 319
202 - } elseif ( $has_connected_owner && ! $is_signed ) {
320 + } elseif ( $has_connected_owner ) {
203 321 // The jetpack.authorize method should be available for unauthenticated users on a site with an
204 322 // active Jetpack connection, so that additional users can link their account.
205 323 $callback = array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' );
206 -
207 324 } else {
208 325 // Any other unsigned request should expose the bootstrap methods.
209 326 $callback = array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' );
210 327 new XMLRPC_Connector( $this );
@@ -231,8 +348,10 @@
231 348 * which is accessible via a different URI. Most of the below is copied directly
232 349 * from /xmlrpc.php so that we're replicating it as closely as possible.
233 350 *
234 351 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
352 + *
353 + * @return never
235 354 */
236 355 public function alternate_xmlrpc() {
237 356 // Some browser-embedded clients send cookies. We don't want them.
238 357 $_COOKIE = array();
@@ -255,9 +374,9 @@
255 374 // Fire off the request.
256 375 nocache_headers();
257 376 $wp_xmlrpc_server->serve_request();
258 377
259 - exit;
378 + exit( 0 );
260 379 }
261 380
262 381 /**
263 382 * Removes all XML-RPC methods that are not `jetpack.*`.
@@ -270,9 +389,9 @@
270 389 public function remove_non_jetpack_xmlrpc_methods( $methods ) {
271 390 $jetpack_methods = array();
272 391
273 392 foreach ( $methods as $method => $callback ) {
274 - if ( 0 === strpos( $method, 'jetpack.' ) ) {
393 + if ( str_starts_with( $method, 'jetpack.' ) ) {
275 394 $jetpack_methods[ $method ] = $callback;
276 395 }
277 396 }
278 397
@@ -297,12 +416,12 @@
297 416
298 417 /**
299 418 * Authenticates XML-RPC and other requests from the Jetpack Server
300 419 *
301 - * @param WP_User|Mixed $user user object if authenticated.
302 - * @param String $username username.
303 - * @param String $password password string.
304 - * @return WP_User|Mixed authenticated user or error.
420 + * @param WP_User|mixed $user user object if authenticated.
421 + * @param string $username username.
422 + * @param string $password password string.
423 + * @return WP_User|mixed authenticated user or error.
305 424 */
306 425 public function authenticate_jetpack( $user, $username, $password ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
307 426 if ( is_a( $user, '\\WP_User' ) ) {
308 427 return $user;
@@ -370,8 +489,15 @@
370 489 if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
371 490 return false;
372 491 }
373 492
493 + // Skip XML-RPC signature verification for OAuth authorization flow.
494 + // OAuth uses GET requests without body-hash and has its own
495 + // signature verification in Authorize_Json_Api class.
496 + if ( isset( $_GET['action'] ) && $_GET['action'] === 'jetpack_json_api_authorization' ) {
497 + return false;
498 + }
499 +
374 500 $signature_details = array(
375 501 'token' => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
376 502 'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
377 503 'nonce' => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
@@ -376,13 +502,18 @@
376 502 'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
377 503 'nonce' => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
378 504 'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
379 505 'method' => isset( $_SERVER['REQUEST_METHOD'] ) ? wp_unslash( $_SERVER['REQUEST_METHOD'] ) : null,
380 - 'url' => wp_unslash( ( isset( $_SERVER['HTTP_HOST'] ) ? $_SERVER['HTTP_HOST'] : null ) . ( isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : null ) ), // Temp - will get real signature URL later.
506 + 'url' => wp_unslash( ( $_SERVER['HTTP_HOST'] ?? null ) . ( $_SERVER['REQUEST_URI'] ?? null ) ), // Temp - will get real signature URL later.
381 507 'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
382 508 );
383 509
384 - $error_type = 'xmlrpc';
510 + // Transport of the incoming request being verified. This signature-verification path
511 + // serves both XML-RPC requests and signed REST requests (REST_Authentication funnels
512 + // REST authentication into verify_xml_rpc_signature()), so the stored error type is
513 + // derived from the actual request context rather than hardcoded.
514 + $error_type = $this->get_current_request_transport();
515 + $error_direction = 'incoming'; // Matches Error_Handler::DIRECTION_INCOMING — see build_connection_error_data() for why the constant is not referenced.
385 516
386 517 // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
387 518 @list( $token_key, $version, $user_id ) = explode( ':', wp_unslash( $_GET['token'] ) );
388 519 // phpcs:enable WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
@@ -390,11 +521,12 @@
390 521 $jetpack_api_version = Constants::get_constant( 'JETPACK__API_VERSION' );
391 522
392 523 if (
393 524 empty( $token_key )
394 - ||
395 - empty( $version ) || (string) $jetpack_api_version !== $version ) {
396 - return new \WP_Error( 'malformed_token', 'Malformed token in request', compact( 'signature_details', 'error_type' ) );
525 + || empty( $version )
526 + || (string) $jetpack_api_version !== $version
527 + ) {
528 + return new \WP_Error( 'malformed_token', 'Malformed token in request', $this->build_connection_error_data( $signature_details, $error_type, $error_direction ) );
397 529 }
398 530
399 531 if ( '0' === $user_id ) {
400 532 $token_type = 'blog';
@@ -404,19 +536,19 @@
404 536 if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
405 537 return new \WP_Error(
406 538 'malformed_user_id',
407 539 'Malformed user_id in request',
408 - compact( 'signature_details', 'error_type' )
540 + $this->build_connection_error_data( $signature_details, $error_type, $error_direction )
409 541 );
410 542 }
411 543 $user_id = (int) $user_id;
412 544
413 545 $user = new \WP_User( $user_id );
414 - if ( ! $user || ! $user->exists() ) {
546 + if ( ! $user->exists() ) {
415 547 return new \WP_Error(
416 548 'unknown_user',
417 549 sprintf( 'User %d does not exist', $user_id ),
418 - compact( 'signature_details', 'error_type' )
550 + $this->build_connection_error_data( $signature_details, $error_type, $error_direction )
419 551 );
420 552 }
421 553 }
422 554
@@ -421,25 +553,28 @@
421 553 }
422 554
423 555 $token = $this->get_tokens()->get_access_token( $user_id, $token_key, false );
424 556 if ( is_wp_error( $token ) ) {
425 - $token->add_data( compact( 'signature_details', 'error_type' ) );
557 + $token->add_data( $this->build_connection_error_data( $signature_details, $error_type, $error_direction ) );
426 558 return $token;
427 559 } elseif ( ! $token ) {
560 + // `get_access_token()` explains itself for every case but one: it returns a bare
561 + // `false` when the tokens are locked (Tokens::is_locked()). The lock is
562 + // one-shot and self-healing.
428 563 return new \WP_Error(
429 - 'unknown_token',
430 - sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
431 - compact( 'signature_details', 'error_type' )
564 + 'tokens_locked',
565 + sprintf( 'Tokens are locked; %s:%s:%d could not be verified', $token_key, $version, $user_id ),
566 + $this->build_connection_error_data( $signature_details, $error_type, $error_direction )
432 567 );
433 568 }
434 569
435 570 $jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
436 - // phpcs:disable WordPress.Security.NonceVerification.Missing
571 + // phpcs:disable WordPress.Security.NonceVerification.Missing -- Used to verify a cryptographic signature of the post data. Also a nonce is verified later in the function.
437 572 if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
438 - $post_data = $_POST;
573 + $post_data = $_POST; // We need all of $_POST in order to verify a cryptographic signature of the post data.
439 574 $file_hashes = array();
440 575 foreach ( $post_data as $post_data_key => $post_data_value ) {
441 - if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
576 + if ( ! str_starts_with( $post_data_key, '_jetpack_file_hmac_' ) ) {
442 577 continue;
443 578 }
444 579 $post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
445 580 $file_hashes[ $post_data_key ] = $post_data_value;
@@ -465,15 +600,25 @@
465 600 );
466 601
467 602 $signature_details['url'] = $jetpack_signature->current_request_url;
468 603
604 + // This path currently can't ever be true, unless a new path is added resulting
605 + // in $signature 'false', null or an empty string. Leaving for additional security.
469 606 if ( ! $signature ) {
470 607 return new \WP_Error(
471 608 'could_not_sign',
472 609 'Unknown signature error',
473 - compact( 'signature_details', 'error_type' )
610 + $this->build_connection_error_data( $signature_details, $error_type, $error_direction )
474 611 );
475 612 } elseif ( is_wp_error( $signature ) ) {
613 + // Jetpack_Signature errors carry their own signature_details (or, for some codes,
614 + // no data at all) but never a type or direction; normalize them into the standard
615 + // error data shape so Error_Handler can attribute and store them.
616 + $signature_error_data = $signature->get_error_data();
617 + if ( isset( $signature_error_data['signature_details'] ) && is_array( $signature_error_data['signature_details'] ) ) {
618 + $signature_details = array_merge( $signature_details, $signature_error_data['signature_details'] );
619 + }
620 + $signature->add_data( $this->build_connection_error_data( $signature_details, $error_type, $error_direction ) );
476 621 return $signature;
477 622 }
478 623
479 624 // phpcs:disable WordPress.Security.NonceVerification.Recommended
@@ -485,9 +630,9 @@
485 630 if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
486 631 return new \WP_Error(
487 632 'invalid_nonce',
488 633 'Could not add nonce',
489 - compact( 'signature_details', 'error_type' )
634 + $this->build_connection_error_data( $signature_details, $error_type, $error_direction )
490 635 );
491 636 }
492 637
493 638 // Be careful about what you do with this debugging data.
@@ -499,9 +644,9 @@
499 644 if ( ! hash_equals( $signature, wp_unslash( $_GET['signature'] ) ) ) {
500 645 return new \WP_Error(
501 646 'signature_mismatch',
502 647 'Signature mismatch',
503 - compact( 'signature_details', 'error_type' )
648 + $this->build_connection_error_data( $signature_details, $error_type, $error_direction )
504 649 );
505 650 }
506 651
507 652 /**
@@ -525,8 +670,66 @@
525 670 );
526 671 }
527 672
528 673 /**
674 + * Determines the transport of the incoming request currently being verified.
675 + *
676 + * @since 8.9.0
677 + *
678 + * @return string Error_Handler::ERROR_TYPE_XMLRPC or Error_Handler::ERROR_TYPE_REST.
679 + */
680 + private function get_current_request_transport() {
681 + $is_xmlrpc = defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST;
682 +
683 + // XMLRPC_REQUEST covers both /xmlrpc.php and the alternate XML-RPC endpoint, which
684 + // defines the constant itself (see setup_xmlrpc_handlers). Outside those, signed REST
685 + // requests are detected via the REST dispatch state. Anything else (e.g. signed
686 + // requests verified on the 'authenticate' filter for regular URLs) keeps the historic
687 + // XML-RPC label rather than guessing at a transport.
688 + $is_rest = ! $is_xmlrpc && ( function_exists( 'wp_is_rest_endpoint' ) ? wp_is_rest_endpoint() : ( defined( 'REST_REQUEST' ) && REST_REQUEST ) );
689 +
690 + // Signature verification can run before REST dispatch is set up: REST_Authentication
691 + // hooks `determine_current_user`, which any plugin can trigger early (e.g. by calling
692 + // wp_get_current_user() on plugins_loaded), before the REST_REQUEST constant exists.
693 + // In that window, recognize REST requests by their URL: the REST prefix in the path,
694 + // or the rest_route query argument used by sites without pretty permalinks.
695 + if ( ! $is_xmlrpc && ! $is_rest ) {
696 + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only used to classify the request transport.
697 + $has_rest_route_arg = isset( $_GET['rest_route'] );
698 + $request_path = (string) wp_parse_url( isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '', PHP_URL_PATH ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Parsed for path comparison only.
699 + $is_rest = $has_rest_route_arg || false !== strpos( $request_path, '/' . rest_get_url_prefix() . '/' );
700 + }
701 +
702 + // The literals match Error_Handler::ERROR_TYPE_REST / ERROR_TYPE_XMLRPC — see
703 + // build_connection_error_data() for why the constants are not referenced.
704 + return $is_rest ? 'rest' : 'xmlrpc';
705 + }
706 +
707 + /**
708 + * Builds the standardized connection error data attached to signature-verification errors.
709 + *
710 + * Wraps `Error_Handler::build_connection_error_data()`, falling back to the legacy
711 + * error-data shape when the loaded Error_Handler predates that method: during a plugin
712 + * update, an older version of the class can already be in memory while this file is the
713 + * new one, and a mid-update request must never fatal. For the same reason, code in this
714 + * class must not reference Error_Handler constants introduced along with that method
715 + * ('xmlrpc', 'rest', 'local_state', 'incoming', 'outgoing') — use the literal values.
716 + *
717 + * @since 8.10.0
718 + *
719 + * @param array $signature_details Details of the request signature being verified.
720 + * @param string $error_type The transport of the request: 'xmlrpc' or 'rest'.
721 + * @param string $error_direction The direction of the request: 'incoming' or 'outgoing'.
722 + * @return array Error data for `WP_Error`.
723 + */
724 + private function build_connection_error_data( $signature_details, $error_type, $error_direction ) {
725 + if ( ! method_exists( Error_Handler::class, 'build_connection_error_data' ) ) {
726 + return compact( 'signature_details', 'error_type' );
727 + }
728 + return Error_Handler::build_connection_error_data( $signature_details, $error_type, $error_direction );
729 + }
730 +
731 + /**
529 732 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI.
530 733 *
531 734 * This method is deprecated since version 1.25.0 of this package. Please use has_connected_owner instead.
532 735 *
@@ -533,9 +736,9 @@
533 736 * Since this method has a wide spread use, we decided not to throw any deprecation warnings for now.
534 737 *
535 738 * @deprecated 1.25.0
536 739 * @see Manager::has_connected_owner
537 - * @return Boolean is the site connected?
740 + * @return bool is the site connected?
538 741 */
539 742 public function is_active() {
540 743 return (bool) $this->get_tokens()->get_access_token( true );
541 744 }
@@ -571,14 +774,36 @@
571 774 *
572 775 * @return bool
573 776 */
574 777 public function is_connected() {
575 - $has_blog_id = (bool) \Jetpack_Options::get_option( 'id' );
576 - $has_blog_token = (bool) $this->get_tokens()->get_access_token();
577 - return $has_blog_id && $has_blog_token;
778 + if ( self::$is_connected === null ) {
779 + if ( ! self::$connection_invalidators_added ) {
780 + $this->add_connection_status_invalidation_hooks();
781 + }
782 +
783 + $has_blog_id = (bool) \Jetpack_Options::get_option( 'id' );
784 + if ( $has_blog_id ) {
785 + self::$is_connected = (bool) $this->get_tokens()->get_access_token();
786 + } else {
787 + // Short-circuit, no need to check for tokens if there's no blog ID.
788 + self::$is_connected = false;
789 + }
790 + }
791 + return self::$is_connected;
578 792 }
579 793
580 794 /**
795 + * Resets the memoized connection status.
796 + * This will force the connection status to be recomputed on the next check.
797 + *
798 + * @since 5.0.0
799 + */
800 + public function reset_connection_status() {
801 + self::$is_connected = null;
802 + self::$connection_owner_id = null;
803 + }
804 +
805 + /**
581 806 * Returns true if the site has at least one connected administrator.
582 807 *
583 808 * @access public
584 809 * @since 1.21.1
@@ -717,18 +942,29 @@
717 942 *
718 943 * @return bool|int Returns the ID of the connection owner or False if no connection owner found.
719 944 */
720 945 public function get_connection_owner_id() {
721 - $owner = $this->get_connection_owner();
722 - return $owner instanceof \WP_User ? $owner->ID : false;
946 + // Check if the memoized value is available.
947 + if ( null === self::$connection_owner_id ) {
948 + $owner = $this->get_connection_owner();
949 + self::$connection_owner_id = $owner instanceof \WP_User ? $owner->ID : 0;
950 + }
951 +
952 + // If the ID is set to 0, there's no valid connection owner.
953 + return self::$connection_owner_id > 0 ? self::$connection_owner_id : false;
723 954 }
724 955
725 956 /**
726 957 * Get the wpcom user data of the current|specified connected user.
727 958 *
728 - * @todo Refactor to properly load the XMLRPC client independently.
959 + * Fetches the data from the WordPress.com `jetpack-wpcom-user-data` REST endpoint
960 + * with a signed request as the connected user. Routing this through
961 + * Client::remote_request() (rather than the legacy `wpcom.getUser` XML-RPC method)
962 + * ensures any connection errors are captured by the Error_Handler.
729 963 *
730 - * @param Integer $user_id the user identifier.
964 + * @since 8.8.1 Fetch the data over REST instead of the `wpcom.getUser` XML-RPC method.
965 + *
966 + * @param int|null $user_id the user identifier.
731 967 * @return bool|array An array with the WPCOM user data on success, false otherwise.
732 968 */
733 969 public function get_connected_user_data( $user_id = null ) {
734 970 if ( ! $user_id ) {
@@ -742,37 +978,290 @@
742 978
743 979 $transient_key = "jetpack_connected_user_data_$user_id";
744 980 $cached_user_data = get_transient( $transient_key );
745 981
982 + if ( 'error' === $cached_user_data ) {
983 + return false;
984 + }
985 +
746 986 if ( $cached_user_data ) {
747 987 return $cached_user_data;
748 988 }
749 989
750 - $xml = new Jetpack_IXR_Client(
751 - array(
752 - 'user_id' => $user_id,
753 - )
990 + $blog_id = (int) \Jetpack_Options::get_option( 'id' );
991 +
992 + // Build a signed request as the connected user. We can't use
993 + // Client::wpcom_json_api_request_as_user() because it always signs as the
994 + // current user, whereas this method may be called for an arbitrary $user_id.
995 + $args = Client::validate_args_for_wpcom_json_api_request(
996 + "/sites/{$blog_id}/jetpack-wpcom-user-data",
997 + '2',
998 + array( 'method' => 'GET' )
754 999 );
755 - $xml->query( 'wpcom.getUser' );
1000 + $args['user_id'] = $user_id;
756 1001
757 - if ( ! $xml->isError() ) {
758 - $user_data = $xml->getResponse();
759 - set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
760 - return $user_data;
1002 + $response = Client::remote_request( $args );
1003 +
1004 + if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
1005 + // Cache errors briefly so a failing remote request doesn't result in
1006 + // a blocking request on every call, e.g. on each admin page
1007 + // load via Initial_State::set_connection_script_data().
1008 + set_transient( $transient_key, 'error', 5 * MINUTE_IN_SECONDS );
1009 +
1010 + return false;
761 1011 }
762 1012
763 - return false;
1013 + $user_data = json_decode( wp_remote_retrieve_body( $response ), true );
1014 +
1015 + if ( ! is_array( $user_data ) || empty( $user_data ) ) {
1016 + set_transient( $transient_key, 'error', 5 * MINUTE_IN_SECONDS );
1017 +
1018 + return false;
1019 + }
1020 +
1021 + set_transient( $transient_key, $user_data, DAY_IN_SECONDS );
1022 +
1023 + return $user_data;
764 1024 }
765 1025
766 1026 /**
1027 + * Returns the WordPress.com user ID of a connected user.
1028 + *
1029 + * Answers only for a user who currently holds a token: the binding outlives any one token, so
1030 + * connectedness is checked here rather than inferred from a row existing. Resolving an unbound
1031 + * user costs a blocking request to WordPress.com, so this is not safe to call per row.
1032 + *
1033 + * @since 9.2.0
1034 + *
1035 + * @param int|false $user_id The local user identifier. Default is the current user.
1036 + * @return int The WordPress.com user ID, or 0 if it could not be determined.
1037 + */
1038 + public function resolve_wpcom_user_id( $user_id = false ) {
1039 + $user_id = $user_id ? absint( $user_id ) : get_current_user_id();
1040 +
1041 + // The binding outlives the token, unlike the transient behind `get_connected_user_data()`,
1042 + // so connectedness is checked here rather than left to the lookup below.
1043 + if ( ! $user_id || ! $this->is_user_connected( $user_id ) ) {
1044 + return 0;
1045 + }
1046 +
1047 + $bound = Utils::get_wpcom_user_id( $user_id );
1048 +
1049 + if ( $bound ) {
1050 + return $bound;
1051 + }
1052 +
1053 + $user_data = $this->get_connected_user_data( $user_id );
1054 +
1055 + // Callers must read 0 as "unknown", never as "no match": a failed lookup lands here too.
1056 + if ( empty( $user_data['ID'] ) ) {
1057 + return 0;
1058 + }
1059 +
1060 + Utils::set_wpcom_user_id( $user_id, (int) $user_data['ID'] );
1061 +
1062 + return (int) $user_data['ID'];
1063 + }
1064 +
1065 + /**
1066 + * Unbind the WordPress.com user ID of any user whose token is new.
1067 + *
1068 + * Every path that changes a user's token writes the `user_tokens` option, so this covers
1069 + * authorize, remote connect and the REST endpoint alike. A token that is added or replaced can
1070 + * name a different WordPress.com account, so any binding it would answer with is unverified. A
1071 + * token merely removed leaves the binding correct, and other subsystems store their own meaning
1072 + * in the same meta, so removals are left alone.
1073 + *
1074 + * @internal Hooked on `pre_update_jetpack_option_user_tokens`, which fires before the write.
1075 + * @since 9.2.0
1076 + *
1077 + * @param string $name The option name.
1078 + * @param mixed $value The tokens about to be written.
1079 + */
1080 + public function unbind_wpcom_user_ids_for_new_tokens( $name, $value ) {
1081 + if ( ! is_array( $value ) ) {
1082 + return;
1083 + }
1084 +
1085 + // A site disconnect deletes the option outright, so the first write back has nothing to
1086 + // diff against — treat that as every token being new rather than skipping the check.
1087 + $previous = \Jetpack_Options::get_option( 'user_tokens' );
1088 + $previous = is_array( $previous ) ? $previous : array();
1089 +
1090 + // Iterating the incoming tokens covers a token being added as well as replaced, and skips
1091 + // removal for free: a user absent from the new set is never visited.
1092 + foreach ( $value as $user_id => $token ) {
1093 + if ( ( $previous[ $user_id ] ?? null ) !== $token ) {
1094 + Utils::delete_wpcom_user_id( $user_id );
1095 + }
1096 + }
1097 + }
1098 +
1099 + /**
1100 + * Drop the cached WordPress.com site record.
1101 + *
1102 + * A caller that fetched the record by another route holds something newer than the cache can,
1103 + * and `jetpack_site_data_fetched` fires on a cached read too. The cached copy has to go, or it
1104 + * keeps announcing the older record and undoes what that caller stored.
1105 + *
1106 + * @since 9.0.0
1107 + *
1108 + * @return void
1109 + */
1110 + public static function delete_cached_site_data() {
1111 + $site_id = \Jetpack_Options::get_option( 'id' );
1112 +
1113 + if ( $site_id ) {
1114 + delete_transient( self::SITE_DATA_TRANSIENT_PREFIX . $site_id );
1115 + }
1116 + }
1117 +
1118 + /**
1119 + * Fetch the site's own record from the WordPress.com `/sites/%d` endpoint.
1120 + *
1121 + * The result is cached briefly. Every plugin that bundles this package serves this route, and
1122 + * the Jetpack dashboard requests it on mount, so an uncached read means a blocking round trip
1123 + * per render.
1124 + *
1125 + * @since 8.10.0
1126 + *
1127 + * @return object|WP_Error The decoded site record, or an error describing the failure.
1128 + */
1129 + public function get_connected_site_data() {
1130 + $site_id = \Jetpack_Options::get_option( 'id' );
1131 +
1132 + if ( ! $site_id ) {
1133 + return new WP_Error( 'site_id_missing', '', array( 'api_error_code' => 'site_id_missing' ) );
1134 + }
1135 +
1136 + $sandbox_secret = null;
1137 +
1138 + // An array cookie (`store_sandbox[]=`) carries no secret to send, and `filter_var()` turns
1139 + // it into `false`.
1140 + if ( isset( $_COOKIE['store_sandbox'] ) && is_string( $_COOKIE['store_sandbox'] ) ) {
1141 + // Keep only RFC 6265 cookie-octets so the value cannot break out of the Cookie header.
1142 + $sandbox_secret = preg_replace( '/[^\x21-\x7E]|[";,\\\\]/', '', filter_var( wp_unslash( $_COOKIE['store_sandbox'] ) ) );
1143 +
1144 + // An empty cookie, or one the sanitizer strips to nothing, is not a sandbox secret.
1145 + // Counting it as one opts the request out of the cache with no sandbox to reach.
1146 + if ( '' === $sandbox_secret ) {
1147 + $sandbox_secret = null;
1148 + }
1149 + }
1150 +
1151 + // A sandboxed request must neither read the shared cache nor seed it with sandbox data.
1152 + $sandboxed = null !== $sandbox_secret;
1153 + $transient_key = self::SITE_DATA_TRANSIENT_PREFIX . $site_id;
1154 +
1155 + // WordPress.com itself requests this route right after a purchase, for the side effect of
1156 + // the `jetpack_site_data_fetched` consumers storing the new plan. Those requests arrive
1157 + // signed with a connection token, which no browser request carries. A cached read would
1158 + // hand that refresh the pre-purchase record and turn it into a no-op, so a signed request
1159 + // always reads from WordPress.com and replaces the cache with the record it fetched.
1160 + $signed = Rest_Authentication::is_signed_with_blog_token() || Rest_Authentication::is_signed_with_user_token();
1161 +
1162 + $result = ( $sandboxed || $signed ) ? false : get_transient( $transient_key );
1163 +
1164 + // Only the array shape stored below can be served. A `pre_transient_*` filter or a damaged
1165 + // object cache entry can hand back anything, and a non-array would throw on
1166 + // `$result['body']` for every request until the entry expired, so it reads as a miss.
1167 + if ( ! is_array( $result ) ) {
1168 + $result = $this->fetch_connected_site_data( $site_id, $sandbox_secret );
1169 +
1170 + // A signed read that failed must not replace a still-usable cached record with the failure.
1171 + if ( ! $sandboxed && ! ( $signed && isset( $result['error'] ) ) ) {
1172 + // Failures expire sooner so an outage recovers without waiting out a full success window.
1173 + set_transient(
1174 + $transient_key,
1175 + $result,
1176 + isset( $result['error'] ) ? 2 * MINUTE_IN_SECONDS : 5 * MINUTE_IN_SECONDS
1177 + );
1178 + }
1179 + }
1180 +
1181 + if ( isset( $result['error'] ) ) {
1182 + return new WP_Error( 'site_data_fetch_failed', '', $result['error'] );
1183 + }
1184 +
1185 + /**
1186 + * Fires after the site record was served, whether it was fetched or read from the cache.
1187 + *
1188 + * Consumers that cache anything derived from the record, such as the current plan,
1189 + * can refresh it here.
1190 + *
1191 + * This fires on a cached read too, so a consumer stays in step with every request that
1192 + * serves the record rather than only the ones that reached WordPress.com.
1193 + *
1194 + * The record is passed as an array rather than the object this method returns, so that a
1195 + * listener cannot mutate the instance that becomes the REST response.
1196 + *
1197 + * @since 9.0.0
1198 + *
1199 + * @param array $record The decoded site record from the WordPress.com `/sites/%d` endpoint.
1200 + */
1201 + do_action( 'jetpack_site_data_fetched', json_decode( $result['body'], true ) );
1202 +
1203 + return json_decode( $result['body'] );
1204 + }
1205 +
1206 + /**
1207 + * Request the site record from WordPress.com.
1208 + *
1209 + * Returns a cacheable array rather than the decoded record so that both outcomes survive a
1210 + * round trip through a transient.
1211 + *
1212 + * @since 9.0.0
1213 + *
1214 + * @param int $site_id The WordPress.com blog ID.
1215 + * @param string|null $sandbox_secret Sanitized store sandbox cookie value, or null when not sandboxed.
1216 + * @return array Either `array( 'body' => string )` or `array( 'error' => array )`.
1217 + */
1218 + private function fetch_connected_site_data( $site_id, $sandbox_secret ) {
1219 + $args = array( 'headers' => array() );
1220 +
1221 + // Allow use a store sandbox. Internal ref: PCYsg-IA-p2.
1222 + if ( null !== $sandbox_secret ) {
1223 + $args['headers']['Cookie'] = "store_sandbox=$sandbox_secret;";
1224 + }
1225 +
1226 + $response = Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d', $site_id ) . '?force=wpcom', '1.1', $args );
1227 + $body = wp_remote_retrieve_body( $response );
1228 + $data = $body ? json_decode( $body ) : null;
1229 +
1230 + if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
1231 + $error_info = array(
1232 + 'api_error_code' => null,
1233 + 'api_http_code' => wp_remote_retrieve_response_code( $response ),
1234 + );
1235 +
1236 + if ( is_wp_error( $response ) ) {
1237 + $error_info['api_error_code'] = $response->get_error_code() ? wp_strip_all_tags( $response->get_error_code() ) : null;
1238 + } elseif ( $data && ! empty( $data->error ) ) {
1239 + $error_info['api_error_code'] = is_string( $data->error ) ? wp_strip_all_tags( $data->error ) : null;
1240 + }
1241 +
1242 + return array( 'error' => $error_info );
1243 + }
1244 +
1245 + if ( ! is_object( $data ) ) {
1246 + return array(
1247 + 'error' => array(
1248 + 'api_error_code' => 'invalid_body',
1249 + 'api_http_code' => 200,
1250 + ),
1251 + );
1252 + }
1253 +
1254 + return array( 'body' => $body );
1255 + }
1256 +
1257 + /**
767 1258 * Returns a user object of the connection owner.
768 1259 *
769 1260 * @return WP_User|false False if no connection owner found.
770 1261 */
771 1262 public function get_connection_owner() {
772 -
773 1263 $user_id = \Jetpack_Options::get_option( 'master_user' );
774 -
775 1264 if ( ! $user_id ) {
776 1265 return false;
777 1266 }
778 1267
@@ -784,8 +1273,28 @@
784 1273 if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
785 1274 $connection_owner = get_userdata( $user_token->external_user_id );
786 1275 }
787 1276
1277 + // Reporting is best-effort and must never fatal a request running mid-plugin-update:
1278 + // skip it when the already-loaded Error_Handler is a stale version predating the factory.
1279 + if ( $connection_owner === false && method_exists( Error_Handler::class, 'build_connection_wp_error' ) ) {
1280 + Error_Handler::get_instance()->report_error(
1281 + Error_Handler::build_connection_wp_error(
1282 + 'invalid_connection_owner',
1283 + 'Invalid connection owner',
1284 + array( 'token' => '' ),
1285 + 'local_state', // Error_Handler::ERROR_TYPE_LOCAL_STATE.
1286 + '', // Local-state errors describe the site's database, not a request, so they have no direction.
1287 + array(
1288 + 'user_id' => $user_id,
1289 + 'has_user_token' => (bool) $user_token,
1290 + )
1291 + ),
1292 + false,
1293 + true
1294 + );
1295 + }
1296 +
788 1297 return $connection_owner;
789 1298 }
790 1299
791 1300 /**
@@ -791,10 +1300,10 @@
791 1300 /**
792 1301 * Returns true if the provided user is the Jetpack connection owner.
793 1302 * If user ID is not specified, the current user will be used.
794 1303 *
795 - * @param Integer|Boolean $user_id the user identifier. False for current user.
796 - * @return Boolean True the user the connection owner, false otherwise.
1304 + * @param int|bool $user_id the user identifier. False for current user.
1305 + * @return bool True the user the connection owner, false otherwise.
797 1306 */
798 1307 public function is_connection_owner( $user_id = false ) {
799 1308 if ( ! $user_id ) {
800 1309 $user_id = get_current_user_id();
@@ -803,16 +1312,633 @@
803 1312 return ( (int) $user_id ) === $this->get_connection_owner_id();
804 1313 }
805 1314
806 1315 /**
1316 + * Determines whether the connection ownership can be transferred to another user.
1317 + *
1318 + * The default Jetpack connection uses a transferable ownership model. A set protected owner
1319 + * anchor locks it outright; otherwise a consumer can declare ownership locked by returning
1320 + * `false` from the `jetpack_connection_ownership_transferable` filter. This is the single
1321 + * chokepoint used both when deciding which connection-error CTA to surface and (eventually)
1322 + * when performing an ownership change.
1323 + *
1324 + * @since 8.8.0
1325 + * @since 9.3.0 A locked protected owner anchor makes ownership non-transferable.
1326 + *
1327 + * @return bool True if ownership can be transferred, false if it is locked.
1328 + */
1329 + public function is_ownership_transferable() {
1330 + // Keyed on the anchor, never on has_protected_owner(): an owner who does not match the
1331 + // anchor is exactly when ownership must stay locked.
1332 + if ( Protected_Owner::is_locked() ) {
1333 + return false;
1334 + }
1335 +
1336 + /**
1337 + * Filters whether the Jetpack connection ownership can be transferred.
1338 + *
1339 + * Return `false` to lock ownership so it can never be taken over.
1340 + *
1341 + * @since 8.8.0
1342 + *
1343 + * @param bool $transferable Whether ownership can be transferred. Default true.
1344 + */
1345 + return (bool) apply_filters( 'jetpack_connection_ownership_transferable', true );
1346 + }
1347 +
1348 + /**
1349 + * Whether a protected owner is required right now.
1350 + *
1351 + * Evaluated at the moment of the request, not as a standing declaration: a consumer may
1352 + * legitimately answer false while it is installed and active — running in test mode, say —
1353 + * and true only at the lifecycle moment that binds something to the owner's identity.
1354 + *
1355 + * @since 9.3.0
1356 + *
1357 + * @return bool True if a protected owner is required at this moment. Default false.
1358 + */
1359 + public function requires_protected_owner() {
1360 + /**
1361 + * Filters whether a protected owner is required at this moment.
1362 + *
1363 + * Return `true` at the point a feature is about to bind to the connection owner's
1364 + * identity. Answering false at other times is expected and supported.
1365 + *
1366 + * @since 9.3.0
1367 + *
1368 + * @param bool $required Whether a protected owner is required. Default false.
1369 + */
1370 + return (bool) apply_filters( 'jetpack_connection_requires_protected_owner', false );
1371 + }
1372 +
1373 + /**
1374 + * Whether the connection owner is the protected owner the anchor names.
1375 + *
1376 + * This is the question consumers gate on before binding anything to the owner's identity.
1377 + *
1378 + * Reads the binding of the current owner rather than searching for whoever holds the anchored
1379 + * ID, so a row on any other user cannot affect the answer. Requiring the owner to hold a live
1380 + * token on top of that is what keeps a row written by another subsystem from ever satisfying
1381 + * this: both halves are load-bearing, and there are tests for each.
1382 + *
1383 + * @since 9.3.0
1384 + *
1385 + * @return bool
1386 + */
1387 + public function has_protected_owner() {
1388 + $anchor = Protected_Owner::get_locked();
1389 +
1390 + if ( ! $anchor ) {
1391 + return false;
1392 + }
1393 +
1394 + $owner_id = $this->get_connection_owner_id();
1395 +
1396 + if ( ! $owner_id ) {
1397 + return false;
1398 + }
1399 +
1400 + return $this->resolve_wpcom_user_id( $owner_id ) === (int) $anchor['wpcom_user_id'];
1401 + }
1402 +
1403 + /**
1404 + * Classify why `has_protected_owner()` answered false, and what would change it.
1405 + *
1406 + * Deliberately inspects only what the gate inspects — the anchor and the current connection
1407 + * owner — so the two can never disagree about the same site. Anything needing a user search or
1408 + * a reachability probe is a different question and is not answered here.
1409 + *
1410 + * `is_current_user_the_po` reads the current user's own stored binding, never a search for
1411 + * whoever holds the anchored ID, so it cannot be confused by a second user carrying the same
1412 + * meta, and never costs a network call. It is a hint for copy, not a gate.
1413 + *
1414 + * @since 9.4.0
1415 + *
1416 + * @return array{status: string, is_current_user_the_po: bool}
1417 + */
1418 + public function resolve_protected_owner_state() {
1419 + $anchor = Protected_Owner::get_locked();
1420 + $current_id = get_current_user_id();
1421 +
1422 + // Only meaningful against an anchor: with none, there is nothing for the user to be.
1423 + // Reads the stored binding rather than resolving it, so classifying a state never costs a
1424 + // WordPress.com round trip. An unbound user reads as false and gets the generic copy.
1425 + $is_current_user_the_po = $anchor
1426 + && Utils::get_wpcom_user_id( $current_id ) === (int) $anchor['wpcom_user_id'];
1427 +
1428 + if ( ! $anchor ) {
1429 + $roles = new Roles();
1430 +
1431 + if ( ! current_user_can( 'jetpack_connect' ) || ! current_user_can( $roles->translate_role_to_cap( 'administrator' ) ) ) {
1432 + // Eligibility is being an admin, not holding the master slot.
1433 + $status = self::PO_STATE_NOT_ELIGIBLE;
1434 + } elseif ( ! $this->is_user_connected( $current_id ) ) {
1435 + // A WordPress.com identity has to exist before it can be confirmed and locked.
1436 + $status = self::PO_STATE_NEEDS_CONNECT_TO_ESTABLISH;
1437 + } else {
1438 + $status = self::PO_STATE_CAN_ESTABLISH;
1439 + }
1440 + } else {
1441 + $owner_id = $this->get_connection_owner_id();
1442 + $owner_wpcom_id = $owner_id ? $this->resolve_wpcom_user_id( $owner_id ) : 0;
1443 +
1444 + if ( ! $owner_wpcom_id ) {
1445 + // A zero is "could not determine", never "does not match", so an owner whose
1446 + // identity cannot be confirmed is reported as needing to reconnect, not replaced.
1447 + $status = self::PO_STATE_NEEDS_OWNER_RECONNECT;
1448 + } elseif ( $owner_wpcom_id !== (int) $anchor['wpcom_user_id'] ) {
1449 + // Legitimate, not broken: the first admin to connect takes a vacant master slot,
1450 + // so an agency can hold it while the protected owner is away.
1451 + $status = self::PO_STATE_NEEDS_DIFFERENT_OWNER;
1452 + } else {
1453 + $status = self::PO_STATE_RE_EVALUATE;
1454 + }
1455 + }
1456 +
1457 + return array(
1458 + 'status' => $status,
1459 + 'is_current_user_the_po' => $is_current_user_the_po,
1460 + );
1461 + }
1462 +
1463 + /**
1464 + * Reconcile this site's protected owner against WordPress.com, which is the owner of record.
1465 + *
1466 + * Runs at connect, when the site has a fresh user token and an answer is cheap, and only once
1467 + * something is anchored: a site with no protected owner asks nothing and behaves as it did
1468 + * before this existed. One answer settles the rest — whether an owner still exists, whether
1469 + * the anchor names them, and whether the user connecting is them — so the anchor, the binding
1470 + * and the master slot are decided together rather than from two calls that could disagree.
1471 + *
1472 + * Only an answer moves anything. Unreachable, refused, unimplemented and malformed leave the
1473 + * anchor exactly as it was: it was confirmed once, and a request that never arrived is no
1474 + * evidence against it.
1475 + *
1476 + * @internal Hooked on `jetpack_user_authorized`.
1477 + * @since 9.8.0
1478 + *
1479 + * @return bool Whether WordPress.com confirmed the anchored identity.
1480 + */
1481 + public function reconcile_protected_owner() {
1482 + $user_id = get_current_user_id();
1483 +
1484 + if ( ! $user_id ) {
1485 + return false;
1486 + }
1487 +
1488 + $anchor = Protected_Owner::get();
1489 +
1490 + // Nothing anchored is nothing to reconcile, and a site with no protected owner must behave
1491 + // exactly as it did before this existed — including making no request. Such a site reaches
1492 + // an owner through the claim instead, which is where confirming belongs.
1493 + if ( ! $anchor ) {
1494 + return false;
1495 + }
1496 +
1497 + $record = $this->query_protected_owner_record( (int) $anchor['wpcom_user_id'] );
1498 +
1499 + // Silence is not an answer. Unreachable, refused and unimplemented leave the anchor exactly
1500 + // as it was: it was confirmed once, and a request that never arrived is no evidence against
1501 + // it. Dropping a good lock because WordPress.com had a bad minute costs a merchant their
1502 + // payouts until the owner happens to connect again.
1503 + if ( ! is_array( $record ) || ! isset( $record['has_owner'] ) ) {
1504 + return false;
1505 + }
1506 +
1507 + // WordPress.com no longer has an owner of record, so neither does this site. Support
1508 + // clearing it at that end is how a wrongly anchored site recovers.
1509 + if ( ! $record['has_owner'] ) {
1510 + Protected_Owner::clear();
1511 +
1512 + return false;
1513 + }
1514 +
1515 + $caller_wpcom_user_id = (int) ( $record['caller_wpcom_user_id'] ?? 0 );
1516 +
1517 + // The identity is disclosed only to the owner it names, so this is the one branch that can
1518 + // learn it — and what it settles is which account the anchor should name, since
1519 + // WordPress.com may have moved the owner since this site last asked.
1520 + if ( ! empty( $record['is_caller'] ) ) {
1521 + return $this->adopt_protected_owner( $user_id, $caller_wpcom_user_id, $anchor );
1522 + }
1523 +
1524 + // Connecting cleared this, and it is the caller's own identity rather than the owner's, so
1525 + // it is written whoever they are. Nothing is anchored on this path, so an early write
1526 + // cannot strand a half-finished lock.
1527 + if ( $caller_wpcom_user_id ) {
1528 + Utils::set_wpcom_user_id( $user_id, $caller_wpcom_user_id );
1529 + }
1530 +
1531 + // Somebody else is connecting. WordPress.com confirms the anchored identity rather than
1532 + // naming the owner, so the answer is the same whoever asks.
1533 + if ( empty( $record['matches'] ) ) {
1534 + Protected_Owner::clear();
1535 +
1536 + return false;
1537 + }
1538 +
1539 + return true;
1540 + }
1541 +
1542 + /**
1543 + * Take WordPress.com's word that the connecting user owns this site.
1544 + *
1545 + * @since 9.8.0
1546 + *
1547 + * @param int $user_id The connecting local user.
1548 + * @param int $wpcom_user_id The connecting user's WordPress.com identity, which this
1549 + * branch has just been told is the owner of record.
1550 + * @param array|null $anchor What this site has anchored, if anything.
1551 + * @return bool Whether the anchor now names that identity.
1552 + */
1553 + private function adopt_protected_owner( $user_id, $wpcom_user_id, $anchor ) {
1554 + // An owner without an identity is a malformed answer, and trusting it would lock the site
1555 + // to nobody.
1556 + if ( ! $wpcom_user_id ) {
1557 + return false;
1558 + }
1559 +
1560 + // Anchored before the binding, so a failed write leaves nothing behind for a later
1561 + // connection to build on. Re-pointing only moves the cached local ID, so it is right only
1562 + // while the anchored identity is the one WordPress.com just confirmed.
1563 + if ( $anchor && (int) $anchor['wpcom_user_id'] === $wpcom_user_id ) {
1564 + Protected_Owner::repoint( $user_id );
1565 + } elseif ( ! Protected_Owner::set( $wpcom_user_id, $user_id ) ) {
1566 + return false;
1567 + }
1568 +
1569 + // Connecting clears the binding, so this writes back the one the answer just confirmed.
1570 + Utils::set_wpcom_user_id( $user_id, $wpcom_user_id );
1571 +
1572 + // Eligibility for the master slot is being an administrator here, which the owner of record
1573 + // need not be.
1574 + if ( user_can( $user_id, ( new Roles() )->translate_role_to_cap( 'administrator' ) )
1575 + && (int) \Jetpack_Options::get_option( 'master_user' ) !== $user_id ) {
1576 + \Jetpack_Options::update_option( 'master_user', $user_id );
1577 + }
1578 +
1579 + return true;
1580 + }
1581 +
1582 + /**
1583 + * Ask WordPress.com whether it still holds the anchored identity as this site's owner.
1584 + *
1585 + * Split from `reconcile_protected_owner()` so the decision it drives can be exercised without a
1586 + * network, which is the half worth testing: every branch of it changes whether a site gates a
1587 + * live feature. The anchored ID is sent so the answer confirms rather than discloses.
1588 + *
1589 + * @since 9.8.0
1590 + *
1591 + * @param int $anchored_wpcom_user_id The WordPress.com identity this site has anchored.
1592 + * @return array|null The record, or null when WordPress.com could not answer.
1593 + */
1594 + protected function query_protected_owner_record( $anchored_wpcom_user_id ) {
1595 + return $this->request_protected_owner_record(
1596 + '/reconcile',
1597 + array( 'anchored_wpcom_user_id' => (int) $anchored_wpcom_user_id )
1598 + );
1599 + }
1600 +
1601 + /**
1602 + * Claim this site's protected ownership for the current user with WordPress.com.
1603 + *
1604 + * Split from `set_protected_owner()` so the decision it drives can be exercised without a
1605 + * network. The identity travels in the signature rather than the payload, so nothing is sent.
1606 + *
1607 + * @since 9.8.0
1608 + *
1609 + * @return array|null The record, or null when WordPress.com could not answer.
1610 + */
1611 + protected function assert_protected_owner_record() {
1612 + return $this->request_protected_owner_record();
1613 + }
1614 +
1615 + /**
1616 + * Give up this site's protected ownership with WordPress.com.
1617 + *
1618 + * Split from `release_protected_owner()` so the decision it drives can be exercised without a
1619 + * network. The identity travels in the signature rather than the payload, so WordPress.com
1620 + * decides whether the caller is the owner it holds.
1621 + *
1622 + * @since 9.9.0
1623 + *
1624 + * @return array|null The record, or null when WordPress.com could not answer.
1625 + */
1626 + protected function relinquish_protected_owner_record() {
1627 + return $this->request_protected_owner_record( '/release' );
1628 + }
1629 +
1630 + /**
1631 + * Call this site's protected-owner resource on WordPress.com, signed as the current user.
1632 + *
1633 + * @since 9.8.1
1634 + *
1635 + * @param string $route The route below the resource, empty for the resource itself.
1636 + * @param array|null $body The request body, or null to send none.
1637 + * @return array|null The record, or null when WordPress.com could not answer.
1638 + */
1639 + private function request_protected_owner_record( $route = '', $body = null ) {
1640 + $path = sprintf(
1641 + '/sites/%d/jetpack-protected-owner%s',
1642 + (int) \Jetpack_Options::get_option( 'id' ),
1643 + $route
1644 + );
1645 +
1646 + $response = Client::wpcom_json_api_request_as_user( $path, '2', array( 'method' => 'POST' ), $body );
1647 +
1648 + // Anything but a 200 is silence rather than an answer: unreachable, refused, or a
1649 + // WordPress.com that does not implement the route. Every caller fails closed on null.
1650 + if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
1651 + return null;
1652 + }
1653 +
1654 + $record = json_decode( wp_remote_retrieve_body( $response ), true );
1655 +
1656 + return is_array( $record ) ? $record : null;
1657 + }
1658 +
1659 + /**
1660 + * Record a user as the protected owner and promote them to connection owner.
1661 + *
1662 + * Gated on `jetpack_connect` rather than on a role: a host can narrow that capability and
1663 + * multisite does. It is false while the package is unconfigured, so a caller that has not
1664 + * registered the connection's capabilities is refused rather than trusted.
1665 + *
1666 + * @since 9.3.0
1667 + * @since 9.6.0 No longer takes how the owner was confirmed.
1668 + * @since 9.8.0 WordPress.com records the owner before anything is anchored here.
1669 + *
1670 + * @param int $user_id The local user to anchor.
1671 + * @return true|WP_Error True on success, WP_Error otherwise.
1672 + */
1673 + public function set_protected_owner( $user_id ) {
1674 + // Authorization precedes validation, so an unauthorized caller cannot use the argument
1675 + // errors below to learn which users are administrators or hold a token.
1676 + if ( ! current_user_can( 'jetpack_connect' ) ) {
1677 + return new WP_Error(
1678 + 'protected_owner_forbidden',
1679 + __( 'You do not have permission to manage the protected owner.', 'jetpack-connection' ),
1680 + array( 'status' => 403 )
1681 + );
1682 + }
1683 +
1684 + $user_id = absint( $user_id );
1685 + $roles = new Roles();
1686 +
1687 + if ( ! user_can( $user_id, $roles->translate_role_to_cap( 'administrator' ) ) ) {
1688 + return new WP_Error(
1689 + 'protected_owner_not_admin',
1690 + __( 'The protected owner must be an administrator.', 'jetpack-connection' ),
1691 + array( 'status' => 400 )
1692 + );
1693 + }
1694 +
1695 + // The claim is signed as the current user, so it can only ever anchor the current user.
1696 + // Anchoring somebody else would be an owner assignment they never agreed to.
1697 + if ( $user_id !== get_current_user_id() ) {
1698 + return new WP_Error(
1699 + 'protected_owner_not_self',
1700 + __( 'A protected owner can only be recorded by the user confirming it.', 'jetpack-connection' ),
1701 + array( 'status' => 400 )
1702 + );
1703 + }
1704 +
1705 + // A stored binding that already disagrees with the anchor is enough to refuse. WordPress.com
1706 + // is still asked when this user has no binding, because that answer is what names them.
1707 + if ( $this->local_anchor_names_someone_else( (int) Utils::get_wpcom_user_id( $user_id ) ) ) {
1708 + return $this->protected_owner_claimed_by_other();
1709 + }
1710 +
1711 + // WordPress.com is asked before anything is written here. It owns the record, so a claim it
1712 + // has not accepted must not leave a locked anchor behind on this site.
1713 + $record = $this->assert_protected_owner_record();
1714 +
1715 + // Fail closed: unreachable, refused, or a WordPress.com that does not implement the call.
1716 + // A site that cannot get an answer must not end up protecting anybody on its own say-so.
1717 + if ( ! is_array( $record ) || empty( $record['status'] ) ) {
1718 + return new WP_Error(
1719 + 'protected_owner_unconfirmed',
1720 + __( 'Could not reach WordPress.com to confirm the protected owner.', 'jetpack-connection' ),
1721 + array( 'status' => 503 )
1722 + );
1723 + }
1724 +
1725 + // Somebody else already holds this site. Beyond support there is no way past this, which is
1726 + // the point: an owner that could be overwritten by the next claimant protects nobody.
1727 + if ( 'locked_to_other' === $record['status'] ) {
1728 + return $this->protected_owner_claimed_by_other();
1729 + }
1730 +
1731 + // Only an accepted claim is anchored: any other verdict is refused, even one carrying an ID.
1732 + if ( ! in_array( $record['status'], array( 'recorded', 'already_yours' ), true ) || empty( $record['wpcom_user_id'] ) ) {
1733 + return new WP_Error(
1734 + 'protected_owner_not_verified',
1735 + __( 'Could not confirm the protected owner with WordPress.com.', 'jetpack-connection' ),
1736 + array( 'status' => 400 )
1737 + );
1738 + }
1739 +
1740 + // A `recorded` answer must not replace an anchor that already names a different account.
1741 + if ( $this->local_anchor_names_someone_else( (int) $record['wpcom_user_id'] ) ) {
1742 + return $this->protected_owner_claimed_by_other();
1743 + }
1744 +
1745 + // Store the binding the anchor will be compared against, so the gate reads local state from
1746 + // here on. Routed through the deduping writer, which clears the ID off any previous holder.
1747 + Utils::set_wpcom_user_id( $user_id, (int) $record['wpcom_user_id'] );
1748 +
1749 + if ( ! Protected_Owner::set( (int) $record['wpcom_user_id'], $user_id ) ) {
1750 + return new WP_Error(
1751 + 'protected_owner_not_stored',
1752 + __( 'Could not store the protected owner.', 'jetpack-connection' ),
1753 + array( 'status' => 500 )
1754 + );
1755 + }
1756 +
1757 + // Written directly rather than through update_connection_owner(): that round-trips to
1758 + // WordPress.com first, and its ownership-change guard will refuse the anchor just set here.
1759 + \Jetpack_Options::update_option( 'master_user', $user_id );
1760 +
1761 + return true;
1762 + }
1763 +
1764 + /**
1765 + * Release the protected owner, leaving ownership open to any connected administrator.
1766 + *
1767 + * WordPress.com holds the record, so it is cleared there first. An anchor dropped only here
1768 + * would leave WordPress.com refusing every later claim as `locked_to_other`, locking the site
1769 + * to nobody rather than unlocking it.
1770 + *
1771 + * Leaves `master_user` alone: releasing the lock does not change who the owner is.
1772 + *
1773 + * @since 9.9.0
1774 + *
1775 + * @return true|WP_Error True on success, WP_Error otherwise.
1776 + */
1777 + public function release_protected_owner() {
1778 + // Authorization precedes everything else, so an unauthorized caller cannot use the
1779 + // refusals below to learn whether this site is protected or by whom.
1780 + if ( ! current_user_can( 'jetpack_connect' ) ) {
1781 + return new WP_Error(
1782 + 'protected_owner_forbidden',
1783 + __( 'You do not have permission to manage the protected owner.', 'jetpack-connection' ),
1784 + array( 'status' => 403 )
1785 + );
1786 + }
1787 +
1788 + // Nothing anchored is already released, so repeating the call is not an error. It can also
1789 + // be an anchor lost while WordPress.com kept its record, which this site cannot tell apart
1790 + // and cannot recover from alone — hence a warning rather than silence.
1791 + $anchor = Protected_Owner::get_locked();
1792 +
1793 + if ( ! $anchor ) {
1794 + wp_trigger_error(
1795 + __METHOD__,
1796 + 'Released with no protected owner on record. If WordPress.com still holds one, this site can no longer claim it back.',
1797 + E_USER_WARNING
1798 + );
1799 +
1800 + return true;
1801 + }
1802 +
1803 + // A local hint that spares an obvious refusal a round trip. WordPress.com is asked anyway
1804 + // whenever this passes, and its answer is the one that decides.
1805 + if ( Utils::get_wpcom_user_id( get_current_user_id() ) !== (int) $anchor['wpcom_user_id'] ) {
1806 + return $this->protected_owner_release_refused();
1807 + }
1808 +
1809 + $record = $this->relinquish_protected_owner_record();
1810 +
1811 + // Fail closed: unreachable, refused, or a WordPress.com that does not implement the call.
1812 + // Clearing on silence would unlock a site WordPress.com still holds.
1813 + if ( ! is_array( $record ) || empty( $record['status'] ) ) {
1814 + return new WP_Error(
1815 + 'protected_owner_unreleased',
1816 + __( 'Could not reach WordPress.com to release the protected owner.', 'jetpack-connection' ),
1817 + array( 'status' => 503 )
1818 + );
1819 + }
1820 +
1821 + if ( 'not_owner' === $record['status'] ) {
1822 + return $this->protected_owner_release_refused();
1823 + }
1824 +
1825 + // `no_owner` is WordPress.com reporting it holds nothing to release, which is the state
1826 + // this call asks for, so the stale anchor here clears alongside an accepted release.
1827 + if ( ! in_array( $record['status'], array( 'released', 'no_owner' ), true ) ) {
1828 + return new WP_Error(
1829 + 'protected_owner_not_released',
1830 + __( 'Could not release the protected owner with WordPress.com.', 'jetpack-connection' ),
1831 + array( 'status' => 400 )
1832 + );
1833 + }
1834 +
1835 + $cleared = $this->clear_protected_owner();
1836 +
1837 + // WordPress.com has already let go, so a local delete that failed is unfinished cleanup
1838 + // rather than a release that did not happen. Retrying is what fixes it: reconcile only
1839 + // runs when somebody authorizes, and WordPress.com now answers this call with `no_owner`.
1840 + if ( is_wp_error( $cleared ) && 'protected_owner_not_cleared' === $cleared->get_error_code() ) {
1841 + return new WP_Error(
1842 + 'protected_owner_not_cleared',
1843 + __( 'Ownership was released with WordPress.com, but this site could not finish clearing it. Try again.', 'jetpack-connection' ),
1844 + array( 'status' => 500 )
1845 + );
1846 + }
1847 +
1848 + return $cleared;
1849 + }
1850 +
1851 + /**
1852 + * The refusal for a caller who is not the owner WordPress.com holds.
1853 + *
1854 + * @since 9.9.0
1855 + *
1856 + * @return WP_Error
1857 + */
1858 + private function protected_owner_release_refused() {
1859 + return new WP_Error(
1860 + 'protected_owner_not_owner',
1861 + __( 'Only the confirmed owner can release ownership of this site.', 'jetpack-connection' ),
1862 + array( 'status' => 403 )
1863 + );
1864 + }
1865 +
1866 + /**
1867 + * Whether a WordPress.com user id would replace the stored anchor.
1868 + *
1869 + * Zero means this user is not named yet, so it is not a conflict.
1870 + *
1871 + * @since 9.9.0
1872 + *
1873 + * @param int $wpcom_user_id WordPress.com user the claim would anchor.
1874 + * @return bool
1875 + */
1876 + private function local_anchor_names_someone_else( $wpcom_user_id ) {
1877 + $anchor = Protected_Owner::get_locked();
1878 +
1879 + return $anchor && $wpcom_user_id && (int) $anchor['wpcom_user_id'] !== (int) $wpcom_user_id;
1880 + }
1881 +
1882 + /**
1883 + * The support path for a site a different account already protects.
1884 + *
1885 + * @since 9.9.0
1886 + *
1887 + * @return WP_Error
1888 + */
1889 + private function protected_owner_claimed_by_other() {
1890 + return new WP_Error(
1891 + 'protected_owner_claimed_by_other',
1892 + __( 'This site is already protected by a different WordPress.com account. Contact support.', 'jetpack-connection' ),
1893 + array( 'status' => 409 )
1894 + );
1895 + }
1896 +
1897 + /**
1898 + * Drop the protected owner anchor, unlocking ownership.
1899 + *
1900 + * Gated on `jetpack_connect` like establishing one, releasing a lock being the more
1901 + * consequential half. The `@internal` tag is documentation; the capability is enforcement.
1902 + *
1903 + * @internal Recovery and support flows only. Consumers must not call this.
1904 + * @since 9.3.0
1905 + *
1906 + * @return true|WP_Error True once no anchor is set, WP_Error otherwise.
1907 + */
1908 + public function clear_protected_owner() {
1909 + if ( ! current_user_can( 'jetpack_connect' ) ) {
1910 + return new WP_Error(
1911 + 'protected_owner_forbidden',
1912 + __( 'You do not have permission to manage the protected owner.', 'jetpack-connection' ),
1913 + array( 'status' => 403 )
1914 + );
1915 + }
1916 +
1917 + Protected_Owner::clear();
1918 +
1919 + // Asked of the outcome rather than of `delete_option()`, which also reports false for an
1920 + // anchor that was already absent — the state the caller asked for.
1921 + if ( Protected_Owner::get() ) {
1922 + return new WP_Error(
1923 + 'protected_owner_not_cleared',
1924 + __( 'Could not clear the protected owner.', 'jetpack-connection' ),
1925 + array( 'status' => 500 )
1926 + );
1927 + }
1928 +
1929 + return true;
1930 + }
1931 +
1932 + /**
807 1933 * Connects the user with a specified ID to a WordPress.com user using the
808 1934 * remote login flow.
809 1935 *
810 1936 * @access public
811 1937 *
812 - * @param Integer $user_id (optional) the user identifier, defaults to current user.
813 - * @param String $redirect_url the URL to redirect the user to for processing, defaults to
814 - * admin_url().
1938 + * @param int|null $user_id (optional) the user identifier, defaults to current user.
1939 + * @param string|null $redirect_url the URL to redirect the user to for processing, defaults to
1940 + * admin_url().
815 1941 * @return WP_Error only in case of a failed user lookup.
816 1942 */
817 1943 public function connect_user( $user_id = null, $redirect_url = null ) {
818 1944 $user = null;
@@ -831,12 +1957,57 @@
831 1957 }
832 1958
833 1959 // Using wp_redirect intentionally because we're redirecting outside.
834 1960 wp_redirect( $this->get_authorization_url( $user, $redirect_url ) ); // phpcs:ignore WordPress.Security.SafeRedirect
835 - exit();
1961 + exit( 0 );
836 1962 }
837 1963
838 1964 /**
1965 + * Force user disconnect.
1966 + *
1967 + * @param int $user_id Local (external) user ID.
1968 + * @param bool $disconnect_all_users Whether to disconnect all users before disconnecting the primary user.
1969 + *
1970 + * @return bool
1971 + */
1972 + public function disconnect_user_force( $user_id, $disconnect_all_users = false ) {
1973 + if ( ! (int) $user_id ) {
1974 + // Missing user ID.
1975 + return false;
1976 + }
1977 + // If we are disconnecting the primary user we may need to disconnect all other users first
1978 + if ( $user_id === $this->get_connection_owner_id() && $disconnect_all_users && ! $this->disconnect_all_users_except_primary() ) {
1979 + return false;
1980 + }
1981 +
1982 + return $this->disconnect_user( $user_id, true, true );
1983 + }
1984 +
1985 + /**
1986 + * Disconnects all users except the primary user.
1987 + *
1988 + * @return bool
1989 + */
1990 + public function disconnect_all_users_except_primary() {
1991 +
1992 + $all_connected_users = $this->get_connected_users();
1993 +
1994 + foreach ( $all_connected_users as $user ) {
1995 + // Skip the primary.
1996 + if ( $user->ID === $this->get_connection_owner_id() ) {
1997 + continue;
1998 + }
1999 + $disconnected = $this->disconnect_user( $user->ID, false, true );
2000 + // If we fail to disconnect any user, we should not proceed with disconnecting the primary user.
2001 + if ( ! $disconnected ) {
2002 + return false;
2003 + }
2004 + }
2005 +
2006 + return true;
2007 + }
2008 +
2009 + /**
839 2010 * Unlinks the current user from the linked WordPress.com user.
840 2011 *
841 2012 * @access public
842 2013 * @static
@@ -842,12 +2013,12 @@
842 2013 * @static
843 2014 *
844 2015 * @todo Refactor to properly load the XMLRPC client independently.
845 2016 *
846 - * @param Integer $user_id the user identifier.
847 - * @param bool $can_overwrite_primary_user Allow for the primary user to be disconnected.
848 - * @param bool $force_disconnect_locally Disconnect user locally even if we were unable to disconnect them from WP.com.
849 - * @return Boolean Whether the disconnection of the user was successful.
2017 + * @param int|null $user_id the user identifier.
2018 + * @param bool $can_overwrite_primary_user Allow for the primary user to be disconnected.
2019 + * @param bool $force_disconnect_locally Disconnect user locally even if we were unable to disconnect them from WP.com.
2020 + * @return bool Whether the disconnection of the user was successful.
850 2021 */
851 2022 public function disconnect_user( $user_id = null, $can_overwrite_primary_user = false, $force_disconnect_locally = false ) {
852 2023 $user_id = empty( $user_id ) ? get_current_user_id() : (int) $user_id;
853 2024 $is_primary_user = Jetpack_Options::get_option( 'master_user' ) === $user_id;
@@ -855,13 +2026,22 @@
855 2026 if ( $is_primary_user && ! $can_overwrite_primary_user ) {
856 2027 return false;
857 2028 }
858 2029
2030 + if ( in_array( $user_id, self::$disconnected_users, true ) ) {
2031 + // The user is already disconnected.
2032 + return false;
2033 + }
2034 +
859 2035 // Attempt to disconnect the user from WordPress.com.
860 2036 $is_disconnected_from_wpcom = $this->unlink_user_from_wpcom( $user_id );
861 2037
862 2038 $is_disconnected_locally = false;
863 2039 if ( $is_disconnected_from_wpcom || $force_disconnect_locally ) {
2040 + // Get the WordPress.com email before disconnecting the user
2041 + $wpcom_user_data = $this->get_connected_user_data( $user_id );
2042 + $wpcom_email = $wpcom_user_data['email'] ?? null;
2043 +
864 2044 // Disconnect the user locally.
865 2045 $is_disconnected_locally = $this->get_tokens()->disconnect_user( $user_id );
866 2046
867 2047 if ( $is_disconnected_locally ) {
@@ -868,8 +2048,14 @@
868 2048 // Delete cached connected user data.
869 2049 $transient_key = "jetpack_connected_user_data_$user_id";
870 2050 delete_transient( $transient_key );
871 2051
2052 + // Clean up account mismatch transients for this user
2053 + if ( $wpcom_email ) {
2054 + $user_account_status = new User_Account_Status();
2055 + $user_account_status->clean_account_mismatch_transients( $wpcom_email );
2056 + }
2057 +
872 2058 /**
873 2059 * Fires after the current user has been unlinked from WordPress.com.
874 2060 *
875 2061 * @since 1.7.0
@@ -880,12 +2066,17 @@
880 2066 do_action( 'jetpack_unlinked_user', $user_id );
881 2067
882 2068 if ( $is_primary_user ) {
883 2069 Jetpack_Options::delete_option( 'master_user' );
2070 +
2071 + // Clear the memoized connection owner ID since it changed
2072 + self::$connection_owner_id = null;
884 2073 }
885 2074 }
886 2075 }
887 2076
2077 + self::$disconnected_users[] = $user_id;
2078 +
888 2079 return $is_disconnected_from_wpcom && $is_disconnected_locally;
889 2080 }
890 2081
891 2082 /**
@@ -910,14 +2101,27 @@
910 2101 /**
911 2102 * Update the connection owner.
912 2103 *
913 2104 * @since 1.29.0
2105 + * @since 9.3.0 Refused while ownership is locked.
2106 + * @since 9.9.0 The anchored owner passes the lock, and moving the site off them
2107 + * releases the anchor.
914 2108 *
915 - * @param Integer $new_owner_id The ID of the user to become the connection owner.
2109 + * @param int $new_owner_id The ID of the user to become the connection owner.
916 2110 *
917 2111 * @return true|WP_Error True if owner successfully changed, WP_Error otherwise.
918 2112 */
919 2113 public function update_connection_owner( $new_owner_id ) {
2114 + // Answered before the arguments are validated: no candidate is valid while ownership is
2115 + // locked, and an argument error would suggest a retry that cannot work.
2116 + if ( ! $this->is_ownership_transferable() && ! $this->current_user_may_move_locked_ownership() ) {
2117 + return new WP_Error(
2118 + 'ownership_locked',
2119 + __( 'The connection owner is locked on this site.', 'jetpack-connection' ),
2120 + array( 'status' => 403 )
2121 + );
2122 + }
2123 +
920 2124 $roles = new Roles();
921 2125 if ( ! user_can( $new_owner_id, $roles->translate_role_to_cap( 'administrator' ) ) ) {
922 2126 return new WP_Error(
923 2127 'new_owner_not_admin',
@@ -951,8 +2155,13 @@
951 2155 // Update the connection owner in Jetpack only if they were successfully updated on WPCOM.
952 2156 // This will ensure consistency with WPCOM.
953 2157 \Jetpack_Options::update_option( 'master_user', $new_owner_id );
954 2158
2159 + // Clear the memoized connection owner ID since it changed
2160 + self::$connection_owner_id = null;
2161 +
2162 + $this->release_anchor_after_transfer( $new_owner_id, $owner_updated_wpcom );
2163 +
955 2164 // Track it.
956 2165 ( new Tracking() )->record_user_event( 'set_connection_owner_success' );
957 2166
958 2167 return true;
@@ -964,15 +2173,99 @@
964 2173 );
965 2174 }
966 2175
967 2176 /**
2177 + * Whether the current user may move the connection despite a locked anchor.
2178 + *
2179 + * The anchor protects an identity, so the owner it names is the one person it is not against.
2180 + *
2181 + * A local hint rather than proof of who that is: the binding is not unique site-wide, and the
2182 + * anchored owner is often not the connection owner here — taking a site back from an agency is
2183 + * the point — so there is no stronger identity to check. WordPress.com decides, marking a
2184 + * switch `po_signed` only when the signing token belongs to the owner of record.
2185 + *
2186 + * A consumer locking ownership through the filter is a separate refusal that still applies to
2187 + * everybody, so it is re-read here with the anchor out of the way.
2188 + *
2189 + * @since 9.9.0
2190 + *
2191 + * @return bool
2192 + */
2193 + private function current_user_may_move_locked_ownership() {
2194 + $anchor = Protected_Owner::get_locked();
2195 + $user_id = get_current_user_id();
2196 +
2197 + if ( ! $anchor || ! $user_id ) {
2198 + return false;
2199 + }
2200 +
2201 + // Both halves, as everywhere else the binding is trusted: it outlives the token, so a
2202 + // disconnected user can still carry the anchored ID.
2203 + if ( ! $this->is_user_connected( $user_id ) ) {
2204 + return false;
2205 + }
2206 +
2207 + // This user's own binding, never a search for whoever holds the anchored ID, which would
2208 + // hand the site to the first match.
2209 + if ( Utils::get_wpcom_user_id( $user_id ) !== (int) $anchor['wpcom_user_id'] ) {
2210 + return false;
2211 + }
2212 +
2213 + /** This filter is documented in projects/packages/connection/src/class-manager.php */
2214 + return (bool) apply_filters( 'jetpack_connection_ownership_transferable', true );
2215 + }
2216 +
2217 + /**
2218 + * Drop the anchor once the site has left the owner it names.
2219 + *
2220 + * Do not make this clear more eagerly. An anchor dropped while WordPress.com kept its own
2221 + * locks the site to nobody, and `reconcile_protected_owner()` returns before asking when
2222 + * there is no local anchor left to repair it with. The reverse mistake costs nothing.
2223 + *
2224 + * @since 9.9.0
2225 + *
2226 + * @param int $new_owner_id The local user who now holds the connection.
2227 + * @param true|array $accepted What WordPress.com answered the switch with: a report of
2228 + * what it did where available, otherwise a bare `true`.
2229 + */
2230 + private function release_anchor_after_transfer( $new_owner_id, $accepted ) {
2231 + $anchor = Protected_Owner::get_locked();
2232 +
2233 + if ( ! $anchor ) {
2234 + return;
2235 + }
2236 +
2237 + // WordPress.com resolves the new owner itself and knows what it kept, so where it reports
2238 + // what it did, that report is the whole answer.
2239 + if ( is_array( $accepted ) ) {
2240 + if ( ! empty( $accepted['released'] ) ) {
2241 + Protected_Owner::clear();
2242 + }
2243 +
2244 + return;
2245 + }
2246 +
2247 + // A bare `true` says only that the switch happened, leaving who the site went to as the
2248 + // best guess available. A zero is "could not determine", which covers the owner taking the
2249 + // site back — the case WordPress.com keeps its record for.
2250 + $new_owner_wpcom_id = $this->resolve_wpcom_user_id( $new_owner_id );
2251 +
2252 + if ( $new_owner_wpcom_id && $new_owner_wpcom_id !== (int) $anchor['wpcom_user_id'] ) {
2253 + Protected_Owner::clear();
2254 + }
2255 + }
2256 +
2257 + /**
968 2258 * Request to WPCOM to update the connection owner.
969 2259 *
970 2260 * @since 1.29.0
2261 + * @since 9.9.0 Returns what WordPress.com answered rather than casting it, so a
2262 + * report of what the switch did can be read. Still falsy on failure.
971 2263 *
972 - * @param Integer $new_owner_id The ID of the user to become the connection owner.
2264 + * @param int $new_owner_id The ID of the user to become the connection owner.
973 2265 *
974 - * @return Boolean Whether the ownership transfer was successful.
2266 + * @return bool|array False if the transfer failed, otherwise what WordPress.com answered:
2267 + * `true`, or a non-empty report such as `array( 'released' => bool )`.
975 2268 */
976 2269 public function update_connection_owner_wpcom( $new_owner_id ) {
977 2270 // Notify WPCOM about the connection owner change.
978 2271 $xml = new Jetpack_IXR_Client(
@@ -989,16 +2282,24 @@
989 2282 if ( $xml->isError() ) {
990 2283 return false;
991 2284 }
992 2285
993 - return (bool) $xml->getResponse();
2286 + $response = $xml->getResponse();
2287 +
2288 + // An array is the switch reporting what it did, and an empty one reports nothing rather
2289 + // than refusing — a bare `true` by another name. Only a falsy non-array is a refusal.
2290 + if ( is_array( $response ) ) {
2291 + return empty( $response ) ? true : $response;
2292 + }
2293 +
2294 + return (bool) $response;
994 2295 }
995 2296
996 2297 /**
997 2298 * Returns the requested Jetpack API URL.
998 2299 *
999 - * @param String $relative_url the relative API path.
1000 - * @return String API URL.
2300 + * @param string $relative_url the relative API path.
2301 + * @return string API URL.
1001 2302 */
1002 2303 public function api_url( $relative_url ) {
1003 2304 $api_base = Constants::get_constant( 'JETPACK__API_BASE' );
1004 2305 $api_version = '/' . Constants::get_constant( 'JETPACK__API_VERSION' ) . '/';
@@ -1008,12 +2309,12 @@
1008 2309 *
1009 2310 * @since 1.7.0
1010 2311 * @since-jetpack 8.0.0
1011 2312 *
1012 - * @param String $url the generated URL.
1013 - * @param String $relative_url the relative URL that was passed as an argument.
1014 - * @param String $api_base the API base string that is being used.
1015 - * @param String $api_version the API version string that is being used.
2313 + * @param string $url the generated URL.
2314 + * @param string $relative_url the relative URL that was passed as an argument.
2315 + * @param string $api_base the API base string that is being used.
2316 + * @param string $api_version the API version string that is being used.
1016 2317 */
1017 2318 return apply_filters(
1018 2319 'jetpack_api_url',
1019 2320 rtrim( $api_base . $relative_url, '/\\' ) . $api_version,
@@ -1025,9 +2326,9 @@
1025 2326
1026 2327 /**
1027 2328 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
1028 2329 *
1029 - * @return String XMLRPC API URL.
2330 + * @return string XMLRPC API URL.
1030 2331 */
1031 2332 public function xmlrpc_api_url() {
1032 2333 $base = preg_replace(
1033 2334 '#(https?://[^?/]+)(/?.*)?$#',
@@ -1041,12 +2342,17 @@
1041 2342 * Attempts Jetpack registration which sets up the site for connection. Should
1042 2343 * remain public because the call to action comes from the current site, not from
1043 2344 * WordPress.com.
1044 2345 *
1045 - * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
2346 + * @param string $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
1046 2347 * @return true|WP_Error The error object.
1047 2348 */
1048 2349 public function register( $api_endpoint = 'register' ) {
2350 + // Clean-up leftover tokens just in-case.
2351 + // This fixes an edge case that was preventing users to register when the blog token was missing but
2352 + // there were still leftover user tokens present.
2353 + $this->delete_all_connection_tokens( true );
2354 +
1049 2355 add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
1050 2356 $secrets = ( new Secrets() )->generate( 'register', get_current_user_id(), 600 );
1051 2357
1052 2358 if ( false === $secrets ) {
@@ -1070,11 +2376,9 @@
1070 2376 $gmt_offset = 0;
1071 2377 }
1072 2378
1073 2379 $stats_options = get_option( 'stats_options' );
1074 - $stats_id = isset( $stats_options['blog_id'] )
1075 - ? $stats_options['blog_id']
1076 - : null;
2380 + $stats_id = $stats_options['blog_id'] ?? null;
1077 2381
1078 2382 /* This action is documented in src/class-package-version-tracker.php */
1079 2383 $package_versions = apply_filters( 'jetpack_package_versions', array() );
1080 2384
@@ -1124,9 +2428,9 @@
1124 2428 ),
1125 2429 'timeout' => $timeout,
1126 2430 );
1127 2431
1128 - $args['body'] = $this->apply_activation_source_to_args( $args['body'] );
2432 + $args['body'] = static::apply_activation_source_to_args( $args['body'] );
1129 2433
1130 2434 // TODO: fix URLs for bad hosts.
1131 2435 $response = Client::_wp_remote_request(
1132 2436 $this->api_url( $api_endpoint ),
@@ -1160,9 +2464,9 @@
1160 2464 } else {
1161 2465 $jetpack_public = false;
1162 2466 }
1163 2467
1164 - \Jetpack_Options::update_options(
2468 + Jetpack_Options::update_options(
1165 2469 array(
1166 2470 'id' => (int) $registration_details->jetpack_id,
1167 2471 'public' => $jetpack_public,
1168 2472 )
@@ -1171,10 +2475,17 @@
1171 2475 update_option( Package_Version_Tracker::PACKAGE_VERSION_OPTION, $package_versions );
1172 2476
1173 2477 $this->get_tokens()->update_blog_token( (string) $registration_details->jetpack_secret );
1174 2478
1175 - $alternate_authorization_url = isset( $registration_details->alternate_authorization_url ) ? $registration_details->alternate_authorization_url : '';
2479 + if ( ! Jetpack_Options::get_option( 'id' ) || ! $this->get_tokens()->get_access_token() ) {
2480 + return new WP_Error(
2481 + 'connection_data_save_failed',
2482 + 'Failed to save connection data in the database'
2483 + );
2484 + }
1176 2485
2486 + $alternate_authorization_url = $registration_details->alternate_authorization_url ?? '';
2487 +
1177 2488 add_filter(
1178 2489 'jetpack_register_site_rest_response',
1179 2490 function ( $response ) use ( $alternate_authorization_url ) {
1180 2491 $response['alternateAuthorizeUrl'] = $alternate_authorization_url;
@@ -1285,9 +2596,9 @@
1285 2596 *
1286 2597 * @since 1.7.0
1287 2598 * @since-jetpack 2.6.0
1288 2599 *
1289 - * @param Mixed $response the response object, or the error object.
2600 + * @param mixed $response the response object, or the error object.
1290 2601 * @return string|WP_Error A JSON object on success or WP_Error on failures
1291 2602 **/
1292 2603 protected function validate_remote_register_response( $response ) {
1293 2604 if ( is_wp_error( $response ) ) {
@@ -1426,8 +2737,18 @@
1426 2737 }
1427 2738 // With site connections in mind, non-admin users can connect their account only if a connection owner exists.
1428 2739 $caps = $this->has_connected_owner() ? array( 'read' ) : array( 'manage_options' );
1429 2740 break;
2741 + case 'jetpack_unlink_user':
2742 + $is_offline_mode = ( new Status() )->is_offline_mode();
2743 + if ( $is_offline_mode ) {
2744 + $caps = array( 'do_not_allow' );
2745 + break;
2746 + }
2747 +
2748 + // Non-admins can always disconnect
2749 + $caps = array( 'read' );
2750 + break;
1430 2751 }
1431 2752 return $caps;
1432 2753 }
1433 2754
@@ -1454,9 +2775,9 @@
1454 2775 * Sets a minimum request timeout, and returns the current timeout
1455 2776 *
1456 2777 * @since 1.7.0
1457 2778 * @since-jetpack 5.4.0
1458 - * @param Integer $min_timeout the minimum timeout value.
2779 + * @param int $min_timeout the minimum timeout value.
1459 2780 **/
1460 2781 public function set_min_time_limit( $min_timeout ) {
1461 2782 $timeout = $this->get_max_execution_time();
1462 2783 if ( $timeout < $min_timeout ) {
@@ -1482,14 +2803,19 @@
1482 2803 if ( ! empty( $cached_date ) ) {
1483 2804 return $cached_date;
1484 2805 }
1485 2806
2807 + /**
2808 + * We don't use the 'ID' field, but need it to overcome a WP caching bug: https://core.trac.wordpress.org/ticket/62003
2809 + *
2810 + * @todo Remote the 'ID' field from users fetching when the issue is fixed and Jetpack-supported WP versions move beyond it.
2811 + */
1486 2812 $earliest_registered_users = get_users(
1487 2813 array(
1488 2814 'role' => 'administrator',
1489 2815 'orderby' => 'user_registered',
1490 2816 'order' => 'ASC',
1491 - 'fields' => array( 'user_registered' ),
2817 + 'fields' => array( 'ID', 'user_registered' ),
1492 2818 'number' => 1,
1493 2819 )
1494 2820 );
1495 2821 $earliest_registration_date = $earliest_registered_users[0]->user_registered;
@@ -1525,18 +2851,18 @@
1525 2851 * @param array $args arguments that need to have the source added.
1526 2852 * @return array $amended arguments.
1527 2853 */
1528 2854 public static function apply_activation_source_to_args( $args ) {
1529 - list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
2855 + $activation_source = get_option( 'jetpack_activation_source' );
1530 2856
1531 - if ( $activation_source_name ) {
2857 + if ( ! empty( $activation_source[0] ) ) {
1532 2858 // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1533 - $args['_as'] = urlencode( $activation_source_name );
2859 + $args['_as'] = urlencode( $activation_source[0] );
1534 2860 }
1535 2861
1536 - if ( $activation_source_keyword ) {
2862 + if ( ! empty( $activation_source[1] ) ) {
1537 2863 // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1538 - $args['_ak'] = urlencode( $activation_source_keyword );
2864 + $args['_ak'] = urlencode( $activation_source[1] );
1539 2865 }
1540 2866
1541 2867 return $args;
1542 2868 }
@@ -1543,11 +2869,11 @@
1543 2869
1544 2870 /**
1545 2871 * Generates two secret tokens and the end of life timestamp for them.
1546 2872 *
1547 - * @param String $action The action name.
1548 - * @param Integer $user_id The user identifier.
1549 - * @param Integer $exp Expiration time in seconds.
2873 + * @param string $action The action name.
2874 + * @param int|bool $user_id The user identifier.
2875 + * @param int $exp Expiration time in seconds.
1550 2876 */
1551 2877 public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1552 2878 return ( new Secrets() )->generate( $action, $user_id, $exp );
1553 2879 }
@@ -1556,10 +2882,10 @@
1556 2882 * Returns two secret tokens and the end of life timestamp for them.
1557 2883 *
1558 2884 * @deprecated 1.24.0 Use Automattic\Jetpack\Connection\Secrets->get() instead.
1559 2885 *
1560 - * @param String $action The action name.
1561 - * @param Integer $user_id The user identifier.
2886 + * @param string $action The action name.
2887 + * @param int $user_id The user identifier.
1562 2888 * @return string|array an array of secrets or an error string.
1563 2889 */
1564 2890 public function get_secrets( $action, $user_id ) {
1565 2891 _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Secrets->get' );
@@ -1570,10 +2896,10 @@
1570 2896 * Deletes secret tokens in case they, for example, have expired.
1571 2897 *
1572 2898 * @deprecated 1.24.0 Use Automattic\Jetpack\Connection\Secrets->delete() instead.
1573 2899 *
1574 - * @param String $action The action name.
1575 - * @param Integer $user_id The user identifier.
2900 + * @param string $action The action name.
2901 + * @param int $user_id The user identifier.
1576 2902 */
1577 2903 public function delete_secrets( $action, $user_id ) {
1578 2904 _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Secrets->delete' );
1579 2905 ( new Secrets() )->delete( $action, $user_id );
@@ -1605,16 +2931,23 @@
1605 2931 if ( ! apply_filters( 'jetpack_connection_delete_all_tokens', true ) ) {
1606 2932 return false;
1607 2933 }
1608 2934
2935 + // The protected owner anchor is a local cache of a record WordPress.com owns. Dropping it
2936 + // here keeps a disconnected site from carrying a lock that names a user who no longer holds
2937 + // a token; the anchor is re-established from WordPress.com when the owner reconnects.
1609 2938 \Jetpack_Options::delete_option(
1610 2939 array(
1611 2940 'master_user',
2941 + 'protected_owner',
1612 2942 'time_diff',
1613 2943 'fallback_no_verify_ssl_certs',
1614 2944 )
1615 2945 );
1616 2946
2947 + // Clear the memoized connection owner ID since it changed
2948 + self::$connection_owner_id = null;
2949 +
1617 2950 ( new Secrets() )->delete_all();
1618 2951 $this->get_tokens()->delete_all();
1619 2952
1620 2953 // Delete cached connected user data.
@@ -1620,8 +2953,11 @@
1620 2953 // Delete cached connected user data.
1621 2954 $transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
1622 2955 delete_transient( $transient_key );
1623 2956
2957 + // Delete the cached site record, which a later connection must not serve.
2958 + self::delete_cached_site_data();
2959 +
1624 2960 // Delete all XML-RPC errors.
1625 2961 Error_Handler::get_instance()->delete_all_errors();
1626 2962
1627 2963 return true;
@@ -1642,8 +2978,13 @@
1642 2978 if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1643 2979 return false;
1644 2980 }
1645 2981
2982 + if ( ( new Status() )->is_offline_mode() && ! apply_filters( 'jetpack_connection_disconnect_site_wpcom_offline_mode', false ) ) {
2983 + // Prevent potential disconnect of the live site by removing WPCOM tokens.
2984 + return false;
2985 + }
2986 +
1646 2987 /**
1647 2988 * Fires upon the disconnect attempt.
1648 2989 * Return `false` to prevent the disconnect.
1649 2990 *
@@ -1685,9 +3026,8 @@
1685 3026 public function reconnect() {
1686 3027 ( new Tracking() )->record_user_event( 'restore_connection_reconnect' );
1687 3028
1688 3029 $this->disconnect_site_wpcom( true );
1689 - $this->delete_all_connection_tokens( true );
1690 3030
1691 3031 return $this->register();
1692 3032 }
1693 3033
@@ -1693,8 +3033,10 @@
1693 3033
1694 3034 /**
1695 3035 * Validate the tokens, and refresh the invalid ones.
1696 3036 *
3037 + * @since 9.8.1 When token validation is inconclusive, check the blog token on its own instead of assuming both are broken.
3038 + *
1697 3039 * @return string|bool|WP_Error True if connection restored or string indicating what's to be done next. A `WP_Error` object or false otherwise.
1698 3040 */
1699 3041 public function restore() {
1700 3042 // If this is a site connection we need to trigger a full reconnection as our only secure means of
@@ -1704,9 +3046,8 @@
1704 3046 }
1705 3047
1706 3048 $validate_tokens_response = $this->get_tokens()->validate();
1707 3049
1708 - // If token validation failed, trigger a full reconnection.
1709 3050 if ( is_array( $validate_tokens_response ) &&
1710 3051 isset( $validate_tokens_response['blog_token']['is_healthy'] ) &&
1711 3052 isset( $validate_tokens_response['user_token']['is_healthy'] ) ) {
1712 3053 $blog_token_healthy = $validate_tokens_response['blog_token']['is_healthy'];
@@ -1711,10 +3052,14 @@
1711 3052 isset( $validate_tokens_response['user_token']['is_healthy'] ) ) {
1712 3053 $blog_token_healthy = $validate_tokens_response['blog_token']['is_healthy'];
1713 3054 $user_token_healthy = $validate_tokens_response['user_token']['is_healthy'];
1714 3055 } else {
1715 - $blog_token_healthy = false;
1716 - $user_token_healthy = false;
3056 + // The paired health check could not run (a token is missing locally — e.g. a
3057 + // deleted owner token — or the request failed): no evidence the blog token is
3058 + // broken, and it's the one credential reconnect() would revoke for every user,
3059 + // so check it on its own before that teardown.
3060 + $blog_token_healthy = true === $this->get_tokens()->validate_blog_token();
3061 + $user_token_healthy = false; // Unknown, treated as unhealthy.
1717 3062 }
1718 3063
1719 3064 // Tokens are both valid, or both invalid. We can't fix the problem we don't see, so the full reconnection is needed.
1720 3065 if ( $blog_token_healthy === $user_token_healthy ) {
@@ -1797,13 +3142,18 @@
1797 3142
1798 3143 /**
1799 3144 * Builds a URL to the Jetpack connection auth page.
1800 3145 *
1801 - * @param WP_User $user (optional) defaults to the current logged in user.
1802 - * @param String $redirect (optional) a redirect URL to use instead of the default.
3146 + * @since 2.7.6 Added optional $from and $raw parameters.
3147 + *
3148 + * @param WP_User|null $user (optional) defaults to the current logged in user.
3149 + * @param string|null $redirect (optional) a redirect URL to use instead of the default.
3150 + * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
3151 + * @param bool $raw If true, URL will not be escaped.
3152 + *
1803 3153 * @return string Connect URL.
1804 3154 */
1805 - public function get_authorization_url( $user = null, $redirect = null ) {
3155 + public function get_authorization_url( $user = null, $redirect = null, $from = false, $raw = false ) {
1806 3156 if ( empty( $user ) ) {
1807 3157 $user = wp_get_current_user();
1808 3158 }
1809 3159
@@ -1846,8 +3196,53 @@
1846 3196 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
1847 3197 */
1848 3198 $auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
1849 3199
3200 + $body_args = array(
3201 + 'response_type' => 'code',
3202 + 'client_id' => \Jetpack_Options::get_option( 'id' ),
3203 + 'redirect_uri' => add_query_arg(
3204 + array(
3205 + 'handler' => 'jetpack-connection-webhooks',
3206 + 'action' => 'authorize',
3207 + '_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
3208 + 'redirect' => $redirect ? rawurlencode( $redirect ) : false,
3209 + ),
3210 + esc_url( $processing_url )
3211 + ),
3212 + 'state' => $user->ID,
3213 + 'scope' => $signed_role,
3214 + 'user_email' => $user->user_email,
3215 + 'user_login' => $user->user_login,
3216 + 'is_active' => $this->has_connected_owner(), // TODO Deprecate this.
3217 + 'jp_version' => (string) Constants::get_constant( 'JETPACK__VERSION' ),
3218 + 'auth_type' => $auth_type,
3219 + 'secret' => $secrets['secret_1'],
3220 + 'blogname' => get_option( 'blogname' ),
3221 + 'site_url' => Urls::site_url(),
3222 + 'home_url' => Urls::home_url(),
3223 + 'site_icon' => get_site_icon_url(),
3224 + 'site_lang' => get_locale(),
3225 + 'site_created' => $this->get_assumed_site_creation_date(),
3226 + 'allow_site_connection' => ! $this->has_connected_owner(),
3227 + 'calypso_env' => ( new Host() )->get_calypso_env(),
3228 + 'source' => ( new Host() )->get_source_query(),
3229 + );
3230 +
3231 + // Include the slugs of every plugin currently using the Jetpack connection so wpcom
3232 + // knows which integrations the site is authorizing on behalf of. `Plugin_Storage::get_all()`
3233 + // returns a `WP_Error` when called before `plugins_loaded`; in that case we silently skip.
3234 + $active_plugins = Plugin_Storage::get_all();
3235 + if ( is_array( $active_plugins ) && ! empty( $active_plugins ) ) {
3236 + $body_args['plugins'] = implode( ',', array_keys( $active_plugins ) );
3237 + }
3238 +
3239 + // Signal to Calypso that the site already has a connection owner so the
3240 + // authorize page can show secondary-connection content where appropriate.
3241 + if ( $this->has_connected_owner() ) {
3242 + $body_args['has_connected_owner'] = true;
3243 + }
3244 +
1850 3245 /**
1851 3246 * Filters the user connection request data for additional property addition.
1852 3247 *
1853 3248 * @since 1.7.0
@@ -1854,50 +3249,45 @@
1854 3249 * @since-jetpack 8.0.0
1855 3250 *
1856 3251 * @param array $request_data request data.
1857 3252 */
1858 - $body = apply_filters(
1859 - 'jetpack_connect_request_body',
1860 - array(
1861 - 'response_type' => 'code',
1862 - 'client_id' => \Jetpack_Options::get_option( 'id' ),
1863 - 'redirect_uri' => add_query_arg(
1864 - array(
1865 - 'handler' => 'jetpack-connection-webhooks',
1866 - 'action' => 'authorize',
1867 - '_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1868 - 'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1869 - ),
1870 - esc_url( $processing_url )
1871 - ),
1872 - 'state' => $user->ID,
1873 - 'scope' => $signed_role,
1874 - 'user_email' => $user->user_email,
1875 - 'user_login' => $user->user_login,
1876 - 'is_active' => $this->has_connected_owner(), // TODO Deprecate this.
1877 - 'jp_version' => (string) Constants::get_constant( 'JETPACK__VERSION' ),
1878 - 'auth_type' => $auth_type,
1879 - 'secret' => $secrets['secret_1'],
1880 - 'blogname' => get_option( 'blogname' ),
1881 - 'site_url' => Urls::site_url(),
1882 - 'home_url' => Urls::home_url(),
1883 - 'site_icon' => get_site_icon_url(),
1884 - 'site_lang' => get_locale(),
1885 - 'site_created' => $this->get_assumed_site_creation_date(),
1886 - 'allow_site_connection' => ! $this->has_connected_owner(),
1887 - )
1888 - );
3253 + $body = apply_filters( 'jetpack_connect_request_body', $body_args );
1889 3254
1890 - $body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
3255 + $body = static::apply_activation_source_to_args( urlencode_deep( $body ) );
1891 3256
1892 3257 $api_url = $this->api_url( 'authorize' );
1893 3258
1894 - return add_query_arg( $body, $api_url );
3259 + $url = add_query_arg( $body, $api_url );
3260 +
3261 + if ( is_network_admin() ) {
3262 + $url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
3263 + }
3264 +
3265 + if ( $from ) {
3266 + $url = add_query_arg( 'from', $from, $url );
3267 + }
3268 +
3269 + if ( $raw ) {
3270 + $url = esc_url_raw( $url );
3271 + }
3272 +
3273 + /**
3274 + * Filter the URL used when connecting a user to a WordPress.com account.
3275 + *
3276 + * @since 2.0.0
3277 + * @since 2.7.6 Added $raw parameter.
3278 + *
3279 + * @param string $url Connection URL.
3280 + * @param bool $raw If true, URL will not be escaped.
3281 + */
3282 + return apply_filters( 'jetpack_build_authorize_url', $url, $raw );
1895 3283 }
1896 3284
1897 3285 /**
1898 3286 * Authorizes the user by obtaining and storing the user token.
1899 3287 *
3288 + * @since 9.8.1 Only a user with `jetpack_connect` can take a vacant connection owner slot.
3289 + *
1900 3290 * @param array $data The request data.
1901 3291 * @return string|\WP_Error Returns a string on success.
1902 3292 * Returns a \WP_Error on failure.
1903 3293 */
@@ -1956,12 +3346,17 @@
1956 3346 if ( ! $token ) {
1957 3347 return new \WP_Error( 'no_token', 'Error generating token.', 400 );
1958 3348 }
1959 3349
1960 - $is_connection_owner = ! $this->has_connected_owner();
3350 + // Only a user who may manage the site connection takes a vacant owner slot; others link as secondary users.
3351 + $is_connection_owner = ! $this->has_connected_owner() && current_user_can( 'jetpack_connect' );
1961 3352
1962 3353 $this->get_tokens()->update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_connection_owner );
1963 3354
3355 + // Delete cached connected user data, so a cached failure from the
3356 + // previous (broken) token doesn't linger after reconnecting.
3357 + delete_transient( "jetpack_connected_user_data_$current_user_id" );
3358 +
1964 3359 /**
1965 3360 * Fires after user has successfully received an auth token.
1966 3361 *
1967 3362 * @since 1.7.0
@@ -2012,10 +3407,12 @@
2012 3407 wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2013 3408
2014 3409 ( new Nonce_Handler() )->clean_all();
2015 3410
3411 + Heartbeat::init()->deactivate();
3412 +
2016 3413 /**
2017 - * Fires when a site is disconnected.
3414 + * Fires before a site is disconnected.
2018 3415 *
2019 3416 * @since 1.36.3
2020 3417 */
2021 3418 do_action( 'jetpack_site_before_disconnected' );
@@ -2106,9 +3503,8 @@
2106 3503 $forbidden_domains = array(
2107 3504 'wordpress.com',
2108 3505 'localhost',
2109 3506 'localhost.localdomain',
2110 - '127.0.0.1',
2111 3507 'local.wordpress.test', // VVV pattern.
2112 3508 'local.wordpress-trunk.test', // VVV pattern.
2113 3509 'src.wordpress-develop.test', // VVV pattern.
2114 3510 'build.wordpress-develop.test', // VVV pattern.
@@ -2162,8 +3558,26 @@
2162 3558 // Just pass back true for now, and let wpcom sort it out.
2163 3559 return true;
2164 3560 }
2165 3561
3562 + $domain = preg_replace( '#^https?://#', '', untrailingslashit( $domain ) );
3563 +
3564 + if ( filter_var( $domain, FILTER_VALIDATE_IP )
3565 + && ! \Automattic\Jetpack\IP\Utils::ip_is_public( $domain )
3566 + ) {
3567 + return new \WP_Error(
3568 + 'fail_ip_forbidden',
3569 + sprintf(
3570 + /* translators: %1$s is a domain name. */
3571 + __(
3572 + 'IP address `%1$s` just failed is_usable_domain check as it is not a public IP address.',
3573 + 'jetpack-connection'
3574 + ),
3575 + $domain
3576 + )
3577 + );
3578 + }
3579 +
2166 3580 return true;
2167 3581 }
2168 3582
2169 3583 /**
@@ -2192,9 +3606,9 @@
2192 3606 * @param array $methods an array of available XMLRPC methods.
2193 3607 * @return array the same array, since this method doesn't add or remove anything.
2194 3608 */
2195 3609 public function xmlrpc_methods( $methods ) {
2196 - $this->raw_post_data = isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ? $GLOBALS['HTTP_RAW_POST_DATA'] : null;
3610 + $this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'] ?? null;
2197 3611 return $methods;
2198 3612 }
2199 3613
2200 3614 /**
@@ -2220,9 +3634,9 @@
2220 3634 /**
2221 3635 * Handles a getOptions XMLRPC method call.
2222 3636 *
2223 3637 * @param array $args method call arguments.
2224 - * @return an amended XMLRPC server options array.
3638 + * @return array|IXR_Error An amended XMLRPC server options array.
2225 3639 */
2226 3640 public function jetpack_get_options( $args ) {
2227 3641 global $wp_xmlrpc_server;
2228 3642
@@ -2448,14 +3862,65 @@
2448 3862
2449 3863 /**
2450 3864 * Disconnect the user from WP.com, and initiate the reconnect process.
2451 3865 *
2452 - * @return bool
3866 + * @since 9.8.0 Added the `$force` parameter.
3867 + *
3868 + * @param bool $force Whether to remove the local token even if WordPress.com does not confirm the unlink.
3869 + * When false, only the current user's own token is refreshed, never the owner's,
3870 + * and only over a healthy blog token.
3871 + * @return true|string|WP_Error True when forced. Otherwise 'authorize' when the user should authorize again, a `WP_Error` object on failure.
2453 3872 */
2454 - public function refresh_user_token() {
2455 - ( new Tracking() )->record_user_event( 'restore_connection_refresh_user_token' );
2456 - $this->disconnect_user( null, true, true );
2457 - return true;
3873 + public function refresh_user_token( $force = true ) {
3874 + $user_id = get_current_user_id();
3875 +
3876 + if ( ! $force ) {
3877 + // Unlinking the owner would leave the site without one.
3878 + if ( ! $user_id || $this->is_site_connection() || $this->get_connection_owner_id() === $user_id ) {
3879 + return new WP_Error(
3880 + 'restore_requires_administrator',
3881 + __( 'An administrator needs to restore the Jetpack connection.', 'jetpack-connection' ),
3882 + array( 'status' => 403 )
3883 + );
3884 + }
3885 +
3886 + // Relinking goes over the blog token, so it must work before anything is unlinked.
3887 + $blog_token_health = $this->get_tokens()->validate_blog_token();
3888 +
3889 + if ( is_wp_error( $blog_token_health ) ) {
3890 + return new WP_Error(
3891 + 'restore_check_failed',
3892 + __( 'The site connection could not be checked. Please try again shortly.', 'jetpack-connection' ),
3893 + array( 'status' => 503 )
3894 + );
3895 + }
3896 +
3897 + if ( true !== $blog_token_health ) {
3898 + return new WP_Error(
3899 + 'restore_requires_administrator',
3900 + __( 'The site connection is broken. An administrator needs to restore it before you can reconnect your account.', 'jetpack-connection' ),
3901 + array( 'status' => 409 )
3902 + );
3903 + }
3904 + }
3905 +
3906 + // A forced refresh unlinks even without a stored token, as it always has.
3907 + if ( $force || $this->is_user_connected( $user_id ) ) {
3908 + ( new Tracking() )->record_user_event( 'restore_connection_refresh_user_token' );
3909 +
3910 + // Unforced, the local token only goes once WordPress.com has unlinked it.
3911 + $unlinked = $this->disconnect_user( $force ? null : $user_id, $force, $force );
3912 +
3913 + if ( ! $force && ! $unlinked ) {
3914 + return new WP_Error(
3915 + 'restore_unlink_failed',
3916 + __( 'Your account could not be disconnected from WordPress.com. Please try again.', 'jetpack-connection' ),
3917 + array( 'status' => 502 )
3918 + );
3919 + }
3920 + }
3921 +
3922 + return $force ? true : 'authorize';
2458 3923 }
2459 3924
2460 3925 /**
2461 3926 * Fetches a signed token.
@@ -2472,8 +3937,12 @@
2472 3937
2473 3938 /**
2474 3939 * If the site-level connection is active, add the list of plugins using connection to the heartbeat (except Jetpack itself)
2475 3940 *
3941 + * @since 6.11.0 Add the list of Jetpack package versions to the heartbeat.
3942 + * @since 8.7.4 Add the missing connection owner and XML-RPC error stats to the heartbeat.
3943 + * @since 8.7.9 Add the site environment stats (WordPress/PHP versions, etc.) to the heartbeat.
3944 + *
2476 3945 * @param array $stats The Heartbeat stats array.
2477 3946 * @return array $stats
2478 3947 */
2479 3948 public function add_stats_to_heartbeat( $stats ) {
@@ -2488,25 +3957,88 @@
2488 3957 $stats_group = isset( $active_plugins_using_connection['jetpack'] ) ? 'combined-connection' : 'standalone-connection';
2489 3958 $stats[ $stats_group ][] = $plugin_slug;
2490 3959 }
2491 3960 }
3961 +
3962 + $stats['jetpack_package_versions'] = apply_filters( 'jetpack_package_versions', array() );
3963 +
3964 + $stats['identitycrisis'] = Identity_Crisis::check_identity_crisis() ? 'yes' : 'no';
3965 +
3966 + // Missing the connection owner?
3967 + $stats['missing-owner'] = $this->is_missing_connection_owner();
3968 +
3969 + $xmlrpc_errors = \Jetpack_Options::get_option( 'xmlrpc_errors', array() );
3970 + if ( $xmlrpc_errors ) {
3971 + $stats['xmlrpc-errors'] = implode( ',', array_keys( $xmlrpc_errors ) );
3972 + \Jetpack_Options::delete_option( 'xmlrpc_errors' );
3973 + }
3974 +
3975 + // Site environment stats (WordPress/PHP versions, site configuration, etc.).
3976 + $stats = array_merge( $stats, Heartbeat::get_environment_stats() );
3977 +
2492 3978 return $stats;
2493 3979 }
2494 3980
2495 3981 /**
3982 + * Records a failed XML-RPC signature verification so it can be reported in the heartbeat.
3983 + *
3984 + * We don't want to expose a detailed error message about why a request failed
3985 + * signature verification, as doing so could leak information. Instead, we track
3986 + * that the error occurred via a Jetpack option and send that data back in the
3987 + * heartbeat. All this does is record the error code, but it's enough to find trends.
3988 + *
3989 + * @since 8.7.4
3990 + *
3991 + * @param \WP_Error $xmlrpc_error The error produced during signature validation.
3992 + * @return void
3993 + */
3994 + public function track_xmlrpc_error( $xmlrpc_error ) {
3995 + $code = is_wp_error( $xmlrpc_error )
3996 + ? $xmlrpc_error->get_error_code()
3997 + : 'should-not-happen';
3998 +
3999 + $xmlrpc_errors = \Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4000 + if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4001 + // No need to update the option if we already have this code stored.
4002 + return;
4003 + }
4004 + $xmlrpc_errors[ $code ] = true;
4005 +
4006 + \Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
4007 + }
4008 +
4009 + /**
2496 4010 * Get the WPCOM or self-hosted site ID.
2497 4011 *
2498 - * @return int|WP_Error
4012 + * @param bool $quiet Return null instead of an error.
4013 + *
4014 + * @return int|WP_Error|null
2499 4015 */
2500 - public static function get_site_id() {
4016 + public static function get_site_id( $quiet = false ) {
2501 4017 $is_wpcom = ( defined( 'IS_WPCOM' ) && IS_WPCOM );
2502 4018 $site_id = $is_wpcom ? get_current_blog_id() : \Jetpack_Options::get_option( 'id' );
2503 4019 if ( ! $site_id ) {
2504 - return new \WP_Error(
2505 - 'unavailable_site_id',
2506 - __( 'Sorry, something is wrong with your Jetpack connection.', 'jetpack-connection' ),
2507 - 403
2508 - );
4020 + return $quiet
4021 + ? null
4022 + : new \WP_Error(
4023 + 'unavailable_site_id',
4024 + __( 'Sorry, something is wrong with your Jetpack connection.', 'jetpack-connection' ),
4025 + 403
4026 + );
2509 4027 }
2510 4028 return (int) $site_id;
4029 + }
4030 +
4031 + /**
4032 + * Check if Jetpack is ready for uninstall cleanup.
4033 + *
4034 + * @param string $current_plugin_slug The current plugin's slug.
4035 + *
4036 + * @return bool
4037 + */
4038 + public static function is_ready_for_cleanup( $current_plugin_slug ) {
4039 + $active_plugins = get_option( Plugin_Storage::ACTIVE_PLUGINS_OPTION_NAME );
4040 +
4041 + return empty( $active_plugins ) || ! is_array( $active_plugins )
4042 + || ( count( $active_plugins ) === 1 && array_key_exists( $current_plugin_slug, $active_plugins ) );
2511 4043 }
2512 4044 }