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