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