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