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