Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
87.91% covered (warning)
87.91%
189 / 215
63.16% covered (warning)
63.16%
12 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Reader_Chat
88.73% covered (warning)
88.73%
189 / 213
63.16% covered (warning)
63.16%
12 / 19
109.18
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 register_settings
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 sync_query_filter_option
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
5
 add_sync_options_whitelist
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_scripts
100.00% covered (success)
100.00%
30 / 30
100.00% covered (success)
100.00%
1 / 1
9
 get_load_strategy
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 add_resource_hints
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_deferred_loader_script
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 is_site_coming_soon_or_unlaunched
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 render_mount_div
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 get_reader_chat_config
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
3
 get_current_post_context
88.46% covered (warning)
88.46%
23 / 26
0.00% covered (danger)
0.00%
0 / 1
9.12
 get_asset_version
83.33% covered (warning)
83.33%
20 / 24
0.00% covered (danger)
0.00%
0 / 1
9.37
 read_local_asset_json
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
3.04
 fetch_remote_asset_json
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 decode_asset_json
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 has_ai_features
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
4.07
 has_search_plan_access
92.31% covered (success)
92.31%
24 / 26
0.00% covered (danger)
0.00%
0 / 1
14.09
 is_dev_mode
50.00% covered (danger)
50.00%
10 / 20
0.00% covered (danger)
0.00%
0 / 1
64.12
1<?php
2/**
3 * Jetpack Reader Chat — Agents Manager CDN loader for blog readers.
4 *
5 * Loads a self-contained reader-chat bundle from the widgets.wp.com CDN
6 * and renders a floating chat UI on singular posts for logged-out visitors.
7 *
8 * The reader-chat bundle inlines all WP dependencies (built without
9 * DependencyExtractionWebpackPlugin) so it works on the frontend
10 * without WordPress's script loader.
11 *
12 * Enable via filter:
13 *   add_filter( 'jetpack_reader_chat_enabled', '__return_true' );
14 *
15 * The bundle is deferred until the visitor interacts with the page; see
16 * the `jetpack_reader_chat_load_strategy` filter.
17 *
18 * @package automattic/jetpack
19 */
20
21namespace Automattic\Jetpack\Extensions\AiAssistantPlugin;
22
23use Automattic\Jetpack\Connection\Manager as Connection_Manager;
24use Automattic\Jetpack\Search\Helper as Search_Helper;
25use Automattic\Jetpack\Search\Plan;
26use Automattic\Jetpack\SEO\Content_Gate;
27use Automattic\Jetpack\Status;
28use Automattic\Jetpack\Status\Host;
29use Jetpack_Options;
30
31if ( ! defined( 'ABSPATH' ) ) {
32    exit( 0 );
33}
34
35const READER_CHAT_JS_URL                  = 'https://widgets.wp.com/agents-manager/reader-chat.min.js';
36const READER_CHAT_CSS_URL                 = 'https://widgets.wp.com/agents-manager/reader-chat.css';
37const READER_CHAT_ASSET_TRANSIENT         = 'jetpack_reader_chat_asset';
38const READER_CHAT_ASSET_FAILURE_CACHE_TTL = 5 * MINUTE_IN_SECONDS;
39const READER_CHAT_QUERY_FILTER_OPTION     = 'reader_chat_query_filter';
40const READER_CHAT_QUERY_FILTER_MAX_BYTES  = 20000;
41
42/**
43 * Handles loading the reader chat UI on the frontend.
44 */
45class Jetpack_Reader_Chat {
46
47    /**
48     * Initialize hooks.
49     *
50     * @return void
51     */
52    public static function init(): void {
53        // Register the setting unconditionally so the Search REST endpoint can
54        // flip it even when the feature is currently disabled.
55        add_action( 'init', array( __CLASS__, 'register_settings' ) );
56        add_filter( 'jetpack_sync_options_whitelist', array( __CLASS__, 'add_sync_options_whitelist' ) );
57
58        /**
59         * Filter to enable or disable the Jetpack Reader Chat feature.
60         *
61         * Defaults to the value of the reader_chat site option (false when
62         * unset). Override programmatically with:
63         *   add_filter( 'jetpack_reader_chat_enabled', '__return_true' );
64         *
65         * @since 15.9
66         *
67         * @param bool $enabled Whether the reader chat is enabled.
68         */
69        if ( ! apply_filters( 'jetpack_reader_chat_enabled', (bool) get_option( 'reader_chat', false ) ) ) {
70            return;
71        }
72
73        /**
74         * Filter whether Reader Chat should hook its public frontend loader.
75         *
76         * @since 15.9
77         *
78         * @param bool $enabled Whether the reader chat frontend loader should be hooked.
79         */
80        if ( ! apply_filters( 'jetpack_reader_chat_enqueue_enabled', true ) ) {
81            return;
82        }
83
84        add_action( 'admin_init', array( __CLASS__, 'sync_query_filter_option' ) );
85        add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
86        add_action( 'wp_footer', array( __CLASS__, 'render_mount_div' ) );
87    }
88
89    /**
90     * Register the reader_chat option so Search settings can read and write it.
91     *
92     * @since 15.9
93     *
94     * @return void
95     */
96    public static function register_settings(): void {
97        register_setting(
98            'jetpack_search',
99            'reader_chat',
100            array(
101                'type'              => 'boolean',
102                'description'       => __( 'Whether Site Chat is enabled on this site.', 'jetpack' ),
103                'sanitize_callback' => 'rest_sanitize_boolean',
104                'default'           => false,
105            )
106        );
107    }
108
109    /**
110     * Evaluate the Site Chat content filter and store it where wpcom can read it.
111     *
112     * The filter is PHP on this site, so wpcom, which answers the chat requests,
113     * can only enforce it through the synced `reader_chat_query_filter` option.
114     *
115     * @since 16.5
116     *
117     * @return void
118     */
119    public static function sync_query_filter_option(): void {
120        /**
121         * Filter the Elasticsearch filter clause that limits which content Site Chat can use.
122         *
123         * Same shape as the `adminQueryFilter` Instant Search option, but applied to
124         * Site Chat only. Return an empty array to apply no restriction. For example,
125         * to hide posts older than a date:
126         *
127         *   array( 'range' => array( 'date' => array( 'gte' => '2024-01-01' ) ) )
128         *
129         * @since 16.5
130         *
131         * @param array $query_filter Elasticsearch filter clause. Default empty.
132         */
133        $query_filter = apply_filters( 'jetpack_site_chat_query_filter', array() );
134
135        // An empty array, not a deleted option, so the autoloaded value never misses the cache.
136        if ( empty( $query_filter ) ) {
137            $query_filter = array();
138        }
139
140        $encoded = is_array( $query_filter ) ? wp_json_encode( $query_filter, JSON_UNESCAPED_SLASHES ) : false;
141        if ( false === $encoded || strlen( $encoded ) > READER_CHAT_QUERY_FILTER_MAX_BYTES ) {
142            // Keep the last good filter: clearing it would expose the content the owner hid.
143            $message = __( 'The Site Chat query filter must be an array under 20 KB. The previous filter stays in effect.', 'jetpack' );
144            _doing_it_wrong( 'jetpack_site_chat_query_filter', esc_html( $message ), '16.5' );
145            return;
146        }
147
148        update_option( READER_CHAT_QUERY_FILTER_OPTION, $query_filter, true );
149    }
150
151    /**
152     * Add Reader Chat's setting to Jetpack Sync's option whitelist.
153     *
154     * Atomic and Jurassic Ninja sites write `reader_chat` locally via
155     * Search settings, while the wpcom-hosted agent reads the wpcom-side option
156     * before serving public chat requests. Syncing the option keeps
157     * the local toggle and agent permission gate aligned.
158     *
159     * @since 15.9
160     *
161     * @param array $options Option names allowed to sync.
162     * @return array Updated option names.
163     */
164    public static function add_sync_options_whitelist( array $options ): array {
165        $options[] = 'reader_chat';
166        return array_values( array_unique( $options ) );
167    }
168
169    /**
170     * Enqueue the reader chat script on the frontend.
171     *
172     * Loads on every public-facing page (home, archives, pages, singular
173     * posts). Skips admin, feeds, and AJAX to keep the bundle off contexts
174     * where the chat UI doesn't belong. currentPost in the config is only
175     * populated on singular views — stream views get general suggestions.
176     *
177     * @return void
178     */
179    public static function enqueue_scripts(): void {
180        if ( is_admin() || is_feed() || wp_doing_ajax() ) {
181            return;
182        }
183
184        if ( self::is_site_coming_soon_or_unlaunched() ) {
185            return;
186        }
187
188        /**
189         * Filter to override the AI features check.
190         *
191         * Set to true to load reader chat regardless of Jetpack connection
192         * status, or false to force-disable. Defaults to null, meaning use
193         * the built-in check. Useful for testing on dev sites.
194         *
195         * @param bool|null $override null = use default check, true/false = override.
196         */
197        $has_features = apply_filters( 'jetpack_reader_chat_has_ai_features', null );
198        if ( ! ( $has_features ?? self::has_ai_features() ) ) {
199            return;
200        }
201
202        if ( ! self::has_search_plan_access() ) {
203            return;
204        }
205
206        $version  = self::get_asset_version();
207        $strategy = self::get_load_strategy();
208        $eager    = 'eager' === $strategy;
209
210        // The reader-chat bundle is self-contained — no WP script dependencies. A src-less
211        // handle prints only its inline scripts, so deferred modes leave the fetch to the loader.
212        wp_register_script( 'jetpack-reader-chat', $eager ? READER_CHAT_JS_URL : false, array(), $version, true );
213        wp_enqueue_script( 'jetpack-reader-chat' );
214
215        if ( $eager ) {
216            wp_enqueue_style( 'jetpack-reader-chat', READER_CHAT_CSS_URL, array(), $version );
217        } else {
218            wp_add_inline_script(
219                'jetpack-reader-chat',
220                self::get_deferred_loader_script( 'idle' === $strategy, $version ),
221                'after'
222            );
223            add_filter( 'wp_resource_hints', array( __CLASS__, 'add_resource_hints' ), 10, 2 );
224        }
225
226        // Inject config for the JS bundle (before the script tag).
227        wp_add_inline_script(
228            'jetpack-reader-chat',
229            'window.JetpackReaderChatConfig = ' . wp_json_encode(
230                self::get_reader_chat_config(),
231                JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP
232            ) . ';',
233            'before'
234        );
235    }
236
237    /**
238     * Get when the frontend should download and run the reader chat bundle.
239     *
240     * @return string 'interaction', 'idle', or 'eager'.
241     */
242    private static function get_load_strategy(): string {
243        /**
244         * Filter when the Site Chat bundle loads on the frontend.
245         *
246         * - 'interaction' (default): on the visitor's first scroll, pointer, touch, key, or focus event.
247         * - 'idle': once the page has finished loading, or on first interaction if that comes sooner.
248         * - 'eager': with the page, as a regular script and stylesheet.
249         *
250         * @since 16.5
251         *
252         * @param string $strategy The load strategy.
253         */
254        $strategy = apply_filters( 'jetpack_reader_chat_load_strategy', 'interaction' );
255
256        return in_array( $strategy, array( 'idle', 'eager' ), true ) ? $strategy : 'interaction';
257    }
258
259    /**
260     * Restore the DNS prefetch WordPress adds for enqueued CDN assets, which a src-less handle loses.
261     *
262     * @param array  $urls          URLs to print for the relation type.
263     * @param string $relation_type The relation type the URLs are printed for.
264     * @return array Updated URLs.
265     */
266    public static function add_resource_hints( $urls, $relation_type ) {
267        if ( 'dns-prefetch' === $relation_type ) {
268            $urls[] = '//widgets.wp.com';
269        }
270        return $urls;
271    }
272
273    /**
274     * Build the inline script that injects the reader chat stylesheet and bundle on demand.
275     *
276     * @param bool             $idle    Whether to also load once the page is idle.
277     * @param string|null|bool $version Asset version, or null to omit the query param.
278     * @return string Inline JavaScript.
279     */
280    private static function get_deferred_loader_script( bool $idle, $version ): string {
281        $ver      = $version ? rawurlencode( $version ) : null;
282        $settings = array(
283            'js'   => add_query_arg( 'ver', $ver, READER_CHAT_JS_URL ),
284            'css'  => add_query_arg( 'ver', $ver, READER_CHAT_CSS_URL ),
285            'idle' => $idle,
286        );
287
288        $loader = <<<'JS'
289( function ( s ) {
290    var events = [ 'pointerdown', 'pointermove', 'keydown', 'touchstart', 'scroll', 'wheel', 'focusin' ];
291    var started = false;
292    function load() {
293        if ( started ) {
294            return;
295        }
296        started = true;
297        events.forEach( function ( e ) {
298            window.removeEventListener( e, load, true );
299        } );
300        // Fetch the bundle alongside the styles, then run it once the styles are in.
301        var preload = document.createElement( 'link' );
302        preload.rel = 'preload';
303        preload.as = 'script';
304        preload.href = s.js;
305        document.head.appendChild( preload );
306        var link = document.createElement( 'link' );
307        link.rel = 'stylesheet';
308        link.href = s.css;
309        link.onload = link.onerror = function () {
310            var script = document.createElement( 'script' );
311            script.src = s.js;
312            document.body.appendChild( script );
313        };
314        document.head.appendChild( link );
315    }
316    // The bundle sets this key while the chat is open, so keep an open chat open across page views.
317    try {
318        var agentId = ( window.JetpackReaderChatConfig || {} ).agentId;
319        if ( '1' === window.sessionStorage.getItem( 'jetpack-reader-chat-open-' + agentId ) ) {
320            return load();
321        }
322    } catch ( e ) {}
323    events.forEach( function ( e ) {
324        window.addEventListener( e, load, { capture: true, passive: true } );
325    } );
326    if ( s.idle ) {
327        var whenIdle = function () {
328            if ( window.requestIdleCallback ) {
329                window.requestIdleCallback( load, { timeout: 2000 } );
330            } else {
331                setTimeout( load, 1 );
332            }
333        };
334        if ( 'complete' === document.readyState ) {
335            whenIdle();
336        } else {
337            window.addEventListener( 'load', whenIdle );
338        }
339    }
340} )(
341JS;
342
343        return $loader . wp_json_encode( $settings, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ) . ' );';
344    }
345
346    /**
347     * Check whether the current site is Coming Soon or unlaunched.
348     *
349     * Reader Chat is a public frontend widget, so it should not mount on sites
350     * that are still hidden behind launch or Coming Soon visibility.
351     *
352     * @return bool Whether the site is hidden by launch or Coming Soon visibility.
353     */
354    private static function is_site_coming_soon_or_unlaunched(): bool {
355        $status = new Status();
356        if ( $status->is_coming_soon() ) {
357            return true;
358        }
359
360        return 'unlaunched' === get_option( 'launch-status' );
361    }
362
363    /**
364     * Render the mount div in the footer.
365     *
366     * Only outputs the div when the script was successfully enqueued.
367     *
368     * @return void
369     */
370    public static function render_mount_div(): void {
371        if ( ! wp_script_is( 'jetpack-reader-chat' ) ) {
372            return;
373        }
374
375        echo '<div id="jetpack-reader-chat"></div>';
376    }
377
378    /**
379     * Build the config object for the reader chat JS bundle.
380     *
381     * @return array The config array for JSON encoding.
382     */
383    private static function get_reader_chat_config(): array {
384        $host = new Host();
385        if ( $host->is_wpcom_simple() ) {
386            $site_id = get_current_blog_id();
387        } else {
388            $site_id = (int) Jetpack_Options::get_option( 'id' );
389        }
390
391        $config = array(
392            'siteId'    => $site_id,
393            'siteUrl'   => home_url(),
394            'siteName'  => get_bloginfo( 'name' ),
395            'isDevMode' => self::is_dev_mode(),
396            'agentId'   => 'reader-chat',
397            // The site locale, not the viewer's: the chat speaks the site's language.
398            'locale'    => get_locale(),
399        );
400
401        $current_post = self::get_current_post_context();
402        if ( null !== $current_post ) {
403            $config['currentPost'] = $current_post;
404        }
405
406        return $config;
407    }
408
409    /**
410     * Build the current post context for the reader chat config.
411     *
412     * Returns null on non-singular views or when no post is available.
413     *
414     * @return array|null Post context, or null when not on a singular view.
415     */
416    private static function get_current_post_context(): ?array {
417        if ( ! is_singular() ) {
418            return null;
419        }
420
421        $post = get_post();
422        if ( ! $post ) {
423            return null;
424        }
425
426        // Only expose current post context for content that is publicly
427        // viewable. Draft/private/future/trash posts can be visible to
428        // editors through previews, but reader chat is public-facing and
429        // should not receive non-public post content in its inline config.
430        if ( is_preview() || ! is_post_publicly_viewable( $post ) ) {
431            return null;
432        }
433
434        // Respect password-protected posts: do not leak body content to
435        // visitors who have not entered the password. Omit the whole
436        // currentPost envelope so the chat doesn't imply it "knows" the
437        // post's content either.
438        if ( post_password_required( $post ) ) {
439            return null;
440        }
441
442        // Gates apply when content renders, so check before reading raw post_content.
443        if ( Content_Gate::is_gated( $post ) ) {
444            return null;
445        }
446
447        $context = array(
448            'id'      => $post->ID,
449            'title'   => get_the_title( $post ),
450            'url'     => get_permalink( $post ),
451            'excerpt' => wp_trim_words( wp_strip_all_tags( $post->post_content ), 120 ),
452            'author'  => get_the_author_meta( 'display_name', (int) $post->post_author ),
453            'date'    => get_the_date( 'F j, Y', $post ),
454        );
455
456        $categories = get_the_category( $post->ID );
457        if ( $categories ) {
458            $context['categories'] = wp_list_pluck( $categories, 'name' );
459        }
460
461        $tags = get_the_tags( $post->ID );
462        if ( $tags ) {
463            $context['tags'] = wp_list_pluck( $tags, 'name' );
464        }
465
466        return $context;
467    }
468
469    /**
470     * Get the version string for the CDN bundle.
471     *
472     * Attempts to read the version from the remote asset manifest.
473     * Falls back to a timestamp in dev mode, or null in production.
474     *
475     * @return string|false|null The version string, or null to omit the query param.
476     */
477    private static function get_asset_version() {
478        $skip_cache = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG;
479
480        if ( ! $skip_cache ) {
481            $cached = get_transient( READER_CHAT_ASSET_TRANSIENT );
482            if ( false !== $cached ) {
483                return $cached['version'] ?? null;
484            }
485        }
486
487        $json_path = 'widgets.wp.com/agents-manager/reader-chat.asset.json';
488
489        // Try local filesystem first (available on WordPress.com).
490        $data = self::read_local_asset_json( ABSPATH . $json_path );
491
492        // Fallback to HTTP fetch.
493        if ( false === $data ) {
494            $data = self::fetch_remote_asset_json( 'https://' . $json_path );
495        }
496
497        if ( false === $data ) {
498            // Dev mode: return a cache-busting version so the sandbox bundle loads.
499            if ( self::is_dev_mode() ) {
500                return 'dev-' . time();
501            }
502            if ( ! $skip_cache ) {
503                set_transient(
504                    READER_CHAT_ASSET_TRANSIENT,
505                    array(
506                        'version' => null,
507                    ),
508                    READER_CHAT_ASSET_FAILURE_CACHE_TTL
509                );
510            }
511            return null;
512        }
513
514        if ( ! $skip_cache ) {
515            set_transient( READER_CHAT_ASSET_TRANSIENT, $data, HOUR_IN_SECONDS );
516        }
517
518        return $data['version'] ?? null;
519    }
520
521    /**
522     * Read and decode a local asset manifest JSON file.
523     *
524     * @param string $path Absolute filesystem path to the JSON file.
525     * @return array|false Decoded data or false on failure.
526     */
527    private static function read_local_asset_json( string $path ) {
528        if ( ! file_exists( $path ) ) {
529            return false;
530        }
531
532        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Local file, not remote URL.
533        $contents = file_get_contents( $path );
534        if ( false === $contents ) {
535            return false;
536        }
537
538        return self::decode_asset_json( $contents );
539    }
540
541    /**
542     * Fetch and decode a remote asset manifest JSON file.
543     *
544     * @param string $url URL to fetch.
545     * @return array|false Decoded data or false on failure.
546     */
547    private static function fetch_remote_asset_json( string $url ) {
548        $response = wp_safe_remote_get( $url );
549        if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
550            return false;
551        }
552
553        return self::decode_asset_json( wp_remote_retrieve_body( $response ) );
554    }
555
556    /**
557     * Decode a JSON asset manifest string and validate the result is an array.
558     *
559     * @param string $contents Raw JSON string.
560     * @return array|false Decoded array or false on decode failure / non-array.
561     */
562    private static function decode_asset_json( string $contents ) {
563        $data = json_decode( $contents, true );
564        if ( JSON_ERROR_NONE !== json_last_error() || ! is_array( $data ) ) {
565            return false;
566        }
567        return $data;
568    }
569
570    /**
571     * Check whether AI features are available for this site.
572     *
573     * @return bool
574     */
575    private static function has_ai_features(): bool {
576        $host = new Host();
577
578        if ( $host->is_wpcom_simple() ) {
579            return true;
580        }
581
582        return ( new Connection_Manager( 'jetpack' ) )->has_connected_owner()
583            && ! ( new Status() )->is_offline_mode()
584            && \Jetpack_AI_Settings::is_ai_enabled();
585    }
586
587    /**
588     * Check whether the current site can serve Reader Chat under its Search plan.
589     *
590     * Uses WordPress.com's local Search plan source on Simple sites. Elsewhere,
591     * uses the cached Jetpack Search plan option instead of forcing a remote
592     * refresh on public frontend requests.
593     *
594     * @return bool
595     */
596    private static function has_search_plan_access(): bool {
597        $plan_access = apply_filters( 'jetpack_reader_chat_has_search_plan_access', null );
598        if ( null !== $plan_access ) {
599            return (bool) $plan_access;
600        }
601
602        $host = new Host();
603        if ( $host->is_wpcom_simple() ) {
604            $blog_id = get_current_blog_id();
605            if ( $blog_id <= 0 ) {
606                return false;
607            }
608
609            if ( function_exists( 'require_lib' ) ) {
610                require_lib( 'jetpack-search' );
611            }
612
613            $wpcom_plan_info_class = '\Jetpack\Search\Plan_Info';
614            if ( class_exists( $wpcom_plan_info_class ) ) {
615                $plan_info = new $wpcom_plan_info_class( $blog_id );
616                return $plan_info->supports_search()
617                    && method_exists( $plan_info, 'is_free_search_plan' )
618                    && ! $plan_info->is_free_search_plan()
619                    && ! $plan_info->is_disabled_due_to_overage();
620            }
621        }
622
623        if ( ! class_exists( Plan::class ) ) {
624            return false;
625        }
626
627        $plan_info = get_option( Plan::JETPACK_SEARCH_PLAN_INFO_OPTION_KEY );
628        if ( ! is_array( $plan_info ) ) {
629            return false;
630        }
631
632        return ! Search_Helper::is_forced_free_plan()
633            && ! empty( $plan_info['supports_search'] )
634            && ( $plan_info['effective_subscription']['product_slug'] ?? null ) !== Plan::JETPACK_SEARCH_FREE_PRODUCT_SLUG
635            && empty( $plan_info['plan_usage']['must_upgrade'] );
636    }
637
638    /**
639     * Check if the current request is from a development environment.
640     *
641     * Matches the pattern used in Jetpack_AI_Sidebar::is_dev_mode().
642     * IMPORTANT: Only use for feature gating, not authorization.
643     *
644     * @return bool
645     */
646    private static function is_dev_mode(): bool {
647        $domain = wp_parse_url( get_site_url(), PHP_URL_HOST );
648        if ( ! is_string( $domain ) ) {
649            return false;
650        }
651
652        if (
653            'localhost' === $domain ||
654            '.jurassic.tube' === stristr( $domain, '.jurassic.tube' ) ||
655            '.jurassic.ninja' === stristr( $domain, '.jurassic.ninja' )
656        ) {
657            return true;
658        }
659
660        if ( function_exists( 'wpcom_is_proxied_request' ) && wpcom_is_proxied_request() ) {
661            return true;
662        }
663
664        if (
665            ( isset( $_SERVER['A8C_PROXIED_REQUEST'] ) && (bool) sanitize_text_field( wp_unslash( $_SERVER['A8C_PROXIED_REQUEST'] ) ) ) ||
666            ( defined( 'A8C_PROXIED_REQUEST' ) && A8C_PROXIED_REQUEST )
667        ) {
668            return true;
669        }
670
671        if ( defined( 'AT_PROXIED_REQUEST' ) && AT_PROXIED_REQUEST && defined( 'ATOMIC_CLIENT_ID' ) ) {
672            switch ( ATOMIC_CLIENT_ID ) {
673                case 1:
674                case 2:
675                case 3: // Pressable
676                case 32:
677                case 118: // Commerce garden client (ciab)
678                    return true;
679            }
680        }
681
682        return false;
683    }
684}