Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.69% covered (success)
97.69%
633 / 648
81.13% covered (warning)
81.13%
43 / 53
CRAP
0.00% covered (danger)
0.00%
0 / 1
Error_Handler
97.69% covered (success)
97.69%
633 / 648
81.13% covered (warning)
81.13%
43 / 53
278
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 get_displayable_errors
99.07% covered (success)
99.07%
107 / 108
0.00% covered (danger)
0.00%
0 / 1
58
 get_error_display_config
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 get_error_display_configs
100.00% covered (success)
100.00%
50 / 50
100.00% covered (success)
100.00%
1 / 1
2
 get_invalid_connection_owner_message
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_blocked_request_message
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_wpcom_ssl_verification_failed_message
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 classify_error_audience
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 has_site_connection_error
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
8
 is_owner_scoped_error
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 get_connect_user_url
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
10
 get_owner_reconnect_message
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 join_owner_error_sentences
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 has_owner_connection_error
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
6
 has_owner_token_rejection
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
7.04
 can_take_owner_slot
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 promote_owner_errors
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
8
 handle_verified_errors
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 should_allow_error_filtering
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
4.25
 jetpack_react_dashboard_error
89.29% covered (warning)
89.29%
25 / 28
0.00% covered (danger)
0.00%
0 / 1
12.18
 get_instance
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 report_error
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
6
 should_report_error
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
5.03
 error_reporting_gate_transient
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 store_error
87.50% covered (warning)
87.50%
14 / 16
0.00% covered (danger)
0.00%
0 / 1
7.10
 build_action_error_data
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
5
 build_error_array
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
5.01
 build_connection_error_data
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
4
 build_connection_wp_error
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 wp_error_to_array
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
13
 send_error_to_wpcom
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
 encrypt_data_to_wpcom
50.00% covered (danger)
50.00%
2 / 4
0.00% covered (danger)
0.00%
0 / 1
2.50
 get_user_id_from_token
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 get_stored_errors
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 get_verified_errors
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 garbage_collector
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
5
 delete_all_errors
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 delete_all_api_errors
95.45% covered (success)
95.45%
21 / 22
0.00% covered (danger)
0.00%
0 / 1
12
 delete_all_errors_and_return_unfiltered_value
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 delete_stored_errors
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 delete_verified_errors
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 purge_error_option_cache
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 delete_error_by_code
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
6
 get_error_by_nonce
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 verify_error
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 register_verify_error_endpoint
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
1
 verify_xml_rpc_error
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 generic_admin_notice_error
94.74% covered (success)
94.74%
36 / 38
0.00% covered (danger)
0.00%
0 / 1
15.03
 check_api_response_for_errors
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
14
 check_signed_request_for_errors
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
6
 check_xmlrpc_fault_for_errors
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 has_external_filters
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 invalidate_displayable_errors_cache
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * The Jetpack Connection error class file.
4 *
5 * @package automattic/jetpack-connection
6 */
7
8namespace Automattic\Jetpack\Connection;
9
10/**
11 * The Jetpack Connection error handler.
12 *
13 * This class stores and surfaces connection (authentication/signature) errors for requests
14 * in both directions: incoming (WP.com to this site) and outgoing (this site to WP.com).
15 *
16 * Flow 1 â€” incoming request errors. Entry point: `report_error()`.
17 *
18 * 1. An incoming XML-RPC or REST API request with an invalid signature triggers an error in
19 *    `Manager::verify_xml_rpc_signature()`, which reports it here. (Signed incoming REST
20 *    requests are funneled into the same verification path by `REST_Authentication`.)
21 * 2. Applies a gate to only process each error code once an hour to avoid overflow
22 * 3. It stores the error in the database, but we don't know yet if this is a valid error, because
23 *    we can't confirm it came from WP.com.
24 * 4. It encrypts the error details and sends it to the wp.com server
25 * 5. wp.com checks it and, if valid, sends a new request back to this site using the verify_xml_rpc_error REST endpoint
26 * 6. This endpoint adds this error to the Verified errors in the database
27 * 7. Triggers a workflow depending on the error (display user an error message, do some self healing, etc.)
28 *
29 * Flow 2 â€” outgoing request errors. Entry points: `check_api_response_for_errors()`,
30 * `check_signed_request_for_errors()`, and `check_xmlrpc_fault_for_errors()`.
31 *
32 * 1. Every signed request made through `Client::remote_request()` has its response checked
33 *    by `check_api_response_for_errors()`. A request that could not be signed at all never
34 *    gets a response, so `Client::remote_request()` passes the signing failure to
35 *    `check_signed_request_for_errors()` instead. An XML-RPC fault arrives as an HTTP 200
36 *    response with an XML body, so it never reaches `check_api_response_for_errors()` either
37 *    (which returns immediately on a 200 and decodes the body as JSON); `Jetpack_IXR_Client::query()`
38 *    calls `check_xmlrpc_fault_for_errors()` directly from its fault branch instead.
39 * 2. When the response (or the signing failure, or the fault) carries a known error code, the
40 *    error is stored and immediately marked verified (the same hourly gate applies). The
41 *    WP.com verification round-trip of flow 1 is skipped because the error arrived in a
42 *    response to a request this site itself initiated and signed â€” the failed response is its
43 *    own evidence â€” or, for signing failures, because the evidence is the site's own state.
44 *
45 * Stored errors carry two orthogonal classification fields:
46 *
47 * - `error_type` â€” the transport/source of the failed request: 'xmlrpc', 'rest',
48 *   'local_state' (connection-state errors that a successful outgoing request cannot
49 *   disprove â€” e.g. `invalid_connection_owner`, or WP.com being blocked from reaching
50 *   this site; stored as 'connection' by package versions <= 8.8), or '' for entries
51 *   stored by older package versions.
52 * - `error_direction` â€” 'incoming', 'outgoing', or '' (legacy entries and
53 *   'local_state'-type errors, which have no direction).
54 *
55 * Note on naming: both option names below contain "xmlrpc" because they predate REST
56 * support. They are intentionally kept as-is to avoid a data migration and breaking
57 * consumers that read the options directly â€” despite the names, they store errors of
58 * every type and direction.
59 *
60 * Errors are stored in the database as options in the following format:
61 *
62 * [
63 *   $error_code => [
64 *     $user_id => [
65 *       $error_details
66 *     ]
67 *   ]
68 * ]
69 *
70 * For each error code we store a maximum of 5 errors for 5 different user ids.
71 *
72 * A user ID can be:
73 * * 0 for blog tokens
74 * * positive integer for user tokens
75 * * 'invalid' for malformed tokens
76 *
77 * Example error structure:
78 * [
79 *   'invalid_token' => [
80 *     '123' => [
81 *       'error_code' => 'invalid_token',
82 *       'user_id' => '123',
83 *       'error_message' => 'The token is invalid',
84 *       'error_data' => ['action' => 'reconnect'],
85 *       'timestamp' => 1234567890,
86 *       'nonce' => 'abc123def',
87 *       'error_type' => 'xmlrpc',
88 *       'error_direction' => 'incoming'
89 *     ]
90 *   ]
91 * ]
92 *
93 * @since 1.14.2
94 */
95class Error_Handler {
96
97    /**
98     * The name of the option that stores the errors
99     *
100     * @since 1.14.2
101     *
102     * @var string
103     */
104    const STORED_ERRORS_OPTION = 'jetpack_connection_xmlrpc_errors';
105
106    /**
107     * The name of the option that stores the errors
108     *
109     * @since 1.14.2
110     *
111     * @var string
112     */
113    const STORED_VERIFIED_ERRORS_OPTION = 'jetpack_connection_xmlrpc_verified_errors';
114
115    /**
116     * The prefix of the transient that controls the gate for each error code
117     *
118     * @since 1.14.2
119     *
120     * @var string
121     */
122    const ERROR_REPORTING_GATE = 'jetpack_connection_error_reporting_gate_';
123
124    /**
125     * `error_type` value for errors from XML-RPC requests.
126     *
127     * @since 8.9.0
128     *
129     * @var string
130     */
131    const ERROR_TYPE_XMLRPC = 'xmlrpc';
132
133    /**
134     * `error_type` value for errors from REST requests.
135     *
136     * @since 8.9.0
137     *
138     * @var string
139     */
140    const ERROR_TYPE_REST = 'rest';
141
142    /**
143     * `error_type` value for local connection-state errors that involve no request,
144     * e.g. `invalid_connection_owner`. The evidence for these errors is the site's own
145     * database, which is also why they carry no `error_direction`.
146     *
147     * Note: package versions <= 8.8 stored these errors with the type 'connection'.
148     *
149     * @since 8.9.0
150     *
151     * @var string
152     */
153    const ERROR_TYPE_LOCAL_STATE = 'local_state';
154
155    /**
156     * `error_direction` value for errors triggered by incoming requests (WP.com to this site).
157     *
158     * @since 8.9.0
159     *
160     * @var string
161     */
162    const DIRECTION_INCOMING = 'incoming';
163
164    /**
165     * `error_direction` value for errors triggered by outgoing requests (this site to WP.com).
166     *
167     * @since 8.9.0
168     *
169     * @var string
170     */
171    const DIRECTION_OUTGOING = 'outgoing';
172
173    /**
174     * Time in seconds a test should live in the database before being discarded
175     *
176     * @since 1.14.2
177     */
178    const ERROR_LIFE_TIME = DAY_IN_SECONDS;
179
180    /**
181     * List of known errors. Only error codes in this list will be handled
182     *
183     * @since 1.14.2
184     *
185     * @var array
186     */
187    public $known_errors = array(
188        // Incoming request token problems (Manager::internal_verify_xml_rpc_signature).
189        'malformed_user_id',         // The user_id segment of the request token is not numeric.
190        'unknown_user',              // The request token's user does not exist on this site.
191        // Incoming and outgoing token problems (Manager::internal_verify_xml_rpc_signature; Client::build_signed_request).
192        'malformed_token',           // Request token is empty/garbled or version-mismatched (incoming); or the local token has no secret half (outgoing).
193        // Locally stored token problems (Tokens::get_access_token).
194        'no_user_tokens',            // The user_tokens option is empty; no user tokens exist at all.
195        'empty_master_user_option',  // The owner's token was requested but the master_user option is empty.
196        'no_token_for_user',         // No stored token for the requested user.
197        'token_malformed',           // The stored token for the requested user is corrupt (missing chunks).
198        'user_id_mismatch',          // The requested user ID doesn't match the user_id segment of their stored token.
199        'no_possible_tokens',        // No stored blog token.
200        'no_valid_user_token',       // The stored user token doesn't match the key the request was signed with.
201        'no_valid_blog_token',       // The stored blog token doesn't match the key the request was signed with.
202        'unknown_token',             // No stored token matches the request token's key.
203        // Signature verification problems (Jetpack_Signature), or errors WPCOM returned
204        // for an outbound request (Error_Handler::check_api_response_for_errors,
205        // Error_Handler::check_xmlrpc_fault_for_errors).
206        'could_not_sign',            // Signing the request failed for an unknown reason.
207        'invalid_scheme',            // Invalid URL scheme when signing.
208        'unknown_scheme_port',       // The URL scheme has no known port, so the signature cannot be built.
209        'invalid_secret',            // The stored token secret is invalid.
210        'invalid_token',             // No token available when signing; from WPCOM: the token used was rejected.
211        'token_mismatch',            // The request token doesn't match the token we hold.
212        'invalid_body',              // The request body is malformed.
213        'invalid_signature',         // A signature parameter is malformed, or the timestamp is off (clock skew).
214        'invalid_body_hash',         // The body hash doesn't match the request body.
215        'invalid_nonce',             // The request nonce could not be added (likely a reuse/replay).
216        'signature_mismatch',        // Computed signature differs: wrong secret, or URL/body drift (domain change, proxy).
217        // Connection state problems (Manager::get_connection_owner, Connection_Health_Tests).
218        'invalid_connection_owner',  // The connection owner cannot be resolved: token missing or WP user deleted.
219        'xmlrpc_request_blocked',    // WP.com reached the site but the request was rejected (firewall, WAF, or server rule).
220        'wpcom_ssl_verification_failed',   // WP.com could not verify the site's SSL certificate when connecting to it (expired, self-signed, or incomplete chain).
221    );
222
223    /**
224     * Holds the instance of this singleton class
225     *
226     * @since 1.14.2
227     *
228     * @var Error_Handler $instance
229     */
230    public static $instance = null;
231
232    /**
233     * Cached displayable errors to avoid duplicate processing
234     *
235     * @since 6.13.10
236     *
237     * @var array|null
238     */
239    private $cached_displayable_errors = null;
240
241    /**
242     * Initialize instance, hooks and load verified errors handlers
243     *
244     * @since 1.14.2
245     */
246    private function __construct() {
247        defined( 'JETPACK__ERRORS_PUBLIC_KEY' ) || define( 'JETPACK__ERRORS_PUBLIC_KEY', 'KdZY80axKX+nWzfrOcizf0jqiFHnrWCl9X8yuaClKgM=' );
248
249        add_action( 'rest_api_init', array( $this, 'register_verify_error_endpoint' ) );
250
251        // Handle verified errors on admin pages.
252        add_action( 'admin_init', array( $this, 'handle_verified_errors' ) );
253
254        // If the site gets reconnected, clear errors.
255        add_action( 'jetpack_site_registered', array( $this, 'delete_all_errors' ) );
256        add_action( 'jetpack_get_site_data_success', array( $this, 'delete_all_api_errors' ) );
257        add_filter( 'jetpack_connection_disconnect_site_wpcom', array( $this, 'delete_all_errors_and_return_unfiltered_value' ) );
258        add_filter( 'jetpack_connection_delete_all_tokens', array( $this, 'delete_all_errors_and_return_unfiltered_value' ) );
259        add_action( 'jetpack_unlinked_user', array( $this, 'delete_all_errors' ) );
260        add_action( 'jetpack_updated_user_token', array( $this, 'delete_all_errors' ) );
261    }
262
263    /**
264     * Gets displayable errors with predefined structure and optional filtering.
265     *
266     * This method returns a hierarchical array of errors (error_code => user_id => error_details)
267     * that can be safely displayed in My Jetpack and other UI components. It includes
268     * predefined error messages and actions, with optional filtering for specific sites.
269     * Only processes a limited set of error codes that are meant to be displayed to users.
270     *
271     * The result is specific to the current viewer: an error is omitted entirely when
272     * they lack the capability to resolve it, so viewer-facing surfaces need not gate
273     * it again. Two exceptions: a context with no current user gets the unfiltered set,
274     * and consumer-injected errors are appended after the gate. See docs/error-handling.md.
275     *
276     * error_data.action is only set when it deviates from the default behavior
277     * (e.g. 'none' to suppress the reconnect CTA, or 'connect_user' with `action_url`
278     * and `action_label` to link to the viewer's own account connection); when absent,
279     * readers fall back to offering the reconnect CTA.
280     *
281     * @since 6.13.10
282     * @since 9.8.0 Withholds a non-admin's reconnect CTA while a site connection error is on record.
283     * @since 9.18.0 Offers `connect_user` to an admin without their own connection viewing an owner error.
284     *
285     * @return array Array of displayable errors with hierarchical structure.
286     *               Example:
287     *               [
288     *                 'invalid_token' => [
289     *                   '123' => [
290     *                     'error_code' => 'invalid_token',
291     *                     'user_id' => '123',
292     *                     'error_message' => 'Your connection with WordPress.com seems to be broken...',
293     *                     'audience' => 'user',
294     *                     'error_data' => [...],
295     *                     'timestamp' => 1234567890,
296     *                     'nonce' => 'abc123def',
297     *                     'error_type' => 'xmlrpc'
298     *                   ]
299     *                 ]
300     *               ]
301     */
302    public function get_displayable_errors() {
303        $viewer_id = get_current_user_id();
304
305        // Check if we have a cached result for this viewer AND no filters are applied.
306        // The output is viewer-dependent (see audience classification below), so the
307        // cache is keyed by the current user.
308        if ( is_array( $this->cached_displayable_errors )
309            && array_key_exists( $viewer_id, $this->cached_displayable_errors )
310            && ! $this->has_external_filters() ) {
311            return $this->cached_displayable_errors[ $viewer_id ];
312        }
313
314        $verified_errors    = $this->get_verified_errors();
315        $displayable_errors = array();
316
317        // The common case is zero verified errors: skip the owner/transferability
318        // lookups entirely then. The external filter below still runs so consumers
319        // (e.g. wpcomsh) can inject errors into an empty set.
320        if ( ! empty( $verified_errors ) ) {
321            $generic_message = __( "Your connection with WordPress.com seems to be broken. If you're experiencing issues, please try reconnecting.", 'jetpack-connection' );
322
323            $owner_id        = (int) \Jetpack_Options::get_option( 'master_user' );
324            $viewer_is_owner = $owner_id > 0 && $viewer_id === $owner_id;
325            $manager         = new Manager();
326            $is_transferable = $manager->is_ownership_transferable();
327
328            // Viewer-wide, so resolved once rather than per error.
329            $viewer_can_connect      = current_user_can( 'jetpack_connect' );
330            $viewer_can_connect_user = current_user_can( 'jetpack_connect_user' );
331            $site_error_on_record    = $this->has_site_connection_error( $verified_errors, $owner_id );
332            $site_connection_broken  = ! $viewer_can_connect && $site_error_on_record;
333            // Connecting runs over the blog token, so a site error needs the reconnect CTA first.
334            $viewer_can_connect_directly = $viewer_id > 0 && $viewer_can_connect && ! $site_error_on_record && ! $manager->is_user_connected( $viewer_id );
335
336            foreach ( $verified_errors as $error_code => $users ) {
337                // Only process error codes that are meant to be displayed to users.
338                // A raw verified error whose code is marked non-displayable in
339                // get_error_display_configs() is never surfaced.
340                $display_config = $this->get_error_display_config( $error_code );
341                if ( null === $display_config ) {
342                    continue;
343                }
344
345                foreach ( $users as $user_id => $error ) {
346                    // An error that cannot be attributed to the blog token or to any user's
347                    // token belongs to no audience and is not actionable by any viewer.
348                    if ( 'invalid' === $user_id ) {
349                        continue;
350                    }
351
352                    // An owner error attributed to someone who is no longer the connection
353                    // owner describes a previous owner's token. Nobody can act on it.
354                    // Only skip when there is a current owner to compare against.
355                    if ( 'invalid_connection_owner' === $error_code
356                        && $owner_id > 0
357                        && (int) $user_id !== $owner_id ) {
358                        continue;
359                    }
360
361                    $audience = $this->classify_error_audience( $user_id, $owner_id );
362
363                    // A viewer is only ever shown errors for: their own user connection, the
364                    // site connection, or the connection owner. Another (non-owner) user's
365                    // broken token is invisible to everyone else, not just non-actionable.
366                    // `invalid_connection_owner` is exempt: when there's no current owner to
367                    // compare against, it falls back to 'user' audience by ID alone.
368                    if ( 'user' === $audience
369                        && (int) $user_id !== $viewer_id
370                        && 'invalid_connection_owner' !== $error_code ) {
371                        continue;
372                    }
373
374                    // An error a viewer cannot act on is withheld entirely.
375                    $viewer_owns_error = 'user' === $audience && ! $this->is_owner_scoped_error( $error_code, $audience );
376
377                    if ( $viewer_id > 0 ) {
378                        $can_view_error = $viewer_owns_error ? $viewer_can_connect_user : $viewer_can_connect;
379
380                        if ( ! $can_view_error ) {
381                            continue;
382                        }
383                    }
384
385                    $message = $generic_message;
386                    $action  = null;
387
388                    if ( isset( $display_config['message_callback'] ) ) {
389                        $message = call_user_func( $display_config['message_callback'], $error );
390                    }
391
392                    // The owner reading their own missing-token error. The message callback
393                    // has no viewer context, so it describes the owner in the third person â€”
394                    // correct for every other reader, but stilted for the owner themselves.
395                    // Only the missing-token flavor needs this: the deleted-WP-user flavor
396                    // cannot be viewed by an owner who no longer exists.
397                    if ( 'owner' === $audience
398                        && $viewer_is_owner
399                        && 'invalid_connection_owner' === $error_code
400                        && ! ( $error['error_data']['has_user_token'] ?? true ) ) {
401                        $message = __( 'You need to reconnect your WordPress.com account to restore the connection.', 'jetpack-connection' );
402                    } elseif ( 'owner' === $audience && ! $viewer_is_owner ) {
403                        // A secondary admin reading the owner's token error: what they're told depends on whether
404                        // they're connected and whether ownership is transferable. Name the owner only to viewers who can act.
405                        $owner_name = '';
406                        if ( $viewer_can_connect ) {
407                            $owner      = get_userdata( $owner_id );
408                            $owner_name = $owner instanceof \WP_User ? $owner->display_name : '';
409                        }
410
411                        // WordPress.com can still refuse a claim the site can't predict, so takeovers say "can", not "will".
412                        $viewer_can_take_slot = $viewer_can_connect && $this->can_take_owner_slot( $manager, $viewer_id, $is_transferable );
413                        // A deleted owner can never reconnect, so the copy offers no "instead".
414                        $owner_deleted = $owner_id > 0 && ! get_userdata( $owner_id );
415                        $lead          = $owner_deleted
416                            ? __( "The connection owner's user account no longer exists on this site.", 'jetpack-connection' )
417                            : self::get_owner_reconnect_message( $owner_name );
418
419                        if ( $viewer_can_connect_directly ) {
420                            if ( ! $viewer_can_take_slot ) {
421                                $next = __( 'You can still connect your own WordPress.com account.', 'jetpack-connection' );
422                            } elseif ( $owner_deleted ) {
423                                $next = __( 'If you connect your account, you can become the new connection owner.', 'jetpack-connection' );
424                            } else {
425                                $next = __( 'If you connect your account instead, you can become the new connection owner.', 'jetpack-connection' );
426                            }
427                            $message = self::join_owner_error_sentences( $lead, $next );
428                            $action  = 'connect_user';
429                        } elseif ( $viewer_can_take_slot ) {
430                            // Restore relinks this admin. The copy promises only the ownership change, never the disconnects a full reconnect adds.
431                            $message = self::join_owner_error_sentences(
432                                $lead,
433                                $owner_deleted
434                                    ? __( 'If you reconnect, you can become the new connection owner.', 'jetpack-connection' )
435                                    : __( 'If you reconnect instead, you can become the new connection owner.', 'jetpack-connection' )
436                            );
437                        } else {
438                            // Reconnecting would only link this admin, so only the owner can fix it.
439                            $message = $lead;
440                            $action  = 'none';
441                        }
442                    }
443
444                    // A non-admin relinks over the site connection, so while it is broken the
445                    // reconnect CTA cannot work for them. A reporter-declared action is left alone.
446                    if ( $viewer_owns_error && $site_connection_broken && empty( $error['error_data']['action'] ) ) {
447                        $message = __( 'Your WordPress.com account connection is broken, and the site connection needs attention too. Ask an administrator to restore the site connection, then reconnect your account.', 'jetpack-connection' );
448                        $action  = 'none';
449                    }
450
451                    $error['audience']      = $audience;
452                    $error['error_message'] = $message;
453
454                    // Only emit error_data.action when it deviates from the default. Readers
455                    // already fall back to the reconnect CTA when no action is set, and
456                    // injecting an explicit 'reconnect' could trip consumer code paths
457                    // reserved for custom actions.
458                    $notice_link = $display_config['notice_link'] ?? array();
459                    $has_link    = ! empty( $notice_link['url'] ) && ! empty( $notice_link['label'] );
460
461                    if ( null !== $action || ! empty( $display_config['support_link'] ) || $has_link ) {
462                        $error_data = ( isset( $error['error_data'] ) && is_array( $error['error_data'] ) ) ? $error['error_data'] : array();
463
464                        if ( null !== $action ) {
465                            $error_data['action'] = $action;
466                        }
467
468                        // No consumer handles `connect_user`, so readers render this as a plain link.
469                        if ( 'connect_user' === $action ) {
470                            $error_data['action_url']     = $this->get_connect_user_url();
471                            $error_data['action_label']   = __( 'Connect your account', 'jetpack-connection' );
472                            $error_data['tracking_event'] = 'jetpack_connection_error_notice_reconnect_cta_click';
473                        }
474
475                        // Flags a reconnect-may-not-fix-it error so the notice offers a
476                        // support link alongside the reconnect CTA. See `support_link` in
477                        // get_error_display_configs().
478                        if ( ! empty( $display_config['support_link'] ) ) {
479                            $error_data['support_link'] = true;
480                        }
481
482                        // Where the resolution lives somewhere else (Site Health for a
483                        // blocked request), carry the link on the error so every notice can
484                        // offer it â€” not just the wp-admin one. Errors like this suppress
485                        // the reconnect CTA, so without it the notice names a problem and
486                        // offers nothing to do about it. See `notice_link` in
487                        // get_error_display_configs().
488                        if ( $has_link ) {
489                            $error_data['notice_link'] = array(
490                                'label' => $notice_link['label'],
491                                'url'   => $notice_link['url'],
492                            );
493                        }
494
495                        $error['error_data'] = $error_data;
496                    }
497
498                    if ( ! isset( $displayable_errors[ $error_code ] ) ) {
499                        $displayable_errors[ $error_code ] = array();
500                    }
501                    $displayable_errors[ $error_code ][ $user_id ] = $error;
502                }
503            }
504
505            // A broken connection owner outranks everything else in the set. Run this
506            // before the external filter below so consumer-injected errors are never
507            // dropped by it â€” they are the consumer's own state, not ours to rank.
508            $displayable_errors = $this->promote_owner_errors( $displayable_errors );
509        }
510
511        /**
512         * Filter displayable connection errors to allow customization of error messages and actions.
513         *
514         * This filter allows sites to customize how connection errors are displayed,
515         * including modifying error messages, actions, and data. Access to this filter
516         * is controlled by should_allow_error_filtering().
517         *
518         * Consumer-injected errors take precedence over the default state. They are not
519         * required to carry the newer `audience` field: it is optional metadata used
520         * only for our own audience-aware messaging, and any reader must treat a missing
521         * value as site-wide (`$error['audience'] ?? 'site'`).
522         *
523         * @since 6.12.0
524         *
525         * @param array $displayable_errors Array of displayable errors with hierarchical structure.
526         * @param array $verified_errors    Array of raw verified errors from the database.
527         */
528        if ( $this->should_allow_error_filtering() ) {
529            $displayable_errors = apply_filters( 'jetpack_connection_get_verified_errors', $displayable_errors, $verified_errors );
530        }
531
532        // Only cache if no external filters are applied
533        if ( ! $this->has_external_filters() ) {
534            if ( ! is_array( $this->cached_displayable_errors ) ) {
535                $this->cached_displayable_errors = array();
536            }
537            $this->cached_displayable_errors[ $viewer_id ] = $displayable_errors;
538        }
539
540        return $displayable_errors;
541    }
542
543    /**
544     * Returns the display configuration for error codes that are meant to be
545     * displayed to users, keyed by error code.
546     *
547     * This is the whitelist consulted by get_displayable_errors(): a raw verified
548     * error whose code is not displayable here is never surfaced. Every code in
549     * `$known_errors` appears in get_error_display_configs(), non-displayable ones
550     * as `false` with the reason recorded alongside them.
551     *
552     * Copy is resolved at display time rather than stored with the error, so messages
553     * follow the viewer's locale and stay current across package updates. Adding a new
554     * error code means adding one entry to get_error_display_configs() â€” no branching
555     * in the display or notice paths.
556     *
557     * Everything here is display-time state that cannot be stored with the error:
558     * copy must resolve in each viewer's locale and follow current code, and the
559     * notice flags describe how this package renders, not the error itself. The
560     * error's *action* is deliberately NOT configured here â€” reporters declare it
561     * at creation time in `error_data['action']` (see `wp_error_to_array()`), since
562     * it is a stable machine token.
563     *
564     * Recognized keys, all optional:
565     * - `message_callback` (callable): receives the stored error array, returns the
566     *   displayable message. Omit to keep the generic reconnect copy.
567     * - `default_admin_notice` (bool): when true, generic_admin_notice_error() shows
568     *   this error's message even when no consumer supplies one via the
569     *   `jetpack_connection_error_notice_message` filter (which still overrides).
570     *   This is the only key that reaches beyond My Jetpack's own display: it opts
571     *   the code into a site-wide wp-admin notice. Leave it unset unless the error
572     *   genuinely needs that broader reach (see `xmlrpc_request_blocked` below for why).
573     * - `notice_link` (array): presentational `label` and `url` for a link the notice
574     *   offers alongside (or instead of) the CTA. It reaches two surfaces, gated
575     *   differently on purpose:
576     *   - The default wp-admin notice appends it only when showing this error's own
577     *     default message. There, `jetpack_connection_error_notice_message` hands the
578     *     consumer a bare string with no way to drop the link, so a filtered message
579     *     that kept it could end up pointing somewhere its copy never mentions.
580     *   - The displayable error carries it as `error_data['notice_link']`
581     *     unconditionally, for the connection JS package to render in its own notices.
582     *     No equivalent gate is possible or needed: `error_message` on this path is
583     *     not filtered through anything, and the one filter that can rewrite it â€”
584     *     `jetpack_connection_displayable_errors` below â€” receives the whole error
585     *     array, link included, so a consumer changing the copy can unset the link in
586     *     the same pass.
587     * - `survives_owner_promotion` (bool): when true, this code is not dropped by
588     *   promote_owner_errors() while the connection owner's own connection is broken.
589     *   Set it only for a code that is not a token problem, and so is not waiting on
590     *   the owner's reconnect to become actionable. Setting it does not make the code
591     *   trigger that reduction â€” it only exempts it from one.
592     * - `support_link` (bool): when true, `error_data['support_link']` is set on the
593     *   displayable error, and My Jetpack's notice appends a "Contact Jetpack
594     *   Support" link next to the reconnect CTA. Set it only where reconnecting is
595     *   not reliably the fix, so the viewer has somewhere else to go.
596     *
597     * @since 8.10.0
598     * @since 8.11.0 Merged with the former hardcoded list in get_displayable_errors():
599     *        this method is now also the whitelist, not just the source of overrides.
600     *
601     * @param string $error_code The error code.
602     * @return array|null Display configuration, or null if this code is not displayable.
603     */
604    private function get_error_display_config( $error_code ) {
605        $config = $this->get_error_display_configs()[ $error_code ] ?? false;
606
607        return false === $config ? null : $config;
608    }
609
610    /**
611     * Returns the display disposition of every code in `$known_errors`, keyed by
612     * error code: an array of display configuration for a displayable code, or
613     * `false` for one that is never surfaced to users.
614     *
615     * Kept in the same order as `$known_errors` so the two read side by side, and
616     * covering every code rather than only the displayable ones.
617     *
618     * Split out from get_error_display_config() so the full set can be enumerated
619     * without invoking that method once per known error code.
620     *
621     * @since 8.11.0
622     *
623     * @return array Display configuration (array) or `false`, keyed by error code.
624     */
625    private function get_error_display_configs() {
626        static $configs = null;
627
628        if ( null !== $configs ) {
629            return $configs;
630        }
631
632        // What each code means is documented once, on `$known_errors`. The comments
633        // here record only the display decision, and only where it isn't obvious: an
634        // uncommented `array()` is a broken token that reconnecting fixes, which is
635        // what the generic copy already says.
636        $configs = array(
637            // Attacker-controllable garbage in an incoming request. Nothing about this
638            // site's own connection is wrong.
639            'malformed_user_id'             => false,
640            // Expected after a user is deleted, and the owner flavor is covered by
641            // invalid_connection_owner. Incoming reports also drive WP.com-side
642            // self-healing, so a notice would surface a problem already resolving itself.
643            'unknown_user'                  => false,
644            'malformed_token'               => array(),
645            // Never connecting a WordPress.com account is expected, not broken. The owner
646            // flavor is covered by invalid_connection_owner.
647            'no_user_tokens'                => false,
648            // Same, for a site that has never had an owner. invalid_connection_owner
649            // covers the case where there was one and it broke.
650            'empty_master_user_option'      => false,
651            // As no_user_tokens, for a single requested user.
652            'no_token_for_user'             => false,
653            'token_malformed'               => array(),
654            // Corrupt local token data, but for one user only, and the
655            // no_valid_user_token/token_malformed pair surfaces it when it actually
656            // blocks a request.
657            'user_id_mismatch'              => false,
658            'no_possible_tokens'            => array(),
659            'no_valid_user_token'           => array(),
660            'no_valid_blog_token'           => array(),
661            'unknown_token'                 => array(),
662            'could_not_sign'                => array(),
663            // Both are about the URL being signed, not the connection: a code bug or an
664            // exotic site URL, which reconnecting does not change.
665            'invalid_scheme'                => false,
666            'unknown_scheme_port'           => false,
667            // Corrupt local token data like token_malformed above, caught at signing time
668            // rather than lookup time. Reconnect fixes it the same way.
669            'invalid_secret'                => array(),
670            'invalid_token'                 => array(),
671            'token_mismatch'                => array(),
672            // Per-request and transport-level, so unaffected by the state of the connection.
673            'invalid_body'                  => false,
674            // Environmental in both directions â€” a malformed parameter or clock skew,
675            // neither of which a reconnect fixes.
676            'invalid_signature'             => false,
677            // Something altered the request in transit. Not a token problem.
678            'invalid_body_hash'             => false,
679            // A replay, or object-cache trouble. Self-resolving per request.
680            'invalid_nonce'                 => false,
681            // The token key matched, so this is usually a proxy, CDN or firewall altering the request,
682            // which a reconnect doesn't fix. Hidden until it has an action of its own.
683            'signature_mismatch'            => false,
684            // Two flavors with different remedies â€” see
685            // get_invalid_connection_owner_message().
686            'invalid_connection_owner'      => array(
687                'message_callback' => array( $this, 'get_invalid_connection_owner_message' ),
688            ),
689            // The token can be perfectly valid here: the site is rejecting WordPress.com's
690            // requests, so a reconnect would be rejected the same way. The callback
691            // suppresses the reconnect CTA and names the real cause, staying brief because
692            // Site Health holds the full diagnosis. Ships a default admin notice because
693            // no other detection path can see this â€” WP.com's requests never arrive. And
694            // it outlives a broken owner, whose reconnect the same rule would block.
695            'xmlrpc_request_blocked'        => array(
696                'message_callback'         => array( $this, 'get_blocked_request_message' ),
697                'default_admin_notice'     => true,
698                'survives_owner_promotion' => true,
699                'notice_link'              => array(
700                    'label' => __( 'Visit Site Health', 'jetpack-connection' ),
701                    'url'   => admin_url( 'site-health.php' ),
702                ),
703            ),
704            // The tokens can be perfectly valid: WP.com cannot verify the site's SSL
705            // certificate, and a reconnect would be rejected the same way â€” so no
706            // reconnect CTA, and it outlives a broken owner. Ships a default admin notice
707            // for the same reason as the blocked error above: WP.com's requests never
708            // arrive, so no other detection path can see this.
709            'wpcom_ssl_verification_failed' => array(
710                'message_callback'         => array( $this, 'get_wpcom_ssl_verification_failed_message' ),
711                'default_admin_notice'     => true,
712                'survives_owner_promotion' => true,
713                'notice_link'              => array(
714                    'label' => __( 'Visit Site Health', 'jetpack-connection' ),
715                    'url'   => admin_url( 'site-health.php' ),
716                ),
717            ),
718        );
719
720        return $configs;
721    }
722
723    /**
724     * Builds the displayable message for the invalid-connection-owner error.
725     *
726     * `has_user_token` (set in Manager::get_connection_owner(), carried through into
727     * `error_data` by wp_error_to_array()) distinguishes the two flavors:
728     * - false: the owner's user token is simply missing â€” they still exist as a
729     *   WP user, so reconnecting as them restores the connection.
730     * - true: the token is there, but the WP user it points at was deleted from
731     *   this site. Nobody can reconnect as a user who no longer exists â€”
732     *   reconnecting here means a different admin becoming the new owner, not
733     *   the original owner logging back in.
734     *
735     * @since 8.11.0
736     *
737     * @param array $error The stored error array.
738     * @return string The message.
739     */
740    private function get_invalid_connection_owner_message( $error ) {
741        if ( ! ( $error['error_data']['has_user_token'] ?? true ) ) {
742            return __( 'The connection owner needs to reconnect their WordPress.com account to restore the connection.', 'jetpack-connection' );
743        }
744
745        return __( 'The WordPress.com account for this connection no longer exists on this site. An administrator needs to reconnect to become the new connection owner.', 'jetpack-connection' );
746    }
747
748    /**
749     * Builds the displayable message for the blocked-request error.
750     *
751     * Deliberately brief: Site Health holds the detailed diagnosis (including the
752     * HTTP status the site returned) and the resolution steps, so the message only
753     * names the condition and points there.
754     *
755     * @since 8.10.0
756     *
757     * @param array $error The stored error array (unused; part of the message_callback contract).
758     * @return string The message.
759     */
760    private function get_blocked_request_message( $error ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
761        return __( 'WordPress.com requests to your site are being blocked, usually by a firewall or security rule. See Site Health for details and next steps.', 'jetpack-connection' );
762    }
763
764    /**
765     * Builds the displayable message for the SSL-verification-failed error.
766     *
767     * Deliberately brief: Site Health holds the transport detail and the resolution
768     * steps, so the message only names the condition and points there.
769     *
770     * @since 9.3.0
771     *
772     * @param array $error The stored error array (unused; part of the message_callback contract).
773     * @return string The message.
774     */
775    private function get_wpcom_ssl_verification_failed_message( $error ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
776        return __( 'WordPress.com cannot securely connect to your site because its SSL certificate could not be verified. See Site Health for details and next steps.', 'jetpack-connection' );
777    }
778
779    /**
780     * Classifies the audience of a stored connection error based on its user ID.
781     *
782     * The audience determines who a connection error is relevant to and, in turn,
783     * how it should be surfaced:
784     * - `site`  : blog-token / site-wide errors (user ID `0`).
785     * - `owner` : errors tied to the connection owner's user token.
786     * - `user`  : errors tied to a specific (non-owner) user's token.
787     *
788     * Unattributable errors (user ID 'invalid') are skipped by the display pipeline
789     * before classification, so this method only receives numeric user IDs.
790     *
791     * @since 8.8.0
792     *
793     * @param string|int $user_id  The user ID associated with the error (`0` or a positive integer).
794     * @param int        $owner_id The local user ID of the connection owner, or 0 if there is none.
795     * @return string One of 'site', 'owner', or 'user'.
796     */
797    private function classify_error_audience( $user_id, $owner_id ) {
798        $user_id = (int) $user_id;
799
800        if ( 0 === $user_id ) {
801            return 'site';
802        }
803
804        if ( $owner_id > 0 && $user_id === $owner_id ) {
805            return 'owner';
806        }
807
808        return 'user';
809    }
810
811    /**
812     * Whether a displayable site-audience error is on record that would stop a user relinking.
813     *
814     * Codes that survive owner promotion are inbound failures (WordPress.com cannot reach or
815     * verify the site), which leave the outbound, blog-token-signed relink working.
816     *
817     * @since 9.8.0
818     *
819     * @param array $verified_errors The verified errors, keyed by error code then user ID.
820     * @param int   $owner_id        The local user ID of the connection owner, or 0 if there is none.
821     * @return bool
822     */
823    private function has_site_connection_error( $verified_errors, $owner_id ) {
824        foreach ( $verified_errors as $error_code => $users ) {
825            $display_config = $this->get_error_display_config( $error_code );
826
827            if ( null === $display_config || ! empty( $display_config['survives_owner_promotion'] ) || ! is_array( $users ) ) {
828                continue;
829            }
830
831            foreach ( array_keys( $users ) as $user_id ) {
832                // Must precede classification, which would cast 'invalid' to 0 and read it as 'site'.
833                if ( 'invalid' === $user_id ) {
834                    continue;
835                }
836
837                if ( 'site' === $this->classify_error_audience( $user_id, $owner_id ) ) {
838                    return true;
839                }
840            }
841        }
842
843        return false;
844    }
845
846    /**
847     * Whether an error describes the connection owner's own connection.
848     *
849     * @since 9.2.0
850     *
851     * @param string $error_code The error code.
852     * @param string $audience   The classified audience.
853     * @return bool
854     */
855    private function is_owner_scoped_error( $error_code, $audience ) {
856        return 'owner' === $audience || 'invalid_connection_owner' === $error_code;
857    }
858
859    /**
860     * The URL that starts the viewer's own account connection and returns them to the current admin page.
861     *
862     * Uses the webhook handler, so it works without the Jetpack plugin's page.
863     * Sends `connection_notice_owner_error` (see CONNECTION_FROM in js-packages/connection) everywhere except Connectors.
864     *
865     * @since 9.18.0
866     *
867     * @return string
868     */
869    private function get_connect_user_url() {
870        $return_url = admin_url( 'admin.php?page=my-jetpack' );
871        $from       = 'connection_notice_owner_error';
872
873        // Errors reach a page in its own render; any other request has no page to return to.
874        if ( is_admin() && ! wp_doing_ajax() && isset( $_SERVER['REQUEST_URI'] ) ) {
875            $request = wp_parse_url( esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
876
877            if ( ! empty( $request['path'] ) ) {
878                $file = basename( $request['path'] );
879
880                wp_parse_str( $request['query'] ?? '', $query_args );
881
882                $page = $query_args['page'] ?? '';
883                $page = is_string( $page ) ? $page : '';
884
885                // Only `page` is kept: other params (a nonce, an `action`) must not replay as a GET after auth.
886                // Re-encoded, because wp_parse_str() decoded it and add_query_arg() doesn't encode.
887                if ( '' !== $page ) {
888                    $return_url = self_admin_url( add_query_arg( 'page', rawurlencode( $page ), $file ) );
889                } elseif ( '.php' === substr( $file, -4 ) ) {
890                    $return_url = self_admin_url( $file );
891                }
892
893                // WordPress.com brands the Connectors screen on its exact legacy `from`.
894                if ( in_array( '' !== $page ? $page : $file, array( 'options-connectors.php', 'options-connectors-wp-admin' ), true ) ) {
895                    $from = 'jetpack-connector';
896                }
897            }
898        }
899
900        return add_query_arg(
901            array(
902                'handler'              => 'jetpack-connection-webhooks',
903                'connect_url_redirect' => 1,
904                'redirect_after_auth'  => rawurlencode( $return_url ),
905                'from'                 => $from,
906                'skip_pricing'         => 1,
907            ),
908            admin_url( 'admin.php' )
909        );
910    }
911
912    /**
913     * The sentence telling a non-owner viewer that the connection owner has to reconnect.
914     *
915     * @since 9.18.0
916     *
917     * @param string $owner_name The owner's display name, or '' when the viewer may not see it.
918     * @return string
919     */
920    private static function get_owner_reconnect_message( $owner_name ) {
921        return $owner_name
922            ? sprintf(
923                /* translators: %s is the display name of the Jetpack connection owner. */
924                __( 'The connection owner (%s) needs to reconnect their WordPress.com account to restore the connection.', 'jetpack-connection' ),
925                $owner_name
926            )
927            : __( 'The connection owner needs to reconnect their WordPress.com account to restore the connection.', 'jetpack-connection' );
928    }
929
930    /**
931     * Joins the owner-error lead with the sentence saying what the viewer can do.
932     *
933     * Translatable, since not every language separates sentences with a space.
934     *
935     * @since 9.18.0
936     *
937     * @param string $lead What is wrong with the owner's connection.
938     * @param string $next What the viewer can do about it.
939     * @return string
940     */
941    private static function join_owner_error_sentences( $lead, $next ) {
942        return sprintf(
943            /* translators: Joins two sentences of a connection error notice. 1: What is wrong with the connection owner's connection. 2: What the viewer can do about it. */
944            __( '%1$s %2$s', 'jetpack-connection' ),
945            $lead,
946            $next
947        );
948    }
949
950    /**
951     * Whether a displayable error is on record for the current connection owner's own connection.
952     *
953     * Drives the notice and Restore; the owner claim uses the stricter has_owner_token_rejection().
954     *
955     * @since 9.18.0
956     *
957     * @return bool
958     */
959    public function has_owner_connection_error() {
960        $owner_id = (int) \Jetpack_Options::get_option( 'master_user' );
961
962        if ( $owner_id <= 0 ) {
963            return false;
964        }
965
966        foreach ( $this->get_verified_errors() as $error_code => $users ) {
967            $display_config = $this->get_error_display_config( $error_code );
968
969            // Keyed on the owner's ID so a previous owner's `invalid_connection_owner` error does not count.
970            if ( null !== $display_config
971                && is_array( $users )
972                && isset( $users[ $owner_id ] ) ) {
973                return true;
974            }
975        }
976
977        return false;
978    }
979
980    /**
981     * Whether WordPress.com has rejected the connection owner's token on a request this site signed.
982     *
983     * Incoming errors don't count: an outsider who knows the owner's token key can get one verified.
984     *
985     * @since 9.18.0
986     *
987     * @return bool
988     */
989    public function has_owner_token_rejection() {
990        $owner_id = (int) \Jetpack_Options::get_option( 'master_user' );
991
992        if ( $owner_id <= 0 ) {
993            return false;
994        }
995
996        $rejection_codes = array( 'invalid_token', 'unknown_token', 'token_mismatch' );
997
998        foreach ( $this->get_verified_errors() as $error_code => $users ) {
999            if ( in_array( $error_code, $rejection_codes, true )
1000                && is_array( $users )
1001                && isset( $users[ $owner_id ]['error_direction'] )
1002                && self::DIRECTION_OUTGOING === $users[ $owner_id ]['error_direction'] ) {
1003                return true;
1004            }
1005        }
1006
1007        return false;
1008    }
1009
1010    /**
1011     * Whether connecting or relinking would make the viewer the connection owner.
1012     *
1013     * @since 9.18.0
1014     *
1015     * @param Manager $manager         The connection manager.
1016     * @param int     $viewer_id       The viewer's user ID.
1017     * @param bool    $is_transferable Whether ownership is transferable, the answer before Manager::can_take_owner_slot().
1018     * @return bool
1019     */
1020    private function can_take_owner_slot( Manager $manager, $viewer_id, $is_transferable ) {
1021        // A partial update can load this class alongside a Manager that predates the method.
1022        return method_exists( $manager, 'can_take_owner_slot' ) ? $manager->can_take_owner_slot( $viewer_id ) : $is_transferable;
1023    }
1024
1025    /**
1026     * Reduces a set of displayable errors to the connection-owner ones when the
1027     * owner's own connection is broken.
1028     *
1029     * The connection owner is the account every other connection on the site hangs
1030     * off. While it is broken, no other error in the set is independently
1031     * actionable.
1032     *
1033     * See is_owner_scoped_error() for which errors count as a broken owner.
1034     *
1035     * A code whose display config sets `survives_owner_promotion` is kept regardless.
1036     * The premise above holds for token errors, whose one remedy is a reconnect the
1037     * owner has to perform first â€” see that key's documentation on
1038     * get_error_display_config() for when it doesn't.
1039     *
1040     * @since 8.11.0
1041     *
1042     * @param array $displayable_errors Displayable errors, keyed by error code then user ID.
1043     * @return array The owner-only subset when the owner is broken, otherwise the input unchanged.
1044     */
1045    private function promote_owner_errors( array $displayable_errors ) {
1046        $owner_errors    = array();
1047        $has_owner_error = false;
1048
1049        foreach ( $displayable_errors as $error_code => $users ) {
1050            // Errors injected by a consumer through the filter that runs after this
1051            // reduction have no config of ours; anything reaching here without one is
1052            // treated as ordinary.
1053            $display_config = $this->get_error_display_config( $error_code );
1054            $survives       = null !== $display_config && ! empty( $display_config['survives_owner_promotion'] );
1055
1056            foreach ( $users as $user_id => $error ) {
1057                $is_owner_error = $this->is_owner_scoped_error( $error_code, $error['audience'] ?? '' );
1058
1059                if ( ! $is_owner_error && ! $survives ) {
1060                    continue;
1061                }
1062
1063                $owner_errors[ $error_code ][ $user_id ] = $error;
1064
1065                // An exempt error is not itself a broken owner, so it must not trigger the
1066                // reduction on its own â€” only survive one triggered by something else.
1067                $has_owner_error = $has_owner_error || $is_owner_error;
1068            }
1069        }
1070
1071        return $has_owner_error ? $owner_errors : $displayable_errors;
1072    }
1073
1074    /**
1075     * Sets up hooks for displaying verified errors on admin pages.
1076     *
1077     * This method is hooked into 'admin_init'. It retrieves displayable errors
1078     * and, if any exist, sets up the necessary action and filter hooks to display
1079     * them in admin notices and the React dashboard.
1080     *
1081     * @since 1.14.2
1082     */
1083    public function handle_verified_errors() {
1084        $displayable_errors = $this->get_displayable_errors();
1085
1086        // If there are any displayable errors, set up the hooks for displaying them in React dashboard and admin notices.
1087        if ( ! empty( $displayable_errors ) ) {
1088            add_action( 'admin_notices', array( $this, 'generic_admin_notice_error' ) );
1089            add_filter( 'react_connection_errors_initial_state', array( $this, 'jetpack_react_dashboard_error' ), 10, 1 );
1090        }
1091    }
1092
1093    /**
1094     * Determines whether error filtering should be allowed.
1095     *
1096     * This method controls access to the jetpack_connection_displayable_errors filter.
1097     * Currently, only WoA sites are allowed to use this filter.
1098     *
1099     * @since 6.13.10
1100     *
1101     * @return bool True if error filtering should be allowed, false otherwise.
1102     */
1103    protected function should_allow_error_filtering() {
1104        $host = new \Automattic\Jetpack\Status\Host();
1105        if ( $host->is_woa_site() || $host->is_vip_site() || $host->is_newspack_site() ) {
1106            return true;
1107        }
1108
1109        return false;
1110    }
1111
1112    /**
1113     * Provides displayable connection errors for the React dashboard in a flat array format.
1114     *
1115     * This method transforms the hierarchical displayable_errors structure into the flat format
1116     * expected by the React dashboard. It's used as a filter for 'react_connection_errors_initial_state'.
1117     * Returns only the first error to avoid overwhelming the user with multiple error messages.
1118     *
1119     * @since 8.9.0
1120     *
1121     * @param array $errors Existing errors from other filters (unused but required for filter signature).
1122     * @return array Array containing only the first displayable error for the React dashboard.
1123     *               Example:
1124     *               [
1125     *                 [
1126     *                   'code' => 'connection_error',
1127     *                   'message' => 'Your connection with WordPress.com seems to be broken...',
1128     *                   'action' => 'reconnect',
1129     *                   'data' => [
1130     *                     'api_error_code' => 'invalid_token',
1131     *                     'action' => 'reconnect',
1132     *                     'audience' => 'site' // Who the error is relevant to: 'site', 'owner', or 'user'.
1133     *                   ]
1134     *                 ]
1135     *               ]
1136     */
1137    public function jetpack_react_dashboard_error( $errors ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1138        $displayable_errors = $this->get_displayable_errors();
1139
1140        // Get the first error only
1141        $first_error_code = array_key_first( $displayable_errors );
1142        if ( ! $first_error_code ) {
1143            return array(); // No errors
1144        }
1145
1146        $first_user_errors = $displayable_errors[ $first_error_code ];
1147        if ( ! is_array( $first_user_errors ) || empty( $first_user_errors ) ) {
1148            return array(); // Invalid error structure
1149        }
1150
1151        $first_error = reset( $first_user_errors );
1152
1153        // Validate error structure
1154        if ( ! is_array( $first_error ) || ! isset( $first_error['error_message'] ) ) {
1155            return array(); // Invalid error structure
1156        }
1157
1158        // Determine the action - use the one from error_data if available, otherwise default to 'reconnect'
1159        $action = 'reconnect'; // Default action for connection errors
1160        if ( isset( $first_error['error_data']['action'] ) && is_string( $first_error['error_data']['action'] ) ) {
1161            $action = $first_error['error_data']['action'];
1162        }
1163
1164        // Safely merge error data, ensuring we don't overwrite critical fields
1165        $error_data = isset( $first_error['error_data'] ) && is_array( $first_error['error_data'] ) ? $first_error['error_data'] : array();
1166
1167        // Build the data array with safe merging
1168        $dashboard_data = array( 'api_error_code' => $first_error_code );
1169
1170        // Add error_data fields, but be careful not to overwrite api_error_code
1171        foreach ( $error_data as $key => $value ) {
1172            if ( 'api_error_code' !== $key ) {
1173                $dashboard_data[ $key ] = $value;
1174            }
1175        }
1176
1177        // Expose the error audience (site/owner/user) so the dashboard can render
1178        // audience-aware copy. Falls back to site-wide for consumer-injected errors
1179        // that predate the audience field.
1180        $dashboard_data['audience'] = $first_error['audience'] ?? 'site';
1181
1182        $dashboard_error = array(
1183            array(
1184                'code'    => 'connection_error',
1185                'message' => $first_error['error_message'],
1186                'action'  => $action,
1187                'data'    => $dashboard_data,
1188            ),
1189        );
1190
1191        return $dashboard_error;
1192    }
1193
1194    /**
1195     * Gets the instance of this singleton class
1196     *
1197     * @since 1.14.2
1198     *
1199     * @return Error_Handler $instance
1200     */
1201    public static function get_instance() {
1202        if ( self::$instance === null ) {
1203            self::$instance = new self();
1204        }
1205        return self::$instance;
1206    }
1207
1208    /**
1209     * Keep track of a connection error that was encountered
1210     *
1211     * This is the entry point of the incoming-request error flow (flow 1 in the class
1212     * docblock) when called with `$skip_wpcom_verification = false` (the default).
1213     *
1214     * Only error codes present in `$known_errors` are handled; anything else is
1215     * silently discarded. The `WP_Error` must carry the data shape produced by
1216     * `build_connection_error_data()`, or it is discarded as well.
1217     *
1218     * @param \WP_Error $error  The error object.
1219     * @param boolean   $force  Force the report, even if should_report_error is false.
1220     * @param boolean   $skip_wpcom_verification Set to 'true' to verify the error locally and skip the WP.com
1221     *                  verification round-trip. Only do this when the error is self-evidencing â€” e.g. it came
1222     *                  from a response WP.com sent to a request this site initiated (the outgoing flow), or
1223     *                  from local connection state. Skipping verification for an incoming request error would
1224     *                  let any unauthenticated requester plant a verified error and trigger its workflows
1225     *                  (admin notices, self-healing), so leave it 'false' for anything derived from an
1226     *                  incoming request.
1227     *
1228     * @return void
1229     * @since 1.14.2
1230     */
1231    public function report_error( \WP_Error $error, $force = false, $skip_wpcom_verification = false ) {
1232        if ( in_array( $error->get_error_code(), $this->known_errors, true ) && ( $this->should_report_error( $error ) || $force ) ) {
1233            $stored_error = $this->store_error( $error );
1234            if ( $stored_error ) {
1235                $skip_wpcom_verification ? $this->verify_error( $stored_error ) : $this->send_error_to_wpcom( $stored_error );
1236            }
1237        }
1238    }
1239
1240    /**
1241     * Checks the status of the gate
1242     *
1243     * This protects the site (and WPCOM) against over loads.
1244     *
1245     * @since 1.14.2
1246     *
1247     * @param \WP_Error $error the error object.
1248     * @return boolean $should_report True if gate is open and the error should be reported.
1249     */
1250    public function should_report_error( \WP_Error $error ) {
1251        if ( defined( '\\JETPACK_DEV_DEBUG' ) && constant( '\\JETPACK_DEV_DEBUG' ) ) {
1252            return true;
1253        }
1254
1255        /**
1256         * Whether to bypass the gate for the error handling
1257         *
1258         * By default, we only process errors once an hour for each error code.
1259         * This is done to avoid overflows. If you need to disable this gate, you can set this variable to true.
1260         *
1261         * This filter is useful for unit testing
1262         *
1263         * @since 1.14.2
1264         *
1265         * @param boolean $bypass_gate whether to bypass the gate. Default is false, do not bypass.
1266         */
1267        $bypass_gate = apply_filters( 'jetpack_connection_bypass_error_reporting_gate', false );
1268        if ( true === $bypass_gate ) {
1269            return true;
1270        }
1271
1272        $transient = self::error_reporting_gate_transient( $error );
1273
1274        if ( get_transient( $transient ) ) {
1275            return false;
1276        }
1277
1278        set_transient( $transient, true, HOUR_IN_SECONDS );
1279        return true;
1280    }
1281
1282    /**
1283     * Builds the reporting-gate transient name for an error.
1284     *
1285     * Keyed by code and direction, not code alone: an outgoing error is reported
1286     * immediately and verified locally (no WP.com round trip), while an incoming error of the
1287     * same code still needs to clear the gate to reach the `verify_xml_rpc_error` round trip
1288     * that triggers WP.com-side self-healing (flow 1 in the class docblock).
1289     *
1290     * @param \WP_Error $error the error object.
1291     * @return string
1292     */
1293    private static function error_reporting_gate_transient( \WP_Error $error ) {
1294        $error_data      = $error->get_error_data();
1295        $error_direction = is_array( $error_data ) && ! empty( $error_data['error_direction'] ) ? $error_data['error_direction'] : '';
1296
1297        return self::ERROR_REPORTING_GATE . $error->get_error_code() . '_' . $error_direction;
1298    }
1299
1300    /**
1301     * Stores the error in the database so we know there is an issue and can inform the user
1302     *
1303     * @since 1.14.2
1304     *
1305     * @param \WP_Error $error the error object.
1306     * @return boolean|array False if stored errors were not updated and the error array if it was successfully stored.
1307     */
1308    public function store_error( \WP_Error $error ) {
1309
1310        $stored_errors = $this->get_stored_errors();
1311        $error_array   = $this->wp_error_to_array( $error );
1312
1313        if ( ! $error_array ) {
1314            return false;
1315        }
1316
1317        $error_code = $error->get_error_code();
1318        $user_id    = $error_array['user_id'];
1319
1320        if ( ! isset( $stored_errors[ $error_code ] ) || ! is_array( $stored_errors[ $error_code ] ) ) {
1321            $stored_errors[ $error_code ] = array();
1322        }
1323
1324        $stored_errors[ $error_code ][ $user_id ] = $error_array;
1325
1326        // Let's store a maximum of 5 different user ids for each error code.
1327        $error_code_count = is_countable( $stored_errors[ $error_code ] ) ? count( $stored_errors[ $error_code ] ) : 0;
1328        if ( $error_code_count > 5 ) {
1329            // array_shift will destroy keys here because they are numeric, so manually remove first item.
1330            $keys = array_keys( $stored_errors[ $error_code ] );
1331            unset( $stored_errors[ $error_code ][ $keys[0] ] );
1332        }
1333
1334        // Deliberately not autoloaded: keeps these ephemeral options out of the shared
1335        // alloptions cache blob, whose write races can resurrect deleted values (CONNECT-457).
1336        if ( update_option( self::STORED_ERRORS_OPTION, $stored_errors, false ) ) {
1337            return $error_array;
1338        }
1339
1340        return false;
1341    }
1342
1343    /**
1344     * Builds action error data for generic JavaScript components.
1345     *
1346     * This helper method creates standardized error_data arrays that work with the generic
1347     * JavaScript error handling components. External plugins (like wpcomsh) can use this
1348     * to ensure their error structures are compatible.
1349     *
1350     * @since 6.16.0
1351     *
1352     * @param array $args Action configuration arguments - only non-empty values will be included.
1353     * @return array Standardized error_data array for JavaScript components.
1354     */
1355    public function build_action_error_data( array $args = array() ) {
1356        // Set default values for variants
1357        $args = wp_parse_args(
1358            $args,
1359            array(
1360                'action_variant'           => 'primary',
1361                'secondary_action_variant' => 'secondary',
1362            )
1363        );
1364
1365        // Start with core data
1366        $error_data = array(
1367            'blog_id' => \Jetpack_Options::get_option( 'id' ),
1368        );
1369
1370        // Validate variant values
1371        $valid_variants = array( 'primary', 'secondary' );
1372        if ( ! in_array( $args['action_variant'], $valid_variants, true ) ) {
1373            $args['action_variant'] = 'primary';
1374        }
1375        if ( ! in_array( $args['secondary_action_variant'], $valid_variants, true ) ) {
1376            $args['secondary_action_variant'] = 'secondary';
1377        }
1378
1379        // Merge extra_data first, then regular args (so args take precedence)
1380        if ( ! empty( $args['extra_data'] ) && is_array( $args['extra_data'] ) ) {
1381            $error_data = array_merge( $error_data, $args['extra_data'] );
1382            unset( $args['extra_data'] ); // Remove from args to avoid duplication
1383        }
1384
1385        // Filter out empty values and merge with error_data
1386        $filtered_args = array_filter(
1387            $args,
1388            function ( $value ) {
1389                return ! empty( $value );
1390            }
1391        );
1392
1393        return array_merge( $error_data, $filtered_args );
1394    }
1395
1396    /**
1397     * Builds a standardized error array for the connection error system.
1398     *
1399     * This method creates a consistent error array structure that can be used
1400     * by both internal error handling and external plugins/customizations.
1401     *
1402     * @since 1.14.2
1403     * @since 8.9.0 Added the `$error_direction` parameter and output field.
1404     *
1405     * @param string $error_code      The error code identifier.
1406     * @param string $error_message   The human-readable error message.
1407     * @param array  $error_data      Additional error data (optional).
1408     * @param string $user_id         The user ID associated with the error (optional).
1409     * @param string $error_type      The type of error (optional). One of the `ERROR_TYPE_*` constants or ''.
1410     * @param string $error_direction The direction of the request that triggered the error (optional).
1411     *                                One of the `DIRECTION_*` constants or ''.
1412     * @return array|false The standardized error array or false on failure.
1413     *                     Example successful return:
1414     *                     [
1415     *                       'error_code' => 'invalid_token',
1416     *                       'user_id' => '123',
1417     *                       'error_message' => 'The token is invalid',
1418     *                       'error_data' => ['action' => 'reconnect'],
1419     *                       'timestamp' => 1234567890,
1420     *                       'nonce' => 'abc123def',
1421     *                       'error_type' => 'xmlrpc',
1422     *                       'error_direction' => 'incoming'
1423     *                     ]
1424     */
1425    public function build_error_array( string $error_code, string $error_message, array $error_data = array(), $user_id = '0', string $error_type = '', string $error_direction = '' ) {
1426        // Validate required parameters
1427        if ( empty( $error_code ) || empty( $error_message ) ) {
1428            return false;
1429        }
1430
1431        // Validate user_id is a string or integer
1432        if ( ! is_string( $user_id ) && ! is_int( $user_id ) ) {
1433            return false;
1434        }
1435
1436        return array(
1437            'error_code'      => $error_code,
1438            'user_id'         => $user_id,
1439            'error_message'   => $error_message,
1440            'error_data'      => $error_data,
1441            'timestamp'       => time(),
1442            'nonce'           => wp_generate_password( 10, false ),
1443            'error_type'      => $error_type,
1444            'error_direction' => $error_direction,
1445        );
1446    }
1447
1448    /**
1449     * Builds the standardized `WP_Error` data payload for a connection error.
1450     *
1451     * This is the single place the error-data contract consumed by `wp_error_to_array()`
1452     * is defined. Use it (or `build_connection_wp_error()`) instead of assembling the
1453     * data array by hand, so every reporter produces the same shape:
1454     *
1455     * - `signature_details` is guaranteed to contain a `token` key (empty string when
1456     *   the error is not tied to a specific token), which `wp_error_to_array()` requires.
1457     *   The token is also what WP.com checks when verifying incoming-flow errors, so its
1458     *   key must not be renamed.
1459     * - `error_type` and `error_direction` are validated against the class constants and
1460     *   stored as '' when the given value is not recognized. For 'local_state' errors the
1461     *   direction is always forced to '' â€” they describe the site's own database, not a
1462     *   request, so a direction would be meaningless and is ignored if passed.
1463     * - `$extra` cannot override the reserved keys: `signature_details`, `error_type`,
1464     *   and `error_direction` always win the merge.
1465     *
1466     * @since 8.9.0
1467     *
1468     * @param array  $signature_details Details of the signed request that failed: `token`,
1469     *                                  and typically `timestamp`, `nonce`, `body_hash`,
1470     *                                  `method`, `url`.
1471     * @param string $error_type        One of the `ERROR_TYPE_*` constants.
1472     * @param string $error_direction   One of the `DIRECTION_*` constants. Ignored for
1473     *                                  'local_state' errors, which have no direction.
1474     * @param array  $extra             Optional additional data, e.g. a `user_id` fallback for
1475     *                                  errors whose token cannot be attributed to a user, or
1476     *                                  `has_user_token` for `invalid_connection_owner`.
1477     * @return array The error data array to pass as the third argument of `WP_Error`.
1478     */
1479    public static function build_connection_error_data( array $signature_details, string $error_type, string $error_direction, array $extra = array() ) {
1480        $valid_types      = array( self::ERROR_TYPE_XMLRPC, self::ERROR_TYPE_REST, self::ERROR_TYPE_LOCAL_STATE );
1481        $valid_directions = array( self::DIRECTION_INCOMING, self::DIRECTION_OUTGOING );
1482
1483        $error_type = in_array( $error_type, $valid_types, true ) ? $error_type : '';
1484
1485        if ( self::ERROR_TYPE_LOCAL_STATE === $error_type ) {
1486            $error_direction = '';
1487        } else {
1488            $error_direction = in_array( $error_direction, $valid_directions, true ) ? $error_direction : '';
1489        }
1490
1491        return array_merge(
1492            $extra,
1493            array(
1494                'signature_details' => array_merge( array( 'token' => '' ), $signature_details ),
1495                'error_type'        => $error_type,
1496                'error_direction'   => $error_direction,
1497            )
1498        );
1499    }
1500
1501    /**
1502     * Builds a `WP_Error` carrying the standardized connection error data.
1503     *
1504     * Convenience wrapper around `build_connection_error_data()` â€” see it for the
1505     * data contract. All connection error reporters should create their `WP_Error`
1506     * objects through this factory.
1507     *
1508     * @since 8.9.0
1509     *
1510     * @param string $error_code        The error code, ideally one of `$known_errors`.
1511     * @param string $error_message     The human-readable error message. `build_error_array()` rejects an
1512     *                                  empty message, so a generic fallback is substituted when this is ''.
1513     * @param array  $signature_details Details of the signed request that failed. See `build_connection_error_data()`.
1514     * @param string $error_type        One of the `ERROR_TYPE_*` constants.
1515     * @param string $error_direction   One of the `DIRECTION_*` constants, or '' for errors with no direction.
1516     * @param array  $extra             Optional additional data. See `build_connection_error_data()`.
1517     * @return \WP_Error
1518     */
1519    public static function build_connection_wp_error( string $error_code, string $error_message, array $signature_details, string $error_type, string $error_direction, array $extra = array() ) {
1520        return new \WP_Error(
1521            $error_code,
1522            '' === $error_message ? __( 'An error occurred with the connection.', 'jetpack-connection' ) : $error_message,
1523            self::build_connection_error_data( $signature_details, $error_type, $error_direction, $extra )
1524        );
1525    }
1526
1527    /**
1528     * Converts a WP_Error object in the array representation we store in the database
1529     *
1530     * The `WP_Error` data must follow the contract defined by `build_connection_error_data()`:
1531     * a `signature_details` array containing at least a `token` key is required, and this
1532     * method returns false without storing anything when it is absent. `error_type` and
1533     * `error_direction` are read from the data and stored as '' when missing.
1534     *
1535     * The user attribution comes from the token in `signature_details`, which identifies
1536     * the exact credential that failed. An explicit `user_id` in the error data is only
1537     * consulted as a fallback when the token yields no user (e.g. non-signature errors
1538     * such as `invalid_connection_owner`, which are reported with an empty token).
1539     *
1540     * @since 1.14.2
1541     *
1542     * @param \WP_Error $error the error object.
1543     * @return boolean|array False if error is invalid or the error array
1544     */
1545    public function wp_error_to_array( \WP_Error $error ) {
1546
1547        $data = $error->get_error_data();
1548
1549        if ( ! isset( $data['signature_details'] ) || ! is_array( $data['signature_details'] ) ) {
1550            return false;
1551        }
1552
1553        $signature_details = $data['signature_details'];
1554
1555        if ( ! isset( $signature_details['token'] ) ) {
1556            return false;
1557        }
1558
1559        $user_id = $this->get_user_id_from_token( $signature_details['token'] );
1560
1561        if ( 'invalid' === $user_id && isset( $data['user_id'] ) && is_numeric( $data['user_id'] ) ) {
1562            $user_id = (string) (int) $data['user_id'];
1563        }
1564
1565        $error_data = $signature_details;
1566
1567        // For invalid_connection_owner, has_user_token distinguishes a missing owner
1568        // token from a deleted owner WP user. Keep it so display code can tell the
1569        // two flavors apart.
1570        if ( isset( $data['has_user_token'] ) ) {
1571            $error_data['has_user_token'] = (bool) $data['has_user_token'];
1572        }
1573
1574        // For xmlrpc_request_blocked, the HTTP status the site returned to WP.com
1575        // (e.g. 403). Keep it so display code can include it in the message.
1576        if ( isset( $data['site_http_status'] ) ) {
1577            $error_data['site_http_status'] = (int) $data['site_http_status'];
1578        }
1579
1580        // The display action declared by the reporter at creation time, e.g. 'none'
1581        // to suppress the reconnect CTA. Only our own reporters set this (it is never
1582        // derived from request data); readers treat a missing action as 'reconnect'.
1583        if ( isset( $data['action'] ) && is_string( $data['action'] ) ) {
1584            $error_data['action'] = $data['action'];
1585        }
1586
1587        return $this->build_error_array(
1588            $error->get_error_code(),
1589            $error->get_error_message(),
1590            $error_data,
1591            $user_id,
1592            empty( $data['error_type'] ) ? '' : $data['error_type'],
1593            empty( $data['error_direction'] ) ? '' : $data['error_direction']
1594        );
1595    }
1596
1597    /**
1598     * Sends the error to WP.com to be verified
1599     *
1600     * @since 1.14.2
1601     *
1602     * @param array $error_array The array representation of the error as it is stored in the database.
1603     * @return bool
1604     */
1605    public function send_error_to_wpcom( $error_array ) {
1606
1607        $blog_id = \Jetpack_Options::get_option( 'id' );
1608
1609        $encrypted_data = $this->encrypt_data_to_wpcom( $error_array );
1610
1611        if ( false === $encrypted_data ) {
1612            return false;
1613        }
1614
1615        $args = array(
1616            'body' => array(
1617                'error_data' => $encrypted_data,
1618            ),
1619        );
1620
1621        // send encrypted data to WP.com Public-API v2.
1622        wp_remote_post( "https://public-api.wordpress.com/wpcom/v2/sites/{$blog_id}/jetpack-report-error/", $args );
1623        return true;
1624    }
1625
1626    /**
1627     * Encrypt data to be sent over to WP.com
1628     *
1629     * @since 1.14.2
1630     *
1631     * @param array|string $data the data to be encoded.
1632     * @return boolean|string The encoded string on success, false on failure
1633     */
1634    public function encrypt_data_to_wpcom( $data ) {
1635
1636        try {
1637            // phpcs:disable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
1638            // phpcs:disable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1639            $encrypted_data = base64_encode( sodium_crypto_box_seal( wp_json_encode( $data, JSON_UNESCAPED_SLASHES ), base64_decode( JETPACK__ERRORS_PUBLIC_KEY ) ) );
1640            // phpcs:enable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
1641            // phpcs:enable WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1642        } catch ( \SodiumException $e ) {
1643            // error encrypting data.
1644            return false;
1645        }
1646
1647        return $encrypted_data;
1648    }
1649
1650    /**
1651     * Extracts the user ID from a token
1652     *
1653     * @since 1.14.2
1654     *
1655     * @param string $token the token used to make the request.
1656     * @return string $the user id or `invalid` if user id not present.
1657     */
1658    public function get_user_id_from_token( $token ) {
1659        $user_id = 'invalid';
1660
1661        if ( $token ) {
1662            $parsed_token = explode( ':', wp_unslash( $token ) );
1663
1664            if ( isset( $parsed_token[2] ) && ctype_digit( $parsed_token[2] ) ) {
1665                $user_id = $parsed_token[2];
1666            }
1667        }
1668
1669        return $user_id;
1670    }
1671
1672    /**
1673     * Gets the reported errors stored in the database
1674     *
1675     * @since 1.14.2
1676     *
1677     * @return array $errors
1678     */
1679    public function get_stored_errors() {
1680
1681        $stored_errors = get_option( self::STORED_ERRORS_OPTION );
1682
1683        if ( ! is_array( $stored_errors ) ) {
1684            $stored_errors = array();
1685        }
1686
1687        $stored_errors = $this->garbage_collector( $stored_errors );
1688
1689        return $stored_errors;
1690    }
1691
1692    /**
1693     * Gets the verified errors stored in the database.
1694     *
1695     * This method retrieves only the errors that are actually stored in the database,
1696     * without applying any filters that might inject additional errors. This is used
1697     * internally by methods that need to modify and store the verified errors back
1698     * to the database to prevent accidentally persisting filtered/injected errors.
1699     *
1700     * @since 1.14.2
1701     *
1702     * @return array $errors
1703     */
1704    public function get_verified_errors() {
1705        $verified_errors = get_option( self::STORED_VERIFIED_ERRORS_OPTION );
1706
1707        if ( ! is_array( $verified_errors ) ) {
1708            $verified_errors = array();
1709        }
1710
1711        $verified_errors = $this->garbage_collector( $verified_errors );
1712
1713        return $verified_errors;
1714    }
1715
1716    /**
1717     * Removes expired errors from the array
1718     *
1719     * This method is called by get_stored_errors and get_verified errors and filters their result
1720     * Whenever a new error is stored to the database or verified, this will be triggered and the
1721     * expired error will be permanently removed from the database
1722     *
1723     * @since 1.14.2
1724     *
1725     * @param array $errors array of errors as stored in the database.
1726     * @return array
1727     */
1728    private function garbage_collector( $errors ) {
1729        foreach ( $errors as $error_code => $users ) {
1730            foreach ( $users as $user_id => $error ) {
1731                if ( empty( $error['timestamp'] ) || self::ERROR_LIFE_TIME < time() - (int) $error['timestamp'] ) {
1732                    unset( $errors[ $error_code ][ $user_id ] );
1733                }
1734            }
1735        }
1736        // Clear empty error codes.
1737        $errors = array_filter(
1738            $errors,
1739            function ( $user_errors ) {
1740                return ! empty( $user_errors );
1741            }
1742        );
1743        return $errors;
1744    }
1745
1746    /**
1747     * Delete all stored and verified errors from the database
1748     *
1749     * @since 1.14.2
1750     *
1751     * @return void
1752     */
1753    public function delete_all_errors() {
1754        $this->delete_stored_errors();
1755        $this->delete_verified_errors();
1756
1757        // Invalidate cache since we deleted all errors
1758        $this->invalidate_displayable_errors_cache();
1759    }
1760
1761    /**
1762     * Delete all stored and verified API errors from the database, leave the non-API errors intact.
1763     *
1764     * Only 'xmlrpc' and 'rest' type errors are deleted. 'local_state' type errors are
1765     * deliberately kept: they describe local connection state (e.g. a missing owner token),
1766     * which a successful API request does not disprove.
1767     *
1768     * @since 1.54.0
1769     *
1770     * @return void
1771     */
1772    public function delete_all_api_errors() {
1773        $type_filter = function ( $errors ) {
1774            if ( is_array( $errors ) ) {
1775                foreach ( $errors as $key => $error ) {
1776                    if ( ! empty( $error['error_type'] ) && in_array( $error['error_type'], array( self::ERROR_TYPE_XMLRPC, self::ERROR_TYPE_REST ), true ) ) {
1777                        unset( $errors[ $key ] );
1778                    }
1779                }
1780            }
1781
1782            return count( $errors ) ? $errors : null;
1783        };
1784
1785        $stored_errors = $this->get_stored_errors();
1786        if ( is_array( $stored_errors ) && count( $stored_errors ) ) {
1787            $stored_errors = array_filter( array_map( $type_filter, $stored_errors ) );
1788            if ( count( $stored_errors ) ) {
1789                update_option( static::STORED_ERRORS_OPTION, $stored_errors, false );
1790            } else {
1791                delete_option( static::STORED_ERRORS_OPTION );
1792            }
1793        }
1794
1795        $verified_errors = $this->get_verified_errors();
1796        if ( is_array( $verified_errors ) && count( $verified_errors ) ) {
1797            $verified_errors = array_filter( array_map( $type_filter, $verified_errors ) );
1798            if ( count( $verified_errors ) ) {
1799                update_option( static::STORED_VERIFIED_ERRORS_OPTION, $verified_errors, false );
1800            } else {
1801                delete_option( static::STORED_VERIFIED_ERRORS_OPTION );
1802            }
1803        }
1804
1805        // Per-key purge only (this warm path â€” a successful site-data fetch â€” must not
1806        // drop the alloptions blob); a legacy blob orphan clears on the next reconnect.
1807        wp_cache_delete( self::STORED_ERRORS_OPTION, 'options' );
1808        wp_cache_delete( self::STORED_VERIFIED_ERRORS_OPTION, 'options' );
1809
1810        // Invalidate cache since we may have deleted verified errors
1811        $this->invalidate_displayable_errors_cache();
1812    }
1813
1814    /**
1815     * Delete all stored and verified errors from the database and returns unfiltered value
1816     *
1817     * This is used to hook into a couple of filters that expect true to not short circuit the disconnection flow
1818     *
1819     * @since 8.9.0
1820     *
1821     * @param mixed $check The input sent by the filter.
1822     * @return boolean
1823     */
1824    public function delete_all_errors_and_return_unfiltered_value( $check ) {
1825        $this->delete_all_errors();
1826        return $check;
1827    }
1828
1829    /**
1830     * Delete the reported errors stored in the database
1831     *
1832     * @since 1.14.2
1833     *
1834     * @return boolean True, if option is successfully deleted. False on failure.
1835     */
1836    public function delete_stored_errors() {
1837        $deleted = delete_option( self::STORED_ERRORS_OPTION );
1838        $this->purge_error_option_cache( self::STORED_ERRORS_OPTION, $deleted );
1839        return $deleted;
1840    }
1841
1842    /**
1843     * Delete the verified errors stored in the database
1844     *
1845     * @since 1.14.2
1846     *
1847     * @return boolean True, if option is successfully deleted. False on failure.
1848     */
1849    public function delete_verified_errors() {
1850        $deleted = delete_option( self::STORED_VERIFIED_ERRORS_OPTION );
1851        $this->purge_error_option_cache( self::STORED_VERIFIED_ERRORS_OPTION, $deleted );
1852        return $deleted;
1853    }
1854
1855    /**
1856     * Purges an error option's object caches after a delete.
1857     *
1858     * Core's delete_option()/update_option() return before touching caches when the
1859     * DB row is missing, so a value resurrected in cache by an alloptions write race
1860     * would otherwise outlive the delete â€” including a reconnect (CONNECT-457). The
1861     * per-key delete covers a post-migration (non-autoloaded) orphan; when the delete
1862     * found no row yet the value is still in the autoloaded blob (a legacy row written
1863     * before these options stopped autoloading), drop that blob too. The blob check
1864     * reads the raw autoloaded set, so it is unaffected by option_* filters and adds
1865     * no query.
1866     *
1867     * @since 9.3.0
1868     *
1869     * @param string $option  The error option name.
1870     * @param bool   $deleted Whether delete_option() found and removed a DB row.
1871     */
1872    private function purge_error_option_cache( $option, $deleted ) {
1873        wp_cache_delete( $option, 'options' );
1874        if ( ! $deleted && isset( wp_load_alloptions()[ $option ] ) ) {
1875            wp_cache_delete( 'alloptions', 'options' );
1876        }
1877    }
1878
1879    /**
1880     * Deletes all stored and verified errors for a single error code.
1881     *
1882     * Used by self-healing flows that can positively confirm one specific error
1883     * condition is gone (e.g. a passing connection test clearing
1884     * `xmlrpc_request_blocked`) without touching unrelated errors.
1885     *
1886     * @since 8.10.0
1887     *
1888     * @param string $error_code The error code to delete.
1889     * @return bool True if any stored or verified error was deleted.
1890     */
1891    public function delete_error_by_code( $error_code ) {
1892        $deleted = false;
1893
1894        // Reopen the reporting gate for this code: deletion means the condition was
1895        // positively confirmed cleared, so a recurrence must be reportable immediately
1896        // rather than suppressed for up to an hour. The gate is keyed by code + direction
1897        // (see error_reporting_gate_transient()), so every direction variant is cleared.
1898        delete_transient( self::ERROR_REPORTING_GATE . $error_code . '_' . self::DIRECTION_INCOMING );
1899        delete_transient( self::ERROR_REPORTING_GATE . $error_code . '_' . self::DIRECTION_OUTGOING );
1900        delete_transient( self::ERROR_REPORTING_GATE . $error_code . '_' );
1901
1902        $stored_errors = $this->get_stored_errors();
1903        if ( isset( $stored_errors[ $error_code ] ) ) {
1904            unset( $stored_errors[ $error_code ] );
1905            $deleted = true;
1906            if ( count( $stored_errors ) ) {
1907                update_option( self::STORED_ERRORS_OPTION, $stored_errors, false );
1908            } else {
1909                delete_option( self::STORED_ERRORS_OPTION );
1910            }
1911        }
1912
1913        $verified_errors = $this->get_verified_errors();
1914        if ( isset( $verified_errors[ $error_code ] ) ) {
1915            unset( $verified_errors[ $error_code ] );
1916            $deleted = true;
1917            if ( count( $verified_errors ) ) {
1918                update_option( self::STORED_VERIFIED_ERRORS_OPTION, $verified_errors, false );
1919            } else {
1920                delete_option( self::STORED_VERIFIED_ERRORS_OPTION );
1921            }
1922        }
1923
1924        if ( $deleted ) {
1925            // Per-key purge only: a legacy blob orphan for these codes is cleared on the
1926            // next reconnect via delete_all_errors(), and GC bounds its display meanwhile.
1927            wp_cache_delete( self::STORED_ERRORS_OPTION, 'options' );
1928            wp_cache_delete( self::STORED_VERIFIED_ERRORS_OPTION, 'options' );
1929            $this->invalidate_displayable_errors_cache();
1930        }
1931
1932        return $deleted;
1933    }
1934
1935    /**
1936     * Gets an error based on the nonce
1937     *
1938     * Receives a nonce and finds the related error.
1939     *
1940     * @since 1.14.2
1941     *
1942     * @param string $nonce The nonce created for the error we want to get.
1943     * @return null|array Returns the error array representation or null if error not found.
1944     */
1945    public function get_error_by_nonce( $nonce ) {
1946        $errors = $this->get_stored_errors();
1947        foreach ( $errors as $user_group ) {
1948            foreach ( $user_group as $error ) {
1949                if ( $error['nonce'] === $nonce ) {
1950                    return $error;
1951                }
1952            }
1953        }
1954        return null;
1955    }
1956
1957    /**
1958     * Adds an error to the verified error list
1959     *
1960     * @since 1.14.2
1961     *
1962     * @param array $error The error array, as it was saved in the unverified errors list.
1963     * @return void
1964     */
1965    public function verify_error( $error ) {
1966
1967        $verified_errors = $this->get_verified_errors();
1968        $error_code      = $error['error_code'];
1969        $user_id         = $error['user_id'];
1970
1971        if ( ! isset( $verified_errors[ $error_code ] ) ) {
1972            $verified_errors[ $error_code ] = array();
1973        }
1974
1975        $verified_errors[ $error_code ][ $user_id ] = $error;
1976
1977        update_option( self::STORED_VERIFIED_ERRORS_OPTION, $verified_errors, false );
1978
1979        // Invalidate cache since we added a new verified error
1980        $this->invalidate_displayable_errors_cache();
1981    }
1982
1983    /**
1984     * Register REST API end point for error handling.
1985     *
1986     * @since 1.14.2
1987     *
1988     * @return void
1989     */
1990    public function register_verify_error_endpoint() {
1991        register_rest_route(
1992            'jetpack/v4',
1993            '/verify_xmlrpc_error',
1994            array(
1995                'methods'             => \WP_REST_Server::CREATABLE,
1996                'callback'            => array( $this, 'verify_xml_rpc_error' ),
1997                'permission_callback' => '__return_true',
1998                'args'                => array(
1999                    'nonce' => array(
2000                        'required' => true,
2001                        'type'     => 'string',
2002                    ),
2003                ),
2004            )
2005        );
2006    }
2007
2008    /**
2009     * Handles verification that a xml rpc error is legit and came from WordPres.com
2010     *
2011     * @since 1.14.2
2012     *
2013     * @param \WP_REST_Request $request The request sent to the WP REST API.
2014     *
2015     * @return boolean
2016     */
2017    public function verify_xml_rpc_error( \WP_REST_Request $request ) {
2018        $error = $this->get_error_by_nonce( $request['nonce'] );
2019
2020        if ( $error ) {
2021            $this->verify_error( $error );
2022            return new \WP_REST_Response( true, 200 );
2023        }
2024
2025        return new \WP_REST_Response( false, 200 );
2026    }
2027
2028    /**
2029     * Prints a generic error notice for all connection errors
2030     *
2031     * @since 8.9.0
2032     *
2033     * @return void
2034     */
2035    public function generic_admin_notice_error() {
2036        // do not add admin notice to the jetpack dashboard.
2037        global $pagenow;
2038        if ( 'admin.php' === $pagenow || isset( $_GET['page'] ) && 'jetpack' === $_GET['page'] ) { // phpcs:ignore
2039            return;
2040        }
2041
2042        if ( ! current_user_can( 'jetpack_connect' ) ) {
2043            return;
2044        }
2045
2046        $displayable_errors = $this->get_displayable_errors();
2047
2048        // Most errors default to no admin notice â€” consumers opt in via the filter
2049        // below, and the React dashboard is the primary surface. Error codes whose
2050        // display config sets `default_admin_notice` provide their own message and
2051        // do not depend on a consumer supplying one.
2052        $default_message = '';
2053        $notice_link     = null;
2054        foreach ( $displayable_errors as $error_code => $user_errors ) {
2055            $display_config = $this->get_error_display_config( $error_code );
2056            if ( empty( $display_config['default_admin_notice'] ) ) {
2057                continue;
2058            }
2059            // On selected hosting platforms the displayable errors pass through a
2060            // consumer filter, so the shape is not guaranteed.
2061            if ( ! is_array( $user_errors ) ) {
2062                continue;
2063            }
2064            $first_error = reset( $user_errors );
2065            if ( is_array( $first_error ) && ! empty( $first_error['error_message'] ) ) {
2066                $default_message = $first_error['error_message'];
2067                $notice_link     = $display_config['notice_link'] ?? null;
2068                break;
2069            }
2070        }
2071
2072        /**
2073         * Filters the message to be displayed in the admin notices area when there's a connection error.
2074         *
2075         * By default we don't display any errors, except for the blocked-request error
2076         * (`xmlrpc_request_blocked`), which provides its own default message.
2077         *
2078         * Return an empty value to disable the message.
2079         *
2080         * @since 8.9.0
2081         * @since 8.10.0 The default message is no longer always empty.
2082         *
2083         * @param string $message The error message.
2084         * @param array  $errors The array of errors. See Automattic\Jetpack\Connection\Error_Handler for details on the array structure.
2085         */
2086        $message = apply_filters( 'jetpack_connection_error_notice_message', $default_message, $displayable_errors );
2087
2088        /**
2089         * Fires inside the admin_notices hook just before displaying the error message for a broken connection.
2090         *
2091         * If you want to disable the default message from being displayed, return an empty value in the jetpack_connection_error_notice_message filter.
2092         *
2093         * @since 8.9.0
2094         *
2095         * @param array $errors The array of errors. See Automattic\Jetpack\Connection\Error_Handler for details on the array structure.
2096         */
2097        do_action( 'jetpack_connection_error_notice', $displayable_errors );
2098
2099        if ( empty( $message ) ) {
2100            return;
2101        }
2102
2103        $notice_content = esc_html( $message );
2104
2105        // Append the link only when the notice is showing the unmodified default
2106        // message â€” a filtered message keeps full control of the copy.
2107        if ( $notice_link && $message === $default_message && ! empty( $notice_link['url'] ) && ! empty( $notice_link['label'] ) ) {
2108            $notice_content .= sprintf(
2109                ' <a href="%1$s">%2$s</a>',
2110                esc_url( $notice_link['url'] ),
2111                esc_html( $notice_link['label'] )
2112            );
2113        }
2114
2115        wp_admin_notice(
2116            $notice_content,
2117            array(
2118                'type'               => 'error',
2119                'dismissible'        => true,
2120                'additional_classes' => array( 'jetpack-message', 'jp-connect' ),
2121                'attributes'         => array( 'style' => 'display:block !important;' ),
2122            )
2123        );
2124    }
2125
2126    /**
2127     * Check an outgoing signed request's response for errors, and store them if needed.
2128     *
2129     * This is the entry point of the outgoing-request error flow (flow 2 in the class
2130     * docblock). `Client::remote_request()` calls it after every outgoing signed request.
2131     * Errors captured here are stored directly as verified â€” the WP.com verification
2132     * round-trip used for incoming errors is unnecessary, because the error arrived in a
2133     * response to a request this site itself initiated and signed.
2134     *
2135     * Note: XML-RPC faults arrive as HTTP 200 responses with an XML body, so they are
2136     * invisible to this method â€” only errors surfaced at the HTTP level with a JSON error
2137     * envelope are captured. `Jetpack_IXR_Client::query()` reports faults itself, via
2138     * check_xmlrpc_fault_for_errors().
2139     *
2140     * @see wp_remote_request() For more information on the $http_response array format.
2141     * @param array|\WP_Error $http_response The response or WP_Error on failure.
2142     * @param array           $auth_data Auth data, allowed keys: `token`, `timestamp`, `nonce`, `body-hash`.
2143     * @param string          $url Request URL.
2144     * @param string          $method Request method.
2145     * @param string          $error_type The transport of the outgoing request: `ERROR_TYPE_XMLRPC` or `ERROR_TYPE_REST`.
2146     *
2147     * @return void
2148     */
2149    public function check_api_response_for_errors( $http_response, $auth_data, $url, $method, $error_type ) {
2150        if ( 200 === wp_remote_retrieve_response_code( $http_response ) || ! is_array( $auth_data ) || ! $url || ! $method ) {
2151            return;
2152        }
2153
2154        $body_raw = wp_remote_retrieve_body( $http_response );
2155        if ( ! $body_raw ) {
2156            return;
2157        }
2158
2159        $body = json_decode( $body_raw, true );
2160
2161        // Support both error envelopes: the legacy v1 JSON-API shape (`error`) and the
2162        // WP-API v2 shape (`code`), the latter used by `wpcom/v2` endpoints such as
2163        // `jetpack-wpcom-user-data`. Prefer `error` for backwards compatibility.
2164        $error_code = is_array( $body ) ? ( $body['error'] ?? $body['code'] ?? null ) : null;
2165
2166        if ( empty( $error_code ) || ( ! is_string( $error_code ) && ! is_int( $error_code ) ) ) {
2167            return;
2168        }
2169
2170        $error = self::build_connection_wp_error(
2171            (string) $error_code,
2172            empty( $body['message'] ) ? '' : $body['message'],
2173            array(
2174                'token'     => empty( $auth_data['token'] ) ? '' : $auth_data['token'],
2175                'timestamp' => empty( $auth_data['timestamp'] ) ? '' : $auth_data['timestamp'],
2176                'nonce'     => empty( $auth_data['nonce'] ) ? '' : $auth_data['nonce'],
2177                // `Client::build_signed_request()` builds this key as `body-hash` (it is sent as an
2178                // `Authorization` header parameter). The snake_case fallback keeps callers that pass
2179                // the stored `signature_details` shape working.
2180                'body_hash' => $auth_data['body-hash'] ?? $auth_data['body_hash'] ?? '',
2181                'method'    => $method,
2182                'url'       => $url,
2183            ),
2184            $error_type,
2185            self::DIRECTION_OUTGOING
2186        );
2187
2188        $this->report_error( $error, false, true );
2189    }
2190
2191    /**
2192     * Check the result of signing an outgoing request for errors, and store them if needed.
2193     *
2194     * This is the second entry point of the outgoing-request error flow (flow 2 in the class
2195     * docblock). It handles failures from `Client::build_signed_request()`, which
2196     * occur before a request is sent and therefore have no response to inspect.
2197     *
2198     * Like response errors in flow 2, these are stored as verified without a WP.com
2199     * round-trip because the site's own token and URL state provides the evidence.
2200     * The hourly reporting gate in `report_error()` still applies.
2201     *
2202     * Codes reaching this method include `malformed_token` and `invalid_body` (from
2203     * `Client::build_signed_request()`), plus the signing errors returned by
2204     * `Jetpack_Signature::sign_request()` (e.g. `invalid_scheme`, `unknown_scheme_port`),
2205     * plus the token-lookup errors raised by `Tokens::get_access_token()` (e.g.
2206     * `no_user_tokens`, `no_token_for_user`). `tokens_locked` also reaches here but is not
2207     * in `known_errors`, so `report_error()` silently discards it â€” see the comment on
2208     * `Client::build_signed_request()`'s `tokens_locked` branch for why.
2209     *
2210     * This includes token lookup, request validation, and request signing errors.
2211     *
2212     * @since 8.10.1
2213     *
2214     * @param mixed  $signing_result The return value of `Client::build_signed_request()`. Ignored unless it is a `WP_Error`.
2215     * @param string $url            Request URL.
2216     * @param string $method         Request method.
2217     * @param string $error_type     The transport of the outgoing request: `ERROR_TYPE_XMLRPC` or `ERROR_TYPE_REST`.
2218     *
2219     * @return void
2220     */
2221    public function check_signed_request_for_errors( $signing_result, $url, $method, $error_type ) {
2222        if ( ! is_wp_error( $signing_result ) ) {
2223            return;
2224        }
2225
2226        // A site with no registration has no tokens to sign with: failed token lookups
2227        // are expected state there, not connection errors â€” and a stale cache view that
2228        // hides a connected site's options must not plant a "verified" error either (CONNECT-457).
2229        if ( ! \Jetpack_Options::get_option( 'id' ) ) {
2230            return;
2231        }
2232
2233        $data = $signing_result->get_error_data();
2234
2235        // The signing errors raised by `Jetpack_Signature` already carry the details of the
2236        // request they failed to sign; the ones raised by `Client` itself carry nothing.
2237        $signature_details = isset( $data['signature_details'] ) && is_array( $data['signature_details'] )
2238            ? $data['signature_details']
2239            : array();
2240
2241        $signature_details += array(
2242            'method' => $method,
2243            'url'    => $url,
2244        );
2245
2246        $error = self::build_connection_wp_error(
2247            (string) $signing_result->get_error_code(),
2248            $signing_result->get_error_message(),
2249            $signature_details,
2250            $error_type,
2251            self::DIRECTION_OUTGOING,
2252            // `Tokens::get_access_token()` attaches `user_id` to the WP_Errors it raises when it
2253            // has already resolved one (see its docblock); pass it through as the attribution
2254            // fallback consulted by `wp_error_to_array()`. Errors with no token to look up at all
2255            // (e.g. `tokens_locked`, `malformed_token` from `Client` itself) carry no such data,
2256            // and fall back to unattributed there.
2257            array( 'user_id' => isset( $data['user_id'] ) ? (int) $data['user_id'] : 0 )
2258        );
2259
2260        $this->report_error( $error, false, true );
2261    }
2262
2263    /**
2264     * Check an outgoing XML-RPC request's fault response for errors, and store them if needed.
2265     *
2266     * This is the third entry point of the outgoing-request error flow (flow 2 in the class
2267     * docblock). XML-RPC faults arrive as HTTP 200 responses with an XML body, so
2268     * check_api_response_for_errors() never sees them â€” it returns immediately on a 200,
2269     * and decodes the body as JSON rather than XML anyway. `Jetpack_IXR_Client::query()`
2270     * calls this method directly from its fault branch instead.
2271     *
2272     * The code/message pair is recovered from the fault string by the caller, via
2273     * `Jetpack_IXR_Client::parse_jetpack_fault_string()` â€” the class that owns the
2274     * `Jetpack: [code] message` convention. An unparseable fault string is the caller's
2275     * concern, not this method's; a fault code reaching here is untrusted input, and it's
2276     * `report_error()`'s `$known_errors` allowlist, not this method, that keeps an
2277     * unrecognized code from being stored. In practice every `jetpack.*` XML-RPC handler
2278     * on WP.com emits fixed string literals here, never attacker- or request-composed
2279     * ones, and the handful that are also `$known_errors` (`unknown_token`,
2280     * `signature_mismatch`, `invalid_token`, `token_mismatch`, `invalid_signature`) are
2281     * the same codes this site itself raises for the same failure â€” WP.com is just
2282     * verifying signatures with the same scheme.
2283     *
2284     * @since 8.10.4
2285     *
2286     * @param string $error_code    The Jetpack error code parsed from the fault string.
2287     * @param string $error_message The error message parsed from the fault string.
2288     * @param string $url           Request URL.
2289     * @param string $method        Request method.
2290     * @param int    $user_id       The local user ID the request was signed for, or `0` for the blog token.
2291     *
2292     * @return void
2293     */
2294    public function check_xmlrpc_fault_for_errors( string $error_code, string $error_message, string $url, string $method, int $user_id = 0 ) {
2295        $error = self::build_connection_wp_error(
2296            $error_code,
2297            $error_message,
2298            array(
2299                'method' => $method,
2300                'url'    => $url,
2301            ),
2302            self::ERROR_TYPE_XMLRPC,
2303            self::DIRECTION_OUTGOING,
2304            array( 'user_id' => $user_id )
2305        );
2306
2307        $this->report_error( $error, false, true );
2308    }
2309
2310    /**
2311     * Determines whether external filters are applied to the get_displayable_errors method.
2312     *
2313     * @since 6.13.10
2314     *
2315     * @return bool True if external filters are applied, false otherwise.
2316     */
2317    private function has_external_filters() {
2318        return has_filter( 'jetpack_connection_get_verified_errors' ) &&
2319            $this->should_allow_error_filtering();
2320    }
2321
2322    /**
2323     * Invalidates the cached displayable errors
2324     *
2325     * @since 6.13.10
2326     *
2327     * @return void
2328     */
2329    private function invalidate_displayable_errors_cache() {
2330        $this->cached_displayable_errors = null;
2331    }
2332}