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