Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
81.23% covered (warning)
81.23%
225 / 277
60.00% covered (warning)
60.00%
6 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
Modules_Abilities
81.82% covered (warning)
81.82%
225 / 275
60.00% covered (warning)
60.00%
6 / 10
97.62
0.00% covered (danger)
0.00%
0 / 1
 enabled_by_default
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_category_slug
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_category_definition
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_abilities
100.00% covered (success)
100.00%
123 / 123
100.00% covered (success)
100.00%
1 / 1
1
 can_view_modules
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 can_manage_modules
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 summarize_module
95.00% covered (success)
95.00%
19 / 20
0.00% covered (danger)
0.00%
0 / 1
14
 get_modules
76.92% covered (warning)
76.92%
30 / 39
0.00% covered (danger)
0.00%
0 / 1
29.50
 set_module_status
65.67% covered (warning)
65.67%
44 / 67
0.00% covered (danger)
0.00%
0 / 1
26.36
 find_conflicting_active_plugin
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
90
1<?php
2/**
3 * Jetpack Modules Abilities Registration
4 *
5 * Registers Jetpack module management abilities with the WordPress Abilities API.
6 *
7 * @package automattic/jetpack
8 */
9
10namespace Automattic\Jetpack\Plugin\Abilities;
11
12use Automattic\Jetpack\WP_Abilities\Registrar;
13use Jetpack;
14
15if ( ! defined( 'ABSPATH' ) ) {
16    exit( 0 );
17}
18
19/**
20 * Registers Jetpack module management abilities with the WordPress Abilities API.
21 *
22 * Exposes a filtered read (`get-modules`) and a declarative state-setter
23 * (`set-module-status`) so AI agents can discover and toggle Jetpack modules
24 * through the standard `wp-abilities/v1` REST surface.
25 */
26class Modules_Abilities extends Registrar {
27
28    /**
29     * {@inheritDoc}
30     */
31    protected static function enabled_by_default(): bool {
32        return true;
33    }
34
35    /**
36     * {@inheritDoc}
37     */
38    public static function get_category_slug(): string {
39        return 'jetpack';
40    }
41
42    /**
43     * {@inheritDoc}
44     *
45     * The `jetpack` ability-category is shared across multiple subpackages
46     * (Connection, Plugin, etc.). `wp_register_ability_category()` only honours
47     * the first registration, so the English source string here is kept
48     * byte-identical to the one in
49     * {@see \Automattic\Jetpack\Connection\Abilities\Connection_Abilities::get_category_definition()}
50     * to keep the visible category text consistent regardless of which
51     * registrar runs first.
52     */
53    public static function get_category_definition(): array {
54        return array(
55            // "Jetpack" is a product name and should not be translated.
56            'label'       => 'Jetpack',
57            'description' => __( 'Abilities provided by Jetpack.', 'jetpack' ),
58        );
59    }
60
61    /**
62     * {@inheritDoc}
63     */
64    public static function get_abilities(): array {
65        $module_schema = array(
66            'type'       => 'object',
67            'properties' => array(
68                'slug'                     => array( 'type' => 'string' ),
69                'name'                     => array( 'type' => 'string' ),
70                'description'              => array( 'type' => 'string' ),
71                'active'                   => array( 'type' => 'boolean' ),
72                'sort'                     => array( 'type' => 'integer' ),
73                'feature'                  => array(
74                    'type'  => 'array',
75                    'items' => array( 'type' => 'string' ),
76                ),
77                'plan_classes'             => array(
78                    'type'  => 'array',
79                    'items' => array( 'type' => 'string' ),
80                ),
81                'requires_connection'      => array( 'type' => 'boolean' ),
82                'requires_user_connection' => array( 'type' => 'boolean' ),
83                'auto_activate'            => array( 'type' => 'string' ),
84                'override'                 => array(
85                    'type' => 'string',
86                    'enum' => array( 'none', 'active', 'inactive' ),
87                ),
88            ),
89        );
90
91        return array(
92            'jetpack/get-modules'       => array(
93                'label'               => __( 'Get Jetpack modules', 'jetpack' ),
94                'description'         => __( 'Return zero or more Jetpack modules as an array. Each element has { slug, name, description, active, sort, feature, plan_classes, requires_connection, requires_user_connection, auto_activate, override }. An override of "active" or "inactive" means a filter or the host forces that state, so jetpack/set-module-status cannot change it. Combine slug / active / feature / search filters to narrow the list. When slug is provided and unknown, the result is an empty array (not an error). Use this before calling jetpack/set-module-status to enumerate legal slugs.', 'jetpack' ),
95                'input_schema'        => array(
96                    'type'                 => 'object',
97                    'default'              => array(),
98                    'properties'           => array(
99                        'slug'    => array(
100                            'type'        => 'string',
101                            'description' => __( 'Return a single module by slug. Unknown slugs yield an empty array.', 'jetpack' ),
102                            'minLength'   => 1,
103                        ),
104                        'active'  => array(
105                            'type'        => 'boolean',
106                            'description' => __( 'When set, only return modules whose current active state matches this value.', 'jetpack' ),
107                        ),
108                        'feature' => array(
109                            'type'        => 'string',
110                            'description' => __( 'Case-insensitive match against a module\'s feature tag (e.g. "Recommended", "Security", "Performance").', 'jetpack' ),
111                            'minLength'   => 1,
112                        ),
113                        'search'  => array(
114                            'type'        => 'string',
115                            'description' => __( 'Case-insensitive substring match against the module name, slug, and description.', 'jetpack' ),
116                            'minLength'   => 1,
117                        ),
118                    ),
119                    'additionalProperties' => false,
120                ),
121                'output_schema'       => array(
122                    'type'  => 'array',
123                    'items' => $module_schema,
124                ),
125                'execute_callback'    => array( __CLASS__, 'get_modules' ),
126                'permission_callback' => array( __CLASS__, 'can_view_modules' ),
127                'meta'                => array(
128                    'annotations'  => array(
129                        'readonly'    => true,
130                        'destructive' => false,
131                        'idempotent'  => true,
132                    ),
133                    'public'       => true,
134                    'show_in_rest' => true,
135                    'mcp'          => array(
136                        'public' => true,
137                        'type'   => 'tool', // default is already "tool", but can be explicit.
138                    ),
139                ),
140            ),
141
142            'jetpack/set-module-status' => array(
143                'label'               => __( 'Set Jetpack module status', 'jetpack' ),
144                'description'         => __( 'Set a Jetpack module\'s active state. Idempotent — setting a module to its current state returns changed=false. Returns { slug, active, changed }. Call jetpack/get-modules first to enumerate valid slugs. Modules requiring a Jetpack connection or a paid plan may fail with jetpack_modules_activate_failed; the message indicates the next step.', 'jetpack' ),
145                'input_schema'        => array(
146                    'type'                 => 'object',
147                    'required'             => array( 'slug', 'active' ),
148                    'properties'           => array(
149                        'slug'   => array(
150                            'type'        => 'string',
151                            'description' => __( 'The Jetpack module slug (e.g. "stats", "sso", "sharedaddy").', 'jetpack' ),
152                            'minLength'   => 1,
153                        ),
154                        'active' => array(
155                            'type'        => 'boolean',
156                            'description' => __( 'Desired active state. true activates the module; false deactivates it.', 'jetpack' ),
157                        ),
158                    ),
159                    'additionalProperties' => false,
160                ),
161                'output_schema'       => array(
162                    'type'       => 'object',
163                    'properties' => array(
164                        'slug'    => array( 'type' => 'string' ),
165                        'active'  => array( 'type' => 'boolean' ),
166                        'changed' => array( 'type' => 'boolean' ),
167                        'note'    => array(
168                            'type'        => 'string',
169                            'description' => __( 'What the change leaves unaffected, when that is not obvious.', 'jetpack' ),
170                        ),
171                    ),
172                ),
173                'execute_callback'    => array( __CLASS__, 'set_module_status' ),
174                'permission_callback' => array( __CLASS__, 'can_manage_modules' ),
175                'meta'                => array(
176                    'annotations'  => array(
177                        'readonly'    => false,
178                        'destructive' => false,
179                        'idempotent'  => true,
180                    ),
181                    'public'       => true,
182                    'show_in_rest' => true,
183                    'mcp'          => array(
184                        'public' => true,
185                        'type'   => 'tool', // default is already "tool", but can be explicit.
186                    ),
187                ),
188            ),
189        );
190    }
191
192    /**
193     * Permission check: can the current user read module listings?
194     *
195     * Mirrors the module list REST route, so subscribers are denied; `jetpack_admin_page`
196     * maps to `edit_posts` outside offline mode, so contributors and up pass.
197     */
198    public static function can_view_modules(): bool {
199        return current_user_can( 'jetpack_admin_page' );
200    }
201
202    /**
203     * Permission check: can the current user toggle modules?
204     */
205    public static function can_manage_modules(): bool {
206        return current_user_can( 'jetpack_manage_modules' )
207            && current_user_can( 'jetpack_activate_modules' );
208    }
209
210    /**
211     * Build the high-signal summary shape used by `get-modules`.
212     *
213     * Adapts the raw `Jetpack::get_module()` array down to the fields agents
214     * actually consume — dropping internal bookkeeping like `module_tags`,
215     * changelog URLs, and file paths. Applies the site's current locale to
216     * `name` and `description` so agent-facing output mirrors what a user
217     * would see in the admin UI.
218     *
219     * @param string $slug      Module slug.
220     * @param bool   $is_active Whether the module is currently active. Passed in to avoid
221     *                          O(N) calls to the `jetpack_active_modules` filter in a list loop.
222     * @return array|null Compact module entry, or null when the module has no info.
223     */
224    private static function summarize_module( $slug, $is_active ) {
225        $mod = Jetpack::get_module( $slug );
226        if ( ! is_array( $mod ) ) {
227            return null;
228        }
229
230        $i18n = function_exists( 'jetpack_get_module_i18n' ) ? jetpack_get_module_i18n( $slug ) : array();
231        $name = isset( $i18n['name'] ) ? (string) $i18n['name'] : ( isset( $mod['name'] ) ? (string) $mod['name'] : $slug );
232        $desc = isset( $i18n['description'] ) ? (string) $i18n['description'] : ( isset( $mod['description'] ) ? (string) $mod['description'] : '' );
233
234        $override = \Jetpack_Modules_Overrides::instance()->get_module_override( $slug );
235
236        return array(
237            'slug'                     => $slug,
238            'name'                     => $name,
239            'description'              => $desc,
240            'active'                   => $is_active,
241            'sort'                     => isset( $mod['sort'] ) ? (int) $mod['sort'] : 10,
242            'feature'                  => isset( $mod['feature'] ) && is_array( $mod['feature'] ) ? array_values( $mod['feature'] ) : array(),
243            'plan_classes'             => isset( $mod['plan_classes'] ) && is_array( $mod['plan_classes'] ) ? array_values( $mod['plan_classes'] ) : array(),
244            'requires_connection'      => ! empty( $mod['requires_connection'] ),
245            'requires_user_connection' => ! empty( $mod['requires_user_connection'] ),
246            'auto_activate'            => isset( $mod['auto_activate'] ) ? (string) $mod['auto_activate'] : 'No',
247            'override'                 => $override ? $override : 'none',
248        );
249    }
250
251    /**
252     * Consolidated read callback. Returns an array of module summaries.
253     *
254     * When `slug` is provided, returns a 0- or 1-element array; unknown slugs
255     * yield an empty array rather than a `WP_Error` so the shape is uniform.
256     *
257     * @param array|null $input Input matching the ability's input_schema.
258     * @return array
259     */
260    public static function get_modules( $input = null ) {
261        $input = is_array( $input ) ? $input : array();
262
263        // Fetch the active-slug map once per call — `Jetpack::is_module_active()` fires the
264        // user-extensible `jetpack_active_modules` filter on each call, so looking up
265        // active state per-module in a loop amplifies any hook cost by N.
266        $active_map = array_flip( Jetpack::get_active_modules() );
267
268        // Narrow the candidate set up front when `slug` is supplied; remaining
269        // filters (active / feature / search) still apply so combinations like
270        // { slug: 'stats', active: false } correctly return an empty array when
271        // stats is active.
272        if ( isset( $input['slug'] ) && is_string( $input['slug'] ) && '' !== $input['slug'] ) {
273            if ( ! Jetpack::is_module( $input['slug'] ) ) {
274                return array();
275            }
276            $candidate_slugs = array( $input['slug'] );
277        } else {
278            $candidate_slugs = Jetpack::get_available_modules();
279        }
280
281        $active_filter  = array_key_exists( 'active', $input ) && is_bool( $input['active'] ) ? $input['active'] : null;
282        $feature_filter = isset( $input['feature'] ) && is_string( $input['feature'] ) && '' !== $input['feature']
283            ? strtolower( $input['feature'] )
284            : null;
285        $search_filter  = isset( $input['search'] ) && is_string( $input['search'] ) && '' !== $input['search']
286            ? strtolower( $input['search'] )
287            : null;
288
289        $out = array();
290        foreach ( $candidate_slugs as $slug ) {
291            $summary = self::summarize_module( $slug, isset( $active_map[ $slug ] ) );
292            if ( null === $summary ) {
293                continue;
294            }
295
296            if ( null !== $active_filter && $summary['active'] !== $active_filter ) {
297                continue;
298            }
299
300            if ( null !== $feature_filter ) {
301                $features_lower = array_map( 'strtolower', $summary['feature'] );
302                if ( ! in_array( $feature_filter, $features_lower, true ) ) {
303                    continue;
304                }
305            }
306
307            if ( null !== $search_filter ) {
308                $haystack = strtolower( $summary['slug'] . ' ' . $summary['name'] . ' ' . $summary['description'] );
309                if ( false === strpos( $haystack, $search_filter ) ) {
310                    continue;
311                }
312            }
313
314            $out[] = $summary;
315        }
316
317        usort(
318            $out,
319            static function ( $a, $b ) {
320                if ( $a['sort'] === $b['sort'] ) {
321                    return strcmp( $a['slug'], $b['slug'] );
322                }
323                return $a['sort'] <=> $b['sort'];
324            }
325        );
326
327        return $out;
328    }
329
330    /**
331     * Declarative state-setter callback. Idempotent: returns changed=false
332     * when the desired state already matches current state.
333     *
334     * @param array|null $input Input matching the ability's input_schema.
335     * @return array|\WP_Error
336     */
337    public static function set_module_status( $input = null ) {
338        $input = is_array( $input ) ? $input : array();
339
340        if ( ! isset( $input['slug'] ) || ! is_string( $input['slug'] ) || '' === $input['slug'] ) {
341            return new \WP_Error(
342                'jetpack_modules_missing_slug',
343                __( 'A module slug is required. Call jetpack/get-modules to enumerate valid slugs.', 'jetpack' )
344            );
345        }
346
347        if ( ! array_key_exists( 'active', $input ) ) {
348            return new \WP_Error(
349                'jetpack_modules_missing_active',
350                __( 'A desired active state (boolean) is required.', 'jetpack' )
351            );
352        }
353        if ( ! is_bool( $input['active'] ) ) {
354            return new \WP_Error(
355                'jetpack_modules_invalid_active',
356                __( 'The active parameter must be a boolean. Strings like "true" / "false" are not accepted.', 'jetpack' )
357            );
358        }
359
360        $slug    = $input['slug'];
361        $desired = $input['active'];
362
363        if ( ! Jetpack::is_module( $slug ) ) {
364            return new \WP_Error(
365                'jetpack_modules_invalid_slug',
366                __( 'Unknown Jetpack module slug. Call jetpack/get-modules to enumerate valid slugs.', 'jetpack' )
367            );
368        }
369
370        $current = Jetpack::is_module_active( $slug );
371
372        if ( $desired === $current ) {
373            return array(
374                'slug'    => $slug,
375                'active'  => $current,
376                'changed' => false,
377            );
378        }
379
380        if ( $desired ) {
381            // Preflight: Jetpack::activate_module() ignores its $exit/$redirect flags when a
382            // conflicting standalone plugin (e.g. WordPress.com Stats vs. the stats module) is
383            // active — it calls wp_safe_redirect()+exit() and would terminate this REST request
384            // mid-response. Refuse here with a structured error instead.
385            $conflict = self::find_conflicting_active_plugin( $slug );
386            if ( null !== $conflict ) {
387                return new \WP_Error(
388                    'jetpack_modules_conflicting_plugin_active',
389                    sprintf(
390                        /* translators: %s: name of the conflicting plugin that must be deactivated first. */
391                        __( 'Cannot activate the module while a conflicting plugin (%s) is active. Deactivate it on the WordPress Plugins screen, then retry.', 'jetpack' ),
392                        $conflict
393                    )
394                );
395            }
396
397            // Always pass exit=false, redirect=false so the ability runs headless over REST.
398            $ok = Jetpack::activate_module( $slug, false, false );
399            if ( ! $ok ) {
400                return new \WP_Error(
401                    'jetpack_modules_activate_failed',
402                    __( 'Unable to activate the module. It may require a Jetpack connection or a higher plan. Inspect requires_connection and plan_classes on the module and retry after those preconditions are met.', 'jetpack' )
403                );
404            }
405        } else {
406            $ok = Jetpack::deactivate_module( $slug );
407            if ( ! $ok ) {
408                return new \WP_Error(
409                    'jetpack_modules_deactivate_failed',
410                    __( 'Unable to deactivate the module.', 'jetpack' )
411                );
412            }
413        }
414
415        // Re-check state: activate_module() / deactivate_module() can return truthy even when a
416        // pre_update_option_jetpack_active_modules filter blocks the option write, so the response
417        // would otherwise lie about reaching the requested state.
418        $actual = Jetpack::is_module_active( $slug );
419        if ( $desired !== $actual ) {
420            return new \WP_Error(
421                'jetpack_modules_state_mismatch',
422                __( 'The module did not reach the requested state. A filter on jetpack_active_modules may have rejected the change.', 'jetpack' )
423            );
424        }
425
426        $result = array(
427            'slug'    => $slug,
428            'active'  => $actual,
429            'changed' => true,
430        );
431
432        $note = $actual ? '' : Jetpack::get_module_deactivation_note( $slug );
433        if ( $note ) {
434            $result['note'] = $note;
435        }
436
437        return $result;
438    }
439
440    /**
441     * Return the human-readable name of the first standalone plugin currently active that
442     * would force {@see Jetpack::activate_module()} to redirect/exit, or null when none.
443     *
444     * Mirrors the lookup in {@see Jetpack_Client_Server::deactivate_plugin()}: prefer the
445     * known plugin file path, fall back to a name match across active plugins.
446     *
447     * @param string $slug Module slug.
448     * @return string|null
449     */
450    private static function find_conflicting_active_plugin( $slug ) {
451        $jetpack = Jetpack::init();
452        if ( empty( $jetpack->plugins_to_deactivate[ $slug ] ) ) {
453            return null;
454        }
455
456        if ( ! function_exists( 'is_plugin_active' ) ) {
457            require_once ABSPATH . 'wp-admin/includes/plugin.php';
458        }
459
460        $active_plugins = null;
461        foreach ( $jetpack->plugins_to_deactivate[ $slug ] as $candidate ) {
462            list( $plugin_file, $plugin_name ) = $candidate;
463
464            if ( is_plugin_active( $plugin_file ) ) {
465                return $plugin_name;
466            }
467
468            if ( null === $active_plugins ) {
469                $active_plugins = Jetpack::get_active_plugins();
470            }
471            foreach ( $active_plugins as $active ) {
472                $data = get_plugin_data( WP_PLUGIN_DIR . '/' . $active );
473                if ( isset( $data['Name'] ) && $data['Name'] === $plugin_name ) {
474                    return $plugin_name;
475                }
476            }
477        }
478
479        return null;
480    }
481}