Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
82.01% covered (warning)
82.01%
155 / 189
64.29% covered (warning)
64.29%
9 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
Monitor_Abilities
82.89% covered (warning)
82.89%
155 / 187
64.29% covered (warning)
64.29%
9 / 14
41.14
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
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 register_category
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_abilities
100.00% covered (success)
100.00%
71 / 71
100.00% covered (success)
100.00%
1 / 1
1
 can_view_monitor
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 can_manage_monitor
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_monitor_status
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
5
 set_notifications
94.87% covered (success)
94.87%
37 / 39
0.00% covered (danger)
0.00%
0 / 1
9.01
 is_user_connected_to_jetpack
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 apply_notifications_update
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 fetch_notifications_state
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 fetch_last_status_change
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 normalize_last_status_change
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
6
1<?php
2/**
3 * Jetpack Monitor Abilities Registration
4 *
5 * Registers Jetpack Downtime Monitor abilities with the WordPress Abilities API.
6 *
7 * @package automattic/jetpack
8 */
9
10namespace Automattic\Jetpack\Plugin\Abilities;
11
12use Automattic\Jetpack\Connection\Manager as Connection_Manager;
13use Automattic\Jetpack\WP_Abilities\Registrar;
14use Jetpack;
15use Jetpack_IXR_Client;
16use Jetpack_Monitor;
17
18if ( ! defined( 'ABSPATH' ) ) {
19    exit( 0 );
20}
21
22/**
23 * Registers Jetpack Downtime Monitor abilities with the WordPress Abilities API.
24 *
25 * Exposes a zero-arg overview read (`get-monitor-status`) and a declarative
26 * state-setter (`set-notifications`) so AI agents can inspect and configure the
27 * site's Downtime Monitor through the standard `wp-abilities/v1` REST surface.
28 */
29class Monitor_Abilities extends Registrar {
30
31    private const MODULE_SLUG = 'monitor';
32
33    /**
34     * {@inheritDoc}
35     */
36    protected static function enabled_by_default(): bool {
37        return true;
38    }
39
40    /**
41     * {@inheritDoc}
42     *
43     * Monitor abilities live under the WordPress core `site` category — it is
44     * registered by the Abilities API itself, so we reference it by slug and
45     * never register it ourselves (see the no-op `register_category()` below).
46     */
47    public static function get_category_slug(): string {
48        return 'site';
49    }
50
51    /**
52     * {@inheritDoc}
53     *
54     * Unused: the `site` category is owned by WordPress core, so
55     * `register_category()` is a no-op and this definition is never passed to
56     * `wp_register_ability_category()`. It remains only to satisfy the abstract
57     * Registrar contract.
58     */
59    public static function get_category_definition(): array {
60        return array();
61    }
62
63    /**
64     * No-op: the `site` ability category is registered by the WordPress core
65     * Abilities API. Re-registering it here would clobber the core definition,
66     * so this registrar only references the category by slug.
67     *
68     * @return void
69     */
70    public static function register_category() {}
71
72    /**
73     * {@inheritDoc}
74     */
75    public static function get_abilities(): array {
76        return array(
77            'jetpack-monitor/get-monitor-status' => array(
78                'label'               => __( 'Get downtime monitoring status', 'jetpack' ),
79                'description'         => __( 'Return the current downtime monitoring state as { module_active, user_connected, notifications_enabled, last_status_change }. notifications_enabled is a boolean (does the current user receive downtime alerts). last_status_change is the timestamp of the most recent up/down status transition recorded by the downtime monitoring service, as a "YYYY-MM-DD HH:mm:ss" UTC string, or null when no transition has been recorded — this reflects the legacy last_status_change projection, not necessarily the last time downtime began. Fails with jetpack_monitor_not_connected when the current user is not connected to Jetpack (connect first via the My Jetpack admin page), or jetpack_monitor_service_unreachable when the remote downtime monitoring service cannot be reached. These abilities are only registered while the Downtime monitoring module (slug `monitor`) is active; if they are absent from wp_get_abilities(), activate that module first.', 'jetpack' ),
80                'input_schema'        => array(
81                    'type'                 => 'object',
82                    'additionalProperties' => false,
83                ),
84                'output_schema'       => array(
85                    'type'       => 'object',
86                    'properties' => array(
87                        'module_active'         => array( 'type' => 'boolean' ),
88                        'user_connected'        => array( 'type' => 'boolean' ),
89                        'notifications_enabled' => array( 'type' => 'boolean' ),
90                        'last_status_change'    => array( 'type' => array( 'string', 'null' ) ),
91                    ),
92                ),
93                'execute_callback'    => array( __CLASS__, 'get_monitor_status' ),
94                'permission_callback' => array( __CLASS__, 'can_view_monitor' ),
95                'meta'                => array(
96                    'annotations'  => array(
97                        'readonly'    => true,
98                        'destructive' => false,
99                        'idempotent'  => true,
100                    ),
101                    'public'       => true,
102                    'show_in_rest' => true,
103                    'mcp'          => array(
104                        'public' => true,
105                        'type'   => 'tool',
106                    ),
107                ),
108            ),
109
110            'jetpack-monitor/set-notifications'  => array(
111                'label'               => __( 'Set downtime monitoring notifications', 'jetpack' ),
112                'description'         => __( 'Enable or disable downtime email notifications for the current user. Idempotent — setting the state to the current value returns changed=false. Returns { enabled, changed }. Preconditions: the Downtime monitoring module must be active and the current user must be connected to Jetpack; call jetpack-monitor/get-monitor-status first to verify the connection. Fails with jetpack_monitor_module_inactive (activate the Downtime monitoring module first — these abilities are only registered while the module is active, so this error indicates a race) or jetpack_monitor_not_connected when preconditions are not met.', 'jetpack' ),
113                'input_schema'        => array(
114                    'type'                 => 'object',
115                    'required'             => array( 'enabled' ),
116                    'properties'           => array(
117                        'enabled' => array(
118                            'type'        => 'boolean',
119                            'description' => __( 'Desired notification state. true enables downtime email notifications for the current user; false disables them.', 'jetpack' ),
120                        ),
121                    ),
122                    'additionalProperties' => false,
123                ),
124                'output_schema'       => array(
125                    'type'       => 'object',
126                    'properties' => array(
127                        'enabled' => array( 'type' => 'boolean' ),
128                        'changed' => array( 'type' => 'boolean' ),
129                    ),
130                ),
131                'execute_callback'    => array( __CLASS__, 'set_notifications' ),
132                'permission_callback' => array( __CLASS__, 'can_manage_monitor' ),
133                'meta'                => array(
134                    'annotations'  => array(
135                        'readonly'    => false,
136                        'destructive' => false,
137                        'idempotent'  => true,
138                    ),
139                    'public'       => true,
140                    'show_in_rest' => true,
141                    'mcp'          => array(
142                        'public' => true,
143                        'type'   => 'tool',
144                    ),
145                ),
146            ),
147        );
148    }
149
150    /**
151     * Permission check: can the current user read Monitor status?
152     */
153    public static function can_view_monitor(): bool {
154        return current_user_can( 'jetpack_admin_page' );
155    }
156
157    /**
158     * Permission check: can the current user manage Monitor notifications?
159     *
160     * The settings API needs `jetpack_configure_modules` (`manage_options`) for this setting, and the
161     * write also updates the current user's local copy (`monitor_receive_notifications{user_id}`) the
162     * settings screen reads.
163     */
164    public static function can_manage_monitor(): bool {
165        return current_user_can( 'manage_options' );
166    }
167
168    /**
169     * Execute: overview read. Returns the full
170     * `{ module_active, user_connected, notifications_enabled, last_status_change }`
171     * shape on the happy path. Surfaces precondition and transport failures as
172     * `WP_Error` so callers (especially AI agents) get an actionable next step
173     * instead of opaque null fields:
174     *
175     * - `jetpack_monitor_module_inactive` — Monitor module is not active.
176     *   Defensive: in practice this is unreachable because the abilities are
177     *   only registered while the module is active.
178     * - `jetpack_monitor_not_connected` — the current user is not connected to
179     *   Jetpack; the remote read needs the user's token. Steers the caller to
180     *   the My Jetpack admin page to connect.
181     * - `jetpack_monitor_service_unreachable` — the remote Monitor service
182     *   returned an error for one of the two underlying XML-RPC reads
183     *   (`isUserInNotifications` or `getLastDowntime`). Transient — retry later.
184     *
185     * `last_status_change` remains `null` on the happy path when no up/down
186     * transition has been recorded yet; that is the documented "no data yet"
187     * signal, not a failure.
188     *
189     * @param array|null $input Ability input (no parameters accepted).
190     * @return array|\WP_Error
191     */
192    public static function get_monitor_status( $input = null ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- Abilities API contract requires execute callbacks to accept the input array even when the schema declares no parameters.
193        $module_active  = Jetpack::is_module_active( self::MODULE_SLUG );
194        $user_connected = static::is_user_connected_to_jetpack();
195
196        if ( ! $module_active ) {
197            return new \WP_Error(
198                'jetpack_monitor_module_inactive',
199                __( 'The Downtime monitoring module is not active. Activate it before reading the downtime monitoring status.', 'jetpack' )
200            );
201        }
202
203        if ( ! $user_connected ) {
204            return new \WP_Error(
205                'jetpack_monitor_not_connected',
206                __( 'User is not connected to Jetpack. Connect first via the My Jetpack admin page, then retry this ability.', 'jetpack' )
207            );
208        }
209
210        $state = static::fetch_notifications_state();
211        if ( is_wp_error( $state ) ) {
212            return new \WP_Error(
213                'jetpack_monitor_service_unreachable',
214                __( 'The remote downtime monitoring service is unreachable. Retry shortly; this is typically transient.', 'jetpack' ),
215                array( 'underlying' => $state->get_error_code() )
216            );
217        }
218
219        $status_change = static::fetch_last_status_change();
220        if ( is_wp_error( $status_change ) ) {
221            return new \WP_Error(
222                'jetpack_monitor_service_unreachable',
223                __( 'The remote downtime monitoring service is unreachable. Retry shortly; this is typically transient.', 'jetpack' ),
224                array( 'underlying' => $status_change->get_error_code() )
225            );
226        }
227
228        return array(
229            'module_active'         => $module_active,
230            'user_connected'        => $user_connected,
231            'notifications_enabled' => (bool) $state,
232            'last_status_change'    => $status_change,
233        );
234    }
235
236    /**
237     * Execute: declarative state-setter. Idempotent — compares desired vs current
238     * and returns changed=false when they match. Either way the current user's
239     * local copy of the value is synced to the remote one (after the write on a
240     * change, and on the no-op path) so the legacy REST reader, which trusts that
241     * copy first, never reports a stale state.
242     *
243     * @param array|null $input Input matching the ability's input_schema.
244     * @return array|\WP_Error
245     */
246    public static function set_notifications( $input = null ) {
247        $input = is_array( $input ) ? $input : array();
248
249        if ( ! array_key_exists( 'enabled', $input ) ) {
250            return new \WP_Error(
251                'jetpack_monitor_missing_enabled',
252                __( 'A desired enabled state (boolean) is required.', 'jetpack' )
253            );
254        }
255        if ( ! is_bool( $input['enabled'] ) ) {
256            return new \WP_Error(
257                'jetpack_monitor_invalid_enabled',
258                __( 'The enabled parameter must be a boolean. Strings like "true" / "false" are not accepted.', 'jetpack' )
259            );
260        }
261
262        if ( ! Jetpack::is_module_active( self::MODULE_SLUG ) ) {
263            return new \WP_Error(
264                'jetpack_monitor_module_inactive',
265                __( 'The Downtime monitoring module is not active. Activate it before configuring notifications.', 'jetpack' )
266            );
267        }
268
269        if ( ! static::is_user_connected_to_jetpack() ) {
270            return new \WP_Error(
271                'jetpack_monitor_not_connected',
272                __( 'The current user is not connected to Jetpack. Connect the user to Jetpack before configuring downtime monitoring notifications.', 'jetpack' )
273            );
274        }
275
276        $desired = $input['enabled'];
277        $current = static::fetch_notifications_state();
278        if ( is_wp_error( $current ) ) {
279            return $current;
280        }
281
282        if ( $desired === $current ) {
283            // Sync even on a no-op, so a stale local copy heals itself.
284            Jetpack_Monitor::save_notifications_copy( $current );
285
286            return array(
287                'enabled' => $current,
288                'changed' => false,
289            );
290        }
291
292        $applied = static::apply_notifications_update( $desired );
293        if ( is_wp_error( $applied ) ) {
294            return $applied;
295        }
296
297        // Keep the legacy REST reader's local copy in sync with the write.
298        Jetpack_Monitor::save_notifications_copy( $desired );
299
300        return array(
301            'enabled' => $desired,
302            'changed' => true,
303        );
304    }
305
306    /**
307     * Whether the current user is connected to Jetpack.
308     *
309     * Extracted as a protected seam so tests can override the connection check
310     * without standing up a full Jetpack token fixture.
311     */
312    protected static function is_user_connected_to_jetpack(): bool {
313        return ( new Connection_Manager( 'jetpack' ) )->is_user_connected();
314    }
315
316    /**
317     * Send the IXR `jetpack.monitor.setNotifications` request to apply the
318     * desired state on the remote Monitor service.
319     *
320     * @param bool $enabled Desired notification state.
321     * @return true|\WP_Error True on success, WP_Error on remote failure.
322     */
323    protected static function apply_notifications_update( bool $enabled ) {
324        $xml = new Jetpack_IXR_Client( array( 'user_id' => get_current_user_id() ) );
325        $xml->query( 'jetpack.monitor.setNotifications', $enabled );
326        if ( $xml->isError() ) {
327            return new \WP_Error(
328                'jetpack_monitor_notifications_update_failed',
329                sprintf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() )
330            );
331        }
332        return true;
333    }
334
335    /**
336     * Fetch the current notifications state from the remote Monitor service.
337     *
338     * @return bool|\WP_Error Boolean preference when the remote call succeeds,
339     *                        WP_Error when the remote call fails.
340     */
341    protected static function fetch_notifications_state() {
342        $xml = new Jetpack_IXR_Client( array( 'user_id' => get_current_user_id() ) );
343        $xml->query( 'jetpack.monitor.isUserInNotifications' );
344        if ( $xml->isError() ) {
345            return new \WP_Error(
346                'jetpack_monitor_notifications_data_unavailable',
347                sprintf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() )
348            );
349        }
350        return (bool) $xml->getResponse();
351    }
352
353    /**
354     * Fetch the last up/down status-change timestamp from the remote Monitor
355     * service, reusing the same transient key and 10-minute TTL written by the
356     * legacy module.
357     *
358     * The remote `jetpack.monitor.getLastDowntime` XML-RPC method returns the
359     * legacy `last_status_change` projection — the time of the most recent
360     * up/down transition, not strictly when downtime began. The transient key
361     * stays `monitor_last_downtime` because that is what the legacy module
362     * writes and we share its cache.
363     *
364     * @return string|null|\WP_Error YYYY-MM-DD HH:mm:ss string, null when no
365     *                               transition has been recorded, or WP_Error
366     *                               on a remote failure.
367     */
368    protected static function fetch_last_status_change() {
369        $cached = get_transient( 'monitor_last_downtime' );
370        if ( false !== $cached ) {
371            return self::normalize_last_status_change( $cached );
372        }
373
374        $xml = new Jetpack_IXR_Client();
375        $xml->query( 'jetpack.monitor.getLastDowntime' );
376        if ( $xml->isError() ) {
377            return new \WP_Error(
378                'jetpack_monitor_downtime_data_unavailable',
379                sprintf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() )
380            );
381        }
382
383        $response = $xml->getResponse();
384        set_transient( 'monitor_last_downtime', $response, 10 * MINUTE_IN_SECONDS );
385        return self::normalize_last_status_change( $response );
386    }
387
388    /**
389     * Normalize a `last_status_change` value into the documented contract:
390     * a `YYYY-MM-DD HH:mm:ss` UTC string, or `null` for "no transition yet".
391     *
392     * Jetpack Monitor v1 returns an empty string when no transition has been
393     * recorded; Monitor v2 may instead surface a MySQL zero-date
394     * (`0000-00-00 00:00:00`) or some other sentinel. Collapse every "no value"
395     * representation to `null` so the ability's `null` contract stays stable
396     * regardless of which backend is active.
397     *
398     * @param mixed $value Raw remote/cached value.
399     * @return string|null Pass-through timestamp string, or null when absent.
400     */
401    protected static function normalize_last_status_change( $value ) {
402        if ( ! is_string( $value ) ) {
403            return null;
404        }
405
406        $value = trim( $value );
407        if ( '' === $value || 0 === strncmp( $value, '0000-00-00', 10 ) ) {
408            return null;
409        }
410
411        $ts = strtotime( $value );
412        if ( false === $ts || $ts <= 0 ) {
413            return null;
414        }
415
416        return $value;
417    }
418}