Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
86.02% covered (warning)
86.02%
80 / 93
94.12% covered (success)
94.12%
16 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_AI_Settings
88.89% covered (warning)
88.89%
80 / 90
94.12% covered (success)
94.12%
16 / 17
52.29
0.00% covered (danger)
0.00%
0 / 1
 init
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 hold_module_off_when_ai_is_off
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
 drop_ai_module
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 register_settings
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
3
 add_sync_options_whitelist
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 apply_master_gates
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
 should_enforce_ai_controls
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 is_ai_enabled
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 host_allows_ai
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_master_enabled
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 site_is_connected
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 user_is_connected
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 get_master_forced_off_route
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
8
 third_party_disables_ai
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 set_master_enabled
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 is_feature_enabled
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 is_ai_seo_enabled
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * Jetpack AI feature settings.
4 *
5 * Central registry for the Jetpack AI master switch and per-feature toggles,
6 * implementing the layered AI gate contract:
7 *
8 *   1. the host allows AI            — WP_AI_SUPPORT, via wp_supports_ai()
9 *   2. the plan includes AI          — connection + plan checks (owned by each feature)
10 *   3. AI is on for the whole site   — the jetpack_ai_enabled option (master switch)
11 *   4. the feature's own switch      — per-feature options surfaced on the AI settings page
12 *
13 * Gates 1 and 3 are enforced by is_ai_enabled(), which plugin load points call
14 * instead of applying `jetpack_ai_enabled` directly: the gates AND in after the
15 * filter chain, so no later-priority callback can override them. The gates also
16 * ride the filter itself for package consumers that cannot reference this class.
17 * Gate 4 options are registered here and consulted at each feature's registration
18 * or enqueue point — a disabled feature must stop loading, not just hide.
19 *
20 * A host or a `jetpack_ai_enabled` callback that turns AI off also drops the `ai`
21 * module from the active list, so module readers agree with the filter.
22 *
23 * @package automattic/jetpack
24 */
25
26use Automattic\Jetpack\Connection\Manager;
27use Automattic\Jetpack\Modules;
28use Automattic\Jetpack\Status;
29use Automattic\Jetpack\Status\Host;
30
31if ( ! defined( 'ABSPATH' ) ) {
32    exit( 0 );
33}
34
35// All consumers require this canonical file once. A class_exists() guard here
36// would be true on the first load because PHP registers unconditional classes
37// before executing the file, returning before the self-initialization below.
38
39/**
40 * Registers the Jetpack AI master switch and per-feature toggle options, and
41 * enforces the host (WP_AI_SUPPORT) and master gates on the AI filters.
42 */
43class Jetpack_AI_Settings {
44
45    /**
46     * Master switch option. Named after the pre-existing `jetpack_ai_enabled`
47     * filter it backs, following the `reader_chat` option/filter precedent.
48     *
49     * @var string
50     */
51    const MASTER_OPTION = 'jetpack_ai_enabled';
52
53    /**
54     * Slug of the `ai` module that acts as the site-wide master switch off
55     * WordPress.com Simple (self-hosted and Atomic), where modules run.
56     *
57     * @var string
58     */
59    const AI_MODULE = 'ai';
60
61    /**
62     * The `jetpack_ai_enabled` route custom code can take to hold AI off, as
63     * reported by {@see self::get_master_forced_off_route()}. Each route names a
64     * different hook, so each needs its own documentation link.
65     *
66     * @var string
67     */
68    const FORCED_OFF_ROUTE_FILTER = 'filter';
69
70    /**
71     * The module-filter route; see {@see self::FORCED_OFF_ROUTE_FILTER}.
72     *
73     * @var string
74     */
75    const FORCED_OFF_ROUTE_MODULES = 'modules';
76
77    /**
78     * The filter route on VIP, which documents this filter as its own supported
79     * off switch and so owns the page to send the reader to.
80     *
81     * @var string
82     */
83    const FORCED_OFF_ROUTE_FILTER_VIP = 'filter-vip';
84
85    /**
86     * Feature key => option name for every toggle on the AI settings page.
87     *
88     * `ai_search` reuses an option owned by the Search surface; the rest are
89     * registered by this class. The automatic-generation option is deliberately
90     * absent: the Traffic page and the SEO dashboard own it.
91     *
92     * @var array
93     */
94    const FEATURE_OPTIONS = array(
95        'writing_assistant' => 'jetpack_ai_writing_assistant_enabled',
96        'image_editor'      => 'jetpack_ai_image_editor_enabled',
97        'ai_seo'            => 'jetpack_ai_seo_enabled',
98        'ai_search'         => 'jetpack_search_ai_answers_enabled',
99    );
100
101    /**
102     * Option defaults. The reused Search option keeps its established opt-in
103     * default; the new per-feature toggles default to on.
104     *
105     * @var array
106     */
107    const FEATURE_DEFAULTS = array(
108        'writing_assistant' => true,
109        'image_editor'      => true,
110        'ai_seo'            => true,
111        'ai_search'         => false,
112    );
113
114    /**
115     * Feature keys whose options this class registers and syncs (the reused
116     * Search option is registered by its owning surface).
117     *
118     * @var array
119     */
120    const OWNED_FEATURES = array( 'writing_assistant', 'image_editor', 'ai_seo' );
121
122    /**
123     * Whether init() has already run.
124     *
125     * @var bool
126     */
127    private static $initialized = false;
128
129    /**
130     * Whether apply_master_gates() should step aside; see
131     * {@see self::third_party_disables_ai()}.
132     *
133     * @var bool
134     */
135    private static $probing_third_party = false;
136
137    /**
138     * Hook everything up. Must run on every request (front-end, editor, REST):
139     * the filters attached here gate feature loading.
140     *
141     * @return void
142     */
143    public static function init() {
144        if ( self::$initialized ) {
145            return;
146        }
147        self::$initialized = true;
148
149        add_action( 'init', array( __CLASS__, 'register_settings' ) );
150        add_filter( 'jetpack_sync_options_whitelist', array( __CLASS__, 'add_sync_options_whitelist' ) );
151
152        // Plugin call sites use is_ai_enabled(), which applies gates 1 (host) and
153        // 3 (master) after the filter chain. This in-chain registration stays for
154        // the package consumers that cannot reference this plugin class
155        // (external-media, my-jetpack): there the gates keep their pre-helper,
156        // priority-10 behavior.
157        add_filter( 'jetpack_ai_enabled', array( __CLASS__, 'apply_master_gates' ) );
158
159        // AI surfaces that do not flow through jetpack_ai_enabled.
160        add_filter( 'jetpack_search_ai_answers_enabled', array( __CLASS__, 'apply_master_gates' ) );
161        add_filter( 'jetpack_ai_sidebar_enabled', array( __CLASS__, 'apply_master_gates' ) );
162        add_filter( 'jetpack_ai_seo_enabled', array( __CLASS__, 'apply_master_gates' ) );
163
164        // Once per request, before the first reader of the active list: Jetpack::load_modules() at priority -2.
165        add_action( 'after_setup_theme', array( __CLASS__, 'hold_module_off_when_ai_is_off' ), -3 );
166    }
167
168    /**
169     * Report a host or a `jetpack_ai_enabled` callback that turns AI off as the `ai` module forced off.
170     *
171     * Registered only while something says no: Jetpack_Modules_Overrides caches its first read of
172     * `jetpack_active_modules`, so an always-on callback would hide every override added later.
173     *
174     * @return void
175     */
176    public static function hold_module_off_when_ai_is_off() {
177        $callback = array( __CLASS__, 'drop_ai_module' );
178
179        // Read once per request: a `wp_supports_ai` or `jetpack_ai_enabled` callback must be registered before `after_setup_theme`.
180        if ( ! ( new Host() )->is_wpcom_simple() && self::should_enforce_ai_controls() && ( ! self::host_allows_ai() || self::third_party_disables_ai() ) ) {
181            add_filter( 'jetpack_active_modules', $callback, 100 );
182            return;
183        }
184
185        remove_filter( 'jetpack_active_modules', $callback, 100 );
186    }
187
188    /**
189     * Strip `ai` from the active list. The stored choice is untouched, so AI
190     * returns as before once nothing turns it off ahead of the module.
191     *
192     * @param array $modules Active module slugs.
193     * @return array
194     */
195    public static function drop_ai_module( $modules ) {
196        return array_values( array_diff( (array) $modules, array( self::AI_MODULE ) ) );
197    }
198
199    /**
200     * Register the master switch and the per-feature options this class owns.
201     *
202     * @return void
203     */
204    public static function register_settings() {
205        $show_in_rest = ! ( new Host() )->is_wpcom_simple();
206
207        $options = array(
208            self::MASTER_OPTION                        => __( 'Whether Jetpack AI is enabled on this site.', 'jetpack' ),
209            self::FEATURE_OPTIONS['writing_assistant'] => __( 'Whether the Jetpack AI writing assistant is enabled.', 'jetpack' ),
210            self::FEATURE_OPTIONS['image_editor']      => __( 'Whether the Jetpack AI image editor is enabled.', 'jetpack' ),
211            self::FEATURE_OPTIONS['ai_seo']            => __( 'Whether the Jetpack AI SEO features are enabled.', 'jetpack' ),
212        );
213
214        // These settings do not belong to Settings > General. A separate group
215        // prevents options.php from clearing values whose fields are absent from
216        // the General form.
217        foreach ( $options as $option => $description ) {
218            register_setting(
219                'jetpack_ai',
220                $option,
221                array(
222                    'type'              => 'boolean',
223                    'description'       => $description,
224                    'sanitize_callback' => 'rest_sanitize_boolean',
225                    // The master option is never exposed over core settings REST:
226                    // off-Simple the `ai` module is the master and the option only
227                    // holds the legacy pre-module opt-out (a core-REST write would
228                    // clobber it without touching the real master); on Simple the
229                    // dedicated feature-settings endpoint is the writable surface.
230                    'show_in_rest'      => self::MASTER_OPTION === $option ? false : $show_in_rest,
231                    'default'           => true,
232                )
233            );
234        }
235    }
236
237    /**
238     * Add the per-feature AI options to Jetpack Sync's option whitelist.
239     *
240     * Atomic and self-hosted sites write these locally; syncing them lets
241     * WordPress.com (Calypso, the multi-site dashboard) read toggle state and
242     * is the prerequisite for mirroring the dashboard AI toggle later.
243     *
244     * The master switch is deliberately absent: off-Simple the `ai` module is
245     * the master, and module state already reaches WordPress.com through the
246     * synced `active_modules` callable — syncing the option as well would add
247     * a second, driftable source of truth for the same bit.
248     *
249     * @param array $options Option names allowed to sync.
250     * @return array Updated option names.
251     */
252    public static function add_sync_options_whitelist( $options ) {
253        $options = (array) $options;
254        foreach ( self::OWNED_FEATURES as $feature ) {
255            $options[] = self::FEATURE_OPTIONS[ $feature ];
256        }
257        return array_values( array_unique( $options ) );
258    }
259
260    /**
261     * Fold the host (gate 1) and master switch (gate 3) into an AI enabled filter.
262     *
263     * Restrictive-only on purpose: `jetpack_ai_enabled` is applied with different
264     * defaults at different call sites (Jetpack_AI_Helper passes false on plain
265     * self-hosted sites; the editor extension hub passes true), so this callback
266     * may only ever turn a yes into a no — returning the option value directly
267     * would flip self-hosted defaults to enabled.
268     *
269     * @param bool $enabled The value the call site computed so far.
270     * @return bool
271     */
272    public static function apply_master_gates( $enabled ) {
273        // Stand aside while third_party_disables_ai() asks the chain what
274        // everyone else says; our own verdict would drown theirs out.
275        if ( self::$probing_third_party ) {
276            return (bool) $enabled;
277        }
278
279        return (bool) $enabled
280            && self::host_allows_ai()
281            && ( ! self::should_enforce_ai_controls() || self::is_master_enabled() );
282    }
283
284    /**
285     * Whether the AI controls — the master switch and the toggles this class owns
286     * — take effect here. Simple keeps its existing option contract, self-hosted
287     * sites use the Jetpack controls, and Atomic remains limited to internal testing.
288     *
289     * @return bool
290     */
291    private static function should_enforce_ai_controls() {
292        $host = new Host();
293        if ( $host->is_wpcom_simple() ) {
294            return true;
295        }
296
297        return ! $host->is_woa_site()
298            || ( function_exists( 'jetpack_is_internal_testing_environment' ) && jetpack_is_internal_testing_environment() );
299    }
300
301    /**
302     * Whether Jetpack AI is enabled on this site, with the host (gate 1) and
303     * master switch (gate 3) as final, non-overridable checks.
304     *
305     * Runs the `jetpack_ai_enabled` filter with the call site's default — the
306     * chain may still enable or disable as before — then ANDs the host and
307     * master gates after it, so no late-priority callback can turn AI back on
308     * once either gate says no. Plugin call sites use this helper; the filter
309     * registration in init() stays for the package consumers that cannot
310     * reference this class.
311     *
312     * @since 16.2
313     *
314     * @param bool $default The call site's computed default. Defaults differ
315     *                      between call sites — see apply_master_gates().
316     * @return bool
317     */
318    public static function is_ai_enabled( $default = true ) {
319        /**
320         * Filter whether the AI features are enabled in the Jetpack plugin.
321         *
322         * @since 11.8
323         *
324         * @param bool $default Are AI features enabled? The default varies by call site.
325         */
326        $enabled = (bool) apply_filters( 'jetpack_ai_enabled', $default );
327
328        return self::apply_master_gates( $enabled );
329    }
330
331    /**
332     * Gate 1: whether the host allows AI at all.
333     *
334     * Defers to core's wp_supports_ai(), which is backed by the WP_AI_SUPPORT
335     * constant and its own filter. This is a server-owner decision: when it is
336     * off, no AI settings should be shown and no upgrade should ever be offered.
337     *
338     * @return bool
339     */
340    public static function host_allows_ai() {
341        return wp_supports_ai();
342    }
343
344    /**
345     * Gate 3: whether the site-wide AI master switch is on.
346     *
347     * The master lives in a different place depending on the platform. On
348     * WordPress.com Simple no Jetpack modules run, so the `jetpack_ai_enabled`
349     * option is the master. Everywhere else (self-hosted and Atomic) the `ai`
350     * module is the real master switch, toggled through the standard Jetpack
351     * module machinery; there the option only carries the legacy pre-module
352     * value the one-time opt-out migration reads, and is never written again.
353     *
354     * @return bool
355     */
356    public static function is_master_enabled() {
357        if ( ( new Host() )->is_wpcom_simple() ) {
358            return (bool) get_option( self::MASTER_OPTION, true );
359        }
360
361        return ( new Modules() )->is_active( self::AI_MODULE );
362    }
363
364    /**
365     * Whether the site's WordPress.com connection can carry AI. Offline mode
366     * counts as disconnected even while the site holds its tokens, and Simple
367     * sites are always connected.
368     *
369     * @return bool
370     */
371    public static function site_is_connected() {
372        return ( new Host() )->is_wpcom_simple()
373            || ( ( new Manager( 'jetpack' ) )->has_connected_owner()
374                && ! ( new Status() )->is_offline_mode() );
375    }
376
377    /**
378     * Whether the current user's own account is connected. Surfaces that proxy
379     * as the requesting user need this on top of {@see self::site_is_connected()}.
380     *
381     * @return bool
382     */
383    public static function user_is_connected() {
384        return ( new Host() )->is_wpcom_simple()
385            || ( new Manager( 'jetpack' ) )->is_user_connected();
386    }
387
388    /**
389     * Which hook custom code used to hold AI off, so the notice can link to the
390     * matching documentation. Always empty on WordPress.com Simple, which runs
391     * no modules.
392     *
393     * @return string One of the FORCED_OFF_ROUTE_* constants, or '' when nothing
394     *                holds AI off.
395     */
396    public static function get_master_forced_off_route() {
397        $host = new Host();
398
399        if ( $host->is_wpcom_simple() ) {
400            return '';
401        }
402
403        if ( self::third_party_disables_ai() ) {
404            return $host->is_vip_site()
405                ? self::FORCED_OFF_ROUTE_FILTER_VIP
406                : self::FORCED_OFF_ROUTE_FILTER;
407        }
408
409        if ( self::is_master_enabled() ) {
410            return '';
411        }
412
413        // Removed from the available list by `jetpack_get_available_modules`.
414        if ( ! in_array( self::AI_MODULE, ( new Modules() )->get_available(), true ) ) {
415            return self::FORCED_OFF_ROUTE_MODULES;
416        }
417
418        // Forced off through `option_jetpack_active_modules` or `jetpack_active_modules`.
419        $overridden = class_exists( 'Jetpack_Modules_Overrides' )
420            && 'inactive' === Jetpack_Modules_Overrides::instance()->get_module_override( self::AI_MODULE );
421
422        return $overridden ? self::FORCED_OFF_ROUTE_MODULES : '';
423    }
424
425    /**
426     * Whether a `jetpack_ai_enabled` callback other than our own gates turns AI off.
427     *
428     * Asks the chain with our gates stood down, so the module this answer drives
429     * (via {@see self::hold_module_off_when_ai_is_off()}) can neither mask nor feed it.
430     *
431     * @return bool
432     */
433    private static function third_party_disables_ai() {
434        self::$probing_third_party = true;
435        try {
436            return ! apply_filters( 'jetpack_ai_enabled', true );
437        } finally {
438            self::$probing_third_party = false;
439        }
440    }
441
442    /**
443     * Set the site-wide AI master switch, writing to whichever store backs it on
444     * this platform (see {@see self::is_master_enabled()}).
445     *
446     * On WordPress.com Simple the `jetpack_ai_enabled` option is the master, so
447     * we update it. Off-Simple the `ai` module is the master, so we activate or
448     * deactivate it. The no-exit / no-redirect arguments are passed to
449     * `Modules::update_status()` so this is safe to call outside a request that
450     * expects to terminate (REST handlers, migrations, CLI).
451     *
452     * @param bool $enabled Whether AI should be enabled site-wide.
453     * @return void
454     */
455    public static function set_master_enabled( bool $enabled ) {
456        if ( ( new Host() )->is_wpcom_simple() ) {
457            update_option( self::MASTER_OPTION, $enabled );
458            return;
459        }
460
461        // The module alone is the master off-Simple. The option is deliberately NOT
462        // written here: WordPress.com derives the master state from the synced
463        // `active_modules` callable, and the stored option must keep its legacy
464        // pre-module value so Jetpack::reconcile_ai_master_optout() can read an
465        // explicit opt-out on sites that upgrade later.
466        ( new Modules() )->update_status( self::AI_MODULE, $enabled, false, false );
467    }
468
469    /**
470     * Gate 4: whether an individual feature's switch is on.
471     *
472     * Checks only the feature's own toggle — callers remain responsible for the
473     * outer gates (most already consult the jetpack_ai_enabled filter, which
474     * carries host + master). Only the matching option is read: a code-level
475     * override belongs on the option itself, through core's own option filters.
476     *
477     * Not {@see self::is_ai_seo_enabled()}, which is this check for the `ai_seo`
478     * key plus its filter and the site-wide gates. Use that one at load points.
479     *
480     * @param string $feature Feature key (see FEATURE_OPTIONS).
481     * @return bool False for unknown features.
482     */
483    public static function is_feature_enabled( $feature ) {
484        if ( ! isset( self::FEATURE_OPTIONS[ $feature ] ) ) {
485            return false;
486        }
487
488        // The toggles this class owns stay on wherever they do not apply: Simple keeps
489        // the existing wp.com settings contract, while Atomic keeps them hidden.
490        // The reused Search option has its own settings surface, so it always honors
491        // its stored value.
492        if ( in_array( $feature, self::OWNED_FEATURES, true )
493            && ( ( new Host() )->is_wpcom_simple() || ! self::should_enforce_ai_controls() ) ) {
494            return true;
495        }
496
497        $option = self::FEATURE_OPTIONS[ $feature ];
498
499        return (bool) get_option( $option, self::FEATURE_DEFAULTS[ $feature ] );
500    }
501
502    /**
503     * Whether AI SEO is enabled after its feature filter and the site-wide AI checks.
504     *
505     * @since 16.2
506     *
507     * @return bool
508     */
509    public static function is_ai_seo_enabled() {
510        /**
511         * Filter whether the Jetpack AI SEO feature is enabled.
512         *
513         * @since 16.2
514         *
515         * @param bool $enabled Whether the SEO feature toggle is on.
516         */
517        $enabled = (bool) apply_filters( 'jetpack_ai_seo_enabled', self::is_feature_enabled( 'ai_seo' ) );
518
519        return $enabled && self::is_ai_enabled();
520    }
521}
522
523// Self-initialize on load. The consuming AI extension files require this file
524// directly (__DIR__-relative) because on WordPress.com Simple the plugin's
525// extension files load through wpcom's own loader and load-jetpack.php never
526// runs. This keeps filter registration identical in both bootstrap paths.
527Jetpack_AI_Settings::init();