Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
78.52% covered (warning)
78.52%
1166 / 1485
58.93% covered (warning)
58.93%
66 / 112
CRAP
0.00% covered (danger)
0.00%
0 / 1
Manager
78.52% covered (warning)
78.52%
1166 / 1485
58.93% covered (warning)
58.93%
66 / 112
3524.83
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 configure
97.62% covered (success)
97.62%
41 / 42
0.00% covered (danger)
0.00%
0 / 1
4
 add_connection_status_invalidation_hooks
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
2
 setup_xmlrpc_handlers
14.81% covered (danger)
14.81%
4 / 27
0.00% covered (danger)
0.00%
0 / 1
85.80
 initialize_rest_api_registration_connector
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 alternate_xmlrpc
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 remove_non_jetpack_xmlrpc_methods
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 require_jetpack_authentication
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 authenticate_jetpack
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
30
 verify_xml_rpc_signature
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 internal_verify_xml_rpc_signature
72.90% covered (warning)
72.90%
78 / 107
0.00% covered (danger)
0.00%
0 / 1
52.39
 get_current_request_transport
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
10
 build_connection_error_data
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 is_active
n/a
0 / 0
n/a
0 / 0
1
 get_tokens
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_registered
n/a
0 / 0
n/a
0 / 0
1
 is_connected
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 reset_connection_status
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 has_connected_admin
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 has_connected_user
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_connected_users
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
10
 has_connected_owner
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_userless
n/a
0 / 0
n/a
0 / 0
1
 is_site_connection
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
 is_missing_connection_owner
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 is_user_connected
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 get_connection_owner_id
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 get_connected_user_data
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
9
 resolve_wpcom_user_id
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
6
 unbind_wpcom_user_ids_for_new_tokens
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
5.07
 delete_cached_site_data
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_connected_site_data
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
14
 fetch_connected_site_data
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
10
 get_connection_owner
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
7
 is_connection_owner
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 is_ownership_transferable
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 requires_protected_owner
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 has_protected_owner
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 resolve_protected_owner_state
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
9
 reconcile_protected_owner
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
9
 adopt_protected_owner
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
7.04
 query_protected_owner_record
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 assert_protected_owner_record
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 relinquish_protected_owner_record
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 request_protected_owner_record
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
 set_protected_owner
100.00% covered (success)
100.00%
48 / 48
100.00% covered (success)
100.00%
1 / 1
12
 release_protected_owner
87.18% covered (warning)
87.18%
34 / 39
0.00% covered (danger)
0.00%
0 / 1
10.21
 protected_owner_release_refused
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 local_anchor_names_someone_else
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 protected_owner_claimed_by_other
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 clear_protected_owner
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
3
 connect_user
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 disconnect_user_force
60.00% covered (warning)
60.00%
3 / 5
0.00% covered (danger)
0.00%
0 / 1
6.60
 disconnect_all_users_except_primary
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 disconnect_user
87.50% covered (warning)
87.50%
21 / 24
0.00% covered (danger)
0.00%
0 / 1
11.24
 unlink_user_from_wpcom
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 update_connection_owner
100.00% covered (success)
100.00%
38 / 38
100.00% covered (success)
100.00%
1 / 1
7
 current_user_may_move_locked_ownership
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 release_anchor_after_transfer
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
6
 update_connection_owner_wpcom
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
4.00
 api_url
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 xmlrpc_api_url
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 register
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
 do_register
87.74% covered (warning)
87.74%
93 / 106
0.00% covered (danger)
0.00%
0 / 1
14.36
 try_registration
93.55% covered (success)
93.55%
29 / 31
0.00% covered (danger)
0.00%
0 / 1
9.02
 get_registration_failure
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 clear_registration_failure
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_plugin_slug
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 add_register_request_param
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 is_xml_extension_available
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 validate_remote_register_response
75.00% covered (warning)
75.00%
36 / 48
0.00% covered (danger)
0.00%
0 / 1
15.64
 add_nonce
n/a
0 / 0
n/a
0 / 0
1
 clean_nonces
n/a
0 / 0
n/a
0 / 0
2
 jetpack_connection_custom_caps
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
10
 get_max_execution_time
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 set_min_time_limit
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 get_assumed_site_creation_date
96.43% covered (success)
96.43%
27 / 28
0.00% covered (danger)
0.00%
0 / 1
3
 apply_activation_source_to_args
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
3.33
 generate_secrets
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_secrets
n/a
0 / 0
n/a
0 / 0
1
 delete_secrets
n/a
0 / 0
n/a
0 / 0
1
 delete_all_connection_tokens
95.00% covered (success)
95.00%
19 / 20
0.00% covered (danger)
0.00%
0 / 1
5
 disconnect_site_wpcom
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
7.07
 remove_connection
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 reconnect
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 restore
95.45% covered (success)
95.45%
21 / 22
0.00% covered (danger)
0.00%
0 / 1
14
 can_relink_as_owner
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 handle_registration
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 validate_tokens
n/a
0 / 0
n/a
0 / 0
1
 verify_secrets
n/a
0 / 0
n/a
0 / 0
1
 handle_authorization
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_token
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_authorization_url
96.36% covered (success)
96.36%
53 / 55
0.00% covered (danger)
0.00%
0 / 1
9
 authorize
80.33% covered (warning)
80.33%
49 / 61
0.00% covered (danger)
0.00%
0 / 1
29.76
 is_owner_slot_unusable
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
 can_take_owner_slot
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
10
 remember_unusable_owner
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
4
 get_owner_token_hash
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
 is_unusable_owner_remembered
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
9
 has_owner_token_rejection
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 can_fill_unconnected_owner_slot
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 has_owner_connection_error
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 disconnect_site
62.50% covered (warning)
62.50%
15 / 24
0.00% covered (danger)
0.00%
0 / 1
11.38
 sha1_base64
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 is_usable_domain
0.00% covered (danger)
0.00%
0 / 65
0.00% covered (danger)
0.00%
0 / 1
90
 get_access_token
n/a
0 / 0
n/a
0 / 0
1
 xmlrpc_methods
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 reset_raw_post_data
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 public_xmlrpc_methods
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 jetpack_get_options
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
12
 xmlrpc_options
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
6
 reset_saved_auth_state
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 sign_role
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 set_plugin_instance
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_plugin
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_connected_plugins
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 disable_plugin
n/a
0 / 0
n/a
0 / 0
1
 enable_plugin
n/a
0 / 0
n/a
0 / 0
1
 is_plugin_enabled
n/a
0 / 0
n/a
0 / 0
1
 refresh_blog_token
76.67% covered (warning)
76.67%
23 / 30
0.00% covered (danger)
0.00%
0 / 1
10.03
 refresh_user_token
100.00% covered (success)
100.00%
31 / 31
100.00% covered (success)
100.00%
1 / 1
13
 get_signed_token
n/a
0 / 0
n/a
0 / 0
1
 add_stats_to_heartbeat
81.25% covered (warning)
81.25%
13 / 16
0.00% covered (danger)
0.00%
0 / 1
7.32
 track_xmlrpc_error
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
4.03
 get_site_id
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
30
 is_ready_for_cleanup
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2/**
3 * The Jetpack Connection manager class file.
4 *
5 * @package automattic/jetpack-connection
6 */
7
8namespace Automattic\Jetpack\Connection;
9
10use Automattic\Jetpack\A8c_Mc_Stats;
11use Automattic\Jetpack\Constants;
12use Automattic\Jetpack\Heartbeat;
13use Automattic\Jetpack\Identity_Crisis;
14use Automattic\Jetpack\Partner;
15use Automattic\Jetpack\Roles;
16use Automattic\Jetpack\Status;
17use Automattic\Jetpack\Status\Host;
18use Automattic\Jetpack\Terms_Of_Service;
19use Automattic\Jetpack\Tracking;
20use IXR_Error;
21use Jetpack_IXR_Client;
22use Jetpack_Options;
23use Jetpack_XMLRPC_Server;
24use WP_Error;
25use WP_User;
26
27/**
28 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
29 * and Jetpack.
30 */
31class Manager {
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     * Per-site user option that carries an unusable owner across a Restore relink, which clears the stored errors.
44     *
45     * @since 9.18.0
46     *
47     * @var string
48     */
49    const RELINK_OWNER_UNUSABLE_META = 'jetpack_relink_owner_unusable';
50
51    /**
52     * Why `has_protected_owner()` answered false, and what would change it.
53     *
54     * `RE_EVALUATE` is the race: the gate said false, and by the time the state was classified the
55     * owner matched after all. It is not a problem to report, it is an instruction to ask again.
56     *
57     * @since 9.4.0
58     */
59    const PO_STATE_NOT_ELIGIBLE               = 'NOT_ELIGIBLE';
60    const PO_STATE_NEEDS_CONNECT_TO_ESTABLISH = 'NEEDS_CONNECT_TO_ESTABLISH';
61    const PO_STATE_CAN_ESTABLISH              = 'CAN_ESTABLISH';
62    const PO_STATE_NEEDS_OWNER_RECONNECT      = 'NEEDS_OWNER_RECONNECT';
63    const PO_STATE_NEEDS_DIFFERENT_OWNER      = 'NEEDS_DIFFERENT_OWNER';
64    const PO_STATE_RE_EVALUATE                = 'RE_EVALUATE';
65
66    /**
67     * A copy of the raw POST data for signature verification purposes.
68     *
69     * @var string
70     */
71    protected $raw_post_data;
72
73    /**
74     * Verification data needs to be stored to properly verify everything.
75     *
76     * @var Object
77     */
78    private $xmlrpc_verification = null;
79
80    /**
81     * Plugin management object.
82     *
83     * @var Plugin
84     */
85    private $plugin = null;
86
87    /**
88     * Error handler object.
89     *
90     * @var Error_Handler
91     */
92    public $error_handler = null;
93
94    /**
95     * Jetpack_XMLRPC_Server object
96     *
97     * @var Jetpack_XMLRPC_Server
98     */
99    public $xmlrpc_server = null;
100
101    /**
102     * Holds extra parameters that will be sent along in the register request body.
103     *
104     * Use Manager::add_register_request_param to add values to this array.
105     *
106     * @since 1.26.0
107     * @var array
108     */
109    private static $extra_register_params = array();
110
111    /**
112     * We store ID's of users already disconnected to prevent multiple disconnect requests.
113     *
114     * @var array
115     */
116    private static $disconnected_users = array();
117
118    /**
119     * Cached connection status.
120     *
121     * @var bool|null True if the site is connected, false if not, null if not determined yet.
122     */
123    private static $is_connected = null;
124
125    /**
126     * Memoized user ID of the connection owner.
127     * If undefined or invalid, set to 0.
128     *
129     * @var null|int
130     */
131    private static $connection_owner_id = null;
132
133    /**
134     * Tracks whether connection status invalidation hooks have been added.
135     *
136     * @var bool
137     */
138    private static $connection_invalidators_added = false;
139
140    /**
141     * The raw HTTP response of the registration request currently being processed.
142     *
143     * @var array|WP_Error|null
144     */
145    private $last_register_response = null;
146
147    /**
148     * Initialize the object.
149     * Make sure to call the "Configure" first.
150     *
151     * @param string $plugin_slug Slug of the plugin using the connection (optional, but encouraged).
152     *
153     * @see \Automattic\Jetpack\Config
154     */
155    public function __construct( $plugin_slug = null ) {
156        if ( $plugin_slug && is_string( $plugin_slug ) ) {
157            $this->set_plugin_instance( new Plugin( $plugin_slug ) );
158        }
159    }
160
161    /**
162     * Initializes required listeners. This is done separately from the constructors
163     * because some objects sometimes need to instantiate separate objects of this class.
164     *
165     * @todo Implement a proper nonce verification.
166     */
167    public static function configure() {
168        $manager = new self();
169
170        add_filter(
171            'jetpack_constant_default_value',
172            __NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
173            10,
174            2
175        );
176
177        $manager->setup_xmlrpc_handlers(
178            null,
179            $manager->has_connected_owner(),
180            $manager->verify_xml_rpc_signature()
181        );
182
183        $manager->error_handler = Error_Handler::get_instance();
184
185        if ( $manager->is_connected() ) {
186            add_filter( 'xmlrpc_methods', array( $manager, 'public_xmlrpc_methods' ) );
187            add_filter( 'shutdown', array( Package_Version_Tracker::class, 'update_on_shutdown' ) );
188        }
189
190        // This runs on priority 11 - at least one api method in the connection package is set to override a previously
191        // existing method from the Jetpack plugin. Running later than Jetpack's api init ensures the override is successful.
192        add_action( 'rest_api_init', array( $manager, 'initialize_rest_api_registration_connector' ), 11 );
193
194        ( new Nonce_Handler() )->init_schedule();
195
196        add_action( 'plugins_loaded', __NAMESPACE__ . '\Plugin_Storage::configure', 100 );
197
198        add_filter( 'map_meta_cap', array( $manager, 'jetpack_connection_custom_caps' ), 1, 4 );
199
200        Heartbeat::init();
201        add_filter( 'jetpack_heartbeat_stats_array', array( $manager, 'add_stats_to_heartbeat' ) );
202        add_action( 'jetpack_verify_signature_error', array( $manager, 'track_xmlrpc_error' ) );
203
204        Webhooks::init( $manager );
205
206        add_action( 'pre_update_jetpack_option_user_tokens', array( $manager, 'unbind_wpcom_user_ids_for_new_tokens' ), 10, 2 );
207        add_action( 'jetpack_user_authorized', array( $manager, 'reconcile_protected_owner' ) );
208
209        // Unlink user before deleting the user from WP.com.
210        add_action( 'deleted_user', array( $manager, 'disconnect_user_force' ), 9, 1 );
211        add_action( 'remove_user_from_blog', array( $manager, 'disconnect_user_force' ), 9, 1 );
212
213        // Add hooks for cleaning up account mismatch transients
214        $user_account_status = new User_Account_Status();
215        add_action( 'delete_user', array( $user_account_status, 'clean_account_mismatch_transients' ), 9, 1 );
216        add_action( 'remove_user_from_blog', array( $user_account_status, 'clean_account_mismatch_transients' ), 9, 1 );
217        add_action( 'user_register', array( $user_account_status, 'clean_account_mismatch_transients' ), 9, 1 );
218        add_action( 'profile_update', array( $user_account_status, 'clean_account_mismatch_transients' ), 9, 1 );
219
220        $manager->add_connection_status_invalidation_hooks();
221
222        // Set up package version hook.
223        add_filter( 'jetpack_package_versions', __NAMESPACE__ . '\Package_Version::send_package_version_to_tracker' );
224
225        if ( defined( 'JETPACK__SANDBOX_DOMAIN' ) && JETPACK__SANDBOX_DOMAIN ) {
226            ( new Server_Sandbox() )->init();
227        }
228
229        // Initialize connection notices.
230        new Connection_Notice();
231
232        // Initialize token locks.
233        new Tokens_Locks();
234
235        // Initial Partner management.
236        Partner::init();
237
238        // WP 7.0+ Connectors screen card.
239        Jetpack_Connector::init();
240
241        // Site Health integration.
242        Site_Health::init();
243    }
244
245    /**
246     * Adds hooks to invalidate the memoized connection status.
247     */
248    private function add_connection_status_invalidation_hooks() {
249        if ( self::$connection_invalidators_added ) {
250            return;
251        }
252
253        // Force is_connected() to recompute after important actions.
254        add_action( 'jetpack_site_registered', array( $this, 'reset_connection_status' ) );
255        add_action( 'jetpack_site_disconnected', array( $this, 'reset_connection_status' ) );
256        // Deletion doesn't fire `pre_update_jetpack_option_*`; see the action's docblock in `Tokens::delete_all()`.
257        add_action( 'jetpack_connection_tokens_deleted', array( $this, 'reset_connection_status' ) );
258        add_action( 'jetpack_sync_register_user', array( $this, 'reset_connection_status' ) );
259        add_action( 'pre_update_jetpack_option_id', array( $this, 'reset_connection_status' ) );
260        add_action( 'pre_update_jetpack_option_blog_token', array( $this, 'reset_connection_status' ) );
261        add_action( 'pre_update_jetpack_option_user_token', array( $this, 'reset_connection_status' ) );
262        add_action( 'pre_update_jetpack_option_user_tokens', array( $this, 'reset_connection_status' ) );
263        add_action( 'pre_update_jetpack_option_master_user', array( $this, 'reset_connection_status' ) );
264        // phpcs:ignore WPCUT.SwitchBlog.SwitchBlog -- wpcom flags **every** use of switch_blog, apparently expecting valid instances to ignore or suppress the sniff.
265        add_action( 'switch_blog', array( $this, 'reset_connection_status' ) );
266        add_action( 'jetpack_external_storage_provider_registered', array( $this, 'reset_connection_status' ), 10, 0 );
267
268        self::$connection_invalidators_added = true;
269    }
270
271    /**
272     * Sets up the XMLRPC request handlers.
273     *
274     * @since 1.25.0 Deprecate $is_active param.
275     * @since 2.8.4 Deprecate $request_params param.
276     *
277     * @param array|null            $deprecated Deprecated. Not used.
278     * @param bool                  $has_connected_owner Whether the site has a connected owner.
279     * @param bool                  $is_signed whether the signature check has been successful.
280     * @param Jetpack_XMLRPC_Server $xmlrpc_server (optional) an instance of the server to use instead of instantiating a new one.
281     */
282    public function setup_xmlrpc_handlers(
283        $deprecated,
284        $has_connected_owner,
285        $is_signed,
286        ?Jetpack_XMLRPC_Server $xmlrpc_server = null
287    ) {
288        add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ), 1000, 2 );
289        if ( $deprecated !== null ) {
290            _deprecated_argument( __METHOD__, '2.8.4' );
291        }
292        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- We are using the 'for' request param to early return unless it's 'jetpack'.
293        if ( ! isset( $_GET['for'] ) || 'jetpack' !== $_GET['for'] ) {
294            return false;
295        }
296
297        // Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
298        // 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.
299        if ( isset( $_GET['jetpack'] ) && 'comms' === $_GET['jetpack'] ) {
300            if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
301                // Use the real constant here for WordPress' sake.
302                define( 'XMLRPC_REQUEST', true );
303            }
304
305            add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
306
307            add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
308        }
309
310        if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
311            return false;
312        }
313
314        // Display errors can cause the XML to be not well formed.
315        // This only affects Jetpack XML-RPC endpoints received from WordPress.com servers.
316        // All other XML-RPC requests are unaffected.
317        @ini_set( 'display_errors', false ); // phpcs:ignore
318
319        if ( $xmlrpc_server ) {
320            $this->xmlrpc_server = $xmlrpc_server;
321        } else {
322            $this->xmlrpc_server = new Jetpack_XMLRPC_Server();
323        }
324
325        $this->require_jetpack_authentication();
326
327        if ( $is_signed ) {
328            // If the site is connected either at a site or user level and the request is signed, expose the methods.
329            // The callback is responsible to determine whether the request is signed with blog or user token and act accordingly.
330            // The actual API methods.
331            $callback = array( $this->xmlrpc_server, 'xmlrpc_methods' );
332
333            // Hack to preserve $HTTP_RAW_POST_DATA.
334            add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
335
336        } elseif ( $has_connected_owner ) {
337            // The jetpack.authorize method should be available for unauthenticated users on a site with an
338            // active Jetpack connection, so that additional users can link their account.
339            $callback = array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' );
340        } else {
341            // Any other unsigned request should expose the bootstrap methods.
342            $callback = array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' );
343            new XMLRPC_Connector( $this );
344        }
345
346        add_filter( 'xmlrpc_methods', $callback );
347
348        // Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
349        add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
350        return true;
351    }
352
353    /**
354     * Initializes the REST API connector on the init hook.
355     */
356    public function initialize_rest_api_registration_connector() {
357        new REST_Connector( $this );
358    }
359
360    /**
361     * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
362     * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
363     * security/firewall policies, we provide our own alternate XML RPC API endpoint
364     * which is accessible via a different URI. Most of the below is copied directly
365     * from /xmlrpc.php so that we're replicating it as closely as possible.
366     *
367     * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
368     *
369     * @return never
370     */
371    public function alternate_xmlrpc() {
372        // Some browser-embedded clients send cookies. We don't want them.
373        $_COOKIE = array();
374
375        include_once ABSPATH . 'wp-admin/includes/admin.php';
376        include_once ABSPATH . WPINC . '/class-IXR.php';
377        include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
378
379        /**
380         * Filters the class used for handling XML-RPC requests.
381         *
382         * @since 1.7.0
383         * @since-jetpack 3.1.0
384         *
385         * @param string $class The name of the XML-RPC server class.
386         */
387        $wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
388        $wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
389
390        // Fire off the request.
391        nocache_headers();
392        $wp_xmlrpc_server->serve_request();
393
394        exit( 0 );
395    }
396
397    /**
398     * Removes all XML-RPC methods that are not `jetpack.*`.
399     * Only used in our alternate XML-RPC endpoint, where we want to
400     * ensure that Core and other plugins' methods are not exposed.
401     *
402     * @param array $methods a list of registered WordPress XMLRPC methods.
403     * @return array filtered $methods
404     */
405    public function remove_non_jetpack_xmlrpc_methods( $methods ) {
406        $jetpack_methods = array();
407
408        foreach ( $methods as $method => $callback ) {
409            if ( str_starts_with( $method, 'jetpack.' ) ) {
410                $jetpack_methods[ $method ] = $callback;
411            }
412        }
413
414        return $jetpack_methods;
415    }
416
417    /**
418     * Removes all other authentication methods not to allow other
419     * methods to validate unauthenticated requests.
420     */
421    public function require_jetpack_authentication() {
422        // Don't let anyone authenticate.
423        $_COOKIE = array();
424        remove_all_filters( 'authenticate' );
425        remove_all_actions( 'wp_login_failed' );
426
427        if ( $this->is_connected() ) {
428            // Allow Jetpack authentication.
429            add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
430        }
431    }
432
433    /**
434     * Authenticates XML-RPC and other requests from the Jetpack Server
435     *
436     * @param WP_User|mixed $user user object if authenticated.
437     * @param string        $username username.
438     * @param string        $password password string.
439     * @return WP_User|mixed authenticated user or error.
440     */
441    public function authenticate_jetpack( $user, $username, $password ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
442        if ( $user instanceof \WP_User ) {
443            return $user;
444        }
445
446        $token_details = $this->verify_xml_rpc_signature();
447
448        if ( ! $token_details ) {
449            return $user;
450        }
451
452        if ( 'user' !== $token_details['type'] ) {
453            return $user;
454        }
455
456        if ( ! $token_details['user_id'] ) {
457            return $user;
458        }
459
460        nocache_headers();
461
462        return new \WP_User( $token_details['user_id'] );
463    }
464
465    /**
466     * Verifies the signature of the current request.
467     *
468     * @return false|array
469     */
470    public function verify_xml_rpc_signature() {
471        if ( $this->xmlrpc_verification === null ) {
472            $this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
473
474            if ( is_wp_error( $this->xmlrpc_verification ) ) {
475                /**
476                 * Action for logging XMLRPC signature verification errors. This data is sensitive.
477                 *
478                 * @since 1.7.0
479                 * @since-jetpack 7.5.0
480                 *
481                 * @param WP_Error $signature_verification_error The verification error
482                 */
483                do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
484
485                Error_Handler::get_instance()->report_error( $this->xmlrpc_verification );
486
487            }
488        }
489
490        return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
491    }
492
493    /**
494     * Verifies the signature of the current request.
495     *
496     * This function has side effects and should not be used. Instead,
497     * use the memoized version `->verify_xml_rpc_signature()`.
498     *
499     * @internal
500     * @todo Refactor to use proper nonce verification.
501     */
502    private function internal_verify_xml_rpc_signature() {
503        // phpcs:disable WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
504        // It's not for us.
505        if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
506            return false;
507        }
508
509        // Skip XML-RPC signature verification for OAuth authorization flow.
510        // OAuth uses GET requests without body-hash and has its own
511        // signature verification in Authorize_Json_Api class.
512        if ( isset( $_GET['action'] ) && $_GET['action'] === 'jetpack_json_api_authorization' ) {
513            return false;
514        }
515
516        $signature_details = array(
517            'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
518            'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
519            'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
520            'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
521            'method'    => isset( $_SERVER['REQUEST_METHOD'] ) ? wp_unslash( $_SERVER['REQUEST_METHOD'] ) : null,
522            'url'       => wp_unslash( ( $_SERVER['HTTP_HOST'] ?? null ) . ( $_SERVER['REQUEST_URI'] ?? null ) ), // Temp - will get real signature URL later.
523            'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
524        );
525
526        // Transport of the incoming request being verified. This signature-verification path
527        // serves both XML-RPC requests and signed REST requests (REST_Authentication funnels
528        // REST authentication into verify_xml_rpc_signature()), so the stored error type is
529        // derived from the actual request context rather than hardcoded.
530        $error_type      = $this->get_current_request_transport();
531        $error_direction = 'incoming'; // Matches Error_Handler::DIRECTION_INCOMING â€” see build_connection_error_data() for why the constant is not referenced.
532
533        // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
534        @list( $token_key, $version, $user_id ) = explode( ':', wp_unslash( $_GET['token'] ) );
535        // phpcs:enable WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
536
537        $jetpack_api_version = Constants::get_constant( 'JETPACK__API_VERSION' );
538
539        if (
540            empty( $token_key )
541                || empty( $version )
542                || (string) $jetpack_api_version !== $version
543        ) {
544            return new \WP_Error( 'malformed_token', 'Malformed token in request', $this->build_connection_error_data( $signature_details, $error_type, $error_direction ) );
545        }
546
547        if ( '0' === $user_id ) {
548            $token_type = 'blog';
549            $user_id    = 0;
550        } else {
551            $token_type = 'user';
552            if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
553                return new \WP_Error(
554                    'malformed_user_id',
555                    'Malformed user_id in request',
556                    $this->build_connection_error_data( $signature_details, $error_type, $error_direction )
557                );
558            }
559            $user_id = (int) $user_id;
560
561            $user = new \WP_User( $user_id );
562            if ( ! $user->exists() ) {
563                return new \WP_Error(
564                    'unknown_user',
565                    sprintf( 'User %d does not exist', $user_id ),
566                    $this->build_connection_error_data( $signature_details, $error_type, $error_direction )
567                );
568            }
569        }
570
571        $token = $this->get_tokens()->get_access_token( $user_id, $token_key, false );
572        if ( is_wp_error( $token ) ) {
573            $token->add_data( $this->build_connection_error_data( $signature_details, $error_type, $error_direction ) );
574            return $token;
575        } elseif ( ! $token ) {
576            // `get_access_token()` explains itself for every case but one: it returns a bare
577            // `false` when the tokens are locked (Tokens::is_locked()). The lock is
578            // one-shot and self-healing.
579            return new \WP_Error(
580                'tokens_locked',
581                sprintf( 'Tokens are locked; %s:%s:%d could not be verified', $token_key, $version, $user_id ),
582                $this->build_connection_error_data( $signature_details, $error_type, $error_direction )
583            );
584        }
585
586        $jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
587        // 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.
588        if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
589            $post_data   = $_POST; // We need all of $_POST in order to verify a cryptographic signature of the post data.
590            $file_hashes = array();
591            foreach ( $post_data as $post_data_key => $post_data_value ) {
592                if ( ! str_starts_with( $post_data_key, '_jetpack_file_hmac_' ) ) {
593                    continue;
594                }
595                $post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
596                $file_hashes[ $post_data_key ] = $post_data_value;
597            }
598
599            foreach ( $file_hashes as $post_data_key => $post_data_value ) {
600                unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
601                $post_data[ $post_data_key ] = $post_data_value;
602            }
603
604            ksort( $post_data );
605
606            $body = http_build_query( stripslashes_deep( $post_data ) );
607        } elseif ( $this->raw_post_data === null ) {
608            $body = file_get_contents( 'php://input' );
609        } else {
610            $body = null;
611        }
612        // phpcs:enable
613
614        $signature = $jetpack_signature->sign_current_request(
615            array( 'body' => $body === null ? $this->raw_post_data : $body )
616        );
617
618        $signature_details['url'] = $jetpack_signature->current_request_url;
619
620        // This path currently can't ever be true, unless a new path is added resulting
621        // in $signature 'false', null or an empty string. Leaving for additional security.
622        if ( ! $signature ) {
623            return new \WP_Error(
624                'could_not_sign',
625                'Unknown signature error',
626                $this->build_connection_error_data( $signature_details, $error_type, $error_direction )
627            );
628        } elseif ( is_wp_error( $signature ) ) {
629            // Jetpack_Signature errors carry their own signature_details (or, for some codes,
630            // no data at all) but never a type or direction; normalize them into the standard
631            // error data shape so Error_Handler can attribute and store them.
632            $signature_error_data = $signature->get_error_data();
633            if ( isset( $signature_error_data['signature_details'] ) && is_array( $signature_error_data['signature_details'] ) ) {
634                $signature_details = array_merge( $signature_details, $signature_error_data['signature_details'] );
635            }
636            $signature->add_data( $this->build_connection_error_data( $signature_details, $error_type, $error_direction ) );
637            return $signature;
638        }
639
640        // phpcs:disable WordPress.Security.NonceVerification.Recommended
641        $timestamp = (int) $_GET['timestamp'];
642        $nonce     = wp_unslash( (string) $_GET['nonce'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- WP Core doesn't sanitize nonces either.
643        // phpcs:enable WordPress.Security.NonceVerification.Recommended
644
645        // Use up the nonce regardless of whether the signature matches.
646        if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
647            return new \WP_Error(
648                'invalid_nonce',
649                'Could not add nonce',
650                $this->build_connection_error_data( $signature_details, $error_type, $error_direction )
651            );
652        }
653
654        // Be careful about what you do with this debugging data.
655        // If a malicious requester has access to the expected signature,
656        // bad things might be possible.
657        $signature_details['expected'] = $signature;
658
659        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
660        if ( ! hash_equals( $signature, wp_unslash( $_GET['signature'] ) ) ) {
661            return new \WP_Error(
662                'signature_mismatch',
663                'Signature mismatch',
664                $this->build_connection_error_data( $signature_details, $error_type, $error_direction )
665            );
666        }
667
668        /**
669         * Action for additional token checking.
670         *
671         * @since 1.7.0
672         * @since-jetpack 7.7.0
673         *
674         * @param array $post_data request data.
675         * @param array $token_data token data.
676         */
677        return apply_filters(
678            'jetpack_signature_check_token',
679            array(
680                'type'      => $token_type,
681                'token_key' => $token_key,
682                'user_id'   => $token->external_user_id,
683            ),
684            $token,
685            $this->raw_post_data
686        );
687    }
688
689    /**
690     * Determines the transport of the incoming request currently being verified.
691     *
692     * @since 8.9.0
693     *
694     * @return string Error_Handler::ERROR_TYPE_XMLRPC or Error_Handler::ERROR_TYPE_REST.
695     */
696    private function get_current_request_transport() {
697        $is_xmlrpc = defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST;
698
699        // XMLRPC_REQUEST covers both /xmlrpc.php and the alternate XML-RPC endpoint, which
700        // defines the constant itself (see setup_xmlrpc_handlers). Outside those, signed REST
701        // requests are detected via the REST dispatch state. Anything else (e.g. signed
702        // requests verified on the 'authenticate' filter for regular URLs) keeps the historic
703        // XML-RPC label rather than guessing at a transport.
704        $is_rest = ! $is_xmlrpc && ( function_exists( 'wp_is_rest_endpoint' ) ? wp_is_rest_endpoint() : ( defined( 'REST_REQUEST' ) && REST_REQUEST ) );
705
706        // Signature verification can run before REST dispatch is set up: REST_Authentication
707        // hooks `determine_current_user`, which any plugin can trigger early (e.g. by calling
708        // wp_get_current_user() on plugins_loaded), before the REST_REQUEST constant exists.
709        // In that window, recognize REST requests by their URL: the REST prefix in the path,
710        // or the rest_route query argument used by sites without pretty permalinks.
711        if ( ! $is_xmlrpc && ! $is_rest ) {
712            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only used to classify the request transport.
713            $has_rest_route_arg = isset( $_GET['rest_route'] );
714            $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.
715            $is_rest            = $has_rest_route_arg || false !== strpos( $request_path, '/' . rest_get_url_prefix() . '/' );
716        }
717
718        // The literals match Error_Handler::ERROR_TYPE_REST / ERROR_TYPE_XMLRPC â€” see
719        // build_connection_error_data() for why the constants are not referenced.
720        return $is_rest ? 'rest' : 'xmlrpc';
721    }
722
723    /**
724     * Builds the standardized connection error data attached to signature-verification errors.
725     *
726     * Wraps `Error_Handler::build_connection_error_data()`, falling back to the legacy
727     * error-data shape when the loaded Error_Handler predates that method: during a plugin
728     * update, an older version of the class can already be in memory while this file is the
729     * new one, and a mid-update request must never fatal. For the same reason, code in this
730     * class must not reference Error_Handler constants introduced along with that method
731     * ('xmlrpc', 'rest', 'local_state', 'incoming', 'outgoing') â€” use the literal values.
732     *
733     * @since 8.10.0
734     *
735     * @param array  $signature_details Details of the request signature being verified.
736     * @param string $error_type        The transport of the request: 'xmlrpc' or 'rest'.
737     * @param string $error_direction   The direction of the request: 'incoming' or 'outgoing'.
738     * @return array Error data for `WP_Error`.
739     */
740    private function build_connection_error_data( $signature_details, $error_type, $error_direction ) {
741        if ( ! method_exists( Error_Handler::class, 'build_connection_error_data' ) ) {
742            return compact( 'signature_details', 'error_type' );
743        }
744        return Error_Handler::build_connection_error_data( $signature_details, $error_type, $error_direction );
745    }
746
747    /**
748     * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI.
749     *
750     * This method is deprecated since version 1.25.0 of this package. Please use has_connected_owner instead.
751     *
752     * Since this method has a wide spread use, we decided not to throw any deprecation warnings for now.
753     *
754     * @deprecated 1.25.0
755     * @see Manager::has_connected_owner
756     * @return bool is the site connected?
757     */
758    public function is_active() {
759        return (bool) $this->get_tokens()->get_access_token( true );
760    }
761
762    /**
763     * Obtains an instance of the Tokens class.
764     *
765     * @return Tokens the Tokens object
766     */
767    public function get_tokens() {
768        return new Tokens();
769    }
770
771    /**
772     * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
773     *
774     * @access public
775     * @deprecated 1.12.1 Use is_connected instead
776     * @see Manager::is_connected
777     *
778     * @return bool
779     */
780    public function is_registered() {
781        _deprecated_function( __METHOD__, '1.12.1' );
782        return $this->is_connected();
783    }
784
785    /**
786     * Returns true if the site has both a token and a blog id, which indicates a site has been connected.
787     *
788     * @access public
789     * @since 1.21.1
790     *
791     * @return bool
792     */
793    public function is_connected() {
794        if ( self::$is_connected === null ) {
795            if ( ! self::$connection_invalidators_added ) {
796                $this->add_connection_status_invalidation_hooks();
797            }
798
799            $has_blog_id = (bool) \Jetpack_Options::get_option( 'id' );
800            if ( $has_blog_id ) {
801                self::$is_connected = (bool) $this->get_tokens()->get_access_token();
802            } else {
803                // Short-circuit, no need to check for tokens if there's no blog ID.
804                self::$is_connected = false;
805            }
806        }
807        return self::$is_connected;
808    }
809
810    /**
811     * Resets the memoized connection status.
812     * This will force the connection status to be recomputed on the next check.
813     *
814     * @since 5.0.0
815     */
816    public function reset_connection_status() {
817        self::$is_connected        = null;
818        self::$connection_owner_id = null;
819    }
820
821    /**
822     * Returns true if the site has at least one connected administrator.
823     *
824     * @access public
825     * @since 1.21.1
826     *
827     * @return bool
828     */
829    public function has_connected_admin() {
830        return (bool) count( $this->get_connected_users( 'manage_options' ) );
831    }
832
833    /**
834     * Returns true if the site has any connected user.
835     *
836     * @access public
837     * @since 1.21.1
838     *
839     * @return bool
840     */
841    public function has_connected_user() {
842        return (bool) count( $this->get_connected_users( 'any', 1 ) );
843    }
844
845    /**
846     * Returns an array of users that have user tokens for communicating with wpcom.
847     * Able to select by specific capability.
848     *
849     * @since 9.9.1 Added $limit parameter.
850     *
851     * @param string   $capability The capability of the user.
852     * @param int|null $limit How many connected users to get before returning.
853     * @return WP_User[] Array of WP_User objects if found.
854     */
855    public function get_connected_users( $capability = 'any', $limit = null ) {
856        $connected_users = array();
857        $user_tokens     = $this->get_tokens()->get_user_tokens();
858
859        if ( ! is_array( $user_tokens ) || empty( $user_tokens ) ) {
860            return $connected_users;
861        }
862        $connected_user_ids = array_keys( $user_tokens );
863
864        if ( ! empty( $connected_user_ids ) ) {
865            foreach ( $connected_user_ids as $id ) {
866                // Check for capability.
867                if ( 'any' !== $capability && ! user_can( $id, $capability ) ) {
868                    continue;
869                }
870
871                $user_data = get_userdata( $id );
872                if ( $user_data instanceof \WP_User ) {
873                    $connected_users[] = $user_data;
874                    if ( $limit && count( $connected_users ) >= $limit ) {
875                        return $connected_users;
876                    }
877                }
878            }
879        }
880
881        return $connected_users;
882    }
883
884    /**
885     * Returns true if the site has a connected Blog owner (master_user).
886     *
887     * @access public
888     * @since 1.21.1
889     *
890     * @return bool
891     */
892    public function has_connected_owner() {
893        return (bool) $this->get_connection_owner_id();
894    }
895
896    /**
897     * Returns true if the site is connected only at a site level.
898     *
899     * Note that we are explicitly checking for the existence of the master_user option in order to account for cases where we don't have any user tokens (user-level connection) but the master_user option is set, which could be the result of a problematic user connection.
900     *
901     * @access public
902     * @since 1.25.0
903     * @deprecated 1.27.0
904     *
905     * @return bool
906     */
907    public function is_userless() {
908        _deprecated_function( __METHOD__, '1.27.0', 'Automattic\\Jetpack\\Connection\\Manager::is_site_connection' );
909        return $this->is_site_connection();
910    }
911
912    /**
913     * Returns true if the site is connected only at a site level.
914     *
915     * Note that we are explicitly checking for the existence of the master_user option in order to account for cases where we don't have any user tokens (user-level connection) but the master_user option is set, which could be the result of a problematic user connection.
916     *
917     * @access public
918     * @since 1.27.0
919     *
920     * @return bool
921     */
922    public function is_site_connection() {
923        return $this->is_connected() && ! $this->has_connected_user() && ! \Jetpack_Options::get_option( 'master_user' );
924    }
925
926    /**
927     * Checks to see if the connection owner of the site is missing.
928     *
929     * @return bool
930     */
931    public function is_missing_connection_owner() {
932        $connection_owner = $this->get_connection_owner_id();
933        if ( ! get_user_by( 'id', $connection_owner ) ) {
934            return true;
935        }
936
937        return false;
938    }
939
940    /**
941     * Returns true if the user with the specified identifier is connected to
942     * WordPress.com.
943     *
944     * @param int $user_id the user identifier. Default is the current user.
945     * @return bool Boolean is the user connected?
946     */
947    public function is_user_connected( $user_id = false ) {
948        $user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
949        if ( ! $user_id ) {
950            return false;
951        }
952
953        return (bool) $this->get_tokens()->get_access_token( $user_id );
954    }
955
956    /**
957     * Returns the local user ID of the connection owner.
958     *
959     * @return bool|int Returns the ID of the connection owner or False if no connection owner found.
960     */
961    public function get_connection_owner_id() {
962        // Check if the memoized value is available.
963        if ( null === self::$connection_owner_id ) {
964            $owner                     = $this->get_connection_owner();
965            self::$connection_owner_id = $owner instanceof \WP_User ? $owner->ID : 0;
966        }
967
968        // If the ID is set to 0, there's no valid connection owner.
969        return self::$connection_owner_id > 0 ? self::$connection_owner_id : false;
970    }
971
972    /**
973     * Get the wpcom user data of the current|specified connected user.
974     *
975     * Fetches the data from the WordPress.com `jetpack-wpcom-user-data` REST endpoint
976     * with a signed request as the connected user. Routing this through
977     * Client::remote_request() (rather than the legacy `wpcom.getUser` XML-RPC method)
978     * ensures any connection errors are captured by the Error_Handler.
979     *
980     * @since 8.8.1 Fetch the data over REST instead of the `wpcom.getUser` XML-RPC method.
981     *
982     * @param int|null $user_id the user identifier.
983     * @return bool|array An array with the WPCOM user data on success, false otherwise.
984     */
985    public function get_connected_user_data( $user_id = null ) {
986        if ( ! $user_id ) {
987            $user_id = get_current_user_id();
988        }
989
990        // Check if the user is connected and return false otherwise.
991        if ( ! $this->is_user_connected( $user_id ) ) {
992            return false;
993        }
994
995        $transient_key    = "jetpack_connected_user_data_$user_id";
996        $cached_user_data = get_transient( $transient_key );
997
998        if ( 'error' === $cached_user_data ) {
999            return false;
1000        }
1001
1002        if ( $cached_user_data ) {
1003            return $cached_user_data;
1004        }
1005
1006        $blog_id = (int) \Jetpack_Options::get_option( 'id' );
1007
1008        // Build a signed request as the connected user. We can't use
1009        // Client::wpcom_json_api_request_as_user() because it always signs as the
1010        // current user, whereas this method may be called for an arbitrary $user_id.
1011        $args            = Client::validate_args_for_wpcom_json_api_request(
1012            "/sites/{$blog_id}/jetpack-wpcom-user-data",
1013            '2',
1014            array( 'method' => 'GET' )
1015        );
1016        $args['user_id'] = $user_id;
1017
1018        $response = Client::remote_request( $args );
1019
1020        if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
1021            // Cache errors briefly so a failing remote request doesn't result in
1022            // a blocking request on every call, e.g. on each admin page
1023            // load via Initial_State::set_connection_script_data().
1024            set_transient( $transient_key, 'error', 5 * MINUTE_IN_SECONDS );
1025
1026            return false;
1027        }
1028
1029        $user_data = json_decode( wp_remote_retrieve_body( $response ), true );
1030
1031        if ( ! is_array( $user_data ) || empty( $user_data ) ) {
1032            set_transient( $transient_key, 'error', 5 * MINUTE_IN_SECONDS );
1033
1034            return false;
1035        }
1036
1037        set_transient( $transient_key, $user_data, DAY_IN_SECONDS );
1038
1039        return $user_data;
1040    }
1041
1042    /**
1043     * Returns the WordPress.com user ID of a connected user.
1044     *
1045     * Answers only for a user who currently holds a token: the binding outlives any one token, so
1046     * connectedness is checked here rather than inferred from a row existing. Resolving an unbound
1047     * user costs a blocking request to WordPress.com, so this is not safe to call per row.
1048     *
1049     * @since 9.2.0
1050     *
1051     * @param int|false $user_id The local user identifier. Default is the current user.
1052     * @return int The WordPress.com user ID, or 0 if it could not be determined.
1053     */
1054    public function resolve_wpcom_user_id( $user_id = false ) {
1055        $user_id = $user_id ? absint( $user_id ) : get_current_user_id();
1056
1057        // The binding outlives the token, unlike the transient behind `get_connected_user_data()`,
1058        // so connectedness is checked here rather than left to the lookup below.
1059        if ( ! $user_id || ! $this->is_user_connected( $user_id ) ) {
1060            return 0;
1061        }
1062
1063        $bound = Utils::get_wpcom_user_id( $user_id );
1064
1065        if ( $bound ) {
1066            return $bound;
1067        }
1068
1069        $user_data = $this->get_connected_user_data( $user_id );
1070
1071        // Callers must read 0 as "unknown", never as "no match": a failed lookup lands here too.
1072        if ( empty( $user_data['ID'] ) ) {
1073            return 0;
1074        }
1075
1076        Utils::set_wpcom_user_id( $user_id, (int) $user_data['ID'] );
1077
1078        return (int) $user_data['ID'];
1079    }
1080
1081    /**
1082     * Unbind the WordPress.com user ID of any user whose token is new.
1083     *
1084     * Every path that changes a user's token writes the `user_tokens` option, so this covers
1085     * authorize, remote connect and the REST endpoint alike. A token that is added or replaced can
1086     * name a different WordPress.com account, so any binding it would answer with is unverified. A
1087     * token merely removed leaves the binding correct, and other subsystems store their own meaning
1088     * in the same meta, so removals are left alone.
1089     *
1090     * @internal Hooked on `pre_update_jetpack_option_user_tokens`, which fires before the write.
1091     * @since 9.2.0
1092     *
1093     * @param string $name  The option name.
1094     * @param mixed  $value The tokens about to be written.
1095     */
1096    public function unbind_wpcom_user_ids_for_new_tokens( $name, $value ) {
1097        if ( ! is_array( $value ) ) {
1098            return;
1099        }
1100
1101        // A site disconnect deletes the option outright, so the first write back has nothing to
1102        // diff against â€” treat that as every token being new rather than skipping the check.
1103        $previous = \Jetpack_Options::get_option( 'user_tokens' );
1104        $previous = is_array( $previous ) ? $previous : array();
1105
1106        // Iterating the incoming tokens covers a token being added as well as replaced, and skips
1107        // removal for free: a user absent from the new set is never visited.
1108        foreach ( $value as $user_id => $token ) {
1109            if ( ( $previous[ $user_id ] ?? null ) !== $token ) {
1110                Utils::delete_wpcom_user_id( $user_id );
1111            }
1112        }
1113    }
1114
1115    /**
1116     * Drop the cached WordPress.com site record.
1117     *
1118     * A caller that fetched the record by another route holds something newer than the cache can,
1119     * and `jetpack_site_data_fetched` fires on a cached read too. The cached copy has to go, or it
1120     * keeps announcing the older record and undoes what that caller stored.
1121     *
1122     * @since 9.0.0
1123     *
1124     * @return void
1125     */
1126    public static function delete_cached_site_data() {
1127        $site_id = \Jetpack_Options::get_option( 'id' );
1128
1129        if ( $site_id ) {
1130            delete_transient( self::SITE_DATA_TRANSIENT_PREFIX . $site_id );
1131        }
1132    }
1133
1134    /**
1135     * Fetch the site's own record from the WordPress.com `/sites/%d` endpoint.
1136     *
1137     * The result is cached briefly. Every plugin that bundles this package serves this route, and
1138     * the Jetpack dashboard requests it on mount, so an uncached read means a blocking round trip
1139     * per render.
1140     *
1141     * @since 8.10.0
1142     *
1143     * @return object|WP_Error The decoded site record, or an error describing the failure.
1144     */
1145    public function get_connected_site_data() {
1146        $site_id = \Jetpack_Options::get_option( 'id' );
1147
1148        if ( ! $site_id ) {
1149            return new WP_Error( 'site_id_missing', '', array( 'api_error_code' => 'site_id_missing' ) );
1150        }
1151
1152        $sandbox_secret = null;
1153
1154        // An array cookie (`store_sandbox[]=`) carries no secret to send, and `filter_var()` turns
1155        // it into `false`.
1156        if ( isset( $_COOKIE['store_sandbox'] ) && is_string( $_COOKIE['store_sandbox'] ) ) {
1157            // Keep only RFC 6265 cookie-octets so the value cannot break out of the Cookie header.
1158            $sandbox_secret = preg_replace( '/[^\x21-\x7E]|[";,\\\\]/', '', filter_var( wp_unslash( $_COOKIE['store_sandbox'] ) ) );
1159
1160            // An empty cookie, or one the sanitizer strips to nothing, is not a sandbox secret.
1161            // Counting it as one opts the request out of the cache with no sandbox to reach.
1162            if ( '' === $sandbox_secret ) {
1163                $sandbox_secret = null;
1164            }
1165        }
1166
1167        // A sandboxed request must neither read the shared cache nor seed it with sandbox data.
1168        $sandboxed     = null !== $sandbox_secret;
1169        $transient_key = self::SITE_DATA_TRANSIENT_PREFIX . $site_id;
1170
1171        // WordPress.com itself requests this route right after a purchase, for the side effect of
1172        // the `jetpack_site_data_fetched` consumers storing the new plan. Those requests arrive
1173        // signed with a connection token, which no browser request carries. A cached read would
1174        // hand that refresh the pre-purchase record and turn it into a no-op, so a signed request
1175        // always reads from WordPress.com and replaces the cache with the record it fetched.
1176        $signed = Rest_Authentication::is_signed_with_blog_token() || Rest_Authentication::is_signed_with_user_token();
1177
1178        $result = ( $sandboxed || $signed ) ? false : get_transient( $transient_key );
1179
1180        // Only the array shape stored below can be served. A `pre_transient_*` filter or a damaged
1181        // object cache entry can hand back anything, and a non-array would throw on
1182        // `$result['body']` for every request until the entry expired, so it reads as a miss.
1183        if ( ! is_array( $result ) ) {
1184            $result = $this->fetch_connected_site_data( $site_id, $sandbox_secret );
1185
1186            // A signed read that failed must not replace a still-usable cached record with the failure.
1187            if ( ! $sandboxed && ! ( $signed && isset( $result['error'] ) ) ) {
1188                // Failures expire sooner so an outage recovers without waiting out a full success window.
1189                set_transient(
1190                    $transient_key,
1191                    $result,
1192                    isset( $result['error'] ) ? 2 * MINUTE_IN_SECONDS : 5 * MINUTE_IN_SECONDS
1193                );
1194            }
1195        }
1196
1197        if ( isset( $result['error'] ) ) {
1198            return new WP_Error( 'site_data_fetch_failed', '', $result['error'] );
1199        }
1200
1201        /**
1202         * Fires after the site record was served, whether it was fetched or read from the cache.
1203         *
1204         * Consumers that cache anything derived from the record, such as the current plan,
1205         * can refresh it here.
1206         *
1207         * This fires on a cached read too, so a consumer stays in step with every request that
1208         * serves the record rather than only the ones that reached WordPress.com.
1209         *
1210         * The record is passed as an array rather than the object this method returns, so that a
1211         * listener cannot mutate the instance that becomes the REST response.
1212         *
1213         * @since 9.0.0
1214         *
1215         * @param array $record The decoded site record from the WordPress.com `/sites/%d` endpoint.
1216         */
1217        do_action( 'jetpack_site_data_fetched', json_decode( $result['body'], true ) );
1218
1219        return json_decode( $result['body'] );
1220    }
1221
1222    /**
1223     * Request the site record from WordPress.com.
1224     *
1225     * Returns a cacheable array rather than the decoded record so that both outcomes survive a
1226     * round trip through a transient.
1227     *
1228     * @since 9.0.0
1229     *
1230     * @param int         $site_id        The WordPress.com blog ID.
1231     * @param string|null $sandbox_secret Sanitized store sandbox cookie value, or null when not sandboxed.
1232     * @return array Either `array( 'body' => string )` or `array( 'error' => array )`.
1233     */
1234    private function fetch_connected_site_data( $site_id, $sandbox_secret ) {
1235        $args = array( 'headers' => array() );
1236
1237        // Allow use a store sandbox. Internal ref: PCYsg-IA-p2.
1238        if ( null !== $sandbox_secret ) {
1239            $args['headers']['Cookie'] = "store_sandbox=$sandbox_secret;";
1240        }
1241
1242        $response = Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d', $site_id ) . '?force=wpcom', '1.1', $args );
1243        $body     = wp_remote_retrieve_body( $response );
1244        $data     = $body ? json_decode( $body ) : null;
1245
1246        if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
1247            $error_info = array(
1248                'api_error_code' => null,
1249                'api_http_code'  => wp_remote_retrieve_response_code( $response ),
1250            );
1251
1252            if ( is_wp_error( $response ) ) {
1253                $error_info['api_error_code'] = $response->get_error_code() ? wp_strip_all_tags( $response->get_error_code() ) : null;
1254            } elseif ( $data && ! empty( $data->error ) ) {
1255                $error_info['api_error_code'] = is_string( $data->error ) ? wp_strip_all_tags( $data->error ) : null;
1256            }
1257
1258            return array( 'error' => $error_info );
1259        }
1260
1261        if ( ! is_object( $data ) ) {
1262            return array(
1263                'error' => array(
1264                    'api_error_code' => 'invalid_body',
1265                    'api_http_code'  => 200,
1266                ),
1267            );
1268        }
1269
1270        return array( 'body' => $body );
1271    }
1272
1273    /**
1274     * Returns a user object of the connection owner.
1275     *
1276     * @return WP_User|false False if no connection owner found.
1277     */
1278    public function get_connection_owner() {
1279        $user_id = \Jetpack_Options::get_option( 'master_user' );
1280        if ( ! $user_id ) {
1281            return false;
1282        }
1283
1284        // Make sure user is connected.
1285        $user_token = $this->get_tokens()->get_access_token( $user_id );
1286
1287        $connection_owner = false;
1288
1289        if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
1290            $connection_owner = get_userdata( $user_token->external_user_id );
1291        }
1292
1293        // Reporting is best-effort and must never fatal a request running mid-plugin-update:
1294        // skip it when the already-loaded Error_Handler is a stale version predating the factory.
1295        if ( $connection_owner === false && method_exists( Error_Handler::class, 'build_connection_wp_error' ) ) {
1296            Error_Handler::get_instance()->report_error(
1297                Error_Handler::build_connection_wp_error(
1298                    'invalid_connection_owner',
1299                    'Invalid connection owner',
1300                    array( 'token' => '' ),
1301                    'local_state', // Error_Handler::ERROR_TYPE_LOCAL_STATE.
1302                    '', // Local-state errors describe the site's database, not a request, so they have no direction.
1303                    array(
1304                        'user_id'        => $user_id,
1305                        'has_user_token' => (bool) $user_token,
1306                    )
1307                ),
1308                false,
1309                true
1310            );
1311        }
1312
1313        return $connection_owner;
1314    }
1315
1316    /**
1317     * Returns true if the provided user is the Jetpack connection owner.
1318     * If user ID is not specified, the current user will be used.
1319     *
1320     * @param int|bool $user_id the user identifier. False for current user.
1321     * @return bool True the user the connection owner, false otherwise.
1322     */
1323    public function is_connection_owner( $user_id = false ) {
1324        if ( ! $user_id ) {
1325            $user_id = get_current_user_id();
1326        }
1327
1328        return ( (int) $user_id ) === $this->get_connection_owner_id();
1329    }
1330
1331    /**
1332     * Determines whether the connection ownership can be transferred to another user.
1333     *
1334     * The default Jetpack connection uses a transferable ownership model; a set protected owner
1335     * anchor locks it. This is the single chokepoint used both when deciding which
1336     * connection-error CTA to surface and when performing an ownership change.
1337     *
1338     * @since 8.8.0
1339     * @since 9.3.0 A locked protected owner anchor makes ownership non-transferable.
1340     * @since 9.11.0 The `jetpack_connection_ownership_transferable` filter is deprecated.
1341     *
1342     * @return bool True if ownership can be transferred, false if it is locked.
1343     */
1344    public function is_ownership_transferable() {
1345        // Keyed on the anchor, never on has_protected_owner(): an owner who does not match the
1346        // anchor is exactly when ownership must stay locked.
1347        if ( Protected_Owner::is_locked() ) {
1348            return false;
1349        }
1350
1351        /**
1352         * Filters whether the Jetpack connection ownership can be transferred.
1353         *
1354         * Return `false` to lock ownership on a site without a protected owner anchor. The
1355         * anchored owner may still transfer ownership despite this deprecated filter.
1356         *
1357         * @since 8.8.0
1358         * @deprecated 9.11.0 The protected owner anchor is the only supported ownership lock.
1359         *
1360         * @param bool $transferable Whether ownership can be transferred. Default true.
1361         */
1362        return (bool) apply_filters_deprecated( 'jetpack_connection_ownership_transferable', array( true ), 'package-9.11.0', '', __( 'The protected owner anchor is the only ownership lock.', 'jetpack-connection' ) );
1363    }
1364
1365    /**
1366     * Whether a protected owner is required right now.
1367     *
1368     * Evaluated at the moment of the request, not as a standing declaration: a consumer may
1369     * legitimately answer false while it is installed and active â€” running in test mode, say â€”
1370     * and true only at the lifecycle moment that binds something to the owner's identity.
1371     *
1372     * @since 9.3.0
1373     *
1374     * @return bool True if a protected owner is required at this moment. Default false.
1375     */
1376    public function requires_protected_owner() {
1377        /**
1378         * Filters whether a protected owner is required at this moment.
1379         *
1380         * Return `true` at the point a feature is about to bind to the connection owner's
1381         * identity. Answering false at other times is expected and supported.
1382         *
1383         * @since 9.3.0
1384         *
1385         * @param bool $required Whether a protected owner is required. Default false.
1386         */
1387        return (bool) apply_filters( 'jetpack_connection_requires_protected_owner', false );
1388    }
1389
1390    /**
1391     * Whether the connection owner is the protected owner the anchor names.
1392     *
1393     * This is the question consumers gate on before binding anything to the owner's identity.
1394     *
1395     * Reads the binding of the current owner rather than searching for whoever holds the anchored
1396     * ID, so a row on any other user cannot affect the answer. Requiring the owner to hold a live
1397     * token on top of that is what keeps a row written by another subsystem from ever satisfying
1398     * this: both halves are load-bearing, and there are tests for each.
1399     *
1400     * @since 9.3.0
1401     *
1402     * @return bool
1403     */
1404    public function has_protected_owner() {
1405        $anchor = Protected_Owner::get_locked();
1406
1407        if ( ! $anchor ) {
1408            return false;
1409        }
1410
1411        $owner_id = $this->get_connection_owner_id();
1412
1413        if ( ! $owner_id ) {
1414            return false;
1415        }
1416
1417        return $this->resolve_wpcom_user_id( $owner_id ) === (int) $anchor['wpcom_user_id'];
1418    }
1419
1420    /**
1421     * Classify why `has_protected_owner()` answered false, and what would change it.
1422     *
1423     * Deliberately inspects only what the gate inspects â€” the anchor and the current connection
1424     * owner â€” so the two can never disagree about the same site. Anything needing a user search or
1425     * a reachability probe is a different question and is not answered here.
1426     *
1427     * `is_current_user_the_po` reads the current user's own stored binding, never a search for
1428     * whoever holds the anchored ID, so it cannot be confused by a second user carrying the same
1429     * meta, and never costs a network call. It is a hint for copy, not a gate.
1430     *
1431     * @since 9.4.0
1432     *
1433     * @return array{status: string, is_current_user_the_po: bool}
1434     */
1435    public function resolve_protected_owner_state() {
1436        $anchor     = Protected_Owner::get_locked();
1437        $current_id = get_current_user_id();
1438
1439        // Only meaningful against an anchor: with none, there is nothing for the user to be.
1440        // Reads the stored binding rather than resolving it, so classifying a state never costs a
1441        // WordPress.com round trip. An unbound user reads as false and gets the generic copy.
1442        $is_current_user_the_po = $anchor
1443            && Utils::get_wpcom_user_id( $current_id ) === (int) $anchor['wpcom_user_id'];
1444
1445        if ( ! $anchor ) {
1446            $roles = new Roles();
1447
1448            if ( ! current_user_can( 'jetpack_connect' ) || ! current_user_can( $roles->translate_role_to_cap( 'administrator' ) ) ) {
1449                // Eligibility is being an admin, not holding the master slot.
1450                $status = self::PO_STATE_NOT_ELIGIBLE;
1451            } elseif ( ! $this->is_user_connected( $current_id ) ) {
1452                // A WordPress.com identity has to exist before it can be confirmed and locked.
1453                $status = self::PO_STATE_NEEDS_CONNECT_TO_ESTABLISH;
1454            } else {
1455                $status = self::PO_STATE_CAN_ESTABLISH;
1456            }
1457        } else {
1458            $owner_id       = $this->get_connection_owner_id();
1459            $owner_wpcom_id = $owner_id ? $this->resolve_wpcom_user_id( $owner_id ) : 0;
1460
1461            if ( ! $owner_wpcom_id ) {
1462                // A zero is "could not determine", never "does not match", so an owner whose
1463                // identity cannot be confirmed is reported as needing to reconnect, not replaced.
1464                $status = self::PO_STATE_NEEDS_OWNER_RECONNECT;
1465            } elseif ( $owner_wpcom_id !== (int) $anchor['wpcom_user_id'] ) {
1466                // Legitimate, not broken: the first admin to connect takes a vacant master slot,
1467                // so an agency can hold it while the protected owner is away.
1468                $status = self::PO_STATE_NEEDS_DIFFERENT_OWNER;
1469            } else {
1470                $status = self::PO_STATE_RE_EVALUATE;
1471            }
1472        }
1473
1474        return array(
1475            'status'                 => $status,
1476            'is_current_user_the_po' => $is_current_user_the_po,
1477        );
1478    }
1479
1480    /**
1481     * Reconcile this site's protected owner against WordPress.com, which is the owner of record.
1482     *
1483     * Runs at connect, when the site has a fresh user token and an answer is cheap, and only once
1484     * something is anchored: a site with no protected owner asks nothing and behaves as it did
1485     * before this existed. One answer settles the rest â€” whether an owner still exists, whether
1486     * the anchor names them, and whether the user connecting is them â€” so the anchor, the binding
1487     * and the master slot are decided together rather than from two calls that could disagree.
1488     *
1489     * Only an answer moves anything. Unreachable, refused, unimplemented and malformed leave the
1490     * anchor exactly as it was: it was confirmed once, and a request that never arrived is no
1491     * evidence against it.
1492     *
1493     * @internal Hooked on `jetpack_user_authorized`.
1494     * @since 9.8.0
1495     *
1496     * @return bool Whether WordPress.com confirmed the anchored identity.
1497     */
1498    public function reconcile_protected_owner() {
1499        $user_id = get_current_user_id();
1500
1501        if ( ! $user_id ) {
1502            return false;
1503        }
1504
1505        $anchor = Protected_Owner::get();
1506
1507        // Nothing anchored is nothing to reconcile, and a site with no protected owner must behave
1508        // exactly as it did before this existed â€” including making no request. Such a site reaches
1509        // an owner through the claim instead, which is where confirming belongs.
1510        if ( ! $anchor ) {
1511            return false;
1512        }
1513
1514        $record = $this->query_protected_owner_record( (int) $anchor['wpcom_user_id'] );
1515
1516        // Silence is not an answer. Unreachable, refused and unimplemented leave the anchor exactly
1517        // as it was: it was confirmed once, and a request that never arrived is no evidence against
1518        // it. Dropping a good lock because WordPress.com had a bad minute costs a merchant their
1519        // payouts until the owner happens to connect again.
1520        if ( ! is_array( $record ) || ! isset( $record['has_owner'] ) ) {
1521            return false;
1522        }
1523
1524        // WordPress.com no longer has an owner of record, so neither does this site. Support
1525        // clearing it at that end is how a wrongly anchored site recovers.
1526        if ( ! $record['has_owner'] ) {
1527            Protected_Owner::clear();
1528
1529            return false;
1530        }
1531
1532        $caller_wpcom_user_id = (int) ( $record['caller_wpcom_user_id'] ?? 0 );
1533
1534        // The identity is disclosed only to the owner it names, so this is the one branch that can
1535        // learn it â€” and what it settles is which account the anchor should name, since
1536        // WordPress.com may have moved the owner since this site last asked.
1537        if ( ! empty( $record['is_caller'] ) ) {
1538            return $this->adopt_protected_owner( $user_id, $caller_wpcom_user_id, $anchor );
1539        }
1540
1541        // Connecting cleared this, and it is the caller's own identity rather than the owner's, so
1542        // it is written whoever they are. Nothing is anchored on this path, so an early write
1543        // cannot strand a half-finished lock.
1544        if ( $caller_wpcom_user_id ) {
1545            Utils::set_wpcom_user_id( $user_id, $caller_wpcom_user_id );
1546        }
1547
1548        // Somebody else is connecting. WordPress.com confirms the anchored identity rather than
1549        // naming the owner, so the answer is the same whoever asks.
1550        if ( empty( $record['matches'] ) ) {
1551            Protected_Owner::clear();
1552
1553            return false;
1554        }
1555
1556        return true;
1557    }
1558
1559    /**
1560     * Take WordPress.com's word that the connecting user owns this site.
1561     *
1562     * @since 9.8.0
1563     *
1564     * @param int        $user_id       The connecting local user.
1565     * @param int        $wpcom_user_id The connecting user's WordPress.com identity, which this
1566     *                                  branch has just been told is the owner of record.
1567     * @param array|null $anchor        What this site has anchored, if anything.
1568     * @return bool Whether the anchor now names that identity.
1569     */
1570    private function adopt_protected_owner( $user_id, $wpcom_user_id, $anchor ) {
1571        // An owner without an identity is a malformed answer, and trusting it would lock the site
1572        // to nobody.
1573        if ( ! $wpcom_user_id ) {
1574            return false;
1575        }
1576
1577        // Anchored before the binding, so a failed write leaves nothing behind for a later
1578        // connection to build on. Re-pointing only moves the cached local ID, so it is right only
1579        // while the anchored identity is the one WordPress.com just confirmed.
1580        if ( $anchor && (int) $anchor['wpcom_user_id'] === $wpcom_user_id ) {
1581            Protected_Owner::repoint( $user_id );
1582        } elseif ( ! Protected_Owner::set( $wpcom_user_id, $user_id ) ) {
1583            return false;
1584        }
1585
1586        // Connecting clears the binding, so this writes back the one the answer just confirmed.
1587        Utils::set_wpcom_user_id( $user_id, $wpcom_user_id );
1588
1589        // Eligibility for the master slot is being an administrator here, which the owner of record
1590        // need not be.
1591        if ( user_can( $user_id, ( new Roles() )->translate_role_to_cap( 'administrator' ) )
1592            && (int) \Jetpack_Options::get_option( 'master_user' ) !== $user_id ) {
1593            \Jetpack_Options::update_option( 'master_user', $user_id );
1594        }
1595
1596        return true;
1597    }
1598
1599    /**
1600     * Ask WordPress.com whether it still holds the anchored identity as this site's owner.
1601     *
1602     * Split from `reconcile_protected_owner()` so the decision it drives can be exercised without a
1603     * network, which is the half worth testing: every branch of it changes whether a site gates a
1604     * live feature. The anchored ID is sent so the answer confirms rather than discloses.
1605     *
1606     * @since 9.8.0
1607     *
1608     * @param int $anchored_wpcom_user_id The WordPress.com identity this site has anchored.
1609     * @return array|null The record, or null when WordPress.com could not answer.
1610     */
1611    protected function query_protected_owner_record( $anchored_wpcom_user_id ) {
1612        return $this->request_protected_owner_record(
1613            '/reconcile',
1614            array( 'anchored_wpcom_user_id' => (int) $anchored_wpcom_user_id )
1615        );
1616    }
1617
1618    /**
1619     * Claim this site's protected ownership for the current user with WordPress.com.
1620     *
1621     * Split from `set_protected_owner()` so the decision it drives can be exercised without a
1622     * network. The identity travels in the signature rather than the payload, so nothing is sent.
1623     *
1624     * @since 9.8.0
1625     *
1626     * @return array|null The record, or null when WordPress.com could not answer.
1627     */
1628    protected function assert_protected_owner_record() {
1629        return $this->request_protected_owner_record();
1630    }
1631
1632    /**
1633     * Give up this site's protected ownership with WordPress.com.
1634     *
1635     * Split from `release_protected_owner()` so the decision it drives can be exercised without a
1636     * network. The identity travels in the signature rather than the payload, so WordPress.com
1637     * decides whether the caller is the owner it holds.
1638     *
1639     * @since 9.9.0
1640     *
1641     * @return array|null The record, or null when WordPress.com could not answer.
1642     */
1643    protected function relinquish_protected_owner_record() {
1644        return $this->request_protected_owner_record( '/release' );
1645    }
1646
1647    /**
1648     * Call this site's protected-owner resource on WordPress.com, signed as the current user.
1649     *
1650     * @since 9.8.1
1651     *
1652     * @param string     $route The route below the resource, empty for the resource itself.
1653     * @param array|null $body  The request body, or null to send none.
1654     * @return array|null The record, or null when WordPress.com could not answer.
1655     */
1656    private function request_protected_owner_record( $route = '', $body = null ) {
1657        $path = sprintf(
1658            '/sites/%d/jetpack-protected-owner%s',
1659            (int) \Jetpack_Options::get_option( 'id' ),
1660            $route
1661        );
1662
1663        $response = Client::wpcom_json_api_request_as_user( $path, '2', array( 'method' => 'POST' ), $body );
1664
1665        // Anything but a 200 is silence rather than an answer: unreachable, refused, or a
1666        // WordPress.com that does not implement the route. Every caller fails closed on null.
1667        if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
1668            return null;
1669        }
1670
1671        $record = json_decode( wp_remote_retrieve_body( $response ), true );
1672
1673        return is_array( $record ) ? $record : null;
1674    }
1675
1676    /**
1677     * Record a user as the protected owner and promote them to connection owner.
1678     *
1679     * Gated on `jetpack_connect` rather than on a role: a host can narrow that capability and
1680     * multisite does. It is false while the package is unconfigured, so a caller that has not
1681     * registered the connection's capabilities is refused rather than trusted.
1682     *
1683     * @since 9.3.0
1684     * @since 9.6.0 No longer takes how the owner was confirmed.
1685     * @since 9.8.0 WordPress.com records the owner before anything is anchored here.
1686     *
1687     * @param int $user_id The local user to anchor.
1688     * @return true|WP_Error True on success, WP_Error otherwise.
1689     */
1690    public function set_protected_owner( $user_id ) {
1691        // Authorization precedes validation, so an unauthorized caller cannot use the argument
1692        // errors below to learn which users are administrators or hold a token.
1693        if ( ! current_user_can( 'jetpack_connect' ) ) {
1694            return new WP_Error(
1695                'protected_owner_forbidden',
1696                __( 'You do not have permission to manage the protected owner.', 'jetpack-connection' ),
1697                array( 'status' => 403 )
1698            );
1699        }
1700
1701        $user_id = absint( $user_id );
1702        $roles   = new Roles();
1703
1704        if ( ! user_can( $user_id, $roles->translate_role_to_cap( 'administrator' ) ) ) {
1705            return new WP_Error(
1706                'protected_owner_not_admin',
1707                __( 'The protected owner must be an administrator.', 'jetpack-connection' ),
1708                array( 'status' => 400 )
1709            );
1710        }
1711
1712        // The claim is signed as the current user, so it can only ever anchor the current user.
1713        // Anchoring somebody else would be an owner assignment they never agreed to.
1714        if ( $user_id !== get_current_user_id() ) {
1715            return new WP_Error(
1716                'protected_owner_not_self',
1717                __( 'A protected owner can only be recorded by the user confirming it.', 'jetpack-connection' ),
1718                array( 'status' => 400 )
1719            );
1720        }
1721
1722        // A stored binding that already disagrees with the anchor is enough to refuse. WordPress.com
1723        // is still asked when this user has no binding, because that answer is what names them.
1724        if ( $this->local_anchor_names_someone_else( (int) Utils::get_wpcom_user_id( $user_id ) ) ) {
1725            return $this->protected_owner_claimed_by_other();
1726        }
1727
1728        // WordPress.com is asked before anything is written here. It owns the record, so a claim it
1729        // has not accepted must not leave a locked anchor behind on this site.
1730        $record = $this->assert_protected_owner_record();
1731
1732        // Fail closed: unreachable, refused, or a WordPress.com that does not implement the call.
1733        // A site that cannot get an answer must not end up protecting anybody on its own say-so.
1734        if ( ! is_array( $record ) || empty( $record['status'] ) ) {
1735            return new WP_Error(
1736                'protected_owner_unconfirmed',
1737                __( 'Could not reach WordPress.com to confirm the protected owner.', 'jetpack-connection' ),
1738                array( 'status' => 503 )
1739            );
1740        }
1741
1742        // Somebody else already holds this site. Beyond support there is no way past this, which is
1743        // the point: an owner that could be overwritten by the next claimant protects nobody.
1744        if ( 'locked_to_other' === $record['status'] ) {
1745            return $this->protected_owner_claimed_by_other();
1746        }
1747
1748        // Only an accepted claim is anchored: any other verdict is refused, even one carrying an ID.
1749        if ( ! in_array( $record['status'], array( 'recorded', 'already_yours' ), true ) || empty( $record['wpcom_user_id'] ) ) {
1750            return new WP_Error(
1751                'protected_owner_not_verified',
1752                __( 'Could not confirm the protected owner with WordPress.com.', 'jetpack-connection' ),
1753                array( 'status' => 400 )
1754            );
1755        }
1756
1757        // A `recorded` answer must not replace an anchor that already names a different account.
1758        if ( $this->local_anchor_names_someone_else( (int) $record['wpcom_user_id'] ) ) {
1759            return $this->protected_owner_claimed_by_other();
1760        }
1761
1762        // Store the binding the anchor will be compared against, so the gate reads local state from
1763        // here on. Routed through the deduping writer, which clears the ID off any previous holder.
1764        Utils::set_wpcom_user_id( $user_id, (int) $record['wpcom_user_id'] );
1765
1766        if ( ! Protected_Owner::set( (int) $record['wpcom_user_id'], $user_id ) ) {
1767            return new WP_Error(
1768                'protected_owner_not_stored',
1769                __( 'Could not store the protected owner.', 'jetpack-connection' ),
1770                array( 'status' => 500 )
1771            );
1772        }
1773
1774        // Written directly rather than through update_connection_owner(): that round-trips to
1775        // WordPress.com first, and its ownership-change guard will refuse the anchor just set here.
1776        \Jetpack_Options::update_option( 'master_user', $user_id );
1777
1778        return true;
1779    }
1780
1781    /**
1782     * Release the protected owner, leaving ownership open to any connected administrator.
1783     *
1784     * WordPress.com holds the record, so it is cleared there first. An anchor dropped only here
1785     * would leave WordPress.com refusing every later claim as `locked_to_other`, locking the site
1786     * to nobody rather than unlocking it.
1787     *
1788     * Leaves `master_user` alone: releasing the lock does not change who the owner is.
1789     *
1790     * @since 9.9.0
1791     *
1792     * @return true|WP_Error True on success, WP_Error otherwise.
1793     */
1794    public function release_protected_owner() {
1795        // Authorization precedes everything else, so an unauthorized caller cannot use the
1796        // refusals below to learn whether this site is protected or by whom.
1797        if ( ! current_user_can( 'jetpack_connect' ) ) {
1798            return new WP_Error(
1799                'protected_owner_forbidden',
1800                __( 'You do not have permission to manage the protected owner.', 'jetpack-connection' ),
1801                array( 'status' => 403 )
1802            );
1803        }
1804
1805        // Nothing anchored is already released, so repeating the call is not an error. It can also
1806        // be an anchor lost while WordPress.com kept its record, which this site cannot tell apart
1807        // and cannot recover from alone â€” hence a warning rather than silence.
1808        $anchor = Protected_Owner::get_locked();
1809
1810        if ( ! $anchor ) {
1811            wp_trigger_error(
1812                __METHOD__,
1813                'Released with no protected owner on record. If WordPress.com still holds one, this site can no longer claim it back.',
1814                E_USER_WARNING
1815            );
1816
1817            return true;
1818        }
1819
1820        // A local hint that spares an obvious refusal a round trip. WordPress.com is asked anyway
1821        // whenever this passes, and its answer is the one that decides.
1822        if ( Utils::get_wpcom_user_id( get_current_user_id() ) !== (int) $anchor['wpcom_user_id'] ) {
1823            return $this->protected_owner_release_refused();
1824        }
1825
1826        $record = $this->relinquish_protected_owner_record();
1827
1828        // Fail closed: unreachable, refused, or a WordPress.com that does not implement the call.
1829        // Clearing on silence would unlock a site WordPress.com still holds.
1830        if ( ! is_array( $record ) || empty( $record['status'] ) ) {
1831            return new WP_Error(
1832                'protected_owner_unreleased',
1833                __( 'Could not reach WordPress.com to release the protected owner.', 'jetpack-connection' ),
1834                array( 'status' => 503 )
1835            );
1836        }
1837
1838        if ( 'not_owner' === $record['status'] ) {
1839            return $this->protected_owner_release_refused();
1840        }
1841
1842        // `no_owner` is WordPress.com reporting it holds nothing to release, which is the state
1843        // this call asks for, so the stale anchor here clears alongside an accepted release.
1844        if ( ! in_array( $record['status'], array( 'released', 'no_owner' ), true ) ) {
1845            return new WP_Error(
1846                'protected_owner_not_released',
1847                __( 'Could not release the protected owner with WordPress.com.', 'jetpack-connection' ),
1848                array( 'status' => 400 )
1849            );
1850        }
1851
1852        $cleared = $this->clear_protected_owner();
1853
1854        // WordPress.com has already let go, so a local delete that failed is unfinished cleanup
1855        // rather than a release that did not happen. Retrying is what fixes it: reconcile only
1856        // runs when somebody authorizes, and WordPress.com now answers this call with `no_owner`.
1857        if ( is_wp_error( $cleared ) && 'protected_owner_not_cleared' === $cleared->get_error_code() ) {
1858            return new WP_Error(
1859                'protected_owner_not_cleared',
1860                __( 'Ownership was released with WordPress.com, but this site could not finish clearing it. Try again.', 'jetpack-connection' ),
1861                array( 'status' => 500 )
1862            );
1863        }
1864
1865        return $cleared;
1866    }
1867
1868    /**
1869     * The refusal for a caller who is not the owner WordPress.com holds.
1870     *
1871     * @since 9.9.0
1872     *
1873     * @return WP_Error
1874     */
1875    private function protected_owner_release_refused() {
1876        return new WP_Error(
1877            'protected_owner_not_owner',
1878            __( 'Only the confirmed owner can release ownership of this site.', 'jetpack-connection' ),
1879            array( 'status' => 403 )
1880        );
1881    }
1882
1883    /**
1884     * Whether a WordPress.com user id would replace the stored anchor.
1885     *
1886     * Zero means this user is not named yet, so it is not a conflict.
1887     *
1888     * @since 9.9.0
1889     *
1890     * @param int $wpcom_user_id WordPress.com user the claim would anchor.
1891     * @return bool
1892     */
1893    private function local_anchor_names_someone_else( $wpcom_user_id ) {
1894        $anchor = Protected_Owner::get_locked();
1895
1896        return $anchor && $wpcom_user_id && (int) $anchor['wpcom_user_id'] !== (int) $wpcom_user_id;
1897    }
1898
1899    /**
1900     * The support path for a site a different account already protects.
1901     *
1902     * @since 9.9.0
1903     *
1904     * @return WP_Error
1905     */
1906    private function protected_owner_claimed_by_other() {
1907        return new WP_Error(
1908            'protected_owner_claimed_by_other',
1909            __( 'This site is already protected by a different WordPress.com account. Contact support.', 'jetpack-connection' ),
1910            array( 'status' => 409 )
1911        );
1912    }
1913
1914    /**
1915     * Drop the protected owner anchor, unlocking ownership.
1916     *
1917     * Gated on `jetpack_connect` like establishing one, releasing a lock being the more
1918     * consequential half. The `@internal` tag is documentation; the capability is enforcement.
1919     *
1920     * @internal Recovery and support flows only. Consumers must not call this.
1921     * @since 9.3.0
1922     *
1923     * @return true|WP_Error True once no anchor is set, WP_Error otherwise.
1924     */
1925    public function clear_protected_owner() {
1926        if ( ! current_user_can( 'jetpack_connect' ) ) {
1927            return new WP_Error(
1928                'protected_owner_forbidden',
1929                __( 'You do not have permission to manage the protected owner.', 'jetpack-connection' ),
1930                array( 'status' => 403 )
1931            );
1932        }
1933
1934        Protected_Owner::clear();
1935
1936        // Asked of the outcome rather than of `delete_option()`, which also reports false for an
1937        // anchor that was already absent â€” the state the caller asked for.
1938        if ( Protected_Owner::get() ) {
1939            return new WP_Error(
1940                'protected_owner_not_cleared',
1941                __( 'Could not clear the protected owner.', 'jetpack-connection' ),
1942                array( 'status' => 500 )
1943            );
1944        }
1945
1946        return true;
1947    }
1948
1949    /**
1950     * Connects the user with a specified ID to a WordPress.com user using the
1951     * remote login flow.
1952     *
1953     * @access public
1954     *
1955     * @param int|null    $user_id (optional) the user identifier, defaults to current user.
1956     * @param string|null $redirect_url the URL to redirect the user to for processing, defaults to
1957     *                             admin_url().
1958     * @return WP_Error only in case of a failed user lookup.
1959     */
1960    public function connect_user( $user_id = null, $redirect_url = null ) {
1961        $user = null;
1962        if ( null === $user_id ) {
1963            $user = wp_get_current_user();
1964        } else {
1965            $user = get_user_by( 'ID', $user_id );
1966        }
1967
1968        if ( empty( $user ) ) {
1969            return new \WP_Error( 'user_not_found', 'Attempting to connect a non-existent user.' );
1970        }
1971
1972        if ( null === $redirect_url ) {
1973            $redirect_url = admin_url();
1974        }
1975
1976        // Using wp_redirect intentionally because we're redirecting outside.
1977        wp_redirect( $this->get_authorization_url( $user, $redirect_url ) ); // phpcs:ignore WordPress.Security.SafeRedirect
1978        exit( 0 );
1979    }
1980
1981    /**
1982     * Force user disconnect.
1983     *
1984     * @param int  $user_id Local (external) user ID.
1985     * @param bool $disconnect_all_users Whether to disconnect all users before disconnecting the primary user.
1986     *
1987     * @return bool
1988     */
1989    public function disconnect_user_force( $user_id, $disconnect_all_users = false ) {
1990        if ( ! (int) $user_id ) {
1991            // Missing user ID.
1992            return false;
1993        }
1994        // If we are disconnecting the primary user we may need to disconnect all other users first
1995        if ( $user_id === $this->get_connection_owner_id() && $disconnect_all_users && ! $this->disconnect_all_users_except_primary() ) {
1996            return false;
1997        }
1998
1999        return $this->disconnect_user( $user_id, true, true );
2000    }
2001
2002    /**
2003     * Disconnects all users except the primary user.
2004     *
2005     * @return bool
2006     */
2007    public function disconnect_all_users_except_primary() {
2008
2009        $all_connected_users = $this->get_connected_users();
2010
2011        foreach ( $all_connected_users as $user ) {
2012            // Skip the primary.
2013            if ( $user->ID === $this->get_connection_owner_id() ) {
2014                continue;
2015            }
2016            $disconnected = $this->disconnect_user( $user->ID, false, true );
2017            // If we fail to disconnect any user, we should not proceed with disconnecting the primary user.
2018            if ( ! $disconnected ) {
2019                return false;
2020            }
2021        }
2022
2023        return true;
2024    }
2025
2026    /**
2027     * Unlinks the current user from the linked WordPress.com user.
2028     *
2029     * @access public
2030     * @static
2031     *
2032     * @todo Refactor to properly load the XMLRPC client independently.
2033     *
2034     * @param int|null $user_id the user identifier.
2035     * @param bool     $can_overwrite_primary_user Allow for the primary user to be disconnected.
2036     * @param bool     $force_disconnect_locally Disconnect user locally even if we were unable to disconnect them from WP.com.
2037     * @return bool Whether the disconnection of the user was successful.
2038     */
2039    public function disconnect_user( $user_id = null, $can_overwrite_primary_user = false, $force_disconnect_locally = false ) {
2040        $user_id         = empty( $user_id ) ? get_current_user_id() : (int) $user_id;
2041        $is_primary_user = Jetpack_Options::get_option( 'master_user' ) === $user_id;
2042
2043        if ( $is_primary_user && ! $can_overwrite_primary_user ) {
2044            return false;
2045        }
2046
2047        if ( in_array( $user_id, self::$disconnected_users, true ) ) {
2048            // The user is already disconnected.
2049            return false;
2050        }
2051
2052        // Attempt to disconnect the user from WordPress.com.
2053        $is_disconnected_from_wpcom = $this->unlink_user_from_wpcom( $user_id );
2054
2055        $is_disconnected_locally = false;
2056        if ( $is_disconnected_from_wpcom || $force_disconnect_locally ) {
2057            // Get the WordPress.com email before disconnecting the user
2058            $wpcom_user_data = $this->get_connected_user_data( $user_id );
2059            $wpcom_email     = $wpcom_user_data['email'] ?? null;
2060
2061            // Disconnect the user locally.
2062            $is_disconnected_locally = $this->get_tokens()->disconnect_user( $user_id );
2063
2064            if ( $is_disconnected_locally ) {
2065                // Delete cached connected user data.
2066                $transient_key = "jetpack_connected_user_data_$user_id";
2067                delete_transient( $transient_key );
2068
2069                // Clean up account mismatch transients for this user
2070                if ( $wpcom_email ) {
2071                    $user_account_status = new User_Account_Status();
2072                    $user_account_status->clean_account_mismatch_transients( $wpcom_email );
2073                }
2074
2075                /**
2076                 * Fires after the current user has been unlinked from WordPress.com.
2077                 *
2078                 * @since 1.7.0
2079                 * @since-jetpack 4.1.0
2080                 *
2081                 * @param int $user_id The current user's ID.
2082                 */
2083                do_action( 'jetpack_unlinked_user', $user_id );
2084
2085                if ( $is_primary_user ) {
2086                    Jetpack_Options::delete_option( 'master_user' );
2087
2088                    // Clear the memoized connection owner ID since it changed
2089                    self::$connection_owner_id = null;
2090                }
2091            }
2092        }
2093
2094        self::$disconnected_users[] = $user_id;
2095
2096        return $is_disconnected_from_wpcom && $is_disconnected_locally;
2097    }
2098
2099    /**
2100     * Request to wpcom for a user to be unlinked from their WordPress.com account
2101     *
2102     * @param int $user_id The user identifier.
2103     *
2104     * @return bool Whether the disconnection of the user was successful.
2105     */
2106    public function unlink_user_from_wpcom( $user_id ) {
2107        // Attempt to disconnect the user from WordPress.com.
2108        $xml = new Jetpack_IXR_Client();
2109
2110        $xml->query( 'jetpack.unlink_user', $user_id );
2111        if ( $xml->isError() ) {
2112            return false;
2113        }
2114
2115        return (bool) $xml->getResponse();
2116    }
2117
2118    /**
2119     * Update the connection owner.
2120     *
2121     * @since 1.29.0
2122     * @since 9.3.0 Refused while ownership is locked.
2123     * @since 9.9.0 The anchored owner passes the lock, and moving the site off them
2124     *                         releases the anchor.
2125     *
2126     * @param int $new_owner_id The ID of the user to become the connection owner.
2127     *
2128     * @return true|WP_Error True if owner successfully changed, WP_Error otherwise.
2129     */
2130    public function update_connection_owner( $new_owner_id ) {
2131        // Answered before the arguments are validated: no candidate is valid while ownership is
2132        // locked, and an argument error would suggest a retry that cannot work.
2133        if ( ! $this->is_ownership_transferable() && ! $this->current_user_may_move_locked_ownership() ) {
2134            return new WP_Error(
2135                'ownership_locked',
2136                __( 'The connection owner is locked on this site.', 'jetpack-connection' ),
2137                array( 'status' => 403 )
2138            );
2139        }
2140
2141        $roles = new Roles();
2142        if ( ! user_can( $new_owner_id, $roles->translate_role_to_cap( 'administrator' ) ) ) {
2143            return new WP_Error(
2144                'new_owner_not_admin',
2145                __( 'New owner is not admin', 'jetpack-connection' ),
2146                array( 'status' => 400 )
2147            );
2148        }
2149
2150        $old_owner_id = $this->get_connection_owner_id();
2151
2152        if ( $old_owner_id === $new_owner_id ) {
2153            return new WP_Error(
2154                'new_owner_is_existing_owner',
2155                __( 'New owner is same as existing owner', 'jetpack-connection' ),
2156                array( 'status' => 400 )
2157            );
2158        }
2159
2160        if ( ! $this->is_user_connected( $new_owner_id ) ) {
2161            return new WP_Error(
2162                'new_owner_not_connected',
2163                __( 'New owner is not connected', 'jetpack-connection' ),
2164                array( 'status' => 400 )
2165            );
2166        }
2167
2168        // Notify WPCOM about the connection owner change.
2169        $owner_updated_wpcom = $this->update_connection_owner_wpcom( $new_owner_id );
2170
2171        if ( $owner_updated_wpcom ) {
2172            // Update the connection owner in Jetpack only if they were successfully updated on WPCOM.
2173            // This will ensure consistency with WPCOM.
2174            \Jetpack_Options::update_option( 'master_user', $new_owner_id );
2175
2176            // Clear the memoized connection owner ID since it changed
2177            self::$connection_owner_id = null;
2178
2179            $this->release_anchor_after_transfer( $new_owner_id, $owner_updated_wpcom );
2180
2181            // Track it.
2182            ( new Tracking() )->record_user_event( 'set_connection_owner_success' );
2183
2184            return true;
2185        }
2186        return new WP_Error(
2187            'error_setting_new_owner',
2188            __( 'Could not confirm new owner.', 'jetpack-connection' ),
2189            array( 'status' => 500 )
2190        );
2191    }
2192
2193    /**
2194     * Whether the current user may move the connection despite a locked anchor.
2195     *
2196     * The anchor protects an identity, so the owner it names is the one person it is not against.
2197     *
2198     * A local hint rather than proof of who that is: the binding is not unique site-wide, and the
2199     * anchored owner is often not the connection owner here â€” taking a site back from an agency is
2200     * the point â€” so there is no stronger identity to check. WordPress.com decides, marking a
2201     * switch `po_signed` only when the signing token belongs to the owner of record.
2202     *
2203     * @since 9.9.0
2204     * @since 9.11.0 No longer refused by the deprecated `jetpack_connection_ownership_transferable` filter.
2205     *
2206     * @return bool
2207     */
2208    private function current_user_may_move_locked_ownership() {
2209        $anchor  = Protected_Owner::get_locked();
2210        $user_id = get_current_user_id();
2211
2212        if ( ! $anchor || ! $user_id ) {
2213            return false;
2214        }
2215
2216        // Both halves, as everywhere else the binding is trusted: it outlives the token, so a
2217        // disconnected user can still carry the anchored ID.
2218        if ( ! $this->is_user_connected( $user_id ) ) {
2219            return false;
2220        }
2221
2222        // This user's own binding, never a search for whoever holds the anchored ID, which would
2223        // hand the site to the first match.
2224        return Utils::get_wpcom_user_id( $user_id ) === (int) $anchor['wpcom_user_id'];
2225    }
2226
2227    /**
2228     * Drop the anchor once the site has left the owner it names.
2229     *
2230     * Do not make this clear more eagerly. An anchor dropped while WordPress.com kept its own
2231     * locks the site to nobody, and `reconcile_protected_owner()` returns before asking when
2232     * there is no local anchor left to repair it with. The reverse mistake costs nothing.
2233     *
2234     * @since 9.9.0
2235     *
2236     * @param int        $new_owner_id The local user who now holds the connection.
2237     * @param true|array $accepted     What WordPress.com answered the switch with: a report of
2238     *                                 what it did where available, otherwise a bare `true`.
2239     */
2240    private function release_anchor_after_transfer( $new_owner_id, $accepted ) {
2241        $anchor = Protected_Owner::get_locked();
2242
2243        if ( ! $anchor ) {
2244            return;
2245        }
2246
2247        // WordPress.com resolves the new owner itself and knows what it kept, so where it reports
2248        // what it did, that report is the whole answer.
2249        if ( is_array( $accepted ) ) {
2250            if ( ! empty( $accepted['released'] ) ) {
2251                Protected_Owner::clear();
2252            }
2253
2254            return;
2255        }
2256
2257        // A bare `true` says only that the switch happened, leaving who the site went to as the
2258        // best guess available. A zero is "could not determine", which covers the owner taking the
2259        // site back â€” the case WordPress.com keeps its record for.
2260        $new_owner_wpcom_id = $this->resolve_wpcom_user_id( $new_owner_id );
2261
2262        if ( $new_owner_wpcom_id && $new_owner_wpcom_id !== (int) $anchor['wpcom_user_id'] ) {
2263            Protected_Owner::clear();
2264        }
2265    }
2266
2267    /**
2268     * Request to WPCOM to update the connection owner.
2269     *
2270     * @since 1.29.0
2271     * @since 9.9.0 Returns what WordPress.com answered rather than casting it, so a
2272     *                         report of what the switch did can be read. Still falsy on failure.
2273     *
2274     * @param int $new_owner_id The ID of the user to become the connection owner.
2275     *
2276     * @return bool|array False if the transfer failed, otherwise what WordPress.com answered:
2277     *                    `true`, or a non-empty report such as `array( 'released' => bool )`.
2278     */
2279    public function update_connection_owner_wpcom( $new_owner_id ) {
2280        // Notify WPCOM about the connection owner change.
2281        $xml = new Jetpack_IXR_Client(
2282            array(
2283                'user_id' => get_current_user_id(),
2284            )
2285        );
2286        $xml->query(
2287            'jetpack.switchBlogOwner',
2288            array(
2289                'new_blog_owner' => $new_owner_id,
2290            )
2291        );
2292        if ( $xml->isError() ) {
2293            return false;
2294        }
2295
2296        $response = $xml->getResponse();
2297
2298        // An array is the switch reporting what it did, and an empty one reports nothing rather
2299        // than refusing â€” a bare `true` by another name. Only a falsy non-array is a refusal.
2300        if ( is_array( $response ) ) {
2301            return empty( $response ) ? true : $response;
2302        }
2303
2304        return (bool) $response;
2305    }
2306
2307    /**
2308     * Returns the requested Jetpack API URL.
2309     *
2310     * @param string $relative_url the relative API path.
2311     * @return string API URL.
2312     */
2313    public function api_url( $relative_url ) {
2314        $api_base    = Constants::get_constant( 'JETPACK__API_BASE' );
2315        $api_version = '/' . Constants::get_constant( 'JETPACK__API_VERSION' ) . '/';
2316
2317        /**
2318         * Filters the API URL that Jetpack uses for server communication.
2319         *
2320         * @since 1.7.0
2321         * @since-jetpack 8.0.0
2322         *
2323         * @param string $url the generated URL.
2324         * @param string $relative_url the relative URL that was passed as an argument.
2325         * @param string $api_base the API base string that is being used.
2326         * @param string $api_version the API version string that is being used.
2327         */
2328        return apply_filters(
2329            'jetpack_api_url',
2330            rtrim( $api_base . $relative_url, '/\\' ) . $api_version,
2331            $relative_url,
2332            $api_base,
2333            $api_version
2334        );
2335    }
2336
2337    /**
2338     * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
2339     *
2340     * @return string XMLRPC API URL.
2341     */
2342    public function xmlrpc_api_url() {
2343        $base = preg_replace(
2344            '#(https?://[^?/]+)(/?.*)?$#',
2345            '\\1',
2346            Constants::get_constant( 'JETPACK__API_BASE' )
2347        );
2348        return untrailingslashit( $base ) . '/xmlrpc.php';
2349    }
2350
2351    /**
2352     * Attempts Jetpack registration which sets up the site for connection. Should
2353     * remain public because the call to action comes from the current site, not from
2354     * WordPress.com.
2355     *
2356     * Always attempts: the retry gate and the offline mode check live in
2357     * `try_registration()`, so unattended callers must go through that instead.
2358     *
2359     * @param string $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
2360     * @return true|WP_Error The error object.
2361     */
2362    public function register( $api_endpoint = 'register' ) {
2363        $this->last_register_response = null;
2364
2365        $result = $this->do_register( $api_endpoint );
2366
2367        if ( is_wp_error( $result ) ) {
2368            Registration_Failure::record(
2369                $result,
2370                $this->last_register_response,
2371                $this->get_plugin_slug()
2372            );
2373        } else {
2374            Registration_Failure::clear();
2375        }
2376
2377        $this->last_register_response = null;
2378
2379        return $result;
2380    }
2381
2382    /**
2383     * Perform the registration request and store the resulting connection data.
2384     *
2385     * @see Manager::register()
2386     *
2387     * @param string $api_endpoint An API endpoint to use.
2388     * @return true|WP_Error The error object.
2389     */
2390    private function do_register( $api_endpoint ) {
2391        // Clean-up leftover tokens just in-case.
2392        // This fixes an edge case that was preventing users to register when the blog token was missing but
2393        // there were still leftover user tokens present.
2394        $this->delete_all_connection_tokens( true );
2395
2396        add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
2397        $secrets = ( new Secrets() )->generate( 'register', get_current_user_id(), 600 );
2398
2399        if ( false === $secrets ) {
2400            return new WP_Error( 'cannot_save_secrets', __( 'Jetpack experienced an issue trying to save options (cannot_save_secrets). We suggest that you contact your hosting provider, and ask them for help checking that the options table is writable on your site.', 'jetpack-connection' ) );
2401        }
2402
2403        if (
2404            empty( $secrets['secret_1'] ) ||
2405            empty( $secrets['secret_2'] ) ||
2406            empty( $secrets['exp'] )
2407        ) {
2408            return new \WP_Error( 'missing_secrets' );
2409        }
2410
2411        // Better to try (and fail) to set a higher timeout than this system
2412        // supports than to have register fail for more users than it should.
2413        $timeout = $this->set_min_time_limit( 60 ) / 2;
2414
2415        $gmt_offset = get_option( 'gmt_offset' );
2416        if ( ! $gmt_offset ) {
2417            $gmt_offset = 0;
2418        }
2419
2420        $stats_options = get_option( 'stats_options' );
2421        $stats_id      = $stats_options['blog_id'] ?? null;
2422
2423        /* This action is documented in src/class-package-version-tracker.php */
2424        $package_versions = apply_filters( 'jetpack_package_versions', array() );
2425
2426        $active_plugins_using_connection = Plugin_Storage::get_all();
2427
2428        /**
2429         * Filters the request body for additional property addition.
2430         *
2431         * @since 1.7.0
2432         * @since-jetpack 7.7.0
2433         *
2434         * @param array $post_data request data.
2435         * @param Array $token_data token data.
2436         */
2437        $body = apply_filters(
2438            'jetpack_register_request_body',
2439            array_merge(
2440                array(
2441                    'siteurl'                  => Urls::site_url(),
2442                    'home'                     => Urls::home_url(),
2443                    'gmt_offset'               => $gmt_offset,
2444                    'timezone_string'          => (string) get_option( 'timezone_string' ),
2445                    'site_name'                => (string) get_option( 'blogname' ),
2446                    'secret_1'                 => $secrets['secret_1'],
2447                    'secret_2'                 => $secrets['secret_2'],
2448                    'site_lang'                => get_locale(),
2449                    'timeout'                  => $timeout,
2450                    'stats_id'                 => $stats_id,
2451                    'state'                    => get_current_user_id(),
2452                    'site_created'             => $this->get_assumed_site_creation_date(),
2453                    'jetpack_version'          => Constants::get_constant( 'JETPACK__VERSION' ),
2454                    'ABSPATH'                  => Constants::get_constant( 'ABSPATH' ),
2455                    'current_user_email'       => wp_get_current_user()->user_email,
2456                    'connect_plugin'           => $this->get_plugin_slug(),
2457                    'package_versions'         => $package_versions,
2458                    'active_connected_plugins' => $active_plugins_using_connection,
2459                ),
2460                self::$extra_register_params
2461            )
2462        );
2463
2464        $args = array(
2465            'method'  => 'POST',
2466            'body'    => $body,
2467            'headers' => array(
2468                'Accept' => 'application/json',
2469            ),
2470            'timeout' => $timeout,
2471        );
2472
2473        $args['body'] = static::apply_activation_source_to_args( $args['body'] );
2474
2475        // TODO: fix URLs for bad hosts.
2476        $response = Client::_wp_remote_request(
2477            $this->api_url( $api_endpoint ),
2478            $args,
2479            true
2480        );
2481
2482        // Kept so that ::register() can read response headers such as `Retry-After`
2483        // when recording the failure.
2484        $this->last_register_response = $response;
2485
2486        // Make sure the response is valid and does not contain any Jetpack errors.
2487        $registration_details = $this->validate_remote_register_response( $response );
2488
2489        if ( is_wp_error( $registration_details ) ) {
2490            return $registration_details;
2491        } elseif ( ! $registration_details ) {
2492            return new \WP_Error(
2493                'unknown_error',
2494                'Unknown error registering your Jetpack site.',
2495                wp_remote_retrieve_response_code( $response )
2496            );
2497        }
2498
2499        if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
2500            return new \WP_Error(
2501                'jetpack_secret',
2502                'Unable to validate registration of your Jetpack site.',
2503                wp_remote_retrieve_response_code( $response )
2504            );
2505        }
2506
2507        if ( isset( $registration_details->jetpack_public ) ) {
2508            $jetpack_public = (int) $registration_details->jetpack_public;
2509        } else {
2510            $jetpack_public = false;
2511        }
2512
2513        Jetpack_Options::update_options(
2514            array(
2515                'id'     => (int) $registration_details->jetpack_id,
2516                'public' => $jetpack_public,
2517            )
2518        );
2519
2520        update_option( Package_Version_Tracker::PACKAGE_VERSION_OPTION, $package_versions );
2521
2522        $this->get_tokens()->update_blog_token( (string) $registration_details->jetpack_secret );
2523
2524        if ( ! Jetpack_Options::get_option( 'id' ) || ! $this->get_tokens()->get_access_token() ) {
2525            return new WP_Error(
2526                'connection_data_save_failed',
2527                'Failed to save connection data in the database'
2528            );
2529        }
2530
2531        $alternate_authorization_url = $registration_details->alternate_authorization_url ?? '';
2532
2533        add_filter(
2534            'jetpack_register_site_rest_response',
2535            function ( $response ) use ( $alternate_authorization_url ) {
2536                $response['alternateAuthorizeUrl'] = $alternate_authorization_url;
2537                return $response;
2538            }
2539        );
2540
2541        /**
2542         * Fires when a site is registered on WordPress.com.
2543         *
2544         * @since 1.7.0
2545         * @since-jetpack 3.7.0
2546         *
2547         * @param int $json->jetpack_id Jetpack Blog ID.
2548         * @param string $json->jetpack_secret Jetpack Blog Token.
2549         * @param int|bool $jetpack_public Is the site public.
2550         */
2551        do_action(
2552            'jetpack_site_registered',
2553            $registration_details->jetpack_id,
2554            $registration_details->jetpack_secret,
2555            $jetpack_public
2556        );
2557
2558        if ( isset( $registration_details->token ) ) {
2559            /**
2560             * Fires when a user token is sent along with the registration data.
2561             *
2562             * @since 1.7.0
2563             * @since-jetpack 7.6.0
2564             *
2565             * @param object $token the administrator token for the newly registered site.
2566             */
2567            do_action( 'jetpack_site_registered_user_token', $registration_details->token );
2568        }
2569
2570        return true;
2571    }
2572
2573    /**
2574     * Attempts Jetpack registration.
2575     *
2576     * Automatic attempts are skipped in offline mode and held back while a previous
2577     * failure still stands. Pass `$force` for attempts a user or partner explicitly
2578     * asked for - those are never held back.
2579     *
2580     * @see Registration_Failure
2581     *
2582     * @since 9.11.0 Added the `$force` parameter, the offline mode check, and the retry backoff.
2583     *
2584     * @param bool $tos_agree Whether the user agreed to TOS.
2585     * @param bool $force     Whether this attempt was explicitly requested by a user.
2586     *
2587     * @return bool|WP_Error
2588     */
2589    public function try_registration( $tos_agree = true, $force = false ) {
2590        if ( ! $force ) {
2591            if ( ( new Status() )->is_offline_mode() ) {
2592                return new WP_Error(
2593                    'offline_mode',
2594                    __( 'Site is in offline mode; WordPress.com registration is not attempted.', 'jetpack-connection' ),
2595                    array( 'status' => 400 )
2596                );
2597            }
2598
2599            $suppressed_error = Registration_Failure::get_suppressed_error();
2600
2601            if ( $suppressed_error ) {
2602                Registration_Failure::record_suppressed_attempt(
2603                    $suppressed_error,
2604                    $this->get_plugin_slug()
2605                );
2606
2607                return $suppressed_error;
2608            }
2609        }
2610
2611        if ( $tos_agree ) {
2612            $terms_of_service = new Terms_Of_Service();
2613            $terms_of_service->agree();
2614        }
2615
2616        /**
2617         * Action fired when the user attempts the registration.
2618         *
2619         * @since 1.26.0
2620         */
2621        $pre_register = apply_filters( 'jetpack_pre_register', null );
2622
2623        if ( is_wp_error( $pre_register ) ) {
2624            return $pre_register;
2625        }
2626
2627        $tracking_data = array();
2628
2629        if ( null !== $this->get_plugin_slug() ) {
2630            $tracking_data['plugin_slug'] = $this->get_plugin_slug();
2631        }
2632
2633        $tracking = new Tracking();
2634        $tracking->record_user_event( 'jpc_register_begin', $tracking_data );
2635
2636        add_filter( 'jetpack_register_request_body', array( Utils::class, 'filter_register_request_body' ) );
2637
2638        $result = $this->register();
2639
2640        remove_filter( 'jetpack_register_request_body', array( Utils::class, 'filter_register_request_body' ) );
2641
2642        // If there was an error with registration and the site was not registered, record this so we can show a message.
2643        if ( ! $result || is_wp_error( $result ) ) {
2644            return $result;
2645        }
2646
2647        return true;
2648    }
2649
2650    /**
2651     * Get the reason the last registration attempt failed, if it still stands.
2652     *
2653     * Lets consuming plugins tell the user why the site is not connected - for
2654     * example that WordPress.com cannot reach a site on a private address - instead
2655     * of leaving the connection silently unavailable.
2656     *
2657     * @since 9.11.0
2658     *
2659     * @return array|null Failure details, or null if the last attempt did not fail or the site is connected.
2660     */
2661    public function get_registration_failure() {
2662        if ( $this->is_connected() ) {
2663            return null;
2664        }
2665
2666        return Registration_Failure::get();
2667    }
2668
2669    /**
2670     * Forget the last registration failure, so the next automatic attempt is not
2671     * held back by it.
2672     *
2673     * For consumers that trigger registration through code that cannot pass the
2674     * `$force` flag to `try_registration()`.
2675     *
2676     * @since 9.11.0
2677     *
2678     * @return void
2679     */
2680    public function clear_registration_failure() {
2681        Registration_Failure::clear();
2682    }
2683
2684    /**
2685     * Get the slug of the plugin this connection is for, if any.
2686     *
2687     * @return string|null
2688     */
2689    private function get_plugin_slug() {
2690        return $this->get_plugin() ? $this->get_plugin()->get_slug() : null;
2691    }
2692
2693    /**
2694     * Adds a parameter to the register request body
2695     *
2696     * @since 1.26.0
2697     *
2698     * @param string $name The name of the parameter to be added.
2699     * @param string $value The value of the parameter to be added.
2700     *
2701     * @throws \InvalidArgumentException If supplied arguments are not strings.
2702     * @return void
2703     */
2704    public function add_register_request_param( $name, $value ) {
2705        if ( ! is_string( $name ) || ! is_string( $value ) ) {
2706            throw new \InvalidArgumentException( 'name and value must be strings' );
2707        }
2708        self::$extra_register_params[ $name ] = $value;
2709    }
2710
2711    /**
2712     * Whether PHP's XML extension, which the XML-RPC connection needs, is available.
2713     *
2714     * @since 9.14.0
2715     *
2716     * @return bool
2717     */
2718    protected function is_xml_extension_available() {
2719        return function_exists( 'xml_parser_create' );
2720    }
2721
2722    /**
2723     * Takes the response from the Jetpack register new site endpoint and
2724     * verifies it worked properly.
2725     *
2726     * @since 1.7.0
2727     * @since-jetpack 2.6.0
2728     *
2729     * @param mixed $response the response object, or the error object.
2730     * @return string|WP_Error A JSON object on success or WP_Error on failures
2731     **/
2732    protected function validate_remote_register_response( $response ) {
2733        if ( is_wp_error( $response ) ) {
2734            return new \WP_Error(
2735                'register_http_request_failed',
2736                $response->get_error_message()
2737            );
2738        }
2739
2740        $code   = wp_remote_retrieve_response_code( $response );
2741        $entity = wp_remote_retrieve_body( $response );
2742
2743        if ( $entity ) {
2744            $registration_response = json_decode( $entity );
2745        } else {
2746            $registration_response = false;
2747        }
2748
2749        $code_type = (int) ( $code / 100 );
2750        if ( 5 === $code_type ) {
2751            return new \WP_Error( 'wpcom_5??', $code );
2752        } elseif ( 408 === $code ) {
2753            return new \WP_Error( 'wpcom_408', $code );
2754        } elseif ( ! empty( $registration_response->error ) ) {
2755            // WordPress.com can't parse the site's XML-RPC reply without PHP's XML extension; name that cause.
2756            if ( 'xml_rpc-32700' === $registration_response->error && ! $this->is_xml_extension_available() ) {
2757                return new \WP_Error(
2758                    'xml_extension_missing',
2759                    __( "PHP's XML extension is not available. Jetpack requires the XML extension to communicate with WordPress.com. Please contact your hosting provider to enable PHP's XML extension.", 'jetpack-connection' ),
2760                    $code
2761                );
2762            }
2763
2764            return new \WP_Error(
2765                (string) $registration_response->error,
2766                isset( $registration_response->error_description ) ? (string) $registration_response->error_description : '',
2767                $code
2768            );
2769        } elseif ( 200 !== $code ) {
2770            return new \WP_Error( 'wpcom_bad_response', $code );
2771        }
2772
2773        // Jetpack ID error block.
2774        if ( empty( $registration_response->jetpack_id ) ) {
2775            return new \WP_Error(
2776                'jetpack_id',
2777                /* translators: %s is an error message string */
2778                sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack-connection' ), $entity ),
2779                $entity
2780            );
2781        } elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
2782            return new \WP_Error(
2783                'jetpack_id',
2784                /* translators: %s is an error message string */
2785                sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack-connection' ), $entity ),
2786                $entity
2787            );
2788        } elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
2789            return new \WP_Error(
2790                'jetpack_id',
2791                /* translators: %s is an error message string */
2792                sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack-connection' ), $entity ),
2793                $entity
2794            );
2795        }
2796
2797        return $registration_response;
2798    }
2799
2800    /**
2801     * Adds a used nonce to a list of known nonces.
2802     *
2803     * @param int    $timestamp the current request timestamp.
2804     * @param string $nonce the nonce value.
2805     * @return bool whether the nonce is unique or not.
2806     *
2807     * @deprecated since 1.24.0
2808     * @see Nonce_Handler::add()
2809     */
2810    public function add_nonce( $timestamp, $nonce ) {
2811        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Nonce_Handler::add' );
2812        return ( new Nonce_Handler() )->add( $timestamp, $nonce );
2813    }
2814
2815    /**
2816     * Cleans nonces that were saved when calling ::add_nonce.
2817     *
2818     * @todo Properly prepare the query before executing it.
2819     *
2820     * @param bool $all whether to clean even non-expired nonces.
2821     *
2822     * @deprecated since 1.24.0
2823     * @see Nonce_Handler::clean_all()
2824     */
2825    public function clean_nonces( $all = false ) {
2826        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Nonce_Handler::clean_all' );
2827        ( new Nonce_Handler() )->clean_all( $all ? PHP_INT_MAX : ( time() - Nonce_Handler::LIFETIME ) );
2828    }
2829
2830    /**
2831     * Sets the Connection custom capabilities.
2832     *
2833     * @param string[] $caps    Array of the user's capabilities.
2834     * @param string   $cap     Capability name.
2835     * @param int      $user_id The user ID.
2836     * @param array    $args    Adds the context to the cap. Typically the object ID.
2837     */
2838    public function jetpack_connection_custom_caps( $caps, $cap, $user_id, $args ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
2839        switch ( $cap ) {
2840            case 'jetpack_connect':
2841            case 'jetpack_reconnect':
2842                $is_offline_mode = ( new Status() )->is_offline_mode();
2843                if ( $is_offline_mode ) {
2844                    $caps = array( 'do_not_allow' );
2845                    break;
2846                }
2847                // Pass through. If it's not offline mode, these should match disconnect.
2848                // Let users disconnect if it's offline mode, just in case things glitch.
2849            case 'jetpack_disconnect':
2850                /**
2851                 * Filters the jetpack_disconnect capability.
2852                 *
2853                 * @since 1.14.2
2854                 *
2855                 * @param array An array containing the capability name.
2856                 */
2857                $caps = apply_filters( 'jetpack_disconnect_cap', array( 'manage_options' ) );
2858                break;
2859            case 'jetpack_connect_user':
2860                $is_offline_mode = ( new Status() )->is_offline_mode();
2861                if ( $is_offline_mode ) {
2862                    $caps = array( 'do_not_allow' );
2863                    break;
2864                }
2865                // With site connections in mind, non-admin users can connect their account only if a connection owner exists.
2866                $caps = $this->has_connected_owner() ? array( 'read' ) : array( 'manage_options' );
2867                break;
2868            case 'jetpack_unlink_user':
2869                $is_offline_mode = ( new Status() )->is_offline_mode();
2870                if ( $is_offline_mode ) {
2871                    $caps = array( 'do_not_allow' );
2872                    break;
2873                }
2874
2875                // Non-admins can always disconnect
2876                $caps = array( 'read' );
2877                break;
2878        }
2879        return $caps;
2880    }
2881
2882    /**
2883     * Builds the timeout limit for queries talking with the wpcom servers.
2884     *
2885     * Based on local php max_execution_time in php.ini
2886     *
2887     * @since 1.7.0
2888     * @since-jetpack 5.4.0
2889     * @return int
2890     **/
2891    public function get_max_execution_time() {
2892        $timeout = (int) ini_get( 'max_execution_time' );
2893
2894        // Ensure exec time set in php.ini.
2895        if ( ! $timeout ) {
2896            $timeout = 30;
2897        }
2898        return $timeout;
2899    }
2900
2901    /**
2902     * Sets a minimum request timeout, and returns the current timeout
2903     *
2904     * @since 1.7.0
2905     * @since-jetpack 5.4.0
2906     * @param int $min_timeout the minimum timeout value.
2907     **/
2908    public function set_min_time_limit( $min_timeout ) {
2909        $timeout = $this->get_max_execution_time();
2910        if ( $timeout < $min_timeout ) {
2911            $timeout = $min_timeout;
2912            set_time_limit( $timeout );
2913        }
2914        return $timeout;
2915    }
2916
2917    /**
2918     * Get our assumed site creation date.
2919     * Calculated based on the earlier date of either:
2920     * - Earliest admin user registration date.
2921     * - Earliest date of post of any post type.
2922     *
2923     * @since 1.7.0
2924     * @since-jetpack 7.2.0
2925     *
2926     * @return string Assumed site creation date and time.
2927     */
2928    public function get_assumed_site_creation_date() {
2929        $cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
2930        if ( ! empty( $cached_date ) ) {
2931            return $cached_date;
2932        }
2933
2934        /**
2935         * We don't use the 'ID' field, but need it to overcome a WP caching bug: https://core.trac.wordpress.org/ticket/62003
2936         *
2937         * @todo Remote the 'ID' field from users fetching when the issue is fixed and Jetpack-supported WP versions move beyond it.
2938         */
2939        $earliest_registered_users  = get_users(
2940            array(
2941                'role'    => 'administrator',
2942                'orderby' => 'user_registered',
2943                'order'   => 'ASC',
2944                'fields'  => array( 'ID', 'user_registered' ),
2945                'number'  => 1,
2946            )
2947        );
2948        $earliest_registration_date = $earliest_registered_users[0]->user_registered;
2949
2950        $earliest_posts = get_posts(
2951            array(
2952                'posts_per_page' => 1,
2953                'post_type'      => 'any',
2954                'post_status'    => 'any',
2955                'orderby'        => 'date',
2956                'order'          => 'ASC',
2957            )
2958        );
2959
2960        // If there are no posts at all, we'll count only on user registration date.
2961        if ( $earliest_posts ) {
2962            $earliest_post_date = $earliest_posts[0]->post_date;
2963        } else {
2964            $earliest_post_date = PHP_INT_MAX;
2965        }
2966
2967        $assumed_date = min( $earliest_registration_date, $earliest_post_date );
2968        set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
2969
2970        return $assumed_date;
2971    }
2972
2973    /**
2974     * Adds the activation source string as a parameter to passed arguments.
2975     *
2976     * @todo Refactor to use rawurlencode() instead of urlencode().
2977     *
2978     * @param array $args arguments that need to have the source added.
2979     * @return array $amended arguments.
2980     */
2981    public static function apply_activation_source_to_args( $args ) {
2982        $activation_source = get_option( 'jetpack_activation_source' );
2983
2984        if ( ! empty( $activation_source[0] ) ) {
2985            // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
2986            $args['_as'] = urlencode( $activation_source[0] );
2987        }
2988
2989        if ( ! empty( $activation_source[1] ) ) {
2990            // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
2991            $args['_ak'] = urlencode( $activation_source[1] );
2992        }
2993
2994        return $args;
2995    }
2996
2997    /**
2998     * Generates two secret tokens and the end of life timestamp for them.
2999     *
3000     * @param string   $action  The action name.
3001     * @param int|bool $user_id The user identifier.
3002     * @param int      $exp     Expiration time in seconds.
3003     */
3004    public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
3005        return ( new Secrets() )->generate( $action, $user_id, $exp );
3006    }
3007
3008    /**
3009     * Returns two secret tokens and the end of life timestamp for them.
3010     *
3011     * @deprecated 1.24.0 Use Automattic\Jetpack\Connection\Secrets->get() instead.
3012     *
3013     * @param string $action  The action name.
3014     * @param int    $user_id The user identifier.
3015     * @return string|array an array of secrets or an error string.
3016     */
3017    public function get_secrets( $action, $user_id ) {
3018        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Secrets->get' );
3019        return ( new Secrets() )->get( $action, $user_id );
3020    }
3021
3022    /**
3023     * Deletes secret tokens in case they, for example, have expired.
3024     *
3025     * @deprecated 1.24.0 Use Automattic\Jetpack\Connection\Secrets->delete() instead.
3026     *
3027     * @param string $action  The action name.
3028     * @param int    $user_id The user identifier.
3029     */
3030    public function delete_secrets( $action, $user_id ) {
3031        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Secrets->delete' );
3032        ( new Secrets() )->delete( $action, $user_id );
3033    }
3034
3035    /**
3036     * Deletes all connection tokens and transients from the local Jetpack site.
3037     * If the plugin object has been provided in the constructor, the function first checks
3038     * whether it's the only active connection.
3039     * If there are any other connections, the function will do nothing and return `false`
3040     * (unless `$ignore_connected_plugins` is set to `true`).
3041     *
3042     * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
3043     *
3044     * @return bool True if disconnected successfully, false otherwise.
3045     */
3046    public function delete_all_connection_tokens( $ignore_connected_plugins = false ) {
3047        // refuse to delete if we're not the last Jetpack plugin installed.
3048        if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
3049            return false;
3050        }
3051
3052        /**
3053         * Fires upon the disconnect attempt.
3054         * Return `false` to prevent the disconnect.
3055         *
3056         * @since 1.14.2
3057         */
3058        if ( ! apply_filters( 'jetpack_connection_delete_all_tokens', true ) ) {
3059            return false;
3060        }
3061
3062        // The protected owner anchor is a local cache of a record WordPress.com owns. Dropping it
3063        // here keeps a disconnected site from carrying a lock that names a user who no longer holds
3064        // a token; the anchor is re-established from WordPress.com when the owner reconnects.
3065        \Jetpack_Options::delete_option(
3066            array(
3067                'master_user',
3068                'protected_owner',
3069                'time_diff',
3070                'fallback_no_verify_ssl_certs',
3071            )
3072        );
3073
3074        // Clear the memoized connection owner ID since it changed
3075        self::$connection_owner_id = null;
3076
3077        ( new Secrets() )->delete_all();
3078        $this->get_tokens()->delete_all();
3079
3080        // Delete cached connected user data.
3081        $transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
3082        delete_transient( $transient_key );
3083
3084        // Delete the cached site record, which a later connection must not serve.
3085        self::delete_cached_site_data();
3086
3087        // Delete all XML-RPC errors.
3088        Error_Handler::get_instance()->delete_all_errors();
3089
3090        return true;
3091    }
3092
3093    /**
3094     * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
3095     * If the plugin object has been provided in the constructor, the function first check
3096     * whether it's the only active connection.
3097     * If there are any other connections, the function will do nothing and return `false`
3098     * (unless `$ignore_connected_plugins` is set to `true`).
3099     *
3100     * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
3101     *
3102     * @return bool True if disconnected successfully, false otherwise.
3103     */
3104    public function disconnect_site_wpcom( $ignore_connected_plugins = false ) {
3105        if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
3106            return false;
3107        }
3108
3109        if ( ( new Status() )->is_offline_mode() && ! apply_filters( 'jetpack_connection_disconnect_site_wpcom_offline_mode', false ) ) {
3110            // Prevent potential disconnect of the live site by removing WPCOM tokens.
3111            return false;
3112        }
3113
3114        /**
3115         * Fires upon the disconnect attempt.
3116         * Return `false` to prevent the disconnect.
3117         *
3118         * @since 1.14.2
3119         */
3120        if ( ! apply_filters( 'jetpack_connection_disconnect_site_wpcom', true, $this ) ) {
3121            return false;
3122        }
3123
3124        $xml = new Jetpack_IXR_Client();
3125        $xml->query( 'jetpack.deregister', get_current_user_id() );
3126
3127        return true;
3128    }
3129
3130    /**
3131     * Disconnect the plugin and remove the tokens.
3132     * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
3133     * This is a proxy method to simplify the Connection package API.
3134     *
3135     * @see Manager::disconnect_site()
3136     *
3137     * @param boolean $disconnect_wpcom Should disconnect_site_wpcom be called.
3138     * @param bool    $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
3139     * @return bool
3140     */
3141    public function remove_connection( $disconnect_wpcom = true, $ignore_connected_plugins = false ) {
3142
3143        $this->disconnect_site( $disconnect_wpcom, $ignore_connected_plugins );
3144
3145        return true;
3146    }
3147
3148    /**
3149     * Completely clearing up the connection, and initiating reconnect.
3150     *
3151     * @return true|WP_Error True if reconnected successfully, a `WP_Error` object otherwise.
3152     */
3153    public function reconnect() {
3154        ( new Tracking() )->record_user_event( 'restore_connection_reconnect' );
3155
3156        $this->disconnect_site_wpcom( true );
3157
3158        return $this->register();
3159    }
3160
3161    /**
3162     * Validate the tokens, and refresh the invalid ones.
3163     *
3164     * Branches on the current user's tokens, not the owner's: a user with no token goes to authorize().
3165     * If both tokens are healthy but the owner has an error, only the current user is relinked.
3166     *
3167     * @since 9.18.0 Relink only the current user when the owner's connection is broken and both tokens are healthy.
3168     * @since 9.8.1 When token validation is inconclusive, check the blog token on its own instead of assuming both are broken.
3169     *
3170     * @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.
3171     */
3172    public function restore() {
3173        // If this is a site connection we need to trigger a full reconnection as our only secure means of
3174        // communication with WPCOM, aka the blog token, is compromised.
3175        if ( $this->is_site_connection() ) {
3176            return $this->reconnect();
3177        }
3178
3179        $validate_tokens_response = $this->get_tokens()->validate();
3180
3181        if ( is_array( $validate_tokens_response ) &&
3182            isset( $validate_tokens_response['blog_token']['is_healthy'] ) &&
3183            isset( $validate_tokens_response['user_token']['is_healthy'] ) ) {
3184            $blog_token_healthy = $validate_tokens_response['blog_token']['is_healthy'];
3185            $user_token_healthy = $validate_tokens_response['user_token']['is_healthy'];
3186        } else {
3187            // The paired health check could not run (a token is missing locally â€” e.g. a
3188            // deleted owner token â€” or the request failed): no evidence the blog token is
3189            // broken, and it's the one credential reconnect() would revoke for every user,
3190            // so check it on its own before that teardown.
3191            $blog_token_healthy = true === $this->get_tokens()->validate_blog_token();
3192            $user_token_healthy = false; // Unknown, treated as unhealthy.
3193        }
3194
3195        // Both healthy, but the owner is recorded as broken: relink only this user, not the whole site.
3196        if ( $blog_token_healthy && $user_token_healthy && $this->can_relink_as_owner() ) {
3197            $this->remember_unusable_owner();
3198            return ( true === $this->refresh_user_token() ) ? 'authorize' : false;
3199        }
3200
3201        // Tokens are both valid, or both invalid. We can't fix the problem we don't see, so the full reconnection is needed.
3202        if ( $blog_token_healthy === $user_token_healthy ) {
3203            $result = $this->reconnect();
3204            return ( true === $result ) ? 'authorize' : $result;
3205        }
3206
3207        if ( ! $blog_token_healthy ) {
3208            return $this->refresh_blog_token();
3209        }
3210
3211        if ( ! $user_token_healthy ) {
3212            $this->remember_unusable_owner();
3213            return ( true === $this->refresh_user_token() ) ? 'authorize' : false;
3214        }
3215
3216        return false;
3217    }
3218
3219    /**
3220     * Whether relinking the current user would repair a recorded broken connection owner.
3221     *
3222     * True when the owner has a recorded error and relinking would make the current user the owner.
3223     * Anyone else would only be linked, so unlinking them would fix nothing.
3224     *
3225     * @since 9.18.0
3226     *
3227     * @return bool
3228     */
3229    private function can_relink_as_owner() {
3230        return $this->has_owner_connection_error() && $this->can_take_owner_slot();
3231    }
3232
3233    /**
3234     * Responds to a WordPress.com call to register the current site.
3235     * Should be changed to protected.
3236     *
3237     * @param array $registration_data Array of [ secret_1, user_id ].
3238     */
3239    public function handle_registration( array $registration_data ) {
3240        list( $registration_secret_1, $registration_user_id ) = $registration_data;
3241        if ( empty( $registration_user_id ) ) {
3242            return new \WP_Error( 'registration_state_invalid', __( 'Invalid Registration State', 'jetpack-connection' ), 400 );
3243        }
3244
3245        return ( new Secrets() )->verify( 'register', $registration_secret_1, (int) $registration_user_id );
3246    }
3247
3248    /**
3249     * Perform the API request to validate the blog and user tokens.
3250     *
3251     * @deprecated 1.24.0 Use Automattic\Jetpack\Connection\Tokens->validate_tokens() instead.
3252     *
3253     * @param int|null $user_id ID of the user we need to validate token for. Current user's ID by default.
3254     *
3255     * @return array|false|WP_Error The API response: `array( 'blog_token_is_healthy' => true|false, 'user_token_is_healthy' => true|false )`.
3256     */
3257    public function validate_tokens( $user_id = null ) {
3258        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Tokens->validate' );
3259        return $this->get_tokens()->validate( $user_id );
3260    }
3261
3262    /**
3263     * Verify a Previously Generated Secret.
3264     *
3265     * @deprecated 1.24.0 Use Automattic\Jetpack\Connection\Secrets->verify() instead.
3266     *
3267     * @param string $action   The type of secret to verify.
3268     * @param string $secret_1 The secret string to compare to what is stored.
3269     * @param int    $user_id  The user ID of the owner of the secret.
3270     * @return \WP_Error|string WP_Error on failure, secret_2 on success.
3271     */
3272    public function verify_secrets( $action, $secret_1, $user_id ) {
3273        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Secrets->verify' );
3274        return ( new Secrets() )->verify( $action, $secret_1, $user_id );
3275    }
3276
3277    /**
3278     * Responds to a WordPress.com call to authorize the current user.
3279     * Should be changed to protected.
3280     */
3281    public function handle_authorization() {
3282    }
3283
3284    /**
3285     * Obtains the auth token.
3286     *
3287     * @param array $data The request data.
3288     * @return object|\WP_Error Returns the auth token on success.
3289     *                          Returns a \WP_Error on failure.
3290     */
3291    public function get_token( $data ) {
3292        return $this->get_tokens()->get( $data, $this->api_url( 'token' ) );
3293    }
3294
3295    /**
3296     * Builds a URL to the Jetpack connection auth page.
3297     *
3298     * @since 2.7.6 Added optional $from and $raw parameters.
3299     *
3300     * @param WP_User|null $user     (optional) defaults to the current logged in user.
3301     * @param string|null  $redirect (optional) a redirect URL to use instead of the default.
3302     * @param bool|string  $from     If not false, adds 'from=$from' param to the connect URL.
3303     * @param bool         $raw If true, URL will not be escaped.
3304     *
3305     * @return string Connect URL.
3306     */
3307    public function get_authorization_url( $user = null, $redirect = null, $from = false, $raw = false ) {
3308        if ( empty( $user ) ) {
3309            $user = wp_get_current_user();
3310        }
3311
3312        $roles       = new Roles();
3313        $role        = $roles->translate_user_to_role( $user );
3314        $signed_role = $this->get_tokens()->sign_role( $role );
3315
3316        /**
3317         * Filter the URL of the first time the user gets redirected back to your site for connection
3318         * data processing.
3319         *
3320         * @since 1.7.0
3321         * @since-jetpack 8.0.0
3322         *
3323         * @param string $redirect_url Defaults to the site admin URL.
3324         */
3325        $processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
3326
3327        /**
3328         * Filter the URL to redirect the user back to when the authorization process
3329         * is complete.
3330         *
3331         * @since 1.7.0
3332         * @since-jetpack 8.0.0
3333         *
3334         * @param string $redirect_url Defaults to the site URL.
3335         */
3336        $redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
3337
3338        $secrets = ( new Secrets() )->generate( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
3339
3340        /**
3341         * Filter the type of authorization.
3342         * 'calypso' completes authorization on wordpress.com/jetpack/connect
3343         * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
3344         *
3345         * @since 1.7.0
3346         * @since-jetpack 4.3.3
3347         *
3348         * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
3349         */
3350        $auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
3351
3352        $body_args = array(
3353            'response_type'         => 'code',
3354            'client_id'             => \Jetpack_Options::get_option( 'id' ),
3355            'redirect_uri'          => add_query_arg(
3356                array(
3357                    'handler'  => 'jetpack-connection-webhooks',
3358                    'action'   => 'authorize',
3359                    '_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
3360                    'redirect' => $redirect ? rawurlencode( $redirect ) : false,
3361                ),
3362                esc_url( $processing_url )
3363            ),
3364            'state'                 => $user->ID,
3365            'scope'                 => $signed_role,
3366            'user_email'            => $user->user_email,
3367            'user_login'            => $user->user_login,
3368            'is_active'             => $this->has_connected_owner(), // TODO Deprecate this.
3369            'jp_version'            => (string) Constants::get_constant( 'JETPACK__VERSION' ),
3370            'auth_type'             => $auth_type,
3371            'secret'                => $secrets['secret_1'],
3372            'blogname'              => get_option( 'blogname' ),
3373            'site_url'              => Urls::site_url(),
3374            'home_url'              => Urls::home_url(),
3375            'site_icon'             => get_site_icon_url(),
3376            'site_lang'             => get_locale(),
3377            'site_created'          => $this->get_assumed_site_creation_date(),
3378            'allow_site_connection' => ! $this->has_connected_owner(),
3379            'calypso_env'           => ( new Host() )->get_calypso_env(),
3380            'source'                => ( new Host() )->get_source_query(),
3381        );
3382
3383        // Include the slugs of every plugin currently using the Jetpack connection so wpcom
3384        // knows which integrations the site is authorizing on behalf of. `Plugin_Storage::get_all()`
3385        // returns a `WP_Error` when called before `plugins_loaded`; in that case we silently skip.
3386        $active_plugins = Plugin_Storage::get_all();
3387        if ( is_array( $active_plugins ) && ! empty( $active_plugins ) ) {
3388            $body_args['plugins'] = implode( ',', array_keys( $active_plugins ) );
3389        }
3390
3391        // Signal to Calypso that the site already has a connection owner so the
3392        // authorize page can show secondary-connection content where appropriate.
3393        if ( $this->has_connected_owner() ) {
3394            $body_args['has_connected_owner'] = true;
3395        }
3396
3397        /**
3398         * Filters the user connection request data for additional property addition.
3399         *
3400         * @since 1.7.0
3401         * @since-jetpack 8.0.0
3402         *
3403         * @param array $request_data request data.
3404         */
3405        $body = apply_filters( 'jetpack_connect_request_body', $body_args );
3406
3407        $body = static::apply_activation_source_to_args( urlencode_deep( $body ) );
3408
3409        $api_url = $this->api_url( 'authorize' );
3410
3411        $url = add_query_arg( $body, $api_url );
3412
3413        if ( is_network_admin() ) {
3414            $url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
3415        }
3416
3417        if ( $from ) {
3418            $url = add_query_arg( 'from', $from, $url );
3419        }
3420
3421        if ( $raw ) {
3422            $url = esc_url_raw( $url );
3423        }
3424
3425        /**
3426         * Filter the URL used when connecting a user to a WordPress.com account.
3427         *
3428         * @since 2.0.0
3429         * @since 2.7.6 Added $raw parameter.
3430         *
3431         * @param string $url Connection URL.
3432         * @param bool   $raw If true, URL will not be escaped.
3433         */
3434        return apply_filters( 'jetpack_build_authorize_url', $url, $raw );
3435    }
3436
3437    /**
3438     * Authorizes the user by obtaining and storing the user token.
3439     *
3440     * When ownership is transferable, the token request claims the owner slot, and a `connection_owner`
3441     * answer from WordPress.com decides the owner. Without an answer, a user with `jetpack_connect`
3442     * takes a vacant slot, unless a lock protects a recorded owner (see can_fill_unconnected_owner_slot()).
3443     * Anyone else is linked as a secondary user.
3444     *
3445     * @since 9.8.1 Only a user with `jetpack_connect` can take a vacant connection owner slot.
3446     * @since 9.18.0 Claim the owner slot, let WordPress.com's answer decide the owner, and stop replacing a locked owner with an unusable token.
3447     *
3448     * @param array $data The request data.
3449     * @return string|\WP_Error 'authorized' when the user is now the connection owner, 'linked'
3450     *                          when connected as a secondary user, or a \WP_Error on failure.
3451     */
3452    public function authorize( $data = array() ) {
3453        /**
3454         * Action fired when user authorization starts.
3455         *
3456         * @since 1.7.0
3457         * @since-jetpack 8.0.0
3458         */
3459        do_action( 'jetpack_authorize_starting' );
3460
3461        $roles = new Roles();
3462        $role  = $roles->translate_current_user_to_role();
3463
3464        if ( ! $role ) {
3465            return new \WP_Error( 'no_role', 'Invalid request.', 400 );
3466        }
3467
3468        $cap = $roles->translate_role_to_cap( $role );
3469        if ( ! $cap ) {
3470            return new \WP_Error( 'no_cap', 'Invalid request.', 400 );
3471        }
3472
3473        // The role passes on its name alone; check the capability `Tokens::get()` will require before WordPress.com issues a token.
3474        if ( ! current_user_can( $cap ) ) {
3475            return new \WP_Error( 'current_user_cannot', 'The current user lacks the capability required for their role.', 400 );
3476        }
3477
3478        if ( ! empty( $data['error'] ) ) {
3479            return new \WP_Error( $data['error'], 'Error included in the request.', 400 );
3480        }
3481
3482        if ( ! isset( $data['state'] ) ) {
3483            return new \WP_Error( 'no_state', 'Request must include state.', 400 );
3484        }
3485
3486        if ( ! ctype_digit( $data['state'] ) ) {
3487            return new \WP_Error( $data['error'], 'State must be an integer.', 400 );
3488        }
3489
3490        $current_user_id = get_current_user_id();
3491        if ( $current_user_id !== (int) $data['state'] ) {
3492            return new \WP_Error( 'wrong_state', 'State does not match current user.', 400 );
3493        }
3494
3495        if ( empty( $data['code'] ) ) {
3496            return new \WP_Error( 'no_code', 'Request must include an authorization code.', 400 );
3497        }
3498
3499        // Only a user who may manage the site connection can own it; others link as secondary users.
3500        $can_manage_connection = current_user_can( 'jetpack_connect' );
3501        $recorded_owner_id     = (int) \Jetpack_Options::get_option( 'master_user' );
3502
3503        // A locked site never claims, so WordPress.com leaves the owner to the site's own rule.
3504        $send_owner_claim = $can_manage_connection && $this->is_ownership_transferable();
3505        $owner_claim      = $send_owner_claim ? array(
3506            'owner_claim'          => 1,
3507            // Read before the token write, which clears the stored errors this reads.
3508            'local_owner_unusable' => $this->is_owner_slot_unusable() ? 1 : 0,
3509        ) : array();
3510
3511        $token_details = null;
3512        $token         = $this->get_tokens()->get(
3513            $data,
3514            $this->api_url( 'token' ),
3515            $owner_claim,
3516            $token_details
3517        );
3518
3519        if ( is_wp_error( $token ) ) {
3520            $code = $token->get_error_code();
3521            if ( empty( $code ) ) {
3522                $code = 'invalid_token';
3523            }
3524            return new \WP_Error( $code, $token->get_error_message(), 400 );
3525        }
3526
3527        if ( ! $token ) {
3528            return new \WP_Error( 'no_token', 'Error generating token.', 400 );
3529        }
3530
3531        // WordPress.com answers only a claim it doesn't block; without an answer, fall back to the vacant-slot rule.
3532        $wpcom_answer        = $send_owner_claim && is_array( $token_details ) && isset( $token_details['connection_owner'] ) ? (bool) $token_details['connection_owner'] : null;
3533        $wpcom_decided       = null !== $wpcom_answer;
3534        $is_connection_owner = $wpcom_decided
3535            ? $wpcom_answer
3536            : $can_manage_connection && ! $this->has_connected_owner() && $this->can_fill_unconnected_owner_slot( $current_user_id );
3537        $owner_changed       = $is_connection_owner && $recorded_owner_id && $recorded_owner_id !== $current_user_id;
3538
3539        $this->get_tokens()->update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_connection_owner );
3540
3541        // Kept until the token request succeeds, so a failed one can retry with it. update_user_token() returns no usable result.
3542        delete_user_option( $current_user_id, self::RELINK_OWNER_UNUSABLE_META );
3543
3544        if ( $owner_changed ) {
3545            // The owner changed under the memoized ID.
3546            $this->reset_connection_status();
3547        }
3548
3549        // Delete cached connected user data, so a cached failure from the
3550        // previous (broken) token doesn't linger after reconnecting.
3551        delete_transient( "jetpack_connected_user_data_$current_user_id" );
3552
3553        /**
3554         * Fires after user has successfully received an auth token.
3555         *
3556         * @since 1.7.0
3557         * @since-jetpack 3.9.0
3558         */
3559        do_action( 'jetpack_user_authorized' );
3560
3561        if ( ! $is_connection_owner ) {
3562            /**
3563             * Action fired when a secondary user has been authorized.
3564             *
3565             * @since 1.7.0
3566             * @since-jetpack 8.0.0
3567             */
3568            do_action( 'jetpack_authorize_ending_linked' );
3569            return 'linked';
3570        }
3571
3572        /**
3573         * Action fired when the master user has been authorized.
3574         *
3575         * @since 1.7.0
3576         * @since-jetpack 8.0.0
3577         *
3578         * @param array $data The request data.
3579         */
3580        do_action( 'jetpack_authorize_ending_authorized', $data );
3581
3582        \Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
3583
3584        ( new Nonce_Handler() )->reschedule();
3585
3586        return 'authorized';
3587    }
3588
3589    /**
3590     * Whether this site has no usable connection owner: none recorded, a missing or malformed token, or a token WordPress.com rejected.
3591     *
3592     * WordPress.com can't see a missing owner or a token the site holds but can't use, so the owner claim reports it.
3593     *
3594     * @since 9.18.0
3595     *
3596     * @param int|null $user_id The authorizing user's ID, whose remembered state counts. Defaults to the current user.
3597     * @return bool
3598     */
3599    private function is_owner_slot_unusable( $user_id = null ) {
3600        return ! $this->has_connected_owner() || $this->has_owner_token_rejection() || $this->is_unusable_owner_remembered( $user_id );
3601    }
3602
3603    /**
3604     * Whether connecting or relinking this user would make them the connection owner.
3605     *
3606     * The one rule behind the owner-error notice, Restore's relink and the connect prompt, so their promises match authorize().
3607     * Where WordPress.com answers the claim, it can still refuse one for a blog with a protected owner there.
3608     *
3609     * @since 9.18.0
3610     *
3611     * @param int|null $user_id The user's ID. Defaults to the current user.
3612     * @return bool
3613     */
3614    public function can_take_owner_slot( $user_id = null ) {
3615        $user_id = null === $user_id ? get_current_user_id() : (int) $user_id;
3616
3617        if ( $user_id <= 0 || ! user_can( $user_id, 'jetpack_connect' ) ) {
3618            return false;
3619        }
3620
3621        $owner_id = (int) \Jetpack_Options::get_option( 'master_user' );
3622
3623        // No owner, the owner themselves, or a deleted owner: authorize()'s fallback gives them the slot.
3624        if ( $owner_id <= 0 || $owner_id === $user_id || ! get_userdata( $owner_id ) ) {
3625            return true;
3626        }
3627
3628        if ( ! $this->is_ownership_transferable() ) {
3629            return false;
3630        }
3631
3632        // WordPress.com ignores claims on Atomic and from non-administrator codes, leaving only the local fallback.
3633        $wpcom_answers = ! ( new Host() )->is_woa_site()
3634            && 'administrator' === ( new Roles() )->translate_user_to_role( get_userdata( $user_id ) );
3635
3636        return $wpcom_answers ? $this->is_owner_slot_unusable( $user_id ) : ! $this->has_connected_owner();
3637    }
3638
3639    /**
3640     * Records for the current user that the owner is unusable, before a Restore relink clears the evidence.
3641     *
3642     * Unlinking deletes every stored error, so authorize() would otherwise report a usable owner.
3643     * The record is tied to the owner's token, so the owner reconnecting voids every user's record at once.
3644     *
3645     * @since 9.18.0
3646     */
3647    private function remember_unusable_owner() {
3648        $user_id = get_current_user_id();
3649
3650        // The evidence alone, so a remembered record can't renew itself.
3651        if ( $user_id && ( ! $this->has_connected_owner() || $this->has_owner_token_rejection() ) ) {
3652            update_user_option(
3653                $user_id,
3654                self::RELINK_OWNER_UNUSABLE_META,
3655                array(
3656                    'owner' => (int) \Jetpack_Options::get_option( 'master_user' ),
3657                    'token' => $this->get_owner_token_hash(),
3658                    'time'  => time(),
3659                )
3660            );
3661        }
3662    }
3663
3664    /**
3665     * A hash of the connection owner's stored token, or an empty string when there is none.
3666     *
3667     * @since 9.18.0
3668     *
3669     * @return string
3670     */
3671    private function get_owner_token_hash() {
3672        $owner_id = (int) \Jetpack_Options::get_option( 'master_user' );
3673        $tokens   = $this->get_tokens()->get_user_tokens();
3674
3675        return $owner_id > 0 && is_array( $tokens ) && ! empty( $tokens[ $owner_id ] ) && is_string( $tokens[ $owner_id ] )
3676            ? wp_hash( $tokens[ $owner_id ] )
3677            : '';
3678    }
3679
3680    /**
3681     * Whether remember_unusable_owner() recorded the current owner and owner token within the last hour.
3682     *
3683     * @since 9.18.0
3684     *
3685     * @param int|null $user_id The user's ID. Defaults to the current user.
3686     * @return bool
3687     */
3688    private function is_unusable_owner_remembered( $user_id = null ) {
3689        $user_id = null === $user_id ? get_current_user_id() : (int) $user_id;
3690        $record  = $user_id > 0 ? get_user_option( self::RELINK_OWNER_UNUSABLE_META, $user_id ) : null;
3691
3692        return is_array( $record )
3693            && isset( $record['owner'] )
3694            && isset( $record['token'] )
3695            && isset( $record['time'] )
3696            && (int) $record['owner'] === (int) \Jetpack_Options::get_option( 'master_user' )
3697            && hash_equals( $this->get_owner_token_hash(), (string) $record['token'] )
3698            && time() - (int) $record['time'] <= HOUR_IN_SECONDS;
3699    }
3700
3701    /**
3702     * Whether WordPress.com has rejected the owner's token on a request this site signed.
3703     *
3704     * @since 9.18.0
3705     *
3706     * @return bool
3707     */
3708    private function has_owner_token_rejection() {
3709        // A partial update can load this class alongside an Error_Handler that predates the method.
3710        return method_exists( Error_Handler::class, 'has_owner_token_rejection' )
3711            && Error_Handler::get_instance()->has_owner_token_rejection();
3712    }
3713
3714    /**
3715     * Whether the authorizing user may fill an owner slot that has no connected owner.
3716     *
3717     * A recorded owner whose token is missing or malformed is not a connected owner, but a lock must
3718     * still protect them. A deleted owner can never reconnect, so their slot counts as vacant.
3719     *
3720     * @since 9.18.0
3721     *
3722     * @param int $user_id The authorizing user's ID.
3723     * @return bool
3724     */
3725    private function can_fill_unconnected_owner_slot( $user_id ) {
3726        $recorded_owner_id = (int) \Jetpack_Options::get_option( 'master_user' );
3727
3728        return ! $recorded_owner_id
3729            || $recorded_owner_id === $user_id
3730            || ! get_userdata( $recorded_owner_id )
3731            || $this->is_ownership_transferable();
3732    }
3733
3734    /**
3735     * Whether an error on record says the connection owner's own connection is broken.
3736     *
3737     * Covers what has_connected_owner() cannot see: a token that is present but rejected by WordPress.com.
3738     *
3739     * @since 9.18.0
3740     *
3741     * @return bool
3742     */
3743    private function has_owner_connection_error() {
3744        // A partial update can load this class alongside an Error_Handler that predates the method.
3745        return method_exists( Error_Handler::class, 'has_owner_connection_error' )
3746            && Error_Handler::get_instance()->has_owner_connection_error();
3747    }
3748
3749    /**
3750     * Disconnects from the Jetpack servers.
3751     * Forgets all connection details and tells the Jetpack servers to do the same.
3752     *
3753     * @param boolean $disconnect_wpcom Should disconnect_site_wpcom be called.
3754     * @param bool    $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
3755     */
3756    public function disconnect_site( $disconnect_wpcom = true, $ignore_connected_plugins = true ) {
3757        if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
3758            return false;
3759        }
3760
3761        wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3762
3763        ( new Nonce_Handler() )->clean_all();
3764
3765        Heartbeat::init()->deactivate();
3766
3767        /**
3768         * Fires before a site is disconnected.
3769         *
3770         * @since 1.36.3
3771         */
3772        do_action( 'jetpack_site_before_disconnected' );
3773
3774        // If the site is in an IDC because sync is not allowed,
3775        // let's make sure to not disconnect the production site.
3776        if ( $disconnect_wpcom ) {
3777            $tracking = new Tracking();
3778            $tracking->record_user_event( 'disconnect_site', array() );
3779
3780            $this->disconnect_site_wpcom( $ignore_connected_plugins );
3781        }
3782
3783        $this->delete_all_connection_tokens( $ignore_connected_plugins );
3784
3785        // Remove tracked package versions, since they depend on the Jetpack Connection.
3786        delete_option( Package_Version_Tracker::PACKAGE_VERSION_OPTION );
3787
3788        // A failure recorded before the site got connected some other way (a migration, a restore) no longer applies.
3789        Registration_Failure::clear();
3790
3791        $jetpack_unique_connection = \Jetpack_Options::get_option( 'unique_connection' );
3792        if ( $jetpack_unique_connection ) {
3793            // Check then record unique disconnection if site has never been disconnected previously.
3794            if ( - 1 === $jetpack_unique_connection['disconnected'] ) {
3795                $jetpack_unique_connection['disconnected'] = 1;
3796            } else {
3797                if ( 0 === $jetpack_unique_connection['disconnected'] ) {
3798                    $a8c_mc_stats_instance = new A8c_Mc_Stats();
3799                    $a8c_mc_stats_instance->add( 'connections', 'unique-disconnect' );
3800                    $a8c_mc_stats_instance->do_server_side_stats();
3801                }
3802                // increment number of times disconnected.
3803                $jetpack_unique_connection['disconnected'] += 1;
3804            }
3805
3806            \Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3807        }
3808
3809        /**
3810         * Fires when a site is disconnected.
3811         *
3812         * @since 1.30.1
3813         */
3814        do_action( 'jetpack_site_disconnected' );
3815    }
3816
3817    /**
3818     * The Base64 Encoding of the SHA1 Hash of the Input.
3819     *
3820     * @param string $text The string to hash.
3821     * @return string
3822     */
3823    public function sha1_base64( $text ) {
3824        return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
3825    }
3826
3827    /**
3828     * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
3829     *
3830     * @param string $domain The domain to check.
3831     *
3832     * @return bool|WP_Error
3833     */
3834    public function is_usable_domain( $domain ) {
3835
3836        // If it's empty, just fail out.
3837        if ( ! $domain ) {
3838            return new \WP_Error(
3839                'fail_domain_empty',
3840                /* translators: %1$s is a domain name. */
3841                sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack-connection' ), $domain )
3842            );
3843        }
3844
3845        /**
3846         * Skips the usuable domain check when connecting a site.
3847         *
3848         * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
3849         *
3850         * @since 1.7.0
3851         * @since-jetpack 4.1.0
3852         *
3853         * @param bool If the check should be skipped. Default false.
3854         */
3855        if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
3856            return true;
3857        }
3858
3859        // None of the explicit localhosts.
3860        $forbidden_domains = array(
3861            'wordpress.com',
3862            'localhost',
3863            'localhost.localdomain',
3864            'local.wordpress.test',         // VVV pattern.
3865            'local.wordpress-trunk.test',   // VVV pattern.
3866            'src.wordpress-develop.test',   // VVV pattern.
3867            'build.wordpress-develop.test', // VVV pattern.
3868        );
3869        if ( in_array( $domain, $forbidden_domains, true ) ) {
3870            return new \WP_Error(
3871                'fail_domain_forbidden',
3872                sprintf(
3873                    /* translators: %1$s is a domain name. */
3874                    __(
3875                        'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
3876                        'jetpack-connection'
3877                    ),
3878                    $domain
3879                )
3880            );
3881        }
3882
3883        // No .test or .local domains.
3884        if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
3885            return new \WP_Error(
3886                'fail_domain_tld',
3887                sprintf(
3888                    /* translators: %1$s is a domain name. */
3889                    __(
3890                        'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
3891                        'jetpack-connection'
3892                    ),
3893                    $domain
3894                )
3895            );
3896        }
3897
3898        // No WPCOM subdomains.
3899        if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
3900            return new \WP_Error(
3901                'fail_subdomain_wpcom',
3902                sprintf(
3903                    /* translators: %1$s is a domain name. */
3904                    __(
3905                        'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
3906                        'jetpack-connection'
3907                    ),
3908                    $domain
3909                )
3910            );
3911        }
3912
3913        // If PHP was compiled without support for the Filter module (very edge case).
3914        if ( ! function_exists( 'filter_var' ) ) {
3915            // Just pass back true for now, and let wpcom sort it out.
3916            return true;
3917        }
3918
3919        $domain = preg_replace( '#^https?://#', '', untrailingslashit( $domain ) );
3920
3921        if ( filter_var( $domain, FILTER_VALIDATE_IP )
3922            && ! \Automattic\Jetpack\IP\Utils::ip_is_public( $domain )
3923        ) {
3924            return new \WP_Error(
3925                'fail_ip_forbidden',
3926                sprintf(
3927                    /* translators: %1$s is a domain name. */
3928                    __(
3929                        'IP address `%1$s` just failed is_usable_domain check as it is not a public IP address.',
3930                        'jetpack-connection'
3931                    ),
3932                    $domain
3933                )
3934            );
3935        }
3936
3937        return true;
3938    }
3939
3940    /**
3941     * Gets the requested token.
3942     *
3943     * @deprecated 1.24.0 Use Automattic\Jetpack\Connection\Tokens->get_access_token() instead.
3944     *
3945     * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
3946     * @param string|false $token_key If provided, check that the token matches the provided input.
3947     * @param bool|true    $suppress_errors If true, return a falsy value when the token isn't found; When false, return a descriptive WP_Error when the token isn't found.
3948     *
3949     * @return object|false
3950     *
3951     * @see $this->get_tokens()->get_access_token()
3952     */
3953    public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
3954        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Tokens->get_access_token' );
3955        return $this->get_tokens()->get_access_token( $user_id, $token_key, $suppress_errors );
3956    }
3957
3958    /**
3959     * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
3960     * since it is passed by reference to various methods.
3961     * Capture it here so we can verify the signature later.
3962     *
3963     * @param array $methods an array of available XMLRPC methods.
3964     * @return array the same array, since this method doesn't add or remove anything.
3965     */
3966    public function xmlrpc_methods( $methods ) {
3967        $this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'] ?? null;
3968        return $methods;
3969    }
3970
3971    /**
3972     * Resets the raw post data parameter for testing purposes.
3973     */
3974    public function reset_raw_post_data() {
3975        $this->raw_post_data = null;
3976    }
3977
3978    /**
3979     * Registering an additional method.
3980     *
3981     * @param array $methods an array of available XMLRPC methods.
3982     * @return array the amended array in case the method is added.
3983     */
3984    public function public_xmlrpc_methods( $methods ) {
3985        if ( array_key_exists( 'wp.getOptions', $methods ) ) {
3986            $methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
3987        }
3988        return $methods;
3989    }
3990
3991    /**
3992     * Handles a getOptions XMLRPC method call.
3993     *
3994     * @param array $args method call arguments.
3995     * @return array|IXR_Error An amended XMLRPC server options array.
3996     */
3997    public function jetpack_get_options( $args ) {
3998        global $wp_xmlrpc_server;
3999
4000        $wp_xmlrpc_server->escape( $args );
4001
4002        $username = $args[1];
4003        $password = $args[2];
4004
4005        $user = $wp_xmlrpc_server->login( $username, $password );
4006        if ( ! $user ) {
4007            return $wp_xmlrpc_server->error;
4008        }
4009
4010        $options   = array();
4011        $user_data = $this->get_connected_user_data();
4012        if ( is_array( $user_data ) ) {
4013            $options['jetpack_user_id']         = array(
4014                'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack-connection' ),
4015                'readonly' => true,
4016                'value'    => $user_data['ID'],
4017            );
4018            $options['jetpack_user_login']      = array(
4019                'desc'     => __( 'The WP.com username of the connected user', 'jetpack-connection' ),
4020                'readonly' => true,
4021                'value'    => $user_data['login'],
4022            );
4023            $options['jetpack_user_email']      = array(
4024                'desc'     => __( 'The WP.com user email of the connected user', 'jetpack-connection' ),
4025                'readonly' => true,
4026                'value'    => $user_data['email'],
4027            );
4028            $options['jetpack_user_site_count'] = array(
4029                'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack-connection' ),
4030                'readonly' => true,
4031                'value'    => $user_data['site_count'],
4032            );
4033        }
4034        $wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
4035        $args                           = stripslashes_deep( $args );
4036        return $wp_xmlrpc_server->wp_getOptions( $args );
4037    }
4038
4039    /**
4040     * Adds Jetpack-specific options to the output of the XMLRPC options method.
4041     *
4042     * @param array $options standard Core options.
4043     * @return array amended options.
4044     */
4045    public function xmlrpc_options( $options ) {
4046        $jetpack_client_id = false;
4047        if ( $this->is_connected() ) {
4048            $jetpack_client_id = \Jetpack_Options::get_option( 'id' );
4049        }
4050        $options['jetpack_version'] = array(
4051            'desc'     => __( 'Jetpack Plugin Version', 'jetpack-connection' ),
4052            'readonly' => true,
4053            'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
4054        );
4055
4056        $options['jetpack_client_id'] = array(
4057            'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack-connection' ),
4058            'readonly' => true,
4059            'value'    => $jetpack_client_id,
4060        );
4061        return $options;
4062    }
4063
4064    /**
4065     * Resets the saved authentication state in between testing requests.
4066     */
4067    public function reset_saved_auth_state() {
4068        $this->xmlrpc_verification = null;
4069    }
4070
4071    /**
4072     * Sign a user role with the master access token.
4073     * If not specified, will default to the current user.
4074     *
4075     * @access public
4076     *
4077     * @param string $role    User role.
4078     * @param int    $user_id ID of the user.
4079     * @return string Signed user role.
4080     */
4081    public function sign_role( $role, $user_id = null ) {
4082        return $this->get_tokens()->sign_role( $role, $user_id );
4083    }
4084
4085    /**
4086     * Set the plugin instance.
4087     *
4088     * @param Plugin $plugin_instance The plugin instance.
4089     *
4090     * @return $this
4091     */
4092    public function set_plugin_instance( Plugin $plugin_instance ) {
4093        $this->plugin = $plugin_instance;
4094
4095        return $this;
4096    }
4097
4098    /**
4099     * Retrieve the plugin management object.
4100     *
4101     * @return Plugin|null
4102     */
4103    public function get_plugin() {
4104        return $this->plugin;
4105    }
4106
4107    /**
4108     * Get all connected plugins information, excluding those disconnected by user.
4109     * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
4110     * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
4111     * so please make sure not to run the method too early in the code.
4112     *
4113     * @return array|WP_Error
4114     */
4115    public function get_connected_plugins() {
4116        $maybe_plugins = Plugin_Storage::get_all();
4117
4118        if ( $maybe_plugins instanceof WP_Error ) {
4119            return $maybe_plugins;
4120        }
4121
4122        return $maybe_plugins;
4123    }
4124
4125    /**
4126     * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
4127     * Note: this method does not remove any access tokens.
4128     *
4129     * @deprecated since 1.39.0
4130     * @return bool
4131     */
4132    public function disable_plugin() {
4133        return null;
4134    }
4135
4136    /**
4137     * Force plugin reconnect after user-initiated disconnect.
4138     * After its called, the plugin will be allowed to use the connection again.
4139     * Note: this method does not initialize access tokens.
4140     *
4141     * @deprecated since 1.39.0.
4142     * @return bool
4143     */
4144    public function enable_plugin() {
4145        return null;
4146    }
4147
4148    /**
4149     * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
4150     * If no plugin slug was passed into the constructor, always returns true.
4151     *
4152     * @deprecated 1.42.0 This method no longer has a purpose after the removal of the soft disconnect feature.
4153     *
4154     * @return bool
4155     */
4156    public function is_plugin_enabled() {
4157        return true;
4158    }
4159
4160    /**
4161     * Perform the API request to refresh the blog token.
4162     * Note that we are making this request on behalf of the Jetpack master user,
4163     * given they were (most probably) the ones that registered the site at the first place.
4164     *
4165     * @return WP_Error|bool The result of updating the blog_token option.
4166     */
4167    public function refresh_blog_token() {
4168        ( new Tracking() )->record_user_event( 'restore_connection_refresh_blog_token' );
4169
4170        $blog_id = \Jetpack_Options::get_option( 'id' );
4171        if ( ! $blog_id ) {
4172            return new WP_Error( 'site_not_registered', 'Site not registered.' );
4173        }
4174
4175        $url     = sprintf(
4176            '%s/%s/v%s/%s',
4177            Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
4178            'wpcom',
4179            '2',
4180            'sites/' . $blog_id . '/jetpack-refresh-blog-token'
4181        );
4182        $method  = 'POST';
4183        $user_id = get_current_user_id();
4184
4185        $response = Client::remote_request( compact( 'url', 'method', 'user_id' ) );
4186
4187        if ( is_wp_error( $response ) ) {
4188            return new WP_Error( 'refresh_blog_token_http_request_failed', $response->get_error_message() );
4189        }
4190
4191        $code   = wp_remote_retrieve_response_code( $response );
4192        $entity = wp_remote_retrieve_body( $response );
4193
4194        if ( $entity ) {
4195            $json = json_decode( $entity );
4196        } else {
4197            $json = false;
4198        }
4199
4200        if ( 200 !== $code ) {
4201            if ( empty( $json->code ) ) {
4202                return new WP_Error( 'unknown', '', $code );
4203            }
4204
4205            /* translators: Error description string. */
4206            $error_description = isset( $json->message ) ? sprintf( __( 'Error Details: %s', 'jetpack-connection' ), (string) $json->message ) : '';
4207
4208            return new WP_Error( (string) $json->code, $error_description, $code );
4209        }
4210
4211        if ( empty( $json->jetpack_secret ) || ! is_scalar( $json->jetpack_secret ) ) {
4212            return new WP_Error( 'jetpack_secret', '', $code );
4213        }
4214
4215        Error_Handler::get_instance()->delete_all_errors();
4216
4217        return $this->get_tokens()->update_blog_token( (string) $json->jetpack_secret );
4218    }
4219
4220    /**
4221     * Disconnect the user from WP.com, and initiate the reconnect process.
4222     *
4223     * @since 9.8.0 Added the `$force` parameter.
4224     *
4225     * @param bool $force Whether to remove the local token even if WordPress.com does not confirm the unlink.
4226     *                    When false, only the current user's own token is refreshed, never the owner's,
4227     *                    and only over a healthy blog token.
4228     * @return true|string|WP_Error True when forced. Otherwise 'authorize' when the user should authorize again, a `WP_Error` object on failure.
4229     */
4230    public function refresh_user_token( $force = true ) {
4231        $user_id = get_current_user_id();
4232
4233        if ( ! $force ) {
4234            // Unlinking the owner would leave the site without one.
4235            if ( ! $user_id || $this->is_site_connection() || $this->get_connection_owner_id() === $user_id ) {
4236                return new WP_Error(
4237                    'restore_requires_administrator',
4238                    __( 'An administrator needs to restore the Jetpack connection.', 'jetpack-connection' ),
4239                    array( 'status' => 403 )
4240                );
4241            }
4242
4243            // Relinking goes over the blog token, so it must work before anything is unlinked.
4244            $blog_token_health = $this->get_tokens()->validate_blog_token();
4245
4246            if ( is_wp_error( $blog_token_health ) ) {
4247                return new WP_Error(
4248                    'restore_check_failed',
4249                    __( 'The site connection could not be checked. Please try again shortly.', 'jetpack-connection' ),
4250                    array( 'status' => 503 )
4251                );
4252            }
4253
4254            if ( true !== $blog_token_health ) {
4255                return new WP_Error(
4256                    'restore_requires_administrator',
4257                    __( 'The site connection is broken. An administrator needs to restore it before you can reconnect your account.', 'jetpack-connection' ),
4258                    array( 'status' => 409 )
4259                );
4260            }
4261        }
4262
4263        // A forced refresh unlinks even without a stored token, as it always has.
4264        if ( $force || $this->is_user_connected( $user_id ) ) {
4265            ( new Tracking() )->record_user_event( 'restore_connection_refresh_user_token' );
4266
4267            // Unforced, the local token only goes once WordPress.com has unlinked it.
4268            $unlinked = $this->disconnect_user( $force ? null : $user_id, $force, $force );
4269
4270            if ( ! $force && ! $unlinked ) {
4271                return new WP_Error(
4272                    'restore_unlink_failed',
4273                    __( 'Your account could not be disconnected from WordPress.com. Please try again.', 'jetpack-connection' ),
4274                    array( 'status' => 502 )
4275                );
4276            }
4277        }
4278
4279        return $force ? true : 'authorize';
4280    }
4281
4282    /**
4283     * Fetches a signed token.
4284     *
4285     * @deprecated 1.24.0 Use Automattic\Jetpack\Connection\Tokens->get_signed_token() instead.
4286     *
4287     * @param object $token the token.
4288     * @return WP_Error|string a signed token
4289     */
4290    public function get_signed_token( $token ) {
4291        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Tokens->get_signed_token' );
4292        return $this->get_tokens()->get_signed_token( $token );
4293    }
4294
4295    /**
4296     * If the site-level connection is active, add the list of plugins using connection to the heartbeat (except Jetpack itself)
4297     *
4298     * @since 6.11.0 Add the list of Jetpack package versions to the heartbeat.
4299     * @since 8.7.4 Add the missing connection owner and XML-RPC error stats to the heartbeat.
4300     * @since 8.7.9 Add the site environment stats (WordPress/PHP versions, etc.) to the heartbeat.
4301     *
4302     * @param array $stats The Heartbeat stats array.
4303     * @return array $stats
4304     */
4305    public function add_stats_to_heartbeat( $stats ) {
4306
4307        if ( ! $this->is_connected() ) {
4308            return $stats;
4309        }
4310
4311        $active_plugins_using_connection = Plugin_Storage::get_all();
4312        foreach ( array_keys( $active_plugins_using_connection ) as $plugin_slug ) {
4313            if ( 'jetpack' !== $plugin_slug ) {
4314                $stats_group             = isset( $active_plugins_using_connection['jetpack'] ) ? 'combined-connection' : 'standalone-connection';
4315                $stats[ $stats_group ][] = $plugin_slug;
4316            }
4317        }
4318
4319        $stats['jetpack_package_versions'] = apply_filters( 'jetpack_package_versions', array() );
4320
4321        $stats['identitycrisis'] = Identity_Crisis::check_identity_crisis() ? 'yes' : 'no';
4322
4323        // Missing the connection owner?
4324        $stats['missing-owner'] = $this->is_missing_connection_owner();
4325
4326        $xmlrpc_errors = \Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4327        if ( $xmlrpc_errors ) {
4328            $stats['xmlrpc-errors'] = implode( ',', array_keys( $xmlrpc_errors ) );
4329            \Jetpack_Options::delete_option( 'xmlrpc_errors' );
4330        }
4331
4332        // Site environment stats (WordPress/PHP versions, site configuration, etc.).
4333        $stats = array_merge( $stats, Heartbeat::get_environment_stats() );
4334
4335        return $stats;
4336    }
4337
4338    /**
4339     * Records a failed XML-RPC signature verification so it can be reported in the heartbeat.
4340     *
4341     * We don't want to expose a detailed error message about why a request failed
4342     * signature verification, as doing so could leak information. Instead, we track
4343     * that the error occurred via a Jetpack option and send that data back in the
4344     * heartbeat. All this does is record the error code, but it's enough to find trends.
4345     *
4346     * @since 8.7.4
4347     *
4348     * @param \WP_Error $xmlrpc_error The error produced during signature validation.
4349     * @return void
4350     */
4351    public function track_xmlrpc_error( $xmlrpc_error ) {
4352        $code = is_wp_error( $xmlrpc_error )
4353            ? $xmlrpc_error->get_error_code()
4354            : 'should-not-happen';
4355
4356        $xmlrpc_errors = \Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4357        if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4358            // No need to update the option if we already have this code stored.
4359            return;
4360        }
4361        $xmlrpc_errors[ $code ] = true;
4362
4363        \Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
4364    }
4365
4366    /**
4367     * Get the WPCOM or self-hosted site ID.
4368     *
4369     * @param bool $quiet Return null instead of an error.
4370     *
4371     * @return int|WP_Error|null
4372     */
4373    public static function get_site_id( $quiet = false ) {
4374        $is_wpcom = ( defined( 'IS_WPCOM' ) && IS_WPCOM );
4375        $site_id  = $is_wpcom ? get_current_blog_id() : \Jetpack_Options::get_option( 'id' );
4376        if ( ! $site_id ) {
4377            return $quiet
4378                ? null
4379                : new \WP_Error(
4380                    'unavailable_site_id',
4381                    __( 'Sorry, something is wrong with your Jetpack connection.', 'jetpack-connection' ),
4382                    403
4383                );
4384        }
4385        return (int) $site_id;
4386    }
4387
4388    /**
4389     * Check if Jetpack is ready for uninstall cleanup.
4390     *
4391     * @param string $current_plugin_slug The current plugin's slug.
4392     *
4393     * @return bool
4394     */
4395    public static function is_ready_for_cleanup( $current_plugin_slug ) {
4396        $active_plugins = get_option( Plugin_Storage::ACTIVE_PLUGINS_OPTION_NAME );
4397
4398        return empty( $active_plugins ) || ! is_array( $active_plugins )
4399            || ( count( $active_plugins ) === 1 && array_key_exists( $current_plugin_slug, $active_plugins ) );
4400    }
4401}