Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
78.55% covered (warning)
78.55%
1168 / 1487
58.93% covered (warning)
58.93%
66 / 112
CRAP
0.00% covered (danger)
0.00%
0 / 1
Manager
78.55% covered (warning)
78.55%
1168 / 1487
58.93% covered (warning)
58.93%
66 / 112
3501.02
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
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
5.03
 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
8.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     * Drop the stored WordPress.com identity of any user whose token is new: the bound user ID, the
1083     * saved Tracks ID, and the cached user data either would be re-resolved from.
1084     *
1085     * Every path that changes a user's token writes the `user_tokens` option, so this covers
1086     * authorize, remote connect and the REST endpoint alike. A token that is added or replaced can
1087     * name a different WordPress.com account, so any binding it would answer with is unverified. A
1088     * token merely removed leaves the binding correct, and other subsystems store their own meaning
1089     * in the same meta, so removals are left alone.
1090     *
1091     * @internal Hooked on `pre_update_jetpack_option_user_tokens`, which fires before the write.
1092     * @since 9.2.0
1093     * @since $$next-version$$ Also drops the saved Tracks ID and the cached user data.
1094     *
1095     * @param string $name  The option name.
1096     * @param mixed  $value The tokens about to be written.
1097     */
1098    public function unbind_wpcom_user_ids_for_new_tokens( $name, $value ) {
1099        if ( ! is_array( $value ) ) {
1100            return;
1101        }
1102
1103        // A site disconnect deletes the option outright, so the first write back has nothing to
1104        // diff against â€” treat that as every token being new rather than skipping the check.
1105        $previous = \Jetpack_Options::get_option( 'user_tokens' );
1106        $previous = is_array( $previous ) ? $previous : array();
1107
1108        // Iterating the incoming tokens covers a token being added as well as replaced, and skips
1109        // removal for free: a user absent from the new set is never visited.
1110        foreach ( $value as $user_id => $token ) {
1111            if ( ( $previous[ $user_id ] ?? null ) !== $token ) {
1112                Utils::delete_wpcom_user_id( $user_id );
1113                delete_user_meta( $user_id, 'jetpack_tracks_wpcom_id' );
1114                // Otherwise both IDs can be re-resolved from the previous account's cached data.
1115                delete_transient( "jetpack_connected_user_data_$user_id" );
1116            }
1117        }
1118    }
1119
1120    /**
1121     * Drop the cached WordPress.com site record.
1122     *
1123     * A caller that fetched the record by another route holds something newer than the cache can,
1124     * and `jetpack_site_data_fetched` fires on a cached read too. The cached copy has to go, or it
1125     * keeps announcing the older record and undoes what that caller stored.
1126     *
1127     * @since 9.0.0
1128     *
1129     * @return void
1130     */
1131    public static function delete_cached_site_data() {
1132        $site_id = \Jetpack_Options::get_option( 'id' );
1133
1134        if ( $site_id ) {
1135            delete_transient( self::SITE_DATA_TRANSIENT_PREFIX . $site_id );
1136        }
1137    }
1138
1139    /**
1140     * Fetch the site's own record from the WordPress.com `/sites/%d` endpoint.
1141     *
1142     * The result is cached briefly. Every plugin that bundles this package serves this route, and
1143     * the Jetpack dashboard requests it on mount, so an uncached read means a blocking round trip
1144     * per render.
1145     *
1146     * @since 8.10.0
1147     *
1148     * @return object|WP_Error The decoded site record, or an error describing the failure.
1149     */
1150    public function get_connected_site_data() {
1151        $site_id = \Jetpack_Options::get_option( 'id' );
1152
1153        if ( ! $site_id ) {
1154            return new WP_Error( 'site_id_missing', '', array( 'api_error_code' => 'site_id_missing' ) );
1155        }
1156
1157        $sandbox_secret = null;
1158
1159        // An array cookie (`store_sandbox[]=`) carries no secret to send, and `filter_var()` turns
1160        // it into `false`.
1161        if ( isset( $_COOKIE['store_sandbox'] ) && is_string( $_COOKIE['store_sandbox'] ) ) {
1162            // Keep only RFC 6265 cookie-octets so the value cannot break out of the Cookie header.
1163            $sandbox_secret = preg_replace( '/[^\x21-\x7E]|[";,\\\\]/', '', filter_var( wp_unslash( $_COOKIE['store_sandbox'] ) ) );
1164
1165            // An empty cookie, or one the sanitizer strips to nothing, is not a sandbox secret.
1166            // Counting it as one opts the request out of the cache with no sandbox to reach.
1167            if ( '' === $sandbox_secret ) {
1168                $sandbox_secret = null;
1169            }
1170        }
1171
1172        // A sandboxed request must neither read the shared cache nor seed it with sandbox data.
1173        $sandboxed     = null !== $sandbox_secret;
1174        $transient_key = self::SITE_DATA_TRANSIENT_PREFIX . $site_id;
1175
1176        // WordPress.com itself requests this route right after a purchase, for the side effect of
1177        // the `jetpack_site_data_fetched` consumers storing the new plan. Those requests arrive
1178        // signed with a connection token, which no browser request carries. A cached read would
1179        // hand that refresh the pre-purchase record and turn it into a no-op, so a signed request
1180        // always reads from WordPress.com and replaces the cache with the record it fetched.
1181        $signed = Rest_Authentication::is_signed_with_blog_token() || Rest_Authentication::is_signed_with_user_token();
1182
1183        $result = ( $sandboxed || $signed ) ? false : get_transient( $transient_key );
1184
1185        // Only the array shape stored below can be served. A `pre_transient_*` filter or a damaged
1186        // object cache entry can hand back anything, and a non-array would throw on
1187        // `$result['body']` for every request until the entry expired, so it reads as a miss.
1188        if ( ! is_array( $result ) ) {
1189            $result = $this->fetch_connected_site_data( $site_id, $sandbox_secret );
1190
1191            // A signed read that failed must not replace a still-usable cached record with the failure.
1192            if ( ! $sandboxed && ! ( $signed && isset( $result['error'] ) ) ) {
1193                // Failures expire sooner so an outage recovers without waiting out a full success window.
1194                set_transient(
1195                    $transient_key,
1196                    $result,
1197                    isset( $result['error'] ) ? 2 * MINUTE_IN_SECONDS : 5 * MINUTE_IN_SECONDS
1198                );
1199            }
1200        }
1201
1202        if ( isset( $result['error'] ) ) {
1203            return new WP_Error( 'site_data_fetch_failed', '', $result['error'] );
1204        }
1205
1206        /**
1207         * Fires after the site record was served, whether it was fetched or read from the cache.
1208         *
1209         * Consumers that cache anything derived from the record, such as the current plan,
1210         * can refresh it here.
1211         *
1212         * This fires on a cached read too, so a consumer stays in step with every request that
1213         * serves the record rather than only the ones that reached WordPress.com.
1214         *
1215         * The record is passed as an array rather than the object this method returns, so that a
1216         * listener cannot mutate the instance that becomes the REST response.
1217         *
1218         * @since 9.0.0
1219         *
1220         * @param array $record The decoded site record from the WordPress.com `/sites/%d` endpoint.
1221         */
1222        do_action( 'jetpack_site_data_fetched', json_decode( $result['body'], true ) );
1223
1224        return json_decode( $result['body'] );
1225    }
1226
1227    /**
1228     * Request the site record from WordPress.com.
1229     *
1230     * Returns a cacheable array rather than the decoded record so that both outcomes survive a
1231     * round trip through a transient.
1232     *
1233     * @since 9.0.0
1234     *
1235     * @param int         $site_id        The WordPress.com blog ID.
1236     * @param string|null $sandbox_secret Sanitized store sandbox cookie value, or null when not sandboxed.
1237     * @return array Either `array( 'body' => string )` or `array( 'error' => array )`.
1238     */
1239    private function fetch_connected_site_data( $site_id, $sandbox_secret ) {
1240        $args = array( 'headers' => array() );
1241
1242        // Allow use a store sandbox. Internal ref: PCYsg-IA-p2.
1243        if ( null !== $sandbox_secret ) {
1244            $args['headers']['Cookie'] = "store_sandbox=$sandbox_secret;";
1245        }
1246
1247        $response = Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d', $site_id ) . '?force=wpcom', '1.1', $args );
1248        $body     = wp_remote_retrieve_body( $response );
1249        $data     = $body ? json_decode( $body ) : null;
1250
1251        if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
1252            $error_info = array(
1253                'api_error_code' => null,
1254                'api_http_code'  => wp_remote_retrieve_response_code( $response ),
1255            );
1256
1257            if ( is_wp_error( $response ) ) {
1258                $error_info['api_error_code'] = $response->get_error_code() ? wp_strip_all_tags( $response->get_error_code() ) : null;
1259            } elseif ( $data && ! empty( $data->error ) ) {
1260                $error_info['api_error_code'] = is_string( $data->error ) ? wp_strip_all_tags( $data->error ) : null;
1261            }
1262
1263            return array( 'error' => $error_info );
1264        }
1265
1266        if ( ! is_object( $data ) ) {
1267            return array(
1268                'error' => array(
1269                    'api_error_code' => 'invalid_body',
1270                    'api_http_code'  => 200,
1271                ),
1272            );
1273        }
1274
1275        return array( 'body' => $body );
1276    }
1277
1278    /**
1279     * Returns a user object of the connection owner.
1280     *
1281     * @return WP_User|false False if no connection owner found.
1282     */
1283    public function get_connection_owner() {
1284        $user_id = \Jetpack_Options::get_option( 'master_user' );
1285        if ( ! $user_id ) {
1286            return false;
1287        }
1288
1289        // Make sure user is connected.
1290        $user_token = $this->get_tokens()->get_access_token( $user_id );
1291
1292        $connection_owner = false;
1293
1294        if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
1295            $connection_owner = get_userdata( $user_token->external_user_id );
1296        }
1297
1298        // Reporting is best-effort and must never fatal a request running mid-plugin-update:
1299        // skip it when the already-loaded Error_Handler is a stale version predating the factory.
1300        if ( $connection_owner === false && method_exists( Error_Handler::class, 'build_connection_wp_error' ) ) {
1301            Error_Handler::get_instance()->report_error(
1302                Error_Handler::build_connection_wp_error(
1303                    'invalid_connection_owner',
1304                    'Invalid connection owner',
1305                    array( 'token' => '' ),
1306                    'local_state', // Error_Handler::ERROR_TYPE_LOCAL_STATE.
1307                    '', // Local-state errors describe the site's database, not a request, so they have no direction.
1308                    array(
1309                        'user_id'        => $user_id,
1310                        'has_user_token' => (bool) $user_token,
1311                    )
1312                ),
1313                false,
1314                true
1315            );
1316        }
1317
1318        return $connection_owner;
1319    }
1320
1321    /**
1322     * Returns true if the provided user is the Jetpack connection owner.
1323     * If user ID is not specified, the current user will be used.
1324     *
1325     * @param int|bool $user_id the user identifier. False for current user.
1326     * @return bool True the user the connection owner, false otherwise.
1327     */
1328    public function is_connection_owner( $user_id = false ) {
1329        if ( ! $user_id ) {
1330            $user_id = get_current_user_id();
1331        }
1332
1333        return ( (int) $user_id ) === $this->get_connection_owner_id();
1334    }
1335
1336    /**
1337     * Determines whether the connection ownership can be transferred to another user.
1338     *
1339     * The default Jetpack connection uses a transferable ownership model; a set protected owner
1340     * anchor locks it. This is the single chokepoint used both when deciding which
1341     * connection-error CTA to surface and when performing an ownership change.
1342     *
1343     * @since 8.8.0
1344     * @since 9.3.0 A locked protected owner anchor makes ownership non-transferable.
1345     * @since 9.11.0 The `jetpack_connection_ownership_transferable` filter is deprecated.
1346     *
1347     * @return bool True if ownership can be transferred, false if it is locked.
1348     */
1349    public function is_ownership_transferable() {
1350        // Keyed on the anchor, never on has_protected_owner(): an owner who does not match the
1351        // anchor is exactly when ownership must stay locked.
1352        if ( Protected_Owner::is_locked() ) {
1353            return false;
1354        }
1355
1356        /**
1357         * Filters whether the Jetpack connection ownership can be transferred.
1358         *
1359         * Return `false` to lock ownership on a site without a protected owner anchor. The
1360         * anchored owner may still transfer ownership despite this deprecated filter.
1361         *
1362         * @since 8.8.0
1363         * @deprecated 9.11.0 The protected owner anchor is the only supported ownership lock.
1364         *
1365         * @param bool $transferable Whether ownership can be transferred. Default true.
1366         */
1367        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' ) );
1368    }
1369
1370    /**
1371     * Whether a protected owner is required right now.
1372     *
1373     * Evaluated at the moment of the request, not as a standing declaration: a consumer may
1374     * legitimately answer false while it is installed and active â€” running in test mode, say â€”
1375     * and true only at the lifecycle moment that binds something to the owner's identity.
1376     *
1377     * @since 9.3.0
1378     *
1379     * @return bool True if a protected owner is required at this moment. Default false.
1380     */
1381    public function requires_protected_owner() {
1382        /**
1383         * Filters whether a protected owner is required at this moment.
1384         *
1385         * Return `true` at the point a feature is about to bind to the connection owner's
1386         * identity. Answering false at other times is expected and supported.
1387         *
1388         * @since 9.3.0
1389         *
1390         * @param bool $required Whether a protected owner is required. Default false.
1391         */
1392        return (bool) apply_filters( 'jetpack_connection_requires_protected_owner', false );
1393    }
1394
1395    /**
1396     * Whether the connection owner is the protected owner the anchor names.
1397     *
1398     * This is the question consumers gate on before binding anything to the owner's identity.
1399     *
1400     * Reads the binding of the current owner rather than searching for whoever holds the anchored
1401     * ID, so a row on any other user cannot affect the answer. Requiring the owner to hold a live
1402     * token on top of that is what keeps a row written by another subsystem from ever satisfying
1403     * this: both halves are load-bearing, and there are tests for each.
1404     *
1405     * @since 9.3.0
1406     *
1407     * @return bool
1408     */
1409    public function has_protected_owner() {
1410        $anchor = Protected_Owner::get_locked();
1411
1412        if ( ! $anchor ) {
1413            return false;
1414        }
1415
1416        $owner_id = $this->get_connection_owner_id();
1417
1418        if ( ! $owner_id ) {
1419            return false;
1420        }
1421
1422        return $this->resolve_wpcom_user_id( $owner_id ) === (int) $anchor['wpcom_user_id'];
1423    }
1424
1425    /**
1426     * Classify why `has_protected_owner()` answered false, and what would change it.
1427     *
1428     * Deliberately inspects only what the gate inspects â€” the anchor and the current connection
1429     * owner â€” so the two can never disagree about the same site. Anything needing a user search or
1430     * a reachability probe is a different question and is not answered here.
1431     *
1432     * `is_current_user_the_po` reads the current user's own stored binding, never a search for
1433     * whoever holds the anchored ID, so it cannot be confused by a second user carrying the same
1434     * meta, and never costs a network call. It is a hint for copy, not a gate.
1435     *
1436     * @since 9.4.0
1437     *
1438     * @return array{status: string, is_current_user_the_po: bool}
1439     */
1440    public function resolve_protected_owner_state() {
1441        $anchor     = Protected_Owner::get_locked();
1442        $current_id = get_current_user_id();
1443
1444        // Only meaningful against an anchor: with none, there is nothing for the user to be.
1445        // Reads the stored binding rather than resolving it, so classifying a state never costs a
1446        // WordPress.com round trip. An unbound user reads as false and gets the generic copy.
1447        $is_current_user_the_po = $anchor
1448            && Utils::get_wpcom_user_id( $current_id ) === (int) $anchor['wpcom_user_id'];
1449
1450        if ( ! $anchor ) {
1451            $roles = new Roles();
1452
1453            if ( ! current_user_can( 'jetpack_connect' ) || ! current_user_can( $roles->translate_role_to_cap( 'administrator' ) ) ) {
1454                // Eligibility is being an admin, not holding the master slot.
1455                $status = self::PO_STATE_NOT_ELIGIBLE;
1456            } elseif ( ! $this->is_user_connected( $current_id ) ) {
1457                // A WordPress.com identity has to exist before it can be confirmed and locked.
1458                $status = self::PO_STATE_NEEDS_CONNECT_TO_ESTABLISH;
1459            } else {
1460                $status = self::PO_STATE_CAN_ESTABLISH;
1461            }
1462        } else {
1463            $owner_id       = $this->get_connection_owner_id();
1464            $owner_wpcom_id = $owner_id ? $this->resolve_wpcom_user_id( $owner_id ) : 0;
1465
1466            if ( ! $owner_wpcom_id ) {
1467                // A zero is "could not determine", never "does not match", so an owner whose
1468                // identity cannot be confirmed is reported as needing to reconnect, not replaced.
1469                $status = self::PO_STATE_NEEDS_OWNER_RECONNECT;
1470            } elseif ( $owner_wpcom_id !== (int) $anchor['wpcom_user_id'] ) {
1471                // Legitimate, not broken: the first admin to connect takes a vacant master slot,
1472                // so an agency can hold it while the protected owner is away.
1473                $status = self::PO_STATE_NEEDS_DIFFERENT_OWNER;
1474            } else {
1475                $status = self::PO_STATE_RE_EVALUATE;
1476            }
1477        }
1478
1479        return array(
1480            'status'                 => $status,
1481            'is_current_user_the_po' => $is_current_user_the_po,
1482        );
1483    }
1484
1485    /**
1486     * Reconcile this site's protected owner against WordPress.com, which is the owner of record.
1487     *
1488     * Runs at connect, when the site has a fresh user token and an answer is cheap, and only once
1489     * something is anchored: a site with no protected owner asks nothing and behaves as it did
1490     * before this existed. One answer settles the rest â€” whether an owner still exists, whether
1491     * the anchor names them, and whether the user connecting is them â€” so the anchor, the binding
1492     * and the master slot are decided together rather than from two calls that could disagree.
1493     *
1494     * Only an answer moves anything. Unreachable, refused, unimplemented and malformed leave the
1495     * anchor exactly as it was: it was confirmed once, and a request that never arrived is no
1496     * evidence against it.
1497     *
1498     * @internal Hooked on `jetpack_user_authorized`.
1499     * @since 9.8.0
1500     *
1501     * @return bool Whether WordPress.com confirmed the anchored identity.
1502     */
1503    public function reconcile_protected_owner() {
1504        $user_id = get_current_user_id();
1505
1506        if ( ! $user_id ) {
1507            return false;
1508        }
1509
1510        $anchor = Protected_Owner::get();
1511
1512        // Nothing anchored is nothing to reconcile, and a site with no protected owner must behave
1513        // exactly as it did before this existed â€” including making no request. Such a site reaches
1514        // an owner through the claim instead, which is where confirming belongs.
1515        if ( ! $anchor ) {
1516            return false;
1517        }
1518
1519        $record = $this->query_protected_owner_record( (int) $anchor['wpcom_user_id'] );
1520
1521        // Silence is not an answer. Unreachable, refused and unimplemented leave the anchor exactly
1522        // as it was: it was confirmed once, and a request that never arrived is no evidence against
1523        // it. Dropping a good lock because WordPress.com had a bad minute costs a merchant their
1524        // payouts until the owner happens to connect again.
1525        if ( ! is_array( $record ) || ! isset( $record['has_owner'] ) ) {
1526            return false;
1527        }
1528
1529        // WordPress.com no longer has an owner of record, so neither does this site. Support
1530        // clearing it at that end is how a wrongly anchored site recovers.
1531        if ( ! $record['has_owner'] ) {
1532            Protected_Owner::clear();
1533
1534            return false;
1535        }
1536
1537        $caller_wpcom_user_id = (int) ( $record['caller_wpcom_user_id'] ?? 0 );
1538
1539        // The identity is disclosed only to the owner it names, so this is the one branch that can
1540        // learn it â€” and what it settles is which account the anchor should name, since
1541        // WordPress.com may have moved the owner since this site last asked.
1542        if ( ! empty( $record['is_caller'] ) ) {
1543            return $this->adopt_protected_owner( $user_id, $caller_wpcom_user_id, $anchor );
1544        }
1545
1546        // Connecting cleared this, and it is the caller's own identity rather than the owner's, so
1547        // it is written whoever they are. Nothing is anchored on this path, so an early write
1548        // cannot strand a half-finished lock.
1549        if ( $caller_wpcom_user_id ) {
1550            Utils::set_wpcom_user_id( $user_id, $caller_wpcom_user_id );
1551        }
1552
1553        // Somebody else is connecting. WordPress.com confirms the anchored identity rather than
1554        // naming the owner, so the answer is the same whoever asks.
1555        if ( empty( $record['matches'] ) ) {
1556            Protected_Owner::clear();
1557
1558            return false;
1559        }
1560
1561        return true;
1562    }
1563
1564    /**
1565     * Take WordPress.com's word that the connecting user owns this site.
1566     *
1567     * @since 9.8.0
1568     *
1569     * @param int        $user_id       The connecting local user.
1570     * @param int        $wpcom_user_id The connecting user's WordPress.com identity, which this
1571     *                                  branch has just been told is the owner of record.
1572     * @param array|null $anchor        What this site has anchored, if anything.
1573     * @return bool Whether the anchor now names that identity.
1574     */
1575    private function adopt_protected_owner( $user_id, $wpcom_user_id, $anchor ) {
1576        // An owner without an identity is a malformed answer, and trusting it would lock the site
1577        // to nobody.
1578        if ( ! $wpcom_user_id ) {
1579            return false;
1580        }
1581
1582        // Anchored before the binding, so a failed write leaves nothing behind for a later
1583        // connection to build on. Re-pointing only moves the cached local ID, so it is right only
1584        // while the anchored identity is the one WordPress.com just confirmed.
1585        if ( $anchor && (int) $anchor['wpcom_user_id'] === $wpcom_user_id ) {
1586            Protected_Owner::repoint( $user_id );
1587        } elseif ( ! Protected_Owner::set( $wpcom_user_id, $user_id ) ) {
1588            return false;
1589        }
1590
1591        // Connecting clears the binding, so this writes back the one the answer just confirmed.
1592        Utils::set_wpcom_user_id( $user_id, $wpcom_user_id );
1593
1594        // Eligibility for the master slot is being an administrator here, which the owner of record
1595        // need not be.
1596        if ( user_can( $user_id, ( new Roles() )->translate_role_to_cap( 'administrator' ) )
1597            && (int) \Jetpack_Options::get_option( 'master_user' ) !== $user_id ) {
1598            \Jetpack_Options::update_option( 'master_user', $user_id );
1599        }
1600
1601        return true;
1602    }
1603
1604    /**
1605     * Ask WordPress.com whether it still holds the anchored identity as this site's owner.
1606     *
1607     * Split from `reconcile_protected_owner()` so the decision it drives can be exercised without a
1608     * network, which is the half worth testing: every branch of it changes whether a site gates a
1609     * live feature. The anchored ID is sent so the answer confirms rather than discloses.
1610     *
1611     * @since 9.8.0
1612     *
1613     * @param int $anchored_wpcom_user_id The WordPress.com identity this site has anchored.
1614     * @return array|null The record, or null when WordPress.com could not answer.
1615     */
1616    protected function query_protected_owner_record( $anchored_wpcom_user_id ) {
1617        return $this->request_protected_owner_record(
1618            '/reconcile',
1619            array( 'anchored_wpcom_user_id' => (int) $anchored_wpcom_user_id )
1620        );
1621    }
1622
1623    /**
1624     * Claim this site's protected ownership for the current user with WordPress.com.
1625     *
1626     * Split from `set_protected_owner()` so the decision it drives can be exercised without a
1627     * network. The identity travels in the signature rather than the payload, so nothing is sent.
1628     *
1629     * @since 9.8.0
1630     *
1631     * @return array|null The record, or null when WordPress.com could not answer.
1632     */
1633    protected function assert_protected_owner_record() {
1634        return $this->request_protected_owner_record();
1635    }
1636
1637    /**
1638     * Give up this site's protected ownership with WordPress.com.
1639     *
1640     * Split from `release_protected_owner()` so the decision it drives can be exercised without a
1641     * network. The identity travels in the signature rather than the payload, so WordPress.com
1642     * decides whether the caller is the owner it holds.
1643     *
1644     * @since 9.9.0
1645     *
1646     * @return array|null The record, or null when WordPress.com could not answer.
1647     */
1648    protected function relinquish_protected_owner_record() {
1649        return $this->request_protected_owner_record( '/release' );
1650    }
1651
1652    /**
1653     * Call this site's protected-owner resource on WordPress.com, signed as the current user.
1654     *
1655     * @since 9.8.1
1656     *
1657     * @param string     $route The route below the resource, empty for the resource itself.
1658     * @param array|null $body  The request body, or null to send none.
1659     * @return array|null The record, or null when WordPress.com could not answer.
1660     */
1661    private function request_protected_owner_record( $route = '', $body = null ) {
1662        $path = sprintf(
1663            '/sites/%d/jetpack-protected-owner%s',
1664            (int) \Jetpack_Options::get_option( 'id' ),
1665            $route
1666        );
1667
1668        $response = Client::wpcom_json_api_request_as_user( $path, '2', array( 'method' => 'POST' ), $body );
1669
1670        // Anything but a 200 is silence rather than an answer: unreachable, refused, or a
1671        // WordPress.com that does not implement the route. Every caller fails closed on null.
1672        if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
1673            return null;
1674        }
1675
1676        $record = json_decode( wp_remote_retrieve_body( $response ), true );
1677
1678        return is_array( $record ) ? $record : null;
1679    }
1680
1681    /**
1682     * Record a user as the protected owner and promote them to connection owner.
1683     *
1684     * Gated on `jetpack_connect` rather than on a role: a host can narrow that capability and
1685     * multisite does. It is false while the package is unconfigured, so a caller that has not
1686     * registered the connection's capabilities is refused rather than trusted.
1687     *
1688     * @since 9.3.0
1689     * @since 9.6.0 No longer takes how the owner was confirmed.
1690     * @since 9.8.0 WordPress.com records the owner before anything is anchored here.
1691     *
1692     * @param int $user_id The local user to anchor.
1693     * @return true|WP_Error True on success, WP_Error otherwise.
1694     */
1695    public function set_protected_owner( $user_id ) {
1696        // Authorization precedes validation, so an unauthorized caller cannot use the argument
1697        // errors below to learn which users are administrators or hold a token.
1698        if ( ! current_user_can( 'jetpack_connect' ) ) {
1699            return new WP_Error(
1700                'protected_owner_forbidden',
1701                __( 'You do not have permission to manage the protected owner.', 'jetpack-connection' ),
1702                array( 'status' => 403 )
1703            );
1704        }
1705
1706        $user_id = absint( $user_id );
1707        $roles   = new Roles();
1708
1709        if ( ! user_can( $user_id, $roles->translate_role_to_cap( 'administrator' ) ) ) {
1710            return new WP_Error(
1711                'protected_owner_not_admin',
1712                __( 'The protected owner must be an administrator.', 'jetpack-connection' ),
1713                array( 'status' => 400 )
1714            );
1715        }
1716
1717        // The claim is signed as the current user, so it can only ever anchor the current user.
1718        // Anchoring somebody else would be an owner assignment they never agreed to.
1719        if ( $user_id !== get_current_user_id() ) {
1720            return new WP_Error(
1721                'protected_owner_not_self',
1722                __( 'A protected owner can only be recorded by the user confirming it.', 'jetpack-connection' ),
1723                array( 'status' => 400 )
1724            );
1725        }
1726
1727        // A stored binding that already disagrees with the anchor is enough to refuse. WordPress.com
1728        // is still asked when this user has no binding, because that answer is what names them.
1729        if ( $this->local_anchor_names_someone_else( (int) Utils::get_wpcom_user_id( $user_id ) ) ) {
1730            return $this->protected_owner_claimed_by_other();
1731        }
1732
1733        // WordPress.com is asked before anything is written here. It owns the record, so a claim it
1734        // has not accepted must not leave a locked anchor behind on this site.
1735        $record = $this->assert_protected_owner_record();
1736
1737        // Fail closed: unreachable, refused, or a WordPress.com that does not implement the call.
1738        // A site that cannot get an answer must not end up protecting anybody on its own say-so.
1739        if ( ! is_array( $record ) || empty( $record['status'] ) ) {
1740            return new WP_Error(
1741                'protected_owner_unconfirmed',
1742                __( 'Could not reach WordPress.com to confirm the protected owner.', 'jetpack-connection' ),
1743                array( 'status' => 503 )
1744            );
1745        }
1746
1747        // Somebody else already holds this site. Beyond support there is no way past this, which is
1748        // the point: an owner that could be overwritten by the next claimant protects nobody.
1749        if ( 'locked_to_other' === $record['status'] ) {
1750            return $this->protected_owner_claimed_by_other();
1751        }
1752
1753        // Only an accepted claim is anchored: any other verdict is refused, even one carrying an ID.
1754        if ( ! in_array( $record['status'], array( 'recorded', 'already_yours' ), true ) || empty( $record['wpcom_user_id'] ) ) {
1755            return new WP_Error(
1756                'protected_owner_not_verified',
1757                __( 'Could not confirm the protected owner with WordPress.com.', 'jetpack-connection' ),
1758                array( 'status' => 400 )
1759            );
1760        }
1761
1762        // A `recorded` answer must not replace an anchor that already names a different account.
1763        if ( $this->local_anchor_names_someone_else( (int) $record['wpcom_user_id'] ) ) {
1764            return $this->protected_owner_claimed_by_other();
1765        }
1766
1767        // Store the binding the anchor will be compared against, so the gate reads local state from
1768        // here on. Routed through the deduping writer, which clears the ID off any previous holder.
1769        Utils::set_wpcom_user_id( $user_id, (int) $record['wpcom_user_id'] );
1770
1771        if ( ! Protected_Owner::set( (int) $record['wpcom_user_id'], $user_id ) ) {
1772            return new WP_Error(
1773                'protected_owner_not_stored',
1774                __( 'Could not store the protected owner.', 'jetpack-connection' ),
1775                array( 'status' => 500 )
1776            );
1777        }
1778
1779        // Written directly rather than through update_connection_owner(): that round-trips to
1780        // WordPress.com first, and its ownership-change guard will refuse the anchor just set here.
1781        \Jetpack_Options::update_option( 'master_user', $user_id );
1782
1783        return true;
1784    }
1785
1786    /**
1787     * Release the protected owner, leaving ownership open to any connected administrator.
1788     *
1789     * WordPress.com holds the record, so it is cleared there first. An anchor dropped only here
1790     * would leave WordPress.com refusing every later claim as `locked_to_other`, locking the site
1791     * to nobody rather than unlocking it.
1792     *
1793     * Leaves `master_user` alone: releasing the lock does not change who the owner is.
1794     *
1795     * @since 9.9.0
1796     *
1797     * @return true|WP_Error True on success, WP_Error otherwise.
1798     */
1799    public function release_protected_owner() {
1800        // Authorization precedes everything else, so an unauthorized caller cannot use the
1801        // refusals below to learn whether this site is protected or by whom.
1802        if ( ! current_user_can( 'jetpack_connect' ) ) {
1803            return new WP_Error(
1804                'protected_owner_forbidden',
1805                __( 'You do not have permission to manage the protected owner.', 'jetpack-connection' ),
1806                array( 'status' => 403 )
1807            );
1808        }
1809
1810        // Nothing anchored is already released, so repeating the call is not an error. It can also
1811        // be an anchor lost while WordPress.com kept its record, which this site cannot tell apart
1812        // and cannot recover from alone â€” hence a warning rather than silence.
1813        $anchor = Protected_Owner::get_locked();
1814
1815        if ( ! $anchor ) {
1816            wp_trigger_error(
1817                __METHOD__,
1818                'Released with no protected owner on record. If WordPress.com still holds one, this site can no longer claim it back.',
1819                E_USER_WARNING
1820            );
1821
1822            return true;
1823        }
1824
1825        // A local hint that spares an obvious refusal a round trip. WordPress.com is asked anyway
1826        // whenever this passes, and its answer is the one that decides.
1827        if ( Utils::get_wpcom_user_id( get_current_user_id() ) !== (int) $anchor['wpcom_user_id'] ) {
1828            return $this->protected_owner_release_refused();
1829        }
1830
1831        $record = $this->relinquish_protected_owner_record();
1832
1833        // Fail closed: unreachable, refused, or a WordPress.com that does not implement the call.
1834        // Clearing on silence would unlock a site WordPress.com still holds.
1835        if ( ! is_array( $record ) || empty( $record['status'] ) ) {
1836            return new WP_Error(
1837                'protected_owner_unreleased',
1838                __( 'Could not reach WordPress.com to release the protected owner.', 'jetpack-connection' ),
1839                array( 'status' => 503 )
1840            );
1841        }
1842
1843        if ( 'not_owner' === $record['status'] ) {
1844            return $this->protected_owner_release_refused();
1845        }
1846
1847        // `no_owner` is WordPress.com reporting it holds nothing to release, which is the state
1848        // this call asks for, so the stale anchor here clears alongside an accepted release.
1849        if ( ! in_array( $record['status'], array( 'released', 'no_owner' ), true ) ) {
1850            return new WP_Error(
1851                'protected_owner_not_released',
1852                __( 'Could not release the protected owner with WordPress.com.', 'jetpack-connection' ),
1853                array( 'status' => 400 )
1854            );
1855        }
1856
1857        $cleared = $this->clear_protected_owner();
1858
1859        // WordPress.com has already let go, so a local delete that failed is unfinished cleanup
1860        // rather than a release that did not happen. Retrying is what fixes it: reconcile only
1861        // runs when somebody authorizes, and WordPress.com now answers this call with `no_owner`.
1862        if ( is_wp_error( $cleared ) && 'protected_owner_not_cleared' === $cleared->get_error_code() ) {
1863            return new WP_Error(
1864                'protected_owner_not_cleared',
1865                __( 'Ownership was released with WordPress.com, but this site could not finish clearing it. Try again.', 'jetpack-connection' ),
1866                array( 'status' => 500 )
1867            );
1868        }
1869
1870        return $cleared;
1871    }
1872
1873    /**
1874     * The refusal for a caller who is not the owner WordPress.com holds.
1875     *
1876     * @since 9.9.0
1877     *
1878     * @return WP_Error
1879     */
1880    private function protected_owner_release_refused() {
1881        return new WP_Error(
1882            'protected_owner_not_owner',
1883            __( 'Only the confirmed owner can release ownership of this site.', 'jetpack-connection' ),
1884            array( 'status' => 403 )
1885        );
1886    }
1887
1888    /**
1889     * Whether a WordPress.com user id would replace the stored anchor.
1890     *
1891     * Zero means this user is not named yet, so it is not a conflict.
1892     *
1893     * @since 9.9.0
1894     *
1895     * @param int $wpcom_user_id WordPress.com user the claim would anchor.
1896     * @return bool
1897     */
1898    private function local_anchor_names_someone_else( $wpcom_user_id ) {
1899        $anchor = Protected_Owner::get_locked();
1900
1901        return $anchor && $wpcom_user_id && (int) $anchor['wpcom_user_id'] !== (int) $wpcom_user_id;
1902    }
1903
1904    /**
1905     * The support path for a site a different account already protects.
1906     *
1907     * @since 9.9.0
1908     *
1909     * @return WP_Error
1910     */
1911    private function protected_owner_claimed_by_other() {
1912        return new WP_Error(
1913            'protected_owner_claimed_by_other',
1914            __( 'This site is already protected by a different WordPress.com account. Contact support.', 'jetpack-connection' ),
1915            array( 'status' => 409 )
1916        );
1917    }
1918
1919    /**
1920     * Drop the protected owner anchor, unlocking ownership.
1921     *
1922     * Gated on `jetpack_connect` like establishing one, releasing a lock being the more
1923     * consequential half. The `@internal` tag is documentation; the capability is enforcement.
1924     *
1925     * @internal Recovery and support flows only. Consumers must not call this.
1926     * @since 9.3.0
1927     *
1928     * @return true|WP_Error True once no anchor is set, WP_Error otherwise.
1929     */
1930    public function clear_protected_owner() {
1931        if ( ! current_user_can( 'jetpack_connect' ) ) {
1932            return new WP_Error(
1933                'protected_owner_forbidden',
1934                __( 'You do not have permission to manage the protected owner.', 'jetpack-connection' ),
1935                array( 'status' => 403 )
1936            );
1937        }
1938
1939        Protected_Owner::clear();
1940
1941        // Asked of the outcome rather than of `delete_option()`, which also reports false for an
1942        // anchor that was already absent â€” the state the caller asked for.
1943        if ( Protected_Owner::get() ) {
1944            return new WP_Error(
1945                'protected_owner_not_cleared',
1946                __( 'Could not clear the protected owner.', 'jetpack-connection' ),
1947                array( 'status' => 500 )
1948            );
1949        }
1950
1951        return true;
1952    }
1953
1954    /**
1955     * Connects the user with a specified ID to a WordPress.com user using the
1956     * remote login flow.
1957     *
1958     * @access public
1959     *
1960     * @param int|null    $user_id (optional) the user identifier, defaults to current user.
1961     * @param string|null $redirect_url the URL to redirect the user to for processing, defaults to
1962     *                             admin_url().
1963     * @return WP_Error only in case of a failed user lookup.
1964     */
1965    public function connect_user( $user_id = null, $redirect_url = null ) {
1966        $user = null;
1967        if ( null === $user_id ) {
1968            $user = wp_get_current_user();
1969        } else {
1970            $user = get_user_by( 'ID', $user_id );
1971        }
1972
1973        if ( empty( $user ) ) {
1974            return new \WP_Error( 'user_not_found', 'Attempting to connect a non-existent user.' );
1975        }
1976
1977        if ( null === $redirect_url ) {
1978            $redirect_url = admin_url();
1979        }
1980
1981        // Using wp_redirect intentionally because we're redirecting outside.
1982        wp_redirect( $this->get_authorization_url( $user, $redirect_url ) ); // phpcs:ignore WordPress.Security.SafeRedirect
1983        exit( 0 );
1984    }
1985
1986    /**
1987     * Force user disconnect.
1988     *
1989     * @param int  $user_id Local (external) user ID.
1990     * @param bool $disconnect_all_users Whether to disconnect all users before disconnecting the primary user.
1991     *
1992     * @return bool
1993     */
1994    public function disconnect_user_force( $user_id, $disconnect_all_users = false ) {
1995        if ( ! (int) $user_id ) {
1996            // Missing user ID.
1997            return false;
1998        }
1999        // If we are disconnecting the primary user we may need to disconnect all other users first
2000        if ( $user_id === $this->get_connection_owner_id() && $disconnect_all_users && ! $this->disconnect_all_users_except_primary() ) {
2001            return false;
2002        }
2003
2004        return $this->disconnect_user( $user_id, true, true );
2005    }
2006
2007    /**
2008     * Disconnects all users except the primary user.
2009     *
2010     * @return bool
2011     */
2012    public function disconnect_all_users_except_primary() {
2013
2014        $all_connected_users = $this->get_connected_users();
2015
2016        foreach ( $all_connected_users as $user ) {
2017            // Skip the primary.
2018            if ( $user->ID === $this->get_connection_owner_id() ) {
2019                continue;
2020            }
2021            $disconnected = $this->disconnect_user( $user->ID, false, true );
2022            // If we fail to disconnect any user, we should not proceed with disconnecting the primary user.
2023            if ( ! $disconnected ) {
2024                return false;
2025            }
2026        }
2027
2028        return true;
2029    }
2030
2031    /**
2032     * Unlinks the current user from the linked WordPress.com user.
2033     *
2034     * @access public
2035     * @static
2036     *
2037     * @todo Refactor to properly load the XMLRPC client independently.
2038     *
2039     * @param int|null $user_id the user identifier.
2040     * @param bool     $can_overwrite_primary_user Allow for the primary user to be disconnected.
2041     * @param bool     $force_disconnect_locally Disconnect user locally even if we were unable to disconnect them from WP.com.
2042     * @return bool Whether the disconnection of the user was successful.
2043     */
2044    public function disconnect_user( $user_id = null, $can_overwrite_primary_user = false, $force_disconnect_locally = false ) {
2045        $user_id         = empty( $user_id ) ? get_current_user_id() : (int) $user_id;
2046        $is_primary_user = Jetpack_Options::get_option( 'master_user' ) === $user_id;
2047
2048        if ( $is_primary_user && ! $can_overwrite_primary_user ) {
2049            return false;
2050        }
2051
2052        if ( in_array( $user_id, self::$disconnected_users, true ) ) {
2053            // The user is already disconnected.
2054            return false;
2055        }
2056
2057        // Attempt to disconnect the user from WordPress.com.
2058        $is_disconnected_from_wpcom = $this->unlink_user_from_wpcom( $user_id );
2059
2060        $is_disconnected_locally = false;
2061        if ( $is_disconnected_from_wpcom || $force_disconnect_locally ) {
2062            // Get the WordPress.com email before disconnecting the user
2063            $wpcom_user_data = $this->get_connected_user_data( $user_id );
2064            $wpcom_email     = $wpcom_user_data['email'] ?? null;
2065
2066            // Disconnect the user locally.
2067            $is_disconnected_locally = $this->get_tokens()->disconnect_user( $user_id );
2068
2069            if ( $is_disconnected_locally ) {
2070                // Delete cached connected user data.
2071                $transient_key = "jetpack_connected_user_data_$user_id";
2072                delete_transient( $transient_key );
2073
2074                // Clean up account mismatch transients for this user
2075                if ( $wpcom_email ) {
2076                    $user_account_status = new User_Account_Status();
2077                    $user_account_status->clean_account_mismatch_transients( $wpcom_email );
2078                }
2079
2080                /**
2081                 * Fires after the current user has been unlinked from WordPress.com.
2082                 *
2083                 * @since 1.7.0
2084                 * @since-jetpack 4.1.0
2085                 *
2086                 * @param int $user_id The current user's ID.
2087                 */
2088                do_action( 'jetpack_unlinked_user', $user_id );
2089
2090                if ( $is_primary_user ) {
2091                    Jetpack_Options::delete_option( 'master_user' );
2092
2093                    // Clear the memoized connection owner ID since it changed
2094                    self::$connection_owner_id = null;
2095                }
2096            }
2097        }
2098
2099        self::$disconnected_users[] = $user_id;
2100
2101        return $is_disconnected_from_wpcom && $is_disconnected_locally;
2102    }
2103
2104    /**
2105     * Request to wpcom for a user to be unlinked from their WordPress.com account
2106     *
2107     * @param int $user_id The user identifier.
2108     *
2109     * @return bool Whether the disconnection of the user was successful.
2110     */
2111    public function unlink_user_from_wpcom( $user_id ) {
2112        // Attempt to disconnect the user from WordPress.com.
2113        $xml = new Jetpack_IXR_Client();
2114
2115        $xml->query( 'jetpack.unlink_user', $user_id );
2116        if ( $xml->isError() ) {
2117            return false;
2118        }
2119
2120        return (bool) $xml->getResponse();
2121    }
2122
2123    /**
2124     * Update the connection owner.
2125     *
2126     * @since 1.29.0
2127     * @since 9.3.0 Refused while ownership is locked.
2128     * @since 9.9.0 The anchored owner passes the lock, and moving the site off them
2129     *                         releases the anchor.
2130     *
2131     * @param int $new_owner_id The ID of the user to become the connection owner.
2132     *
2133     * @return true|WP_Error True if owner successfully changed, WP_Error otherwise.
2134     */
2135    public function update_connection_owner( $new_owner_id ) {
2136        // Answered before the arguments are validated: no candidate is valid while ownership is
2137        // locked, and an argument error would suggest a retry that cannot work.
2138        if ( ! $this->is_ownership_transferable() && ! $this->current_user_may_move_locked_ownership() ) {
2139            return new WP_Error(
2140                'ownership_locked',
2141                __( 'The connection owner is locked on this site.', 'jetpack-connection' ),
2142                array( 'status' => 403 )
2143            );
2144        }
2145
2146        $roles = new Roles();
2147        if ( ! user_can( $new_owner_id, $roles->translate_role_to_cap( 'administrator' ) ) ) {
2148            return new WP_Error(
2149                'new_owner_not_admin',
2150                __( 'New owner is not admin', 'jetpack-connection' ),
2151                array( 'status' => 400 )
2152            );
2153        }
2154
2155        $old_owner_id = $this->get_connection_owner_id();
2156
2157        if ( $old_owner_id === $new_owner_id ) {
2158            return new WP_Error(
2159                'new_owner_is_existing_owner',
2160                __( 'New owner is same as existing owner', 'jetpack-connection' ),
2161                array( 'status' => 400 )
2162            );
2163        }
2164
2165        if ( ! $this->is_user_connected( $new_owner_id ) ) {
2166            return new WP_Error(
2167                'new_owner_not_connected',
2168                __( 'New owner is not connected', 'jetpack-connection' ),
2169                array( 'status' => 400 )
2170            );
2171        }
2172
2173        // Notify WPCOM about the connection owner change.
2174        $owner_updated_wpcom = $this->update_connection_owner_wpcom( $new_owner_id );
2175
2176        if ( $owner_updated_wpcom ) {
2177            // Update the connection owner in Jetpack only if they were successfully updated on WPCOM.
2178            // This will ensure consistency with WPCOM.
2179            \Jetpack_Options::update_option( 'master_user', $new_owner_id );
2180
2181            // Clear the memoized connection owner ID since it changed
2182            self::$connection_owner_id = null;
2183
2184            $this->release_anchor_after_transfer( $new_owner_id, $owner_updated_wpcom );
2185
2186            // Track it.
2187            ( new Tracking() )->record_user_event( 'set_connection_owner_success' );
2188
2189            return true;
2190        }
2191        return new WP_Error(
2192            'error_setting_new_owner',
2193            __( 'Could not confirm new owner.', 'jetpack-connection' ),
2194            array( 'status' => 500 )
2195        );
2196    }
2197
2198    /**
2199     * Whether the current user may move the connection despite a locked anchor.
2200     *
2201     * The anchor protects an identity, so the owner it names is the one person it is not against.
2202     *
2203     * A local hint rather than proof of who that is: the binding is not unique site-wide, and the
2204     * anchored owner is often not the connection owner here â€” taking a site back from an agency is
2205     * the point â€” so there is no stronger identity to check. WordPress.com decides, marking a
2206     * switch `po_signed` only when the signing token belongs to the owner of record.
2207     *
2208     * @since 9.9.0
2209     * @since 9.11.0 No longer refused by the deprecated `jetpack_connection_ownership_transferable` filter.
2210     *
2211     * @return bool
2212     */
2213    private function current_user_may_move_locked_ownership() {
2214        $anchor  = Protected_Owner::get_locked();
2215        $user_id = get_current_user_id();
2216
2217        if ( ! $anchor || ! $user_id ) {
2218            return false;
2219        }
2220
2221        // Both halves, as everywhere else the binding is trusted: it outlives the token, so a
2222        // disconnected user can still carry the anchored ID.
2223        if ( ! $this->is_user_connected( $user_id ) ) {
2224            return false;
2225        }
2226
2227        // This user's own binding, never a search for whoever holds the anchored ID, which would
2228        // hand the site to the first match.
2229        return Utils::get_wpcom_user_id( $user_id ) === (int) $anchor['wpcom_user_id'];
2230    }
2231
2232    /**
2233     * Drop the anchor once the site has left the owner it names.
2234     *
2235     * Do not make this clear more eagerly. An anchor dropped while WordPress.com kept its own
2236     * locks the site to nobody, and `reconcile_protected_owner()` returns before asking when
2237     * there is no local anchor left to repair it with. The reverse mistake costs nothing.
2238     *
2239     * @since 9.9.0
2240     *
2241     * @param int        $new_owner_id The local user who now holds the connection.
2242     * @param true|array $accepted     What WordPress.com answered the switch with: a report of
2243     *                                 what it did where available, otherwise a bare `true`.
2244     */
2245    private function release_anchor_after_transfer( $new_owner_id, $accepted ) {
2246        $anchor = Protected_Owner::get_locked();
2247
2248        if ( ! $anchor ) {
2249            return;
2250        }
2251
2252        // WordPress.com resolves the new owner itself and knows what it kept, so where it reports
2253        // what it did, that report is the whole answer.
2254        if ( is_array( $accepted ) ) {
2255            if ( ! empty( $accepted['released'] ) ) {
2256                Protected_Owner::clear();
2257            }
2258
2259            return;
2260        }
2261
2262        // A bare `true` says only that the switch happened, leaving who the site went to as the
2263        // best guess available. A zero is "could not determine", which covers the owner taking the
2264        // site back â€” the case WordPress.com keeps its record for.
2265        $new_owner_wpcom_id = $this->resolve_wpcom_user_id( $new_owner_id );
2266
2267        if ( $new_owner_wpcom_id && $new_owner_wpcom_id !== (int) $anchor['wpcom_user_id'] ) {
2268            Protected_Owner::clear();
2269        }
2270    }
2271
2272    /**
2273     * Request to WPCOM to update the connection owner.
2274     *
2275     * @since 1.29.0
2276     * @since 9.9.0 Returns what WordPress.com answered rather than casting it, so a
2277     *                         report of what the switch did can be read. Still falsy on failure.
2278     *
2279     * @param int $new_owner_id The ID of the user to become the connection owner.
2280     *
2281     * @return bool|array False if the transfer failed, otherwise what WordPress.com answered:
2282     *                    `true`, or a non-empty report such as `array( 'released' => bool )`.
2283     */
2284    public function update_connection_owner_wpcom( $new_owner_id ) {
2285        // Notify WPCOM about the connection owner change.
2286        $xml = new Jetpack_IXR_Client(
2287            array(
2288                'user_id' => get_current_user_id(),
2289            )
2290        );
2291        $xml->query(
2292            'jetpack.switchBlogOwner',
2293            array(
2294                'new_blog_owner' => $new_owner_id,
2295            )
2296        );
2297        if ( $xml->isError() ) {
2298            return false;
2299        }
2300
2301        $response = $xml->getResponse();
2302
2303        // An array is the switch reporting what it did, and an empty one reports nothing rather
2304        // than refusing â€” a bare `true` by another name. Only a falsy non-array is a refusal.
2305        if ( is_array( $response ) ) {
2306            return empty( $response ) ? true : $response;
2307        }
2308
2309        return (bool) $response;
2310    }
2311
2312    /**
2313     * Returns the requested Jetpack API URL.
2314     *
2315     * @param string $relative_url the relative API path.
2316     * @return string API URL.
2317     */
2318    public function api_url( $relative_url ) {
2319        $api_base    = Constants::get_constant( 'JETPACK__API_BASE' );
2320        $api_version = '/' . Constants::get_constant( 'JETPACK__API_VERSION' ) . '/';
2321
2322        /**
2323         * Filters the API URL that Jetpack uses for server communication.
2324         *
2325         * @since 1.7.0
2326         * @since-jetpack 8.0.0
2327         *
2328         * @param string $url the generated URL.
2329         * @param string $relative_url the relative URL that was passed as an argument.
2330         * @param string $api_base the API base string that is being used.
2331         * @param string $api_version the API version string that is being used.
2332         */
2333        return apply_filters(
2334            'jetpack_api_url',
2335            rtrim( $api_base . $relative_url, '/\\' ) . $api_version,
2336            $relative_url,
2337            $api_base,
2338            $api_version
2339        );
2340    }
2341
2342    /**
2343     * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
2344     *
2345     * @return string XMLRPC API URL.
2346     */
2347    public function xmlrpc_api_url() {
2348        $base = preg_replace(
2349            '#(https?://[^?/]+)(/?.*)?$#',
2350            '\\1',
2351            Constants::get_constant( 'JETPACK__API_BASE' )
2352        );
2353        return untrailingslashit( $base ) . '/xmlrpc.php';
2354    }
2355
2356    /**
2357     * Attempts Jetpack registration which sets up the site for connection. Should
2358     * remain public because the call to action comes from the current site, not from
2359     * WordPress.com.
2360     *
2361     * Always attempts: the retry gate and the offline mode check live in
2362     * `try_registration()`, so unattended callers must go through that instead.
2363     *
2364     * @param string $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
2365     * @return true|WP_Error The error object.
2366     */
2367    public function register( $api_endpoint = 'register' ) {
2368        $this->last_register_response = null;
2369
2370        $result = $this->do_register( $api_endpoint );
2371
2372        if ( is_wp_error( $result ) ) {
2373            Registration_Failure::record(
2374                $result,
2375                $this->last_register_response,
2376                $this->get_plugin_slug()
2377            );
2378        } else {
2379            Registration_Failure::clear();
2380        }
2381
2382        $this->last_register_response = null;
2383
2384        return $result;
2385    }
2386
2387    /**
2388     * Perform the registration request and store the resulting connection data.
2389     *
2390     * @see Manager::register()
2391     *
2392     * @param string $api_endpoint An API endpoint to use.
2393     * @return true|WP_Error The error object.
2394     */
2395    private function do_register( $api_endpoint ) {
2396        // Clean-up leftover tokens just in-case.
2397        // This fixes an edge case that was preventing users to register when the blog token was missing but
2398        // there were still leftover user tokens present.
2399        $this->delete_all_connection_tokens( true );
2400
2401        add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
2402        $secrets = ( new Secrets() )->generate( 'register', get_current_user_id(), 600 );
2403
2404        if ( false === $secrets ) {
2405            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' ) );
2406        }
2407
2408        if (
2409            empty( $secrets['secret_1'] ) ||
2410            empty( $secrets['secret_2'] ) ||
2411            empty( $secrets['exp'] )
2412        ) {
2413            return new \WP_Error( 'missing_secrets' );
2414        }
2415
2416        // Better to try (and fail) to set a higher timeout than this system
2417        // supports than to have register fail for more users than it should.
2418        $timeout = $this->set_min_time_limit( 60 ) / 2;
2419
2420        $gmt_offset = get_option( 'gmt_offset' );
2421        if ( ! $gmt_offset ) {
2422            $gmt_offset = 0;
2423        }
2424
2425        $stats_options = get_option( 'stats_options' );
2426        $stats_id      = $stats_options['blog_id'] ?? null;
2427
2428        /* This action is documented in src/class-package-version-tracker.php */
2429        $package_versions = apply_filters( 'jetpack_package_versions', array() );
2430
2431        $active_plugins_using_connection = Plugin_Storage::get_all();
2432
2433        /**
2434         * Filters the request body for additional property addition.
2435         *
2436         * @since 1.7.0
2437         * @since-jetpack 7.7.0
2438         *
2439         * @param array $post_data request data.
2440         * @param Array $token_data token data.
2441         */
2442        $body = apply_filters(
2443            'jetpack_register_request_body',
2444            array_merge(
2445                array(
2446                    'siteurl'                  => Urls::site_url(),
2447                    'home'                     => Urls::home_url(),
2448                    'gmt_offset'               => $gmt_offset,
2449                    'timezone_string'          => (string) get_option( 'timezone_string' ),
2450                    'site_name'                => (string) get_option( 'blogname' ),
2451                    'secret_1'                 => $secrets['secret_1'],
2452                    'secret_2'                 => $secrets['secret_2'],
2453                    'site_lang'                => get_locale(),
2454                    'timeout'                  => $timeout,
2455                    'stats_id'                 => $stats_id,
2456                    'state'                    => get_current_user_id(),
2457                    'site_created'             => $this->get_assumed_site_creation_date(),
2458                    'jetpack_version'          => Constants::get_constant( 'JETPACK__VERSION' ),
2459                    'ABSPATH'                  => Constants::get_constant( 'ABSPATH' ),
2460                    'current_user_email'       => wp_get_current_user()->user_email,
2461                    'connect_plugin'           => $this->get_plugin_slug(),
2462                    'package_versions'         => $package_versions,
2463                    'active_connected_plugins' => $active_plugins_using_connection,
2464                ),
2465                self::$extra_register_params
2466            )
2467        );
2468
2469        $args = array(
2470            'method'  => 'POST',
2471            'body'    => $body,
2472            'headers' => array(
2473                'Accept' => 'application/json',
2474            ),
2475            'timeout' => $timeout,
2476        );
2477
2478        $args['body'] = static::apply_activation_source_to_args( $args['body'] );
2479
2480        // TODO: fix URLs for bad hosts.
2481        $response = Client::_wp_remote_request(
2482            $this->api_url( $api_endpoint ),
2483            $args,
2484            true
2485        );
2486
2487        // Kept so that ::register() can read response headers such as `Retry-After`
2488        // when recording the failure.
2489        $this->last_register_response = $response;
2490
2491        // Make sure the response is valid and does not contain any Jetpack errors.
2492        $registration_details = $this->validate_remote_register_response( $response );
2493
2494        if ( is_wp_error( $registration_details ) ) {
2495            return $registration_details;
2496        } elseif ( ! $registration_details ) {
2497            return new \WP_Error(
2498                'unknown_error',
2499                'Unknown error registering your Jetpack site.',
2500                wp_remote_retrieve_response_code( $response )
2501            );
2502        }
2503
2504        if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
2505            return new \WP_Error(
2506                'jetpack_secret',
2507                'Unable to validate registration of your Jetpack site.',
2508                wp_remote_retrieve_response_code( $response )
2509            );
2510        }
2511
2512        if ( isset( $registration_details->jetpack_public ) ) {
2513            $jetpack_public = (int) $registration_details->jetpack_public;
2514        } else {
2515            $jetpack_public = false;
2516        }
2517
2518        Jetpack_Options::update_options(
2519            array(
2520                'id'     => (int) $registration_details->jetpack_id,
2521                'public' => $jetpack_public,
2522            )
2523        );
2524
2525        update_option( Package_Version_Tracker::PACKAGE_VERSION_OPTION, $package_versions );
2526
2527        $this->get_tokens()->update_blog_token( (string) $registration_details->jetpack_secret );
2528
2529        if ( ! Jetpack_Options::get_option( 'id' ) || ! $this->get_tokens()->get_access_token() ) {
2530            return new WP_Error(
2531                'connection_data_save_failed',
2532                'Failed to save connection data in the database'
2533            );
2534        }
2535
2536        $alternate_authorization_url = $registration_details->alternate_authorization_url ?? '';
2537
2538        add_filter(
2539            'jetpack_register_site_rest_response',
2540            function ( $response ) use ( $alternate_authorization_url ) {
2541                $response['alternateAuthorizeUrl'] = $alternate_authorization_url;
2542                return $response;
2543            }
2544        );
2545
2546        /**
2547         * Fires when a site is registered on WordPress.com.
2548         *
2549         * @since 1.7.0
2550         * @since-jetpack 3.7.0
2551         *
2552         * @param int $json->jetpack_id Jetpack Blog ID.
2553         * @param string $json->jetpack_secret Jetpack Blog Token.
2554         * @param int|bool $jetpack_public Is the site public.
2555         */
2556        do_action(
2557            'jetpack_site_registered',
2558            $registration_details->jetpack_id,
2559            $registration_details->jetpack_secret,
2560            $jetpack_public
2561        );
2562
2563        if ( isset( $registration_details->token ) ) {
2564            /**
2565             * Fires when a user token is sent along with the registration data.
2566             *
2567             * @since 1.7.0
2568             * @since-jetpack 7.6.0
2569             *
2570             * @param object $token the administrator token for the newly registered site.
2571             */
2572            do_action( 'jetpack_site_registered_user_token', $registration_details->token );
2573        }
2574
2575        return true;
2576    }
2577
2578    /**
2579     * Attempts Jetpack registration.
2580     *
2581     * Automatic attempts are skipped in offline mode and held back while a previous
2582     * failure still stands. Pass `$force` for attempts a user or partner explicitly
2583     * asked for - those are never held back.
2584     *
2585     * @see Registration_Failure
2586     *
2587     * @since 9.11.0 Added the `$force` parameter, the offline mode check, and the retry backoff.
2588     *
2589     * @param bool $tos_agree Whether the user agreed to TOS.
2590     * @param bool $force     Whether this attempt was explicitly requested by a user.
2591     *
2592     * @return true|WP_Error
2593     */
2594    public function try_registration( $tos_agree = true, $force = false ) {
2595        if ( ! $force ) {
2596            if ( ( new Status() )->is_offline_mode() ) {
2597                return new WP_Error(
2598                    'offline_mode',
2599                    __( 'Site is in offline mode; WordPress.com registration is not attempted.', 'jetpack-connection' ),
2600                    array( 'status' => 400 )
2601                );
2602            }
2603
2604            $suppressed_error = Registration_Failure::get_suppressed_error();
2605
2606            if ( $suppressed_error ) {
2607                Registration_Failure::record_suppressed_attempt(
2608                    $suppressed_error,
2609                    $this->get_plugin_slug()
2610                );
2611
2612                return $suppressed_error;
2613            }
2614        }
2615
2616        if ( $tos_agree ) {
2617            $terms_of_service = new Terms_Of_Service();
2618            $terms_of_service->agree();
2619        }
2620
2621        /**
2622         * Action fired when the user attempts the registration.
2623         *
2624         * @since 1.26.0
2625         */
2626        $pre_register = apply_filters( 'jetpack_pre_register', null );
2627
2628        if ( is_wp_error( $pre_register ) ) {
2629            return $pre_register;
2630        }
2631
2632        $tracking_data = array();
2633
2634        if ( null !== $this->get_plugin_slug() ) {
2635            $tracking_data['plugin_slug'] = $this->get_plugin_slug();
2636        }
2637
2638        $tracking = new Tracking();
2639        $tracking->record_user_event( 'jpc_register_begin', $tracking_data );
2640
2641        add_filter( 'jetpack_register_request_body', array( Utils::class, 'filter_register_request_body' ) );
2642
2643        $result = $this->register();
2644
2645        remove_filter( 'jetpack_register_request_body', array( Utils::class, 'filter_register_request_body' ) );
2646
2647        // If there was an error with registration and the site was not registered, record this so we can show a message.
2648        if ( is_wp_error( $result ) ) {
2649            return $result;
2650        }
2651
2652        return true;
2653    }
2654
2655    /**
2656     * Get the reason the last registration attempt failed, if it still stands.
2657     *
2658     * Lets consuming plugins tell the user why the site is not connected - for
2659     * example that WordPress.com cannot reach a site on a private address - instead
2660     * of leaving the connection silently unavailable.
2661     *
2662     * @since 9.11.0
2663     *
2664     * @return array|null Failure details, or null if the last attempt did not fail or the site is connected.
2665     */
2666    public function get_registration_failure() {
2667        if ( $this->is_connected() ) {
2668            return null;
2669        }
2670
2671        return Registration_Failure::get();
2672    }
2673
2674    /**
2675     * Forget the last registration failure, so the next automatic attempt is not
2676     * held back by it.
2677     *
2678     * For consumers that trigger registration through code that cannot pass the
2679     * `$force` flag to `try_registration()`.
2680     *
2681     * @since 9.11.0
2682     *
2683     * @return void
2684     */
2685    public function clear_registration_failure() {
2686        Registration_Failure::clear();
2687    }
2688
2689    /**
2690     * Get the slug of the plugin this connection is for, if any.
2691     *
2692     * @return string|null
2693     */
2694    private function get_plugin_slug() {
2695        return $this->get_plugin() ? $this->get_plugin()->get_slug() : null;
2696    }
2697
2698    /**
2699     * Adds a parameter to the register request body
2700     *
2701     * @since 1.26.0
2702     *
2703     * @param string $name The name of the parameter to be added.
2704     * @param string $value The value of the parameter to be added.
2705     *
2706     * @throws \InvalidArgumentException If supplied arguments are not strings.
2707     * @return void
2708     */
2709    public function add_register_request_param( $name, $value ) {
2710        if ( ! is_string( $name ) || ! is_string( $value ) ) {
2711            throw new \InvalidArgumentException( 'name and value must be strings' );
2712        }
2713        self::$extra_register_params[ $name ] = $value;
2714    }
2715
2716    /**
2717     * Whether PHP's XML extension, which the XML-RPC connection needs, is available.
2718     *
2719     * @since 9.14.0
2720     *
2721     * @return bool
2722     */
2723    protected function is_xml_extension_available() {
2724        return function_exists( 'xml_parser_create' );
2725    }
2726
2727    /**
2728     * Takes the response from the Jetpack register new site endpoint and
2729     * verifies it worked properly.
2730     *
2731     * @since 1.7.0
2732     * @since-jetpack 2.6.0
2733     *
2734     * @param mixed $response the response object, or the error object.
2735     * @return string|WP_Error A JSON object on success or WP_Error on failures
2736     **/
2737    protected function validate_remote_register_response( $response ) {
2738        if ( is_wp_error( $response ) ) {
2739            return new \WP_Error(
2740                'register_http_request_failed',
2741                $response->get_error_message()
2742            );
2743        }
2744
2745        $code   = wp_remote_retrieve_response_code( $response );
2746        $entity = wp_remote_retrieve_body( $response );
2747
2748        if ( $entity ) {
2749            $registration_response = json_decode( $entity );
2750        } else {
2751            $registration_response = false;
2752        }
2753
2754        $code_type = (int) ( $code / 100 );
2755        if ( 5 === $code_type ) {
2756            return new \WP_Error( 'wpcom_5??', $code );
2757        } elseif ( 408 === $code ) {
2758            return new \WP_Error( 'wpcom_408', $code );
2759        } elseif ( ! empty( $registration_response->error ) ) {
2760            // WordPress.com can't parse the site's XML-RPC reply without PHP's XML extension; name that cause.
2761            if ( 'xml_rpc-32700' === $registration_response->error && ! $this->is_xml_extension_available() ) {
2762                return new \WP_Error(
2763                    'xml_extension_missing',
2764                    __( "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' ),
2765                    $code
2766                );
2767            }
2768
2769            return new \WP_Error(
2770                (string) $registration_response->error,
2771                isset( $registration_response->error_description ) ? (string) $registration_response->error_description : '',
2772                $code
2773            );
2774        } elseif ( 200 !== $code ) {
2775            return new \WP_Error( 'wpcom_bad_response', $code );
2776        }
2777
2778        // Jetpack ID error block.
2779        if ( empty( $registration_response->jetpack_id ) ) {
2780            return new \WP_Error(
2781                'jetpack_id',
2782                /* translators: %s is an error message string */
2783                sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack-connection' ), $entity ),
2784                $entity
2785            );
2786        } elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
2787            return new \WP_Error(
2788                'jetpack_id',
2789                /* translators: %s is an error message string */
2790                sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack-connection' ), $entity ),
2791                $entity
2792            );
2793        } elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
2794            return new \WP_Error(
2795                'jetpack_id',
2796                /* translators: %s is an error message string */
2797                sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack-connection' ), $entity ),
2798                $entity
2799            );
2800        }
2801
2802        return $registration_response;
2803    }
2804
2805    /**
2806     * Adds a used nonce to a list of known nonces.
2807     *
2808     * @param int    $timestamp the current request timestamp.
2809     * @param string $nonce the nonce value.
2810     * @return bool whether the nonce is unique or not.
2811     *
2812     * @deprecated since 1.24.0
2813     * @see Nonce_Handler::add()
2814     */
2815    public function add_nonce( $timestamp, $nonce ) {
2816        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Nonce_Handler::add' );
2817        return ( new Nonce_Handler() )->add( $timestamp, $nonce );
2818    }
2819
2820    /**
2821     * Cleans nonces that were saved when calling ::add_nonce.
2822     *
2823     * @todo Properly prepare the query before executing it.
2824     *
2825     * @param bool $all whether to clean even non-expired nonces.
2826     *
2827     * @deprecated since 1.24.0
2828     * @see Nonce_Handler::clean_all()
2829     */
2830    public function clean_nonces( $all = false ) {
2831        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Nonce_Handler::clean_all' );
2832        ( new Nonce_Handler() )->clean_all( $all ? PHP_INT_MAX : ( time() - Nonce_Handler::LIFETIME ) );
2833    }
2834
2835    /**
2836     * Sets the Connection custom capabilities.
2837     *
2838     * @param string[] $caps    Array of the user's capabilities.
2839     * @param string   $cap     Capability name.
2840     * @param int      $user_id The user ID.
2841     * @param array    $args    Adds the context to the cap. Typically the object ID.
2842     */
2843    public function jetpack_connection_custom_caps( $caps, $cap, $user_id, $args ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
2844        switch ( $cap ) {
2845            case 'jetpack_connect':
2846            case 'jetpack_reconnect':
2847                $is_offline_mode = ( new Status() )->is_offline_mode();
2848                if ( $is_offline_mode ) {
2849                    $caps = array( 'do_not_allow' );
2850                    break;
2851                }
2852                // Pass through. If it's not offline mode, these should match disconnect.
2853                // Let users disconnect if it's offline mode, just in case things glitch.
2854            case 'jetpack_disconnect':
2855                /**
2856                 * Filters the jetpack_disconnect capability.
2857                 *
2858                 * @since 1.14.2
2859                 *
2860                 * @param array An array containing the capability name.
2861                 */
2862                $caps = apply_filters( 'jetpack_disconnect_cap', array( 'manage_options' ) );
2863                break;
2864            case 'jetpack_connect_user':
2865                $is_offline_mode = ( new Status() )->is_offline_mode();
2866                if ( $is_offline_mode ) {
2867                    $caps = array( 'do_not_allow' );
2868                    break;
2869                }
2870                // With site connections in mind, non-admin users can connect their account only if a connection owner exists.
2871                $caps = $this->has_connected_owner() ? array( 'read' ) : array( 'manage_options' );
2872                break;
2873            case 'jetpack_unlink_user':
2874                $is_offline_mode = ( new Status() )->is_offline_mode();
2875                if ( $is_offline_mode ) {
2876                    $caps = array( 'do_not_allow' );
2877                    break;
2878                }
2879
2880                // Non-admins can always disconnect
2881                $caps = array( 'read' );
2882                break;
2883        }
2884        return $caps;
2885    }
2886
2887    /**
2888     * Builds the timeout limit for queries talking with the wpcom servers.
2889     *
2890     * Based on local php max_execution_time in php.ini
2891     *
2892     * @since 1.7.0
2893     * @since-jetpack 5.4.0
2894     * @return int
2895     **/
2896    public function get_max_execution_time() {
2897        $timeout = (int) ini_get( 'max_execution_time' );
2898
2899        // Ensure exec time set in php.ini.
2900        if ( ! $timeout ) {
2901            $timeout = 30;
2902        }
2903        return $timeout;
2904    }
2905
2906    /**
2907     * Sets a minimum request timeout, and returns the current timeout
2908     *
2909     * @since 1.7.0
2910     * @since-jetpack 5.4.0
2911     * @param int $min_timeout the minimum timeout value.
2912     **/
2913    public function set_min_time_limit( $min_timeout ) {
2914        $timeout = $this->get_max_execution_time();
2915        if ( $timeout < $min_timeout ) {
2916            $timeout = $min_timeout;
2917            set_time_limit( $timeout );
2918        }
2919        return $timeout;
2920    }
2921
2922    /**
2923     * Get our assumed site creation date.
2924     * Calculated based on the earlier date of either:
2925     * - Earliest admin user registration date.
2926     * - Earliest date of post of any post type.
2927     *
2928     * @since 1.7.0
2929     * @since-jetpack 7.2.0
2930     *
2931     * @return string Assumed site creation date and time.
2932     */
2933    public function get_assumed_site_creation_date() {
2934        $cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
2935        if ( ! empty( $cached_date ) ) {
2936            return $cached_date;
2937        }
2938
2939        /**
2940         * We don't use the 'ID' field, but need it to overcome a WP caching bug: https://core.trac.wordpress.org/ticket/62003
2941         *
2942         * @todo Remote the 'ID' field from users fetching when the issue is fixed and Jetpack-supported WP versions move beyond it.
2943         */
2944        $earliest_registered_users  = get_users(
2945            array(
2946                'role'    => 'administrator',
2947                'orderby' => 'user_registered',
2948                'order'   => 'ASC',
2949                'fields'  => array( 'ID', 'user_registered' ),
2950                'number'  => 1,
2951            )
2952        );
2953        $earliest_registration_date = $earliest_registered_users[0]->user_registered;
2954
2955        $earliest_posts = get_posts(
2956            array(
2957                'posts_per_page' => 1,
2958                'post_type'      => 'any',
2959                'post_status'    => 'any',
2960                'orderby'        => 'date',
2961                'order'          => 'ASC',
2962            )
2963        );
2964
2965        // If there are no posts at all, we'll count only on user registration date.
2966        if ( $earliest_posts ) {
2967            $earliest_post_date = $earliest_posts[0]->post_date;
2968        } else {
2969            $earliest_post_date = PHP_INT_MAX;
2970        }
2971
2972        $assumed_date = min( $earliest_registration_date, $earliest_post_date );
2973        set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
2974
2975        return $assumed_date;
2976    }
2977
2978    /**
2979     * Adds the activation source string as a parameter to passed arguments.
2980     *
2981     * @todo Refactor to use rawurlencode() instead of urlencode().
2982     *
2983     * @param array $args arguments that need to have the source added.
2984     * @return array $amended arguments.
2985     */
2986    public static function apply_activation_source_to_args( $args ) {
2987        $activation_source = get_option( 'jetpack_activation_source' );
2988
2989        if ( ! empty( $activation_source[0] ) ) {
2990            // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
2991            $args['_as'] = urlencode( $activation_source[0] );
2992        }
2993
2994        if ( ! empty( $activation_source[1] ) ) {
2995            // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
2996            $args['_ak'] = urlencode( $activation_source[1] );
2997        }
2998
2999        return $args;
3000    }
3001
3002    /**
3003     * Generates two secret tokens and the end of life timestamp for them.
3004     *
3005     * @param string   $action  The action name.
3006     * @param int|bool $user_id The user identifier.
3007     * @param int      $exp     Expiration time in seconds.
3008     */
3009    public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
3010        return ( new Secrets() )->generate( $action, $user_id, $exp );
3011    }
3012
3013    /**
3014     * Returns two secret tokens and the end of life timestamp for them.
3015     *
3016     * @deprecated 1.24.0 Use Automattic\Jetpack\Connection\Secrets->get() instead.
3017     *
3018     * @param string $action  The action name.
3019     * @param int    $user_id The user identifier.
3020     * @return string|array an array of secrets or an error string.
3021     */
3022    public function get_secrets( $action, $user_id ) {
3023        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Secrets->get' );
3024        return ( new Secrets() )->get( $action, $user_id );
3025    }
3026
3027    /**
3028     * Deletes secret tokens in case they, for example, have expired.
3029     *
3030     * @deprecated 1.24.0 Use Automattic\Jetpack\Connection\Secrets->delete() instead.
3031     *
3032     * @param string $action  The action name.
3033     * @param int    $user_id The user identifier.
3034     */
3035    public function delete_secrets( $action, $user_id ) {
3036        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Secrets->delete' );
3037        ( new Secrets() )->delete( $action, $user_id );
3038    }
3039
3040    /**
3041     * Deletes all connection tokens and transients from the local Jetpack site.
3042     * If the plugin object has been provided in the constructor, the function first checks
3043     * whether it's the only active connection.
3044     * If there are any other connections, the function will do nothing and return `false`
3045     * (unless `$ignore_connected_plugins` is set to `true`).
3046     *
3047     * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
3048     *
3049     * @return bool True if disconnected successfully, false otherwise.
3050     */
3051    public function delete_all_connection_tokens( $ignore_connected_plugins = false ) {
3052        // refuse to delete if we're not the last Jetpack plugin installed.
3053        if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
3054            return false;
3055        }
3056
3057        /**
3058         * Fires upon the disconnect attempt.
3059         * Return `false` to prevent the disconnect.
3060         *
3061         * @since 1.14.2
3062         */
3063        if ( ! apply_filters( 'jetpack_connection_delete_all_tokens', true ) ) {
3064            return false;
3065        }
3066
3067        // The protected owner anchor is a local cache of a record WordPress.com owns. Dropping it
3068        // here keeps a disconnected site from carrying a lock that names a user who no longer holds
3069        // a token; the anchor is re-established from WordPress.com when the owner reconnects.
3070        \Jetpack_Options::delete_option(
3071            array(
3072                'master_user',
3073                'protected_owner',
3074                'time_diff',
3075                'fallback_no_verify_ssl_certs',
3076            )
3077        );
3078
3079        // Clear the memoized connection owner ID since it changed
3080        self::$connection_owner_id = null;
3081
3082        ( new Secrets() )->delete_all();
3083        $this->get_tokens()->delete_all();
3084
3085        // Delete cached connected user data.
3086        $transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
3087        delete_transient( $transient_key );
3088
3089        // Delete the cached site record, which a later connection must not serve.
3090        self::delete_cached_site_data();
3091
3092        // Delete all XML-RPC errors.
3093        Error_Handler::get_instance()->delete_all_errors();
3094
3095        return true;
3096    }
3097
3098    /**
3099     * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
3100     * If the plugin object has been provided in the constructor, the function first check
3101     * whether it's the only active connection.
3102     * If there are any other connections, the function will do nothing and return `false`
3103     * (unless `$ignore_connected_plugins` is set to `true`).
3104     *
3105     * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
3106     *
3107     * @return bool True if disconnected successfully, false otherwise.
3108     */
3109    public function disconnect_site_wpcom( $ignore_connected_plugins = false ) {
3110        if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
3111            return false;
3112        }
3113
3114        if ( ( new Status() )->is_offline_mode() && ! apply_filters( 'jetpack_connection_disconnect_site_wpcom_offline_mode', false ) ) {
3115            // Prevent potential disconnect of the live site by removing WPCOM tokens.
3116            return false;
3117        }
3118
3119        /**
3120         * Fires upon the disconnect attempt.
3121         * Return `false` to prevent the disconnect.
3122         *
3123         * @since 1.14.2
3124         */
3125        if ( ! apply_filters( 'jetpack_connection_disconnect_site_wpcom', true, $this ) ) {
3126            return false;
3127        }
3128
3129        $xml = new Jetpack_IXR_Client();
3130        $xml->query( 'jetpack.deregister', get_current_user_id() );
3131
3132        return true;
3133    }
3134
3135    /**
3136     * Disconnect the plugin and remove the tokens.
3137     * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
3138     * This is a proxy method to simplify the Connection package API.
3139     *
3140     * @see Manager::disconnect_site()
3141     *
3142     * @param boolean $disconnect_wpcom Should disconnect_site_wpcom be called.
3143     * @param bool    $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
3144     * @return bool
3145     */
3146    public function remove_connection( $disconnect_wpcom = true, $ignore_connected_plugins = false ) {
3147
3148        $this->disconnect_site( $disconnect_wpcom, $ignore_connected_plugins );
3149
3150        return true;
3151    }
3152
3153    /**
3154     * Completely clearing up the connection, and initiating reconnect.
3155     *
3156     * @return true|WP_Error True if reconnected successfully, a `WP_Error` object otherwise.
3157     */
3158    public function reconnect() {
3159        ( new Tracking() )->record_user_event( 'restore_connection_reconnect' );
3160
3161        $this->disconnect_site_wpcom( true );
3162
3163        return $this->register();
3164    }
3165
3166    /**
3167     * Validate the tokens, and refresh the invalid ones.
3168     *
3169     * Branches on the current user's tokens, not the owner's: a user with no token goes to authorize().
3170     * If both tokens are healthy but the owner has an error, only the current user is relinked.
3171     *
3172     * @since 9.18.0 Relink only the current user when the owner's connection is broken and both tokens are healthy.
3173     * @since 9.8.1 When token validation is inconclusive, check the blog token on its own instead of assuming both are broken.
3174     *
3175     * @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.
3176     */
3177    public function restore() {
3178        // If this is a site connection we need to trigger a full reconnection as our only secure means of
3179        // communication with WPCOM, aka the blog token, is compromised.
3180        if ( $this->is_site_connection() ) {
3181            return $this->reconnect();
3182        }
3183
3184        $validate_tokens_response = $this->get_tokens()->validate();
3185
3186        if ( is_array( $validate_tokens_response ) &&
3187            isset( $validate_tokens_response['blog_token']['is_healthy'] ) &&
3188            isset( $validate_tokens_response['user_token']['is_healthy'] ) ) {
3189            $blog_token_healthy = $validate_tokens_response['blog_token']['is_healthy'];
3190            $user_token_healthy = $validate_tokens_response['user_token']['is_healthy'];
3191        } else {
3192            // The paired health check could not run (a token is missing locally â€” e.g. a
3193            // deleted owner token â€” or the request failed): no evidence the blog token is
3194            // broken, and it's the one credential reconnect() would revoke for every user,
3195            // so check it on its own before that teardown.
3196            $blog_token_healthy = true === $this->get_tokens()->validate_blog_token();
3197            $user_token_healthy = false; // Unknown, treated as unhealthy.
3198        }
3199
3200        // Both healthy, but the owner is recorded as broken: relink only this user, not the whole site.
3201        if ( $blog_token_healthy && $user_token_healthy && $this->can_relink_as_owner() ) {
3202            $this->remember_unusable_owner();
3203            return ( true === $this->refresh_user_token() ) ? 'authorize' : false;
3204        }
3205
3206        // Tokens are both valid, or both invalid. We can't fix the problem we don't see, so the full reconnection is needed.
3207        if ( $blog_token_healthy === $user_token_healthy ) {
3208            $result = $this->reconnect();
3209            return ( true === $result ) ? 'authorize' : $result;
3210        }
3211
3212        if ( ! $blog_token_healthy ) {
3213            return $this->refresh_blog_token();
3214        }
3215
3216        if ( ! $user_token_healthy ) {
3217            $this->remember_unusable_owner();
3218            return ( true === $this->refresh_user_token() ) ? 'authorize' : false;
3219        }
3220
3221        return false;
3222    }
3223
3224    /**
3225     * Whether relinking the current user would repair a recorded broken connection owner.
3226     *
3227     * True when the owner has a recorded error and relinking would make the current user the owner.
3228     * Anyone else would only be linked, so unlinking them would fix nothing.
3229     *
3230     * @since 9.18.0
3231     *
3232     * @return bool
3233     */
3234    private function can_relink_as_owner() {
3235        return $this->has_owner_connection_error() && $this->can_take_owner_slot();
3236    }
3237
3238    /**
3239     * Responds to a WordPress.com call to register the current site.
3240     * Should be changed to protected.
3241     *
3242     * @param array $registration_data Array of [ secret_1, user_id ].
3243     */
3244    public function handle_registration( array $registration_data ) {
3245        list( $registration_secret_1, $registration_user_id ) = $registration_data;
3246        if ( empty( $registration_user_id ) ) {
3247            return new \WP_Error( 'registration_state_invalid', __( 'Invalid Registration State', 'jetpack-connection' ), 400 );
3248        }
3249
3250        return ( new Secrets() )->verify( 'register', $registration_secret_1, (int) $registration_user_id );
3251    }
3252
3253    /**
3254     * Perform the API request to validate the blog and user tokens.
3255     *
3256     * @deprecated 1.24.0 Use Automattic\Jetpack\Connection\Tokens->validate_tokens() instead.
3257     *
3258     * @param int|null $user_id ID of the user we need to validate token for. Current user's ID by default.
3259     *
3260     * @return array|false|WP_Error The API response: `array( 'blog_token_is_healthy' => true|false, 'user_token_is_healthy' => true|false )`.
3261     */
3262    public function validate_tokens( $user_id = null ) {
3263        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Tokens->validate' );
3264        return $this->get_tokens()->validate( $user_id );
3265    }
3266
3267    /**
3268     * Verify a Previously Generated Secret.
3269     *
3270     * @deprecated 1.24.0 Use Automattic\Jetpack\Connection\Secrets->verify() instead.
3271     *
3272     * @param string $action   The type of secret to verify.
3273     * @param string $secret_1 The secret string to compare to what is stored.
3274     * @param int    $user_id  The user ID of the owner of the secret.
3275     * @return \WP_Error|string WP_Error on failure, secret_2 on success.
3276     */
3277    public function verify_secrets( $action, $secret_1, $user_id ) {
3278        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Secrets->verify' );
3279        return ( new Secrets() )->verify( $action, $secret_1, $user_id );
3280    }
3281
3282    /**
3283     * Responds to a WordPress.com call to authorize the current user.
3284     * Should be changed to protected.
3285     */
3286    public function handle_authorization() {
3287    }
3288
3289    /**
3290     * Obtains the auth token.
3291     *
3292     * @param array $data The request data.
3293     * @return object|\WP_Error Returns the auth token on success.
3294     *                          Returns a \WP_Error on failure.
3295     */
3296    public function get_token( $data ) {
3297        return $this->get_tokens()->get( $data, $this->api_url( 'token' ) );
3298    }
3299
3300    /**
3301     * Builds a URL to the Jetpack connection auth page.
3302     *
3303     * @since 2.7.6 Added optional $from and $raw parameters.
3304     *
3305     * @param WP_User|null $user     (optional) defaults to the current logged in user.
3306     * @param string|null  $redirect (optional) a redirect URL to use instead of the default.
3307     * @param bool|string  $from     If not false, adds 'from=$from' param to the connect URL.
3308     * @param bool         $raw If true, URL will not be escaped.
3309     *
3310     * @return string Connect URL.
3311     */
3312    public function get_authorization_url( $user = null, $redirect = null, $from = false, $raw = false ) {
3313        if ( empty( $user ) ) {
3314            $user = wp_get_current_user();
3315        }
3316
3317        $roles       = new Roles();
3318        $role        = $roles->translate_user_to_role( $user );
3319        $signed_role = $this->get_tokens()->sign_role( $role );
3320
3321        /**
3322         * Filter the URL of the first time the user gets redirected back to your site for connection
3323         * data processing.
3324         *
3325         * @since 1.7.0
3326         * @since-jetpack 8.0.0
3327         *
3328         * @param string $redirect_url Defaults to the site admin URL.
3329         */
3330        $processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
3331
3332        /**
3333         * Filter the URL to redirect the user back to when the authorization process
3334         * is complete.
3335         *
3336         * @since 1.7.0
3337         * @since-jetpack 8.0.0
3338         *
3339         * @param string $redirect_url Defaults to the site URL.
3340         */
3341        $redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
3342
3343        $secrets = ( new Secrets() )->generate( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
3344
3345        /**
3346         * Filter the type of authorization.
3347         * 'calypso' completes authorization on wordpress.com/jetpack/connect
3348         * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
3349         *
3350         * @since 1.7.0
3351         * @since-jetpack 4.3.3
3352         *
3353         * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
3354         */
3355        $auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
3356
3357        $body_args = array(
3358            'response_type'         => 'code',
3359            'client_id'             => \Jetpack_Options::get_option( 'id' ),
3360            'redirect_uri'          => add_query_arg(
3361                array(
3362                    'handler'  => 'jetpack-connection-webhooks',
3363                    'action'   => 'authorize',
3364                    '_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
3365                    'redirect' => $redirect ? rawurlencode( $redirect ) : false,
3366                ),
3367                esc_url( $processing_url )
3368            ),
3369            'state'                 => $user->ID,
3370            'scope'                 => $signed_role,
3371            'user_email'            => $user->user_email,
3372            'user_login'            => $user->user_login,
3373            'is_active'             => $this->has_connected_owner(), // TODO Deprecate this.
3374            'jp_version'            => (string) Constants::get_constant( 'JETPACK__VERSION' ),
3375            'auth_type'             => $auth_type,
3376            'secret'                => $secrets['secret_1'],
3377            'blogname'              => get_option( 'blogname' ),
3378            'site_url'              => Urls::site_url(),
3379            'home_url'              => Urls::home_url(),
3380            'site_icon'             => get_site_icon_url(),
3381            'site_lang'             => get_locale(),
3382            'site_created'          => $this->get_assumed_site_creation_date(),
3383            'allow_site_connection' => ! $this->has_connected_owner(),
3384            'calypso_env'           => ( new Host() )->get_calypso_env(),
3385            'source'                => ( new Host() )->get_source_query(),
3386        );
3387
3388        // Include the slugs of every plugin currently using the Jetpack connection so wpcom
3389        // knows which integrations the site is authorizing on behalf of. `Plugin_Storage::get_all()`
3390        // returns a `WP_Error` when called before `plugins_loaded`; in that case we silently skip.
3391        $active_plugins = Plugin_Storage::get_all();
3392        if ( is_array( $active_plugins ) && ! empty( $active_plugins ) ) {
3393            $body_args['plugins'] = implode( ',', array_keys( $active_plugins ) );
3394        }
3395
3396        // Signal to Calypso that the site already has a connection owner so the
3397        // authorize page can show secondary-connection content where appropriate.
3398        if ( $this->has_connected_owner() ) {
3399            $body_args['has_connected_owner'] = true;
3400        }
3401
3402        /**
3403         * Filters the user connection request data for additional property addition.
3404         *
3405         * @since 1.7.0
3406         * @since-jetpack 8.0.0
3407         *
3408         * @param array $request_data request data.
3409         */
3410        $body = apply_filters( 'jetpack_connect_request_body', $body_args );
3411
3412        $body = static::apply_activation_source_to_args( urlencode_deep( $body ) );
3413
3414        $api_url = $this->api_url( 'authorize' );
3415
3416        $url = add_query_arg( $body, $api_url );
3417
3418        if ( is_network_admin() ) {
3419            $url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
3420        }
3421
3422        if ( $from ) {
3423            $url = add_query_arg( 'from', $from, $url );
3424        }
3425
3426        if ( $raw ) {
3427            $url = esc_url_raw( $url );
3428        }
3429
3430        /**
3431         * Filter the URL used when connecting a user to a WordPress.com account.
3432         *
3433         * @since 2.0.0
3434         * @since 2.7.6 Added $raw parameter.
3435         *
3436         * @param string $url Connection URL.
3437         * @param bool   $raw If true, URL will not be escaped.
3438         */
3439        return apply_filters( 'jetpack_build_authorize_url', $url, $raw );
3440    }
3441
3442    /**
3443     * Authorizes the user by obtaining and storing the user token.
3444     *
3445     * When ownership is transferable, the token request claims the owner slot, and a `connection_owner`
3446     * answer from WordPress.com decides the owner. Without an answer, a user with `jetpack_connect`
3447     * takes a vacant slot, unless a lock protects a recorded owner (see can_fill_unconnected_owner_slot()).
3448     * Anyone else is linked as a secondary user.
3449     *
3450     * @since 9.8.1 Only a user with `jetpack_connect` can take a vacant connection owner slot.
3451     * @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.
3452     *
3453     * @param array $data The request data.
3454     * @return string|\WP_Error 'authorized' when the user is now the connection owner, 'linked'
3455     *                          when connected as a secondary user, or a \WP_Error on failure.
3456     */
3457    public function authorize( $data = array() ) {
3458        /**
3459         * Action fired when user authorization starts.
3460         *
3461         * @since 1.7.0
3462         * @since-jetpack 8.0.0
3463         */
3464        do_action( 'jetpack_authorize_starting' );
3465
3466        $roles = new Roles();
3467        $role  = $roles->translate_current_user_to_role();
3468
3469        if ( ! $role ) {
3470            return new \WP_Error( 'no_role', 'Invalid request.', 400 );
3471        }
3472
3473        $cap = $roles->translate_role_to_cap( $role );
3474        if ( ! $cap ) {
3475            return new \WP_Error( 'no_cap', 'Invalid request.', 400 );
3476        }
3477
3478        // The role passes on its name alone; check the capability `Tokens::get()` will require before WordPress.com issues a token.
3479        if ( ! current_user_can( $cap ) ) {
3480            return new \WP_Error( 'current_user_cannot', 'The current user lacks the capability required for their role.', 400 );
3481        }
3482
3483        if ( ! empty( $data['error'] ) ) {
3484            return new \WP_Error( $data['error'], 'Error included in the request.', 400 );
3485        }
3486
3487        if ( ! isset( $data['state'] ) ) {
3488            return new \WP_Error( 'no_state', 'Request must include state.', 400 );
3489        }
3490
3491        if ( ! ctype_digit( $data['state'] ) ) {
3492            return new \WP_Error( $data['error'], 'State must be an integer.', 400 );
3493        }
3494
3495        $current_user_id = get_current_user_id();
3496        if ( $current_user_id !== (int) $data['state'] ) {
3497            return new \WP_Error( 'wrong_state', 'State does not match current user.', 400 );
3498        }
3499
3500        if ( empty( $data['code'] ) ) {
3501            return new \WP_Error( 'no_code', 'Request must include an authorization code.', 400 );
3502        }
3503
3504        // Only a user who may manage the site connection can own it; others link as secondary users.
3505        $can_manage_connection = current_user_can( 'jetpack_connect' );
3506        $recorded_owner_id     = (int) \Jetpack_Options::get_option( 'master_user' );
3507
3508        // A locked site never claims, so WordPress.com leaves the owner to the site's own rule.
3509        $send_owner_claim = $can_manage_connection && $this->is_ownership_transferable();
3510        $owner_claim      = $send_owner_claim ? array(
3511            'owner_claim'          => 1,
3512            // Read before the token write, which clears the stored errors this reads.
3513            'local_owner_unusable' => $this->is_owner_slot_unusable() ? 1 : 0,
3514        ) : array();
3515
3516        $token_details = null;
3517        $token         = $this->get_tokens()->get(
3518            $data,
3519            $this->api_url( 'token' ),
3520            $owner_claim,
3521            $token_details
3522        );
3523
3524        if ( is_wp_error( $token ) ) {
3525            $code = $token->get_error_code();
3526            if ( empty( $code ) ) {
3527                $code = 'invalid_token';
3528            }
3529            return new \WP_Error( $code, $token->get_error_message(), 400 );
3530        }
3531
3532        if ( ! $token ) {
3533            return new \WP_Error( 'no_token', 'Error generating token.', 400 );
3534        }
3535
3536        // WordPress.com answers only a claim it doesn't block; without an answer, fall back to the vacant-slot rule.
3537        $wpcom_answer        = $send_owner_claim && is_array( $token_details ) && isset( $token_details['connection_owner'] ) ? (bool) $token_details['connection_owner'] : null;
3538        $wpcom_decided       = null !== $wpcom_answer;
3539        $is_connection_owner = $wpcom_decided
3540            ? $wpcom_answer
3541            : $can_manage_connection && ! $this->has_connected_owner() && $this->can_fill_unconnected_owner_slot( $current_user_id );
3542        $owner_changed       = $is_connection_owner && $recorded_owner_id && $recorded_owner_id !== $current_user_id;
3543
3544        $this->get_tokens()->update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_connection_owner );
3545
3546        // Kept until the token request succeeds, so a failed one can retry with it. update_user_token() returns no usable result.
3547        delete_user_option( $current_user_id, self::RELINK_OWNER_UNUSABLE_META );
3548
3549        if ( $owner_changed ) {
3550            // The owner changed under the memoized ID.
3551            $this->reset_connection_status();
3552        }
3553
3554        // Delete cached connected user data, so a cached failure from the
3555        // previous (broken) token doesn't linger after reconnecting.
3556        delete_transient( "jetpack_connected_user_data_$current_user_id" );
3557
3558        /**
3559         * Fires after user has successfully received an auth token.
3560         *
3561         * @since 1.7.0
3562         * @since-jetpack 3.9.0
3563         */
3564        do_action( 'jetpack_user_authorized' );
3565
3566        if ( ! $is_connection_owner ) {
3567            /**
3568             * Action fired when a secondary user has been authorized.
3569             *
3570             * @since 1.7.0
3571             * @since-jetpack 8.0.0
3572             */
3573            do_action( 'jetpack_authorize_ending_linked' );
3574            return 'linked';
3575        }
3576
3577        /**
3578         * Action fired when the master user has been authorized.
3579         *
3580         * @since 1.7.0
3581         * @since-jetpack 8.0.0
3582         *
3583         * @param array $data The request data.
3584         */
3585        do_action( 'jetpack_authorize_ending_authorized', $data );
3586
3587        \Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
3588
3589        ( new Nonce_Handler() )->reschedule();
3590
3591        return 'authorized';
3592    }
3593
3594    /**
3595     * Whether this site has no usable connection owner: none recorded, a missing or malformed token, or a token WordPress.com rejected.
3596     *
3597     * WordPress.com can't see a missing owner or a token the site holds but can't use, so the owner claim reports it.
3598     *
3599     * @since 9.18.0
3600     *
3601     * @param int|null $user_id The authorizing user's ID, whose remembered state counts. Defaults to the current user.
3602     * @return bool
3603     */
3604    private function is_owner_slot_unusable( $user_id = null ) {
3605        return ! $this->has_connected_owner() || $this->has_owner_token_rejection() || $this->is_unusable_owner_remembered( $user_id );
3606    }
3607
3608    /**
3609     * Whether connecting or relinking this user would make them the connection owner.
3610     *
3611     * The one rule behind the owner-error notice, Restore's relink and the connect prompt, so their promises match authorize().
3612     * Where WordPress.com answers the claim, it can still refuse one for a blog with a protected owner there.
3613     *
3614     * @since 9.18.0
3615     *
3616     * @param int|null $user_id The user's ID. Defaults to the current user.
3617     * @return bool
3618     */
3619    public function can_take_owner_slot( $user_id = null ) {
3620        $user_id = null === $user_id ? get_current_user_id() : (int) $user_id;
3621
3622        if ( $user_id <= 0 || ! user_can( $user_id, 'jetpack_connect' ) ) {
3623            return false;
3624        }
3625
3626        $owner_id = (int) \Jetpack_Options::get_option( 'master_user' );
3627
3628        // No owner, the owner themselves, or a deleted owner: authorize()'s fallback gives them the slot.
3629        if ( $owner_id <= 0 || $owner_id === $user_id || ! get_userdata( $owner_id ) ) {
3630            return true;
3631        }
3632
3633        if ( ! $this->is_ownership_transferable() ) {
3634            return false;
3635        }
3636
3637        // WordPress.com ignores claims on Atomic and from non-administrator codes, leaving only the local fallback.
3638        $wpcom_answers = ! ( new Host() )->is_woa_site()
3639            && 'administrator' === ( new Roles() )->translate_user_to_role( get_userdata( $user_id ) );
3640
3641        return $wpcom_answers ? $this->is_owner_slot_unusable( $user_id ) : ! $this->has_connected_owner();
3642    }
3643
3644    /**
3645     * Records for the current user that the owner is unusable, before a Restore relink clears the evidence.
3646     *
3647     * Unlinking deletes every stored error, so authorize() would otherwise report a usable owner.
3648     * The record is tied to the owner's token, so the owner reconnecting voids every user's record at once.
3649     *
3650     * @since 9.18.0
3651     */
3652    private function remember_unusable_owner() {
3653        $user_id = get_current_user_id();
3654
3655        // The evidence alone, so a remembered record can't renew itself.
3656        if ( $user_id && ( ! $this->has_connected_owner() || $this->has_owner_token_rejection() ) ) {
3657            update_user_option(
3658                $user_id,
3659                self::RELINK_OWNER_UNUSABLE_META,
3660                array(
3661                    'owner' => (int) \Jetpack_Options::get_option( 'master_user' ),
3662                    'token' => $this->get_owner_token_hash(),
3663                    'time'  => time(),
3664                )
3665            );
3666        }
3667    }
3668
3669    /**
3670     * A hash of the connection owner's stored token, or an empty string when there is none.
3671     *
3672     * @since 9.18.0
3673     *
3674     * @return string
3675     */
3676    private function get_owner_token_hash() {
3677        $owner_id = (int) \Jetpack_Options::get_option( 'master_user' );
3678        $tokens   = $this->get_tokens()->get_user_tokens();
3679
3680        return $owner_id > 0 && is_array( $tokens ) && ! empty( $tokens[ $owner_id ] ) && is_string( $tokens[ $owner_id ] )
3681            ? wp_hash( $tokens[ $owner_id ] )
3682            : '';
3683    }
3684
3685    /**
3686     * Whether remember_unusable_owner() recorded the current owner and owner token within the last hour.
3687     *
3688     * @since 9.18.0
3689     *
3690     * @param int|null $user_id The user's ID. Defaults to the current user.
3691     * @return bool
3692     */
3693    private function is_unusable_owner_remembered( $user_id = null ) {
3694        $user_id = null === $user_id ? get_current_user_id() : (int) $user_id;
3695        $record  = $user_id > 0 ? get_user_option( self::RELINK_OWNER_UNUSABLE_META, $user_id ) : null;
3696
3697        return is_array( $record )
3698            && isset( $record['owner'] )
3699            && isset( $record['token'] )
3700            && isset( $record['time'] )
3701            && (int) $record['owner'] === (int) \Jetpack_Options::get_option( 'master_user' )
3702            && hash_equals( $this->get_owner_token_hash(), (string) $record['token'] )
3703            && time() - (int) $record['time'] <= HOUR_IN_SECONDS;
3704    }
3705
3706    /**
3707     * Whether WordPress.com has rejected the owner's token on a request this site signed.
3708     *
3709     * @since 9.18.0
3710     *
3711     * @return bool
3712     */
3713    private function has_owner_token_rejection() {
3714        // A partial update can load this class alongside an Error_Handler that predates the method.
3715        return method_exists( Error_Handler::class, 'has_owner_token_rejection' )
3716            && Error_Handler::get_instance()->has_owner_token_rejection();
3717    }
3718
3719    /**
3720     * Whether the authorizing user may fill an owner slot that has no connected owner.
3721     *
3722     * A recorded owner whose token is missing or malformed is not a connected owner, but a lock must
3723     * still protect them. A deleted owner can never reconnect, so their slot counts as vacant.
3724     *
3725     * @since 9.18.0
3726     *
3727     * @param int $user_id The authorizing user's ID.
3728     * @return bool
3729     */
3730    private function can_fill_unconnected_owner_slot( $user_id ) {
3731        $recorded_owner_id = (int) \Jetpack_Options::get_option( 'master_user' );
3732
3733        return ! $recorded_owner_id
3734            || $recorded_owner_id === $user_id
3735            || ! get_userdata( $recorded_owner_id )
3736            || $this->is_ownership_transferable();
3737    }
3738
3739    /**
3740     * Whether an error on record says the connection owner's own connection is broken.
3741     *
3742     * Covers what has_connected_owner() cannot see: a token that is present but rejected by WordPress.com.
3743     *
3744     * @since 9.18.0
3745     *
3746     * @return bool
3747     */
3748    private function has_owner_connection_error() {
3749        // A partial update can load this class alongside an Error_Handler that predates the method.
3750        return method_exists( Error_Handler::class, 'has_owner_connection_error' )
3751            && Error_Handler::get_instance()->has_owner_connection_error();
3752    }
3753
3754    /**
3755     * Disconnects from the Jetpack servers.
3756     * Forgets all connection details and tells the Jetpack servers to do the same.
3757     *
3758     * @param boolean $disconnect_wpcom Should disconnect_site_wpcom be called.
3759     * @param bool    $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
3760     */
3761    public function disconnect_site( $disconnect_wpcom = true, $ignore_connected_plugins = true ) {
3762        if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
3763            return false;
3764        }
3765
3766        wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3767
3768        ( new Nonce_Handler() )->clean_all();
3769
3770        Heartbeat::init()->deactivate();
3771
3772        /**
3773         * Fires before a site is disconnected.
3774         *
3775         * @since 1.36.3
3776         */
3777        do_action( 'jetpack_site_before_disconnected' );
3778
3779        // If the site is in an IDC because sync is not allowed,
3780        // let's make sure to not disconnect the production site.
3781        if ( $disconnect_wpcom ) {
3782            $tracking = new Tracking();
3783            $tracking->record_user_event( 'disconnect_site', array() );
3784
3785            $this->disconnect_site_wpcom( $ignore_connected_plugins );
3786        }
3787
3788        $this->delete_all_connection_tokens( $ignore_connected_plugins );
3789
3790        // Remove tracked package versions, since they depend on the Jetpack Connection.
3791        delete_option( Package_Version_Tracker::PACKAGE_VERSION_OPTION );
3792
3793        // A failure recorded before the site got connected some other way (a migration, a restore) no longer applies.
3794        Registration_Failure::clear();
3795
3796        $jetpack_unique_connection = \Jetpack_Options::get_option( 'unique_connection' );
3797        if ( $jetpack_unique_connection ) {
3798            // Check then record unique disconnection if site has never been disconnected previously.
3799            if ( - 1 === $jetpack_unique_connection['disconnected'] ) {
3800                $jetpack_unique_connection['disconnected'] = 1;
3801            } else {
3802                if ( 0 === $jetpack_unique_connection['disconnected'] ) {
3803                    $a8c_mc_stats_instance = new A8c_Mc_Stats();
3804                    $a8c_mc_stats_instance->add( 'connections', 'unique-disconnect' );
3805                    $a8c_mc_stats_instance->do_server_side_stats();
3806                }
3807                // increment number of times disconnected.
3808                $jetpack_unique_connection['disconnected'] += 1;
3809            }
3810
3811            \Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3812        }
3813
3814        /**
3815         * Fires when a site is disconnected.
3816         *
3817         * @since 1.30.1
3818         */
3819        do_action( 'jetpack_site_disconnected' );
3820    }
3821
3822    /**
3823     * The Base64 Encoding of the SHA1 Hash of the Input.
3824     *
3825     * @param string $text The string to hash.
3826     * @return string
3827     */
3828    public function sha1_base64( $text ) {
3829        return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
3830    }
3831
3832    /**
3833     * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
3834     *
3835     * @param string $domain The domain to check.
3836     *
3837     * @return bool|WP_Error
3838     */
3839    public function is_usable_domain( $domain ) {
3840
3841        // If it's empty, just fail out.
3842        if ( ! $domain ) {
3843            return new \WP_Error(
3844                'fail_domain_empty',
3845                /* translators: %1$s is a domain name. */
3846                sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack-connection' ), $domain )
3847            );
3848        }
3849
3850        /**
3851         * Skips the usuable domain check when connecting a site.
3852         *
3853         * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
3854         *
3855         * @since 1.7.0
3856         * @since-jetpack 4.1.0
3857         *
3858         * @param bool If the check should be skipped. Default false.
3859         */
3860        if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
3861            return true;
3862        }
3863
3864        // None of the explicit localhosts.
3865        $forbidden_domains = array(
3866            'wordpress.com',
3867            'localhost',
3868            'localhost.localdomain',
3869            'local.wordpress.test',         // VVV pattern.
3870            'local.wordpress-trunk.test',   // VVV pattern.
3871            'src.wordpress-develop.test',   // VVV pattern.
3872            'build.wordpress-develop.test', // VVV pattern.
3873        );
3874        if ( in_array( $domain, $forbidden_domains, true ) ) {
3875            return new \WP_Error(
3876                'fail_domain_forbidden',
3877                sprintf(
3878                    /* translators: %1$s is a domain name. */
3879                    __(
3880                        'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
3881                        'jetpack-connection'
3882                    ),
3883                    $domain
3884                )
3885            );
3886        }
3887
3888        // No .test or .local domains.
3889        if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
3890            return new \WP_Error(
3891                'fail_domain_tld',
3892                sprintf(
3893                    /* translators: %1$s is a domain name. */
3894                    __(
3895                        'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
3896                        'jetpack-connection'
3897                    ),
3898                    $domain
3899                )
3900            );
3901        }
3902
3903        // No WPCOM subdomains.
3904        if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
3905            return new \WP_Error(
3906                'fail_subdomain_wpcom',
3907                sprintf(
3908                    /* translators: %1$s is a domain name. */
3909                    __(
3910                        'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
3911                        'jetpack-connection'
3912                    ),
3913                    $domain
3914                )
3915            );
3916        }
3917
3918        // If PHP was compiled without support for the Filter module (very edge case).
3919        if ( ! function_exists( 'filter_var' ) ) {
3920            // Just pass back true for now, and let wpcom sort it out.
3921            return true;
3922        }
3923
3924        $domain = preg_replace( '#^https?://#', '', untrailingslashit( $domain ) );
3925
3926        if ( filter_var( $domain, FILTER_VALIDATE_IP )
3927            && ! \Automattic\Jetpack\IP\Utils::ip_is_public( $domain )
3928        ) {
3929            return new \WP_Error(
3930                'fail_ip_forbidden',
3931                sprintf(
3932                    /* translators: %1$s is a domain name. */
3933                    __(
3934                        'IP address `%1$s` just failed is_usable_domain check as it is not a public IP address.',
3935                        'jetpack-connection'
3936                    ),
3937                    $domain
3938                )
3939            );
3940        }
3941
3942        return true;
3943    }
3944
3945    /**
3946     * Gets the requested token.
3947     *
3948     * @deprecated 1.24.0 Use Automattic\Jetpack\Connection\Tokens->get_access_token() instead.
3949     *
3950     * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
3951     * @param string|false $token_key If provided, check that the token matches the provided input.
3952     * @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.
3953     *
3954     * @return object|false
3955     *
3956     * @see $this->get_tokens()->get_access_token()
3957     */
3958    public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
3959        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Tokens->get_access_token' );
3960        return $this->get_tokens()->get_access_token( $user_id, $token_key, $suppress_errors );
3961    }
3962
3963    /**
3964     * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
3965     * since it is passed by reference to various methods.
3966     * Capture it here so we can verify the signature later.
3967     *
3968     * @param array $methods an array of available XMLRPC methods.
3969     * @return array the same array, since this method doesn't add or remove anything.
3970     */
3971    public function xmlrpc_methods( $methods ) {
3972        $this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'] ?? null;
3973        return $methods;
3974    }
3975
3976    /**
3977     * Resets the raw post data parameter for testing purposes.
3978     */
3979    public function reset_raw_post_data() {
3980        $this->raw_post_data = null;
3981    }
3982
3983    /**
3984     * Registering an additional method.
3985     *
3986     * @param array $methods an array of available XMLRPC methods.
3987     * @return array the amended array in case the method is added.
3988     */
3989    public function public_xmlrpc_methods( $methods ) {
3990        if ( array_key_exists( 'wp.getOptions', $methods ) ) {
3991            $methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
3992        }
3993        return $methods;
3994    }
3995
3996    /**
3997     * Handles a getOptions XMLRPC method call.
3998     *
3999     * @param array $args method call arguments.
4000     * @return array|IXR_Error An amended XMLRPC server options array.
4001     */
4002    public function jetpack_get_options( $args ) {
4003        global $wp_xmlrpc_server;
4004
4005        $wp_xmlrpc_server->escape( $args );
4006
4007        $username = $args[1];
4008        $password = $args[2];
4009
4010        $user = $wp_xmlrpc_server->login( $username, $password );
4011        if ( ! $user ) {
4012            return $wp_xmlrpc_server->error;
4013        }
4014
4015        $options   = array();
4016        $user_data = $this->get_connected_user_data();
4017        if ( is_array( $user_data ) ) {
4018            $options['jetpack_user_id']         = array(
4019                'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack-connection' ),
4020                'readonly' => true,
4021                'value'    => $user_data['ID'],
4022            );
4023            $options['jetpack_user_login']      = array(
4024                'desc'     => __( 'The WP.com username of the connected user', 'jetpack-connection' ),
4025                'readonly' => true,
4026                'value'    => $user_data['login'],
4027            );
4028            $options['jetpack_user_email']      = array(
4029                'desc'     => __( 'The WP.com user email of the connected user', 'jetpack-connection' ),
4030                'readonly' => true,
4031                'value'    => $user_data['email'],
4032            );
4033            $options['jetpack_user_site_count'] = array(
4034                'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack-connection' ),
4035                'readonly' => true,
4036                'value'    => $user_data['site_count'],
4037            );
4038        }
4039        $wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
4040        $args                           = stripslashes_deep( $args );
4041        return $wp_xmlrpc_server->wp_getOptions( $args );
4042    }
4043
4044    /**
4045     * Adds Jetpack-specific options to the output of the XMLRPC options method.
4046     *
4047     * @param array $options standard Core options.
4048     * @return array amended options.
4049     */
4050    public function xmlrpc_options( $options ) {
4051        $jetpack_client_id = false;
4052        if ( $this->is_connected() ) {
4053            $jetpack_client_id = \Jetpack_Options::get_option( 'id' );
4054        }
4055        $options['jetpack_version'] = array(
4056            'desc'     => __( 'Jetpack Plugin Version', 'jetpack-connection' ),
4057            'readonly' => true,
4058            'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
4059        );
4060
4061        $options['jetpack_client_id'] = array(
4062            'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack-connection' ),
4063            'readonly' => true,
4064            'value'    => $jetpack_client_id,
4065        );
4066        return $options;
4067    }
4068
4069    /**
4070     * Resets the saved authentication state in between testing requests.
4071     */
4072    public function reset_saved_auth_state() {
4073        $this->xmlrpc_verification = null;
4074    }
4075
4076    /**
4077     * Sign a user role with the master access token.
4078     * If not specified, will default to the current user.
4079     *
4080     * @access public
4081     *
4082     * @param string $role    User role.
4083     * @param int    $user_id ID of the user.
4084     * @return string Signed user role.
4085     */
4086    public function sign_role( $role, $user_id = null ) {
4087        return $this->get_tokens()->sign_role( $role, $user_id );
4088    }
4089
4090    /**
4091     * Set the plugin instance.
4092     *
4093     * @param Plugin $plugin_instance The plugin instance.
4094     *
4095     * @return $this
4096     */
4097    public function set_plugin_instance( Plugin $plugin_instance ) {
4098        $this->plugin = $plugin_instance;
4099
4100        return $this;
4101    }
4102
4103    /**
4104     * Retrieve the plugin management object.
4105     *
4106     * @return Plugin|null
4107     */
4108    public function get_plugin() {
4109        return $this->plugin;
4110    }
4111
4112    /**
4113     * Get all connected plugins information, excluding those disconnected by user.
4114     * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
4115     * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
4116     * so please make sure not to run the method too early in the code.
4117     *
4118     * @return array|WP_Error
4119     */
4120    public function get_connected_plugins() {
4121        $maybe_plugins = Plugin_Storage::get_all();
4122
4123        if ( $maybe_plugins instanceof WP_Error ) {
4124            return $maybe_plugins;
4125        }
4126
4127        return $maybe_plugins;
4128    }
4129
4130    /**
4131     * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
4132     * Note: this method does not remove any access tokens.
4133     *
4134     * @deprecated since 1.39.0
4135     * @return bool
4136     */
4137    public function disable_plugin() {
4138        return null;
4139    }
4140
4141    /**
4142     * Force plugin reconnect after user-initiated disconnect.
4143     * After its called, the plugin will be allowed to use the connection again.
4144     * Note: this method does not initialize access tokens.
4145     *
4146     * @deprecated since 1.39.0.
4147     * @return bool
4148     */
4149    public function enable_plugin() {
4150        return null;
4151    }
4152
4153    /**
4154     * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
4155     * If no plugin slug was passed into the constructor, always returns true.
4156     *
4157     * @deprecated 1.42.0 This method no longer has a purpose after the removal of the soft disconnect feature.
4158     *
4159     * @return bool
4160     */
4161    public function is_plugin_enabled() {
4162        return true;
4163    }
4164
4165    /**
4166     * Perform the API request to refresh the blog token.
4167     * Note that we are making this request on behalf of the Jetpack master user,
4168     * given they were (most probably) the ones that registered the site at the first place.
4169     *
4170     * @return WP_Error|bool The result of updating the blog_token option.
4171     */
4172    public function refresh_blog_token() {
4173        ( new Tracking() )->record_user_event( 'restore_connection_refresh_blog_token' );
4174
4175        $blog_id = \Jetpack_Options::get_option( 'id' );
4176        if ( ! $blog_id ) {
4177            return new WP_Error( 'site_not_registered', 'Site not registered.' );
4178        }
4179
4180        $url     = sprintf(
4181            '%s/%s/v%s/%s',
4182            Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
4183            'wpcom',
4184            '2',
4185            'sites/' . $blog_id . '/jetpack-refresh-blog-token'
4186        );
4187        $method  = 'POST';
4188        $user_id = get_current_user_id();
4189
4190        $response = Client::remote_request( compact( 'url', 'method', 'user_id' ) );
4191
4192        if ( is_wp_error( $response ) ) {
4193            return new WP_Error( 'refresh_blog_token_http_request_failed', $response->get_error_message() );
4194        }
4195
4196        $code   = wp_remote_retrieve_response_code( $response );
4197        $entity = wp_remote_retrieve_body( $response );
4198
4199        if ( $entity ) {
4200            $json = json_decode( $entity );
4201        } else {
4202            $json = false;
4203        }
4204
4205        if ( 200 !== $code ) {
4206            if ( empty( $json->code ) ) {
4207                return new WP_Error( 'unknown', '', $code );
4208            }
4209
4210            /* translators: Error description string. */
4211            $error_description = isset( $json->message ) ? sprintf( __( 'Error Details: %s', 'jetpack-connection' ), (string) $json->message ) : '';
4212
4213            return new WP_Error( (string) $json->code, $error_description, $code );
4214        }
4215
4216        if ( empty( $json->jetpack_secret ) || ! is_scalar( $json->jetpack_secret ) ) {
4217            return new WP_Error( 'jetpack_secret', '', $code );
4218        }
4219
4220        Error_Handler::get_instance()->delete_all_errors();
4221
4222        return $this->get_tokens()->update_blog_token( (string) $json->jetpack_secret );
4223    }
4224
4225    /**
4226     * Disconnect the user from WP.com, and initiate the reconnect process.
4227     *
4228     * @since 9.8.0 Added the `$force` parameter.
4229     *
4230     * @param bool $force Whether to remove the local token even if WordPress.com does not confirm the unlink.
4231     *                    When false, only the current user's own token is refreshed, never the owner's,
4232     *                    and only over a healthy blog token.
4233     * @return true|string|WP_Error True when forced. Otherwise 'authorize' when the user should authorize again, a `WP_Error` object on failure.
4234     */
4235    public function refresh_user_token( $force = true ) {
4236        $user_id = get_current_user_id();
4237
4238        if ( ! $force ) {
4239            // Unlinking the owner would leave the site without one.
4240            if ( ! $user_id || $this->is_site_connection() || $this->get_connection_owner_id() === $user_id ) {
4241                return new WP_Error(
4242                    'restore_requires_administrator',
4243                    __( 'An administrator needs to restore the Jetpack connection.', 'jetpack-connection' ),
4244                    array( 'status' => 403 )
4245                );
4246            }
4247
4248            // Relinking goes over the blog token, so it must work before anything is unlinked.
4249            $blog_token_health = $this->get_tokens()->validate_blog_token();
4250
4251            if ( is_wp_error( $blog_token_health ) ) {
4252                return new WP_Error(
4253                    'restore_check_failed',
4254                    __( 'The site connection could not be checked. Please try again shortly.', 'jetpack-connection' ),
4255                    array( 'status' => 503 )
4256                );
4257            }
4258
4259            if ( true !== $blog_token_health ) {
4260                return new WP_Error(
4261                    'restore_requires_administrator',
4262                    __( 'The site connection is broken. An administrator needs to restore it before you can reconnect your account.', 'jetpack-connection' ),
4263                    array( 'status' => 409 )
4264                );
4265            }
4266        }
4267
4268        // A forced refresh unlinks even without a stored token, as it always has.
4269        if ( $force || $this->is_user_connected( $user_id ) ) {
4270            ( new Tracking() )->record_user_event( 'restore_connection_refresh_user_token' );
4271
4272            // Unforced, the local token only goes once WordPress.com has unlinked it.
4273            $unlinked = $this->disconnect_user( $force ? null : $user_id, $force, $force );
4274
4275            if ( ! $force && ! $unlinked ) {
4276                return new WP_Error(
4277                    'restore_unlink_failed',
4278                    __( 'Your account could not be disconnected from WordPress.com. Please try again.', 'jetpack-connection' ),
4279                    array( 'status' => 502 )
4280                );
4281            }
4282        }
4283
4284        return $force ? true : 'authorize';
4285    }
4286
4287    /**
4288     * Fetches a signed token.
4289     *
4290     * @deprecated 1.24.0 Use Automattic\Jetpack\Connection\Tokens->get_signed_token() instead.
4291     *
4292     * @param object $token the token.
4293     * @return WP_Error|string a signed token
4294     */
4295    public function get_signed_token( $token ) {
4296        _deprecated_function( __METHOD__, '1.24.0', 'Automattic\\Jetpack\\Connection\\Tokens->get_signed_token' );
4297        return $this->get_tokens()->get_signed_token( $token );
4298    }
4299
4300    /**
4301     * If the site-level connection is active, add the list of plugins using connection to the heartbeat (except Jetpack itself)
4302     *
4303     * @since 6.11.0 Add the list of Jetpack package versions to the heartbeat.
4304     * @since 8.7.4 Add the missing connection owner and XML-RPC error stats to the heartbeat.
4305     * @since 8.7.9 Add the site environment stats (WordPress/PHP versions, etc.) to the heartbeat.
4306     *
4307     * @param array $stats The Heartbeat stats array.
4308     * @return array $stats
4309     */
4310    public function add_stats_to_heartbeat( $stats ) {
4311
4312        if ( ! $this->is_connected() ) {
4313            return $stats;
4314        }
4315
4316        $active_plugins_using_connection = Plugin_Storage::get_all();
4317        foreach ( array_keys( $active_plugins_using_connection ) as $plugin_slug ) {
4318            if ( 'jetpack' !== $plugin_slug ) {
4319                $stats_group             = isset( $active_plugins_using_connection['jetpack'] ) ? 'combined-connection' : 'standalone-connection';
4320                $stats[ $stats_group ][] = $plugin_slug;
4321            }
4322        }
4323
4324        $stats['jetpack_package_versions'] = apply_filters( 'jetpack_package_versions', array() );
4325
4326        $stats['identitycrisis'] = Identity_Crisis::check_identity_crisis() ? 'yes' : 'no';
4327
4328        // Missing the connection owner?
4329        $stats['missing-owner'] = $this->is_missing_connection_owner();
4330
4331        $xmlrpc_errors = \Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4332        if ( $xmlrpc_errors ) {
4333            $stats['xmlrpc-errors'] = implode( ',', array_keys( $xmlrpc_errors ) );
4334            \Jetpack_Options::delete_option( 'xmlrpc_errors' );
4335        }
4336
4337        // Site environment stats (WordPress/PHP versions, site configuration, etc.).
4338        $stats = array_merge( $stats, Heartbeat::get_environment_stats() );
4339
4340        return $stats;
4341    }
4342
4343    /**
4344     * Records a failed XML-RPC signature verification so it can be reported in the heartbeat.
4345     *
4346     * We don't want to expose a detailed error message about why a request failed
4347     * signature verification, as doing so could leak information. Instead, we track
4348     * that the error occurred via a Jetpack option and send that data back in the
4349     * heartbeat. All this does is record the error code, but it's enough to find trends.
4350     *
4351     * @since 8.7.4
4352     *
4353     * @param \WP_Error $xmlrpc_error The error produced during signature validation.
4354     * @return void
4355     */
4356    public function track_xmlrpc_error( $xmlrpc_error ) {
4357        $code = is_wp_error( $xmlrpc_error )
4358            ? $xmlrpc_error->get_error_code()
4359            : 'should-not-happen';
4360
4361        $xmlrpc_errors = \Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4362        if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4363            // No need to update the option if we already have this code stored.
4364            return;
4365        }
4366        $xmlrpc_errors[ $code ] = true;
4367
4368        \Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
4369    }
4370
4371    /**
4372     * Get the WPCOM or self-hosted site ID.
4373     *
4374     * @param bool $quiet Return null instead of an error.
4375     *
4376     * @return int|WP_Error|null
4377     */
4378    public static function get_site_id( $quiet = false ) {
4379        $is_wpcom = ( defined( 'IS_WPCOM' ) && IS_WPCOM );
4380        $site_id  = $is_wpcom ? get_current_blog_id() : \Jetpack_Options::get_option( 'id' );
4381        if ( ! $site_id ) {
4382            return $quiet
4383                ? null
4384                : new \WP_Error(
4385                    'unavailable_site_id',
4386                    __( 'Sorry, something is wrong with your Jetpack connection.', 'jetpack-connection' ),
4387                    403
4388                );
4389        }
4390        return (int) $site_id;
4391    }
4392
4393    /**
4394     * Check if Jetpack is ready for uninstall cleanup.
4395     *
4396     * @param string $current_plugin_slug The current plugin's slug.
4397     *
4398     * @return bool
4399     */
4400    public static function is_ready_for_cleanup( $current_plugin_slug ) {
4401        $active_plugins = get_option( Plugin_Storage::ACTIVE_PLUGINS_OPTION_NAME );
4402
4403        return empty( $active_plugins ) || ! is_array( $active_plugins )
4404            || ( count( $active_plugins ) === 1 && array_key_exists( $current_plugin_slug, $active_plugins ) );
4405    }
4406}