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