Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
71.68% covered (warning)
71.68%
286 / 399
44.44% covered (danger)
44.44%
16 / 36
CRAP
0.00% covered (danger)
0.00%
0 / 1
Identity_Crisis
71.68% covered (warning)
71.68%
286 / 399
44.44% covered (danger)
44.44%
16 / 36
888.64
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 __construct
87.50% covered (warning)
87.50%
14 / 16
0.00% covered (danger)
0.00%
0 / 1
2.01
 do_jetpack_idc_disconnect
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 jetpack_connection_disconnect_site_wpcom_filter
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 maybe_clear_migrate_option
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
90
 wordpress_init
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 add_idc_query_args_to_url
84.62% covered (warning)
84.62%
22 / 26
0.00% covered (danger)
0.00%
0 / 1
10.36
 display_admin_bar_button
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
20
 check_identity_crisis
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 check_http_response_for_idc_detected
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 check_response_for_idc
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
 get_idc_option_with_preserved_timing
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 get_valid_delay_from_existing_idc
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
5.05
 has_same_wpcom_urls
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
8.05
 clear_all_idc_options
81.82% covered (warning)
81.82%
9 / 11
0.00% covered (danger)
0.00%
0 / 1
2.02
 validate_sync_error_idc_option
96.00% covered (success)
96.00%
24 / 25
0.00% covered (danger)
0.00%
0 / 1
20
 reverse_wpcom_urls_for_idc
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 should_remote_validate_idc
80.00% covered (warning)
80.00%
8 / 10
0.00% covered (danger)
0.00%
0 / 1
5.20
 remote_validate_idc
91.67% covered (success)
91.67%
55 / 60
0.00% covered (danger)
0.00%
0 / 1
15.13
 invalidate_idc_option_cache
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 normalize_url_protocol_agnostic
36.36% covered (danger)
36.36%
4 / 11
0.00% covered (danger)
0.00%
0 / 1
8.12
 get_sync_error_idc_option
95.65% covered (success)
95.65%
22 / 23
0.00% covered (danger)
0.00%
0 / 1
7
 should_handle_idc
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 has_identity_crisis
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 safe_mode_is_confirmed
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_mismatched_urls
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
9
 detect_possible_dynamic_site_url
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
30
 locate_wp_config
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
72
 add_secret_to_url_validation_response
80.00% covered (warning)
80.00%
8 / 10
0.00% covered (danger)
0.00%
0 / 1
4.13
 url_is_ip
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 register_request_body
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 site_registered
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 maybe_update_ip_requester
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 set_ip_requester_for_idc
95.00% covered (success)
95.00%
19 / 20
0.00% covered (danger)
0.00%
0 / 1
7
 update_ip_requester
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 add_ip_requester_to_url_validation_response
30.00% covered (danger)
30.00%
3 / 10
0.00% covered (danger)
0.00%
0 / 1
13.57
1<?php
2/**
3 * Identity_Crisis class of the Connection package.
4 *
5 * @package  automattic/jetpack-connection
6 */
7
8namespace Automattic\Jetpack;
9
10use Automattic\Jetpack\Connection\Client;
11use Automattic\Jetpack\Connection\Manager as Connection_Manager;
12use Automattic\Jetpack\Connection\Urls;
13use Automattic\Jetpack\IdentityCrisis\Exception;
14use Automattic\Jetpack\IdentityCrisis\UI;
15use Automattic\Jetpack\IdentityCrisis\URL_Secret;
16use Jetpack_Options;
17use WP_Error;
18
19/**
20 * This class will handle everything involved with fixing an Identity Crisis.
21 *
22 * @since automattic/jetpack-identity-crisis:0.2.0
23 * @since-jetpack 4.4.0
24 * @since 2.9.0
25 */
26class Identity_Crisis {
27    /**
28     * Persistent WPCOM blog ID that stays in the options after disconnect.
29     */
30    const PERSISTENT_BLOG_ID_OPTION_NAME = 'jetpack_persistent_blog_id';
31
32    /**
33     * Initial delay for IDC validation in seconds (1 hour).
34     */
35    const IDC_VALIDATION_INITIAL_DELAY = 3600;
36
37    /**
38     * Maximum delay for IDC validation in seconds (30 days).
39     */
40    const IDC_VALIDATION_MAX_DELAY = 2592000;
41
42    /**
43     * Instance of the object.
44     *
45     * @var Identity_Crisis
46     **/
47    private static $instance = null;
48
49    /**
50     * The wpcom value of the home URL.
51     *
52     * @var string
53     */
54    public static $wpcom_home_url;
55
56    /**
57     * Has safe mode been confirmed?
58     * Beware, it never contains `true` for non-admins, so doesn't always reflect the actual value.
59     *
60     * @var bool
61     */
62    public static $is_safe_mode_confirmed;
63
64    /**
65     * The current screen, which is set if the current user is a non-admin and this is an admin page.
66     *
67     * @var \WP_Screen
68     */
69    public static $current_screen;
70
71    /**
72     * Initializer.
73     *
74     * @return object
75     */
76    public static function init() {
77        if ( self::$instance === null ) {
78            self::$instance = new Identity_Crisis();
79        }
80
81        return self::$instance;
82    }
83
84    /**
85     * Class constructor.
86     *
87     * @return void
88     */
89    private function __construct() {
90        add_action( 'jetpack_sync_processed_actions', array( $this, 'maybe_clear_migrate_option' ) );
91        add_action( 'rest_api_init', array( 'Automattic\\Jetpack\\IdentityCrisis\\REST_Endpoints', 'initialize_rest_api' ) );
92        add_action( 'jetpack_idc_disconnect', array( __CLASS__, 'do_jetpack_idc_disconnect' ) );
93        add_action( 'jetpack_received_remote_request_response', array( $this, 'check_http_response_for_idc_detected' ) );
94
95        add_filter( 'jetpack_connection_disconnect_site_wpcom', array( __CLASS__, 'jetpack_connection_disconnect_site_wpcom_filter' ) );
96
97        add_filter( 'jetpack_remote_request_url', array( $this, 'add_idc_query_args_to_url' ) );
98
99        add_filter( 'jetpack_connection_validate_urls_for_idc_mitigation_response', array( static::class, 'add_secret_to_url_validation_response' ) );
100        add_filter( 'jetpack_connection_validate_urls_for_idc_mitigation_response', array( static::class, 'add_ip_requester_to_url_validation_response' ) );
101
102        add_filter( 'jetpack_options', array( static::class, 'reverse_wpcom_urls_for_idc' ) );
103
104        add_filter( 'jetpack_register_request_body', array( static::class, 'register_request_body' ) );
105        add_action( 'jetpack_site_registered', array( static::class, 'site_registered' ) );
106
107        $urls_in_crisis = self::check_identity_crisis();
108        if ( false === $urls_in_crisis ) {
109            return;
110        }
111
112        self::$wpcom_home_url = $urls_in_crisis['wpcom_home'];
113        add_action( 'init', array( $this, 'wordpress_init' ) );
114    }
115
116    /**
117     * Disconnect current connection and clear IDC options.
118     */
119    public static function do_jetpack_idc_disconnect() {
120        $connection = new Connection_Manager();
121
122        // If the site is in an IDC because sync is not allowed,
123        // let's make sure to not disconnect the production site.
124        if ( ! self::validate_sync_error_idc_option() ) {
125            $connection->disconnect_site( true );
126        } else {
127            $connection->disconnect_site( false );
128        }
129
130        delete_option( static::PERSISTENT_BLOG_ID_OPTION_NAME );
131
132        // Clear IDC options.
133        self::clear_all_idc_options();
134    }
135
136    /**
137     * Filter to prevent site from disconnecting from WPCOM if it's in an IDC.
138     *
139     * @see jetpack_connection_disconnect_site_wpcom filter.
140     *
141     * @return bool False if the site is in IDC, true otherwise.
142     */
143    public static function jetpack_connection_disconnect_site_wpcom_filter() {
144        return ! self::validate_sync_error_idc_option();
145    }
146
147    /**
148     * This method loops through the array of processed items from sync and checks if one of the items was the
149     * home_url or site_url callable. If so, then we delete the jetpack_migrate_for_idc option.
150     *
151     * @param array $processed_items Array of processed items that were synced to WordPress.com.
152     */
153    public function maybe_clear_migrate_option( $processed_items ) {
154        foreach ( (array) $processed_items as $item ) {
155
156            // First, is this item a jetpack_sync_callable action? If so, then proceed.
157            $callable_args = ( is_array( $item ) && isset( $item[0] ) && isset( $item[1] ) && 'jetpack_sync_callable' === $item[0] )
158                ? $item[1]
159                : null;
160
161            // Second, if $callable_args is set, check if the callable was home_url or site_url. If so,
162            // clear the migrate option.
163            if (
164                isset( $callable_args[0] )
165                && ( 'home_url' === $callable_args[0] || 'site_url' === $callable_args[1] )
166            ) {
167                Jetpack_Options::delete_option( 'migrate_for_idc' );
168                break;
169            }
170        }
171    }
172
173    /**
174     * WordPress init.
175     *
176     * @return void
177     */
178    public function wordpress_init() {
179        if ( current_user_can( 'jetpack_disconnect' ) ) {
180            if (
181                isset( $_GET['jetpack_idc_clear_confirmation'] ) && isset( $_GET['_wpnonce'] ) &&
182                wp_verify_nonce( $_GET['_wpnonce'], 'jetpack_idc_clear_confirmation' ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- WordPress core doesn't unslash or verify nonces either.
183            ) {
184                Jetpack_Options::delete_option( 'safe_mode_confirmed' );
185                self::$is_safe_mode_confirmed = false;
186            } else {
187                self::$is_safe_mode_confirmed = (bool) Jetpack_Options::get_option( 'safe_mode_confirmed' );
188            }
189        }
190
191        // 121 Priority so that it's the most inner Jetpack item in the admin bar.
192        add_action( 'admin_bar_menu', array( $this, 'display_admin_bar_button' ), 121 );
193
194        UI::init();
195    }
196
197    /**
198     * Add the idc query arguments to the url.
199     *
200     * @param string $url The remote request url.
201     */
202    public function add_idc_query_args_to_url( $url ) {
203        $status = new Status();
204        if ( ! is_string( $url )
205            || $status->is_offline_mode()
206            || self::validate_sync_error_idc_option() ) {
207            return $url;
208        }
209        $home_url = Urls::home_url();
210        $site_url = Urls::site_url();
211        $hostname = wp_parse_url( $site_url, PHP_URL_HOST );
212
213        // If request is from an IP, make sure ip_requester option is set
214        if ( self::url_is_ip( $hostname ) ) {
215            self::maybe_update_ip_requester( $hostname );
216        }
217
218        $query_args = array(
219            'home'    => $home_url,
220            'siteurl' => $site_url,
221        );
222
223        if ( self::should_handle_idc() ) {
224            $query_args['idc'] = true;
225        }
226
227        if ( \Jetpack_Options::get_option( 'migrate_for_idc', false ) ) {
228            $query_args['migrate_for_idc'] = true;
229        }
230
231        if ( is_multisite() ) {
232            $query_args['multisite'] = true;
233        }
234
235        // Appended rather than merged with add_query_arg(), which decodes the existing query once and so changes what the caller's encoded keys mean.
236        $fragment = '';
237        $position = strpos( $url, '#' );
238        if ( false !== $position ) {
239            $fragment = substr( $url, $position );
240            $url      = substr( $url, 0, $position );
241        }
242
243        return $url . ( false === strpos( $url, '?' ) ? '?' : '&' ) . http_build_query( $query_args, '', '&' ) . $fragment;
244    }
245
246    /**
247     * Renders the admin bar button.
248     *
249     * @return void
250     */
251    public function display_admin_bar_button() {
252        global $wp_admin_bar;
253
254        $href = is_admin()
255            ? add_query_arg( 'jetpack_idc_clear_confirmation', '1' )
256            : add_query_arg( 'jetpack_idc_clear_confirmation', '1', admin_url() );
257
258        $href = wp_nonce_url( $href, 'jetpack_idc_clear_confirmation' );
259
260        $consumer_data = UI::get_consumer_data();
261        $label         = isset( $consumer_data['customContent']['adminBarSafeModeLabel'] )
262            ? esc_html( $consumer_data['customContent']['adminBarSafeModeLabel'] )
263            : esc_html__( 'Jetpack Safe Mode', 'jetpack-connection' );
264
265        $title = sprintf(
266            '<span class="jp-idc-admin-bar">%s %s</span>',
267            '<span class="dashicons dashicons-info-outline"></span>',
268            $label
269        );
270
271        $menu = array(
272            'id'     => 'jetpack-idc',
273            'title'  => $title,
274            'href'   => esc_url( $href ),
275            'parent' => 'top-secondary',
276        );
277
278        if ( ! self::$is_safe_mode_confirmed ) {
279            $menu['meta'] = array(
280                'class' => 'hide',
281            );
282        }
283
284        $wp_admin_bar->add_node( $menu );
285    }
286
287    /**
288     * Checks if the site is currently in an identity crisis.
289     *
290     * @return array|bool Array of options that are in a crisis, or false if everything is OK.
291     */
292    public static function check_identity_crisis() {
293        $connection = new Connection_Manager( 'jetpack' );
294
295        if ( ! $connection->is_connected() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
296            return false;
297        }
298        return Jetpack_Options::get_option( 'sync_error_idc' );
299    }
300
301    /**
302     * Checks the HTTP response body for the 'idc_detected' key. If the key exists,
303     * checks the idc_detected value for a valid idc error.
304     *
305     * @param array|WP_Error $http_response The HTTP response.
306     *
307     * @return bool Whether the site is in an identity crisis.
308     */
309    public function check_http_response_for_idc_detected( $http_response ) {
310        if ( ! is_array( $http_response ) ) {
311            return false;
312        }
313        $response_body = json_decode( wp_remote_retrieve_body( $http_response ), true );
314
315        if ( isset( $response_body['idc_detected'] ) ) {
316            return $this->check_response_for_idc( $response_body['idc_detected'] );
317        }
318
319        if ( isset( $response_body['migrated_for_idc'] ) ) {
320            Jetpack_Options::delete_option( 'migrate_for_idc' );
321        }
322
323        return false;
324    }
325
326    /**
327     * Checks the WPCOM response to determine if the site is in an identity crisis. Updates the
328     * sync_error_idc option if it is.
329     *
330     * @param array $response The response data.
331     *
332     * @return bool Whether the site is in an identity crisis.
333     */
334    public function check_response_for_idc( $response ) {
335        if ( is_array( $response ) && isset( $response['error_code'] ) ) {
336            $error_code              = $response['error_code'];
337            $allowed_idc_error_codes = array(
338                'jetpack_url_mismatch',
339                'jetpack_home_url_mismatch',
340                'jetpack_site_url_mismatch',
341            );
342
343            if ( in_array( $error_code, $allowed_idc_error_codes, true ) ) {
344                // This is a defensive fallback.
345                $new_idc_data = self::get_idc_option_with_preserved_timing( $response );
346                Jetpack_Options::update_option( 'sync_error_idc', $new_idc_data );
347            }
348
349            return true;
350        }
351
352        return false;
353    }
354
355    /**
356     * Gets IDC option data with timing preserved from existing option if appropriate.
357     *
358     * This is a defensive fallback for edge cases where IDC errors are repeatedly detected
359     * even though the site should be in IDC mode. However, edge cases can cause the option
360     * to be deleted, triggering new IDC detections.
361     *
362     * @param array $response The IDC error response from WordPress.com.
363     *
364     * @return array The IDC option data, with timing preserved if the wpcom URLs match.
365     */
366    private static function get_idc_option_with_preserved_timing( $response ) {
367        // Get existing IDC option to check if this is the same error.
368        $existing_idc = Jetpack_Options::get_option( 'sync_error_idc' );
369
370        // Get the new error data with fresh timing values.
371        $new_idc_data = self::get_sync_error_idc_option( $response );
372
373        // If an existing IDC exists and the wpcom URLs match, preserve the backoff delay.
374        if ( is_array( $existing_idc ) && self::has_same_wpcom_urls( $existing_idc, $new_idc_data ) ) {
375            // Same wpcom URLs - preserve the backoff delay.
376            // Note: last_checked is already set to time() by get_sync_error_idc_option(),
377            // which is correct - we want to record that we just saw this error again.
378            $preserved_delay = self::get_valid_delay_from_existing_idc( $existing_idc );
379            if ( $preserved_delay !== null ) {
380                $new_idc_data['next_check_delay'] = $preserved_delay;
381            }
382        }
383        // else: Different wpcom URLs or first time - use fresh timing from get_sync_error_idc_option().
384
385        return $new_idc_data;
386    }
387
388    /**
389     * Extracts and validates the next_check_delay from an existing IDC option.
390     *
391     * @param array $existing_idc The existing IDC option data.
392     *
393     * @return int|null The validated delay in seconds, or null if invalid.
394     */
395    private static function get_valid_delay_from_existing_idc( $existing_idc ) {
396        if ( ! isset( $existing_idc['next_check_delay'] ) ) {
397            return null;
398        }
399
400        $delay = $existing_idc['next_check_delay'];
401
402        // Validate the delay is numeric and within acceptable bounds.
403        if (
404            ! is_numeric( $delay ) ||
405            $delay < self::IDC_VALIDATION_INITIAL_DELAY ||
406            $delay > self::IDC_VALIDATION_MAX_DELAY
407        ) {
408            return null;
409        }
410
411        return (int) $delay;
412    }
413
414    /**
415     * Determines if two IDC error arrays have the same wpcom URLs.
416     *
417     * The wpcom URLs are stored in reversed form in the database, but the jetpack_options
418     * filter un-reverses them when retrieved. This method normalizes both sets of URLs
419     * to reversed form before comparing.
420     *
421     * @param array $idc1 First IDC error data (from get_option, may be un-reversed).
422     * @param array $idc2 Second IDC error data (from get_sync_error_idc_option, reversed).
423     *
424     * @return bool True if they have the same wpcom URLs.
425     */
426    private static function has_same_wpcom_urls( $idc1, $idc2 ) {
427        // Both must have wpcom_home and wpcom_siteurl to be comparable.
428        if (
429            ! isset( $idc1['wpcom_home'] ) ||
430            ! isset( $idc1['wpcom_siteurl'] ) ||
431            ! isset( $idc2['wpcom_home'] ) ||
432            ! isset( $idc2['wpcom_siteurl'] ) ||
433            ! isset( $idc1['reversed_url'] ) ||
434            ! isset( $idc2['reversed_url'] )
435        ) {
436            return false;
437        }
438
439        // The existing IDC data has been un-reversed by the jetpack_options filter when
440        // retrieved via Jetpack_Options::get_option(), so the wpcom URLs are in normal format.
441        // The new data from get_sync_error_idc_option() has reversed URLs.
442        // Reverse the existing URLs to match the format of the new data for comparison.
443        $existing_wpcom_home    = strrev( $idc1['wpcom_home'] );
444        $existing_wpcom_siteurl = strrev( $idc1['wpcom_siteurl'] );
445
446        // Compare the reversed URLs.
447        return $existing_wpcom_home === $idc2['wpcom_home']
448            && $existing_wpcom_siteurl === $idc2['wpcom_siteurl'];
449    }
450
451    /**
452     * Clears all IDC specific options. This method is used on disconnect and reconnect.
453     *
454     * @return void
455     */
456    public static function clear_all_idc_options() {
457        // If the site is currently in IDC, let's also clear the VaultPress connection options.
458        // We have to check if the site is in IDC, otherwise we'd be clearing the VaultPress
459        // connection any time the Jetpack connection is cycled.
460        if ( self::validate_sync_error_idc_option() ) {
461            delete_option( 'vaultpress' );
462            delete_option( 'vaultpress_auto_register' );
463        }
464
465        Jetpack_Options::delete_option(
466            array(
467                'sync_error_idc',
468                'safe_mode_confirmed',
469                'migrate_for_idc',
470            )
471        );
472
473        delete_transient( 'jetpack_idc_possible_dynamic_site_url_detected' );
474    }
475
476    /**
477     * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
478     *
479     * @return bool
480     * @since-jetpack 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
481     *
482     * @since 0.2.0
483     * @since-jetpack 4.4.0
484     */
485    public static function validate_sync_error_idc_option() {
486        $is_valid = false;
487
488        // Is the site opted in and does the stored sync_error_idc option match what we now generate?
489        $sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
490        if ( $sync_error && self::should_handle_idc() ) {
491            // Ensure backward compatibility: add validation timing fields if missing.
492            // Also ensure $sync_error is an array (could be a scalar from older code).
493            if ( ! is_array( $sync_error ) ) {
494                $sync_error = array();
495            }
496            if ( ! isset( $sync_error['last_checked'] ) ) {
497                $sync_error['last_checked'] = 0;
498            }
499            if ( ! isset( $sync_error['next_check_delay'] ) ) {
500                $sync_error['next_check_delay'] = self::IDC_VALIDATION_INITIAL_DELAY;
501            }
502
503            $local_options = self::get_sync_error_idc_option();
504
505            // Ensure all values are set.
506            if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
507                // If the WP.com expected home and siteurl match local home and siteurl it is not valid IDC.
508                if (
509                    isset( $sync_error['wpcom_home'] ) &&
510                    isset( $sync_error['wpcom_siteurl'] ) &&
511                    $sync_error['wpcom_home'] === $local_options['home'] &&
512                    $sync_error['wpcom_siteurl'] === $local_options['siteurl']
513                ) {
514                    // Enable migrate_for_idc so that sync actions are accepted.
515                    Jetpack_Options::update_option( 'migrate_for_idc', true );
516                } elseif ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
517                    $is_valid = true;
518
519                    // Check if it's time to validate the IDC with a remote call to WordPress.com.
520                    if ( self::should_remote_validate_idc( $sync_error ) ) {
521                        // Perform remote validation.
522                        if ( self::remote_validate_idc( $sync_error ) ) {
523                            // IDC was cleared remotely. The option is already deleted by
524                            // remote_validate_idc(), so return false immediately to
525                            // avoid double deletion and allow the filter to run.
526                            return (bool) apply_filters( 'jetpack_sync_error_idc_validation', false );
527                        }
528                    }
529                }
530            }
531        }
532
533        /**
534         * Filters whether the sync_error_idc option is valid.
535         *
536         * @param bool $is_valid If the sync_error_idc is valid or not.
537         *
538         * @since 0.2.0
539         * @since-jetpack 4.4.0
540         */
541        $is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
542
543        if ( ! $is_valid && $sync_error ) {
544            // Since the option exists, and did not validate, delete it.
545            Jetpack_Options::delete_option( 'sync_error_idc' );
546        }
547
548        return $is_valid;
549    }
550
551    /**
552     * Reverses WP.com URLs stored in sync_error_idc option.
553     *
554     * @param array $sync_error error option containing reversed URLs.
555     * @return array
556     */
557    public static function reverse_wpcom_urls_for_idc( $sync_error ) {
558        if ( isset( $sync_error['reversed_url'] ) ) {
559            if ( array_key_exists( 'wpcom_siteurl', $sync_error ) ) {
560                $sync_error['wpcom_siteurl'] = strrev( $sync_error['wpcom_siteurl'] );
561            }
562            if ( array_key_exists( 'wpcom_home', $sync_error ) ) {
563                $sync_error['wpcom_home'] = strrev( $sync_error['wpcom_home'] );
564            }
565        }
566        return $sync_error;
567    }
568
569    /**
570     * Checks if enough time has passed to validate the IDC with a remote call.
571     *
572     * Uses progressive delay: starts at 1 hour, doubles each time (1h, 2h, 4h, 8h, 16h...),
573     * and stops checking once the maximum delay of 30 days is reached.
574     *
575     * @param array $sync_error The stored sync_error_idc option.
576     * @return bool True if validation should be performed, false otherwise.
577     */
578    public static function should_remote_validate_idc( $sync_error ) {
579        // Respect the user's decision to stay in safe mode.
580        // If safe mode is confirmed, don't attempt validation.
581        if ( self::safe_mode_is_confirmed() ) {
582            return false;
583        }
584
585        // If a validation is already in progress or recently completed, don't trigger another.
586        if ( get_transient( 'jetpack_idc_validation_lock' ) ) {
587            return false;
588        }
589
590        // If delay is not set or invalid, validate immediately to bring into new system.
591        if ( empty( $sync_error['next_check_delay'] ) ) {
592            return true;
593        }
594
595        // If delay has reached or exceeded the maximum, stop validating.
596        if ( $sync_error['next_check_delay'] >= self::IDC_VALIDATION_MAX_DELAY ) {
597            return false;
598        }
599
600        // Check if enough time has passed since the last check.
601        $time_since_last_check = time() - ( $sync_error['last_checked'] ?? 0 );
602        return $time_since_last_check >= $sync_error['next_check_delay'];
603    }
604
605    /**
606     * Validates the stored IDC by making a remote call to WordPress.com.
607     *
608     * Makes a lightweight API call to check if WordPress.com still detects an IDC.
609     * If no IDC is detected in the response, the local IDC option is cleared.
610     * If an IDC is still detected, the option is refreshed with the latest URL data from
611     * WordPress.com and the validation timestamps are updated with progressive backoff.
612     * If the request fails (network error, timeout, etc.), timing is updated to prevent
613     * immediate retries but the delay interval is not increased.
614     *
615     * @param array $sync_error The stored sync_error_idc option with timing fields.
616     * @return bool True if IDC was cleared, false otherwise.
617     */
618    public static function remote_validate_idc( $sync_error ) {
619        // Prevent recursive calls that could cause infinite loops within the same request.
620        static $is_validating = false;
621        if ( $is_validating ) {
622            return false;
623        }
624
625        $blog_id = Jetpack_Options::get_option( 'id' );
626        if ( ! $blog_id ) {
627            // Site not registered - IDC state is invalid without a connection to WordPress.com.
628            // Clear the IDC since there's nothing to validate against, and the site can't
629            // restore the blog_id while in IDC anyway (connection flow is blocked).
630            Jetpack_Options::delete_option( 'sync_error_idc' );
631            return true; // Return true to indicate IDC was cleared.
632        }
633
634        // Use a transient lock to prevent concurrent validations across multiple requests.
635        // Lock for the full backoff duration to prevent retries during the delay window.
636        $lock_key      = 'jetpack_idc_validation_lock';
637        $lock_duration = $sync_error['next_check_delay'] ?? self::IDC_VALIDATION_INITIAL_DELAY;
638
639        if ( get_transient( $lock_key ) ) {
640            return false;
641        }
642
643        // Set the lock and verify it was set successfully.
644        // If the write fails, bail immediately to prevent request floods.
645        if ( ! set_transient( $lock_key, true, $lock_duration ) ) {
646            return false; // Bail - can't prevent concurrent requests.
647        }
648
649        $is_validating = true;
650
651        // Update last_checked before making the API call.
652        // This prevents retries even if the API call hangs, times out, or response handling fails.
653        $sync_error['last_checked'] = time();
654        // Note: update_option may return false if value unchanged, which is OK.
655        // We only bail if we can't verify the option exists with correct timestamp.
656        Jetpack_Options::update_option( 'sync_error_idc', $sync_error );
657
658        // Verify the critical timing field was persisted.
659        // This protects against caching/DB issues that would cause request floods.
660        $verified_option = Jetpack_Options::get_option( 'sync_error_idc' );
661        if (
662            ! is_array( $verified_option ) ||
663            empty( $verified_option['last_checked'] ) ||
664            (int) $verified_option['last_checked'] !== (int) $sync_error['last_checked']
665        ) {
666            // Option is missing, corrupted, or has incorrect timestamp - BAIL to prevent retries.
667            delete_transient( $lock_key );
668            $is_validating = false;
669            return false;
670        }
671
672        // Build API path with current URLs as query params.
673        // We must explicitly include URLs because add_idc_query_args_to_url() skips
674        // adding them when the site is in IDC (to prevent sync). For revalidation,
675        // we need WordPress.com to compare current URLs against what it has stored.
676        // We use the jetpack-token-health/blog endpoint which performs IDC detection
677        // and returns idc_detected in the response when URLs don't match.
678        $api_path = sprintf(
679            'sites/%d/jetpack-token-health/blog?home=%s&siteurl=%s&idc=1&idc_validation=1',
680            $blog_id,
681            rawurlencode( Urls::home_url() ),
682            rawurlencode( Urls::site_url() )
683        );
684
685        // Make an API call to WordPress.com to check token health and IDC status.
686        // The response will include 'idc_detected' if URLs still mismatch.
687        $response = Client::wpcom_json_api_request_as_blog(
688            $api_path,
689            '2',
690            array( 'method' => 'GET' ),
691            null,
692            'wpcom'
693        );
694
695        // Parse response body - will be null/false if request failed or JSON is invalid.
696        $body = null;
697        if ( ! is_wp_error( $response ) && 200 === wp_remote_retrieve_response_code( $response ) ) {
698            $body = json_decode( wp_remote_retrieve_body( $response ), true );
699        }
700
701        // Check for success: valid response with no idc_detected means IDC is resolved.
702        if ( is_array( $body ) && empty( $body['idc_detected'] ) ) {
703            Jetpack_Options::delete_option( 'sync_error_idc' );
704            delete_transient( $lock_key );
705            $is_validating = false;
706            return true;
707        }
708
709        // IDC still exists or request failed - update timing.
710        $idc_detected = is_array( $body ) && ! empty( $body['idc_detected'] ) && is_array( $body['idc_detected'] );
711
712        if ( $idc_detected ) {
713            // Valid idc_detected response - refresh data and apply exponential backoff.
714            // @phan-suppress-next-line PhanTypeArraySuspiciousNullable -- $body is verified as array in $idc_detected check
715            $fresh_idc_data                     = self::get_sync_error_idc_option( $body['idc_detected'] );
716            $fresh_idc_data['last_checked']     = time();
717            $fresh_idc_data['next_check_delay'] = min(
718                ( $sync_error['next_check_delay'] ?? self::IDC_VALIDATION_INITIAL_DELAY ) * 2,
719                self::IDC_VALIDATION_MAX_DELAY
720            );
721            Jetpack_Options::update_option( 'sync_error_idc', $fresh_idc_data );
722            self::invalidate_idc_option_cache();
723        } else {
724            // Network error, invalid JSON, or non-200 - just update last_checked without backoff.
725            $sync_error['last_checked'] = time();
726            Jetpack_Options::update_option( 'sync_error_idc', $sync_error );
727            self::invalidate_idc_option_cache();
728        }
729
730        delete_transient( $lock_key );
731        $is_validating = false;
732        return false;
733    }
734
735    /**
736     * Invalidate the cache for the sync_error_idc option.
737     *
738     * This ensures that subsequent requests read fresh data from the database
739     * rather than stale cached values, which is critical for preventing request floods.
740     *
741     * Note: This directly calls wp_cache_delete with the 'jetpack_options' cache group,
742     * which couples this code to the internal caching implementation of Jetpack_Options.
743     * If Jetpack_Options changes its caching strategy, this method will need to be updated.
744     *
745     * @return void
746     */
747    private static function invalidate_idc_option_cache() {
748        wp_cache_delete( 'sync_error_idc', 'jetpack_options' );
749    }
750
751    /**
752     * Normalizes a url by doing three things:
753     *  - Strips protocol
754     *  - Strips www
755     *  - Adds a trailing slash
756     *
757     * @param string $url URL to parse.
758     *
759     * @return WP_Error|string
760     * @since 0.2.0
761     * @since-jetpack 4.4.0
762     */
763    public static function normalize_url_protocol_agnostic( $url ) {
764        $parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
765        if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
766            return new WP_Error(
767                'cannot_parse_url',
768                sprintf(
769                /* translators: %s: URL to parse. */
770                    esc_html__( 'Cannot parse URL %s', 'jetpack-connection' ),
771                    $url
772                )
773            );
774        }
775
776        // Strip www and protocols.
777        $url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
778
779        return $url;
780    }
781
782    /**
783     * Gets the value that is to be saved in the jetpack_sync_error_idc option.
784     *
785     * @param array $response HTTP response.
786     *
787     * @return array Array of the local urls, wpcom urls, and error code.
788     * @since 0.2.0
789     * @since-jetpack 4.4.0
790     * @since-jetpack 5.4.0 Add transient since home/siteurl retrieved directly from DB.
791     */
792    public static function get_sync_error_idc_option( $response = array() ) {
793        // Since the local options will hit the database directly, store the values
794        // in a transient to allow for autoloading and caching on subsequent views.
795        $local_options = get_transient( 'jetpack_idc_local' );
796        if ( false === $local_options ) {
797            $local_options = array(
798                'home'    => Urls::home_url(),
799                'siteurl' => Urls::site_url(),
800            );
801            set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
802        }
803
804        $options = array_merge( $local_options, $response );
805
806        $returned_values = array();
807        foreach ( $options as $key => $option ) {
808            if ( 'error_code' === $key ) {
809                $returned_values[ $key ] = $option;
810                continue;
811            }
812
813            $normalized_url = self::normalize_url_protocol_agnostic( $option );
814            if ( is_wp_error( $normalized_url ) ) {
815                continue;
816            }
817
818            $returned_values[ $key ] = $normalized_url;
819        }
820        // We need to protect WPCOM URLs from search & replace by reversing them. See https://wp.me/pf5801-3R
821        // Add 'reversed_url' key for backward compatibility
822        if ( array_key_exists( 'wpcom_home', $returned_values ) && array_key_exists( 'wpcom_siteurl', $returned_values ) ) {
823            $returned_values['reversed_url'] = true;
824            $returned_values                 = self::reverse_wpcom_urls_for_idc( $returned_values );
825        }
826
827        // Add validation timing fields.
828        // Set last_checked to current time so remote validation doesn't trigger immediately.
829        // This ensures the first validation happens after the initial delay period.
830        $returned_values['last_checked']     = time();
831        $returned_values['next_check_delay'] = self::IDC_VALIDATION_INITIAL_DELAY;
832
833        return $returned_values;
834    }
835
836    /**
837     * Returns the value of the jetpack_should_handle_idc filter or constant.
838     * If set to true, the site will be put into staging mode.
839     *
840     * This method uses both the current jetpack_should_handle_idc filter
841     * and constant to determine whether an IDC should be handled.
842     *
843     * @return bool
844     * @since 0.2.6
845     */
846    public static function should_handle_idc() {
847        if ( Constants::is_defined( 'JETPACK_SHOULD_HANDLE_IDC' ) ) {
848            $default = Constants::get_constant( 'JETPACK_SHOULD_HANDLE_IDC' );
849        } else {
850            $default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
851        }
852
853        /**
854         * Allows sites to opt in for IDC mitigation which blocks the site from syncing to WordPress.com when the home
855         * URL or site URL do not match what WordPress.com expects. The default value is either true, or the value of
856         * JETPACK_SHOULD_HANDLE_IDC constant if set.
857         *
858         * @param bool $default Whether the site is opted in to IDC mitigation.
859         *
860         * @since 0.2.6
861         */
862        return (bool) apply_filters( 'jetpack_should_handle_idc', $default );
863    }
864
865    /**
866     * Whether the site is undergoing identity crisis.
867     *
868     * @return bool
869     */
870    public static function has_identity_crisis() {
871        return false !== static::check_identity_crisis() && ! static::$is_safe_mode_confirmed;
872    }
873
874    /**
875     * Whether an admin has confirmed safe mode.
876     * Unlike `static::$is_safe_mode_confirmed` this function always returns the actual flag value.
877     *
878     * @return bool
879     */
880    public static function safe_mode_is_confirmed() {
881        return Jetpack_Options::get_option( 'safe_mode_confirmed' );
882    }
883
884    /**
885     * Returns the mismatched URLs.
886     *
887     * @return array|bool The mismatched urls, or false if the site is not connected, offline, in safe mode, or the IDC error is not valid.
888     */
889    public static function get_mismatched_urls() {
890        if ( ! static::has_identity_crisis() ) {
891            return false;
892        }
893
894        $data = static::check_identity_crisis();
895
896        if ( ! $data ||
897            ! isset( $data['error_code'] ) ||
898            ! isset( $data['wpcom_home'] ) ||
899            ! isset( $data['home'] ) ||
900            ! isset( $data['wpcom_siteurl'] ) ||
901            ! isset( $data['siteurl'] )
902        ) {
903            // The jetpack_sync_error_idc option is missing a key.
904            return false;
905        }
906
907        if ( 'jetpack_site_url_mismatch' === $data['error_code'] ) {
908            return array(
909                'wpcom_url'   => $data['wpcom_siteurl'],
910                'current_url' => $data['siteurl'],
911            );
912        }
913
914        return array(
915            'wpcom_url'   => $data['wpcom_home'],
916            'current_url' => $data['home'],
917        );
918    }
919
920    /**
921     * Try to detect $_SERVER['HTTP_HOST'] being used within WP_SITEURL or WP_HOME definitions inside of wp-config.
922     *
923     * If `HTTP_HOST` usage is found, it's possbile (though not certain) that site URLs are dynamic.
924     *
925     * When a site URL is dynamic, it can lead to a Jetpack IDC. If potentially dynamic usage is detected,
926     * helpful support info will be shown on the IDC UI about setting a static site/home URL.
927     *
928     * @return bool True if potentially dynamic site urls were detected in wp-config, false otherwise.
929     */
930    public static function detect_possible_dynamic_site_url() {
931        $transient_key = 'jetpack_idc_possible_dynamic_site_url_detected';
932        $transient_val = get_transient( $transient_key );
933
934        if ( false !== $transient_val ) {
935            return (bool) $transient_val;
936        }
937
938        $path      = self::locate_wp_config();
939        $wp_config = $path ? file_get_contents( $path ) : false; // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
940        if ( $wp_config ) {
941            $matched = preg_match(
942                '/define ?\( ?[\'"](?:WP_SITEURL|WP_HOME).+(?:HTTP_HOST).+\);/',
943                $wp_config
944            );
945
946            if ( $matched ) {
947                set_transient( $transient_key, 1, HOUR_IN_SECONDS );
948                return true;
949            }
950        }
951
952        set_transient( $transient_key, 0, HOUR_IN_SECONDS );
953        return false;
954    }
955
956    /**
957     * Gets path to WordPress configuration.
958     * Source: https://github.com/wp-cli/wp-cli/blob/master/php/utils.php
959     *
960     * @return string
961     */
962    public static function locate_wp_config() {
963        static $path;
964
965        if ( null === $path ) {
966            $path = false;
967
968            if ( getenv( 'WP_CONFIG_PATH' ) && file_exists( getenv( 'WP_CONFIG_PATH' ) ) ) {
969                $path = getenv( 'WP_CONFIG_PATH' );
970            } elseif ( file_exists( ABSPATH . 'wp-config.php' ) ) {
971                $path = ABSPATH . 'wp-config.php';
972            } elseif ( file_exists( dirname( ABSPATH ) . '/wp-config.php' ) && ! file_exists( dirname( ABSPATH ) . '/wp-settings.php' ) ) {
973                $path = dirname( ABSPATH ) . '/wp-config.php';
974            }
975
976            if ( $path ) {
977                $path = realpath( $path );
978            }
979        }
980
981        return $path;
982    }
983
984    /**
985     * Adds `url_secret` to the `jetpack.idcUrlValidation` URL validation endpoint.
986     * Adds `url_secret_error` in case of an error.
987     *
988     * @param array $response The endpoint response that we're modifying.
989     *
990     * @return array
991     *
992     * phpcs:ignore Squiz.Commenting.FunctionCommentThrowTag -- The exception is being caught, false positive.
993     */
994    public static function add_secret_to_url_validation_response( array $response ) {
995        // Only checking the database option to limit the effect.
996        if ( get_option( 'jetpack_offline_mode' ) ) {
997            $response['offline_mode'] = '1';
998            return $response;
999        }
1000
1001        try {
1002            $secret = new URL_Secret();
1003
1004            $secret->create();
1005
1006            if ( $secret->exists() ) {
1007                $response['url_secret'] = $secret->get_secret();
1008            }
1009        } catch ( Exception $e ) {
1010            $response['url_secret_error'] = new WP_Error( 'unable_to_create_url_secret', $e->getMessage() );
1011        }
1012
1013        return $response;
1014    }
1015
1016    /**
1017     * Check if URL is an IP.
1018     *
1019     * @param string $hostname The hostname to check.
1020     * @return bool
1021     */
1022    public static function url_is_ip( $hostname = null ) {
1023
1024        if ( ! $hostname ) {
1025            $hostname = wp_parse_url( Urls::site_url(), PHP_URL_HOST );
1026        }
1027
1028        $is_ip = filter_var( $hostname, FILTER_VALIDATE_IP ) !== false ? $hostname : false;
1029        return $is_ip;
1030    }
1031
1032    /**
1033     * Add IDC-related data to the registration query.
1034     *
1035     * @param array $params The existing query params.
1036     *
1037     * @return array
1038     */
1039    public static function register_request_body( array $params ) {
1040        $persistent_blog_id = get_option( static::PERSISTENT_BLOG_ID_OPTION_NAME );
1041        if ( $persistent_blog_id ) {
1042            $params['persistent_blog_id'] = $persistent_blog_id;
1043            $params['url_secret']         = URL_Secret::create_secret( 'registration_request_url_secret_failed' );
1044        }
1045
1046        return $params;
1047    }
1048
1049    /**
1050     * Set the necessary options when site gets registered.
1051     *
1052     * @param int $blog_id The blog ID.
1053     *
1054     * @return void
1055     */
1056    public static function site_registered( $blog_id ) {
1057        update_option( static::PERSISTENT_BLOG_ID_OPTION_NAME, (int) $blog_id, false );
1058    }
1059
1060    /**
1061     * Check if we need to update the ip_requester option.
1062     *
1063     * @param string $hostname The hostname to check.
1064     *
1065     * @return void
1066     */
1067    public static function maybe_update_ip_requester( $hostname ) {
1068        // Check if transient exists
1069        $transient_key = ip2long( $hostname );
1070        if ( $transient_key && ! get_transient( 'jetpack_idc_ip_requester_' . $transient_key ) ) {
1071            self::set_ip_requester_for_idc( $hostname, $transient_key );
1072        }
1073    }
1074
1075    /**
1076     * If URL is an IP, add the IP value to the ip_requester option with its expiry value.
1077     *
1078     * @param string $hostname The hostname to check.
1079     * @param int    $transient_key The transient key.
1080     */
1081    public static function set_ip_requester_for_idc( $hostname, $transient_key ) {
1082        // Check if option exists
1083        $data = Jetpack_Options::get_option( 'identity_crisis_ip_requester' );
1084
1085        $ip_requester = array(
1086            'ip'         => $hostname,
1087            'expires_at' => time() + 360,
1088        );
1089
1090        // If not set, initialize it
1091        if ( empty( $data ) ) {
1092            $data = array( $ip_requester );
1093        } else {
1094            $updated_data  = array();
1095            $updated_value = false;
1096
1097            // Remove expired values and update existing IP
1098            foreach ( $data as $item ) {
1099                if ( time() > $item['expires_at'] ) {
1100                    continue; // Skip expired IP
1101                }
1102
1103                if ( $item['ip'] === $hostname ) {
1104                    $item['expires_at'] = time() + 360;
1105                    $updated_value      = true;
1106                }
1107
1108                $updated_data[] = $item;
1109            }
1110
1111            if ( ! $updated_value || empty( $updated_data ) ) {
1112                $updated_data[] = $ip_requester;
1113            }
1114
1115            $data = $updated_data;
1116        }
1117
1118        self::update_ip_requester( $data, $transient_key );
1119    }
1120
1121    /**
1122     * Update the ip_requester option and set a transient to expire in 5 minutes.
1123     *
1124     * @param array $data The data to be updated.
1125     * @param int   $transient_key The transient key.
1126     *
1127     * @return void
1128     */
1129    public static function update_ip_requester( $data, $transient_key ) {
1130        // Update the option
1131        $updated = Jetpack_Options::update_option( 'identity_crisis_ip_requester', $data );
1132        // Set a transient to expire in 5 minutes
1133        if ( $updated ) {
1134            $transient_name = 'jetpack_idc_ip_requester_' . $transient_key;
1135            set_transient( $transient_name, $data, 300 );
1136        }
1137    }
1138
1139    /**
1140     * Adds `ip_requester` to the `jetpack.idcUrlValidation` URL validation endpoint.
1141     *
1142     * @param array $response The enpoint response that we're modifying.
1143     *
1144     * @return array
1145     */
1146    public static function add_ip_requester_to_url_validation_response( array $response ) {
1147        $requesters = Jetpack_Options::get_option( 'identity_crisis_ip_requester' );
1148        if ( $requesters ) {
1149            // Loop through the requesters and add the IP to the response if it's not expired
1150            $i = 0;
1151            foreach ( $requesters as $ip ) {
1152                if ( $ip['expires_at'] > time() ) {
1153                    $response['ip_requester'][] = $ip['ip'];
1154                }
1155                // Limit the response to five IPs
1156                $i = ++$i;
1157                if ( $i === 5 ) {
1158                    break;
1159                }
1160            }
1161        }
1162        return $response;
1163    }
1164}