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