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