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