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