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