Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
87.12% covered (warning)
87.12%
142 / 163
70.59% covered (warning)
70.59%
12 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
Sitemaps_Abilities
88.20% covered (warning)
88.20%
142 / 161
70.59% covered (warning)
70.59%
12 / 17
34.79
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%
79 / 79
100.00% covered (success)
100.00%
1 / 1
1
 can_view_sitemaps
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 can_manage_sitemaps
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_status
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 request_rebuild
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
3
 get_master_sitemap_url
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 get_master_sitemap_xml
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 get_sitemap_entries
92.59% covered (success)
92.59%
25 / 27
0.00% covered (danger)
0.00%
0 / 1
8.03
 is_news_sitemap_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 count_published
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 is_build_running
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_build_queued
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 schedule_rebuild
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_next_scheduled_at
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * Jetpack Sitemaps Abilities Registration
4 *
5 * Registers Jetpack Sitemaps 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 Sitemaps abilities with the WordPress Abilities API.
21 *
22 * Exposes a zero-arg sitemap status read (`get-status`) and a zero-arg rebuild
23 * dispatch (`request-rebuild`) so AI agents can inspect sitemap freshness and
24 * trigger a regeneration through the standard `wp-abilities/v1` REST surface.
25 *
26 * Both abilities only register while the Sitemaps module is active — the
27 * surrounding `modules/sitemaps.php` is only loaded by Jetpack when the module
28 * is on, so the `Sitemaps_Abilities::init()` call at the bottom of that file
29 * is the gate.
30 */
31class Sitemaps_Abilities extends Registrar {
32
33    private const MODULE_SLUG = 'sitemaps';
34
35    /**
36     * Cron hook name used by the Sitemaps module to drive incremental builds.
37     *
38     * Kept as a const here rather than imported from `Jetpack_Sitemap_Manager`
39     * because the manager registers it as an action name only — there is no
40     * canonical PHP constant to reference, and the value is part of the
41     * module's stable public surface (it shows up in `wp cron list`).
42     */
43    private const CRON_HOOK = 'jp_sitemap_cron_hook';
44
45    /**
46     * Transient written by `Jetpack_Sitemap_State::check_out()` while a build
47     * step is in progress. Presence of this transient is the canonical
48     * "build currently running" signal; its 15-minute TTL means the signal
49     * self-clears if a build crashes without unlocking.
50     */
51    private const STATE_LOCK_TRANSIENT = 'jetpack-sitemap-state-lock';
52
53    /**
54     * {@inheritDoc}
55     *
56     * Sitemaps abilities live under the WordPress core `site` category — it is
57     * registered by the Abilities API itself, so we reference it by slug and
58     * never register it ourselves (see the no-op `register_category()` below).
59     */
60    public static function get_category_slug(): string {
61        return 'site';
62    }
63
64    /**
65     * {@inheritDoc}
66     *
67     * Unused: the `site` category is owned by WordPress core, so
68     * `register_category()` is a no-op and this definition is never passed to
69     * `wp_register_ability_category()`. It remains only to satisfy the abstract
70     * Registrar contract.
71     */
72    public static function get_category_definition(): array {
73        return array();
74    }
75
76    /**
77     * No-op: the `site` ability category is registered by the WordPress core
78     * Abilities API. Re-registering it here would clobber the core definition,
79     * so this registrar only references the category by slug.
80     *
81     * @return void
82     */
83    public static function register_category() {}
84
85    /**
86     * {@inheritDoc}
87     */
88    public static function get_abilities(): array {
89        return array(
90            'jetpack-sitemaps/get-status'      => array(
91                'label'               => __( 'Get Jetpack Sitemaps status', 'jetpack' ),
92                'description'         => __( 'Return the current state of the Jetpack-generated XML sitemaps as { active, url, post_count, page_count, news_sitemap_enabled, sitemaps }. `active` reflects whether the Sitemaps module is on. `url` is the public sitemap.xml entry point. `post_count` / `page_count` are the published `post` / `page` counts (the same baseline the WordPress core sitemap uses). `news_sitemap_enabled` reflects the `jetpack_news_sitemap_include_in_robotstxt` filter (default true). `sitemaps` is the list of child sitemaps actually present in the served sitemap.xml index — each entry is `{ loc, lastmod }`, where `lastmod` is the W3C datetime string the sitemap exposes (or null when that entry omits one). `sitemaps` is an empty array until a master sitemap has been generated. These abilities are only registered while the Sitemaps module is active; if they are absent from wp_get_abilities(), activate the Sitemaps module first.', 'jetpack' ),
93                'input_schema'        => array(
94                    'type'                 => 'object',
95                    'additionalProperties' => false,
96                ),
97                'output_schema'       => array(
98                    'type'       => 'object',
99                    'properties' => array(
100                        'active'               => array( 'type' => 'boolean' ),
101                        'url'                  => array( 'type' => 'string' ),
102                        'post_count'           => array( 'type' => 'integer' ),
103                        'page_count'           => array( 'type' => 'integer' ),
104                        'news_sitemap_enabled' => array( 'type' => 'boolean' ),
105                        'sitemaps'             => array(
106                            'type'  => 'array',
107                            'items' => array(
108                                'type'       => 'object',
109                                'properties' => array(
110                                    'loc'     => array( 'type' => 'string' ),
111                                    'lastmod' => array( 'type' => array( 'string', 'null' ) ),
112                                ),
113                            ),
114                        ),
115                    ),
116                ),
117                'execute_callback'    => array( __CLASS__, 'get_status' ),
118                'permission_callback' => array( __CLASS__, 'can_view_sitemaps' ),
119                'meta'                => array(
120                    'annotations'  => array(
121                        'readonly'    => true,
122                        'destructive' => false,
123                        'idempotent'  => true,
124                    ),
125                    'public'       => true,
126                    'show_in_rest' => true,
127                    'mcp'          => array(
128                        'public' => true,
129                        'type'   => 'tool', // default is already "tool", but can be explicit.
130                    ),
131                ),
132            ),
133
134            'jetpack-sitemaps/request-rebuild' => array(
135                'label'               => __( 'Request a Jetpack Sitemaps rebuild', 'jetpack' ),
136                'description'         => __( 'Dispatch a full sitemap regeneration by scheduling the existing `jp_sitemap_cron_hook` cron event. Returns { dispatched, status, next_scheduled_at } where status is one of "queued" (a single-event cron tick was just scheduled), "running" (a build is already in flight per the `jetpack-sitemap-state-lock` transient), or "already_running" (alias of "running"; surfaced so callers can branch on either spelling). `next_scheduled_at` is the next `jp_sitemap_cron_hook` tick as an ISO 8601 UTC string with an explicit `Z` zone designator (e.g. `2026-05-19T19:33:20Z`), or null when nothing is scheduled (e.g. status=running with no future tick queued) — it tells the caller when the build they queued (or the one already pending) will actually run. Idempotent — calling this while a build is already in flight or already queued returns dispatched=false and the matching status rather than stacking duplicate cron events.', 'jetpack' ),
137                'input_schema'        => array(
138                    'type'                 => 'object',
139                    'additionalProperties' => false,
140                ),
141                'output_schema'       => array(
142                    'type'       => 'object',
143                    'properties' => array(
144                        'dispatched'        => array( 'type' => 'boolean' ),
145                        'status'            => array(
146                            'type' => 'string',
147                            'enum' => array( 'queued', 'running', 'already_running' ),
148                        ),
149                        'next_scheduled_at' => array( 'type' => array( 'string', 'null' ) ),
150                    ),
151                ),
152                'execute_callback'    => array( __CLASS__, 'request_rebuild' ),
153                'permission_callback' => array( __CLASS__, 'can_manage_sitemaps' ),
154                'meta'                => array(
155                    'annotations'  => array(
156                        'readonly'    => false,
157                        'destructive' => false,
158                        'idempotent'  => true,
159                    ),
160                    'public'       => true,
161                    'show_in_rest' => true,
162                    'mcp'          => array(
163                        'public' => true,
164                        'type'   => 'tool', // default is already "tool", but can be explicit.
165                    ),
166                ),
167            ),
168        );
169    }
170
171    /**
172     * Permission check: can the current user read sitemap status?
173     *
174     * Sitemap status is metadata about publicly-served XML — anyone who can
175     * manage content (`edit_posts`) is allowed to see it. Reads do not modify
176     * state and do not expose secrets.
177     */
178    public static function can_view_sitemaps(): bool {
179        return current_user_can( 'edit_posts' );
180    }
181
182    /**
183     * Permission check: can the current user dispatch a sitemap rebuild?
184     *
185     * Rebuild scheduling writes to cron + transient state and can run for
186     * minutes on large sites, so it is gated on `manage_options` (admin only).
187     */
188    public static function can_manage_sitemaps(): bool {
189        return current_user_can( 'manage_options' );
190    }
191
192    /**
193     * Execute: status read.
194     *
195     * Surfaces an opinionated, agent-friendly projection of the module's state:
196     * - `active` from `Jetpack::is_module_active`.
197     * - `url` from `jetpack_sitemap_uri()`, the same helper the public sitemap
198     *   router uses.
199     * - `post_count` / `page_count` from `wp_count_posts()->publish`, the
200     *   same baseline used by the WordPress core sitemap. Cheap; no joins.
201     * - `news_sitemap_enabled` from the `jetpack_news_sitemap_include_in_robotstxt`
202     *   filter (the same filter that controls news-sitemap robots.txt inclusion).
203     * - `sitemaps` from the served master sitemap document itself (see
204     *   `get_sitemap_entries()`) — the real child-sitemap list with each
205     *   entry's own `lastmod`, rather than a synthetic last-build timestamp.
206     *
207     * @param array|null $input Ability input (no parameters accepted).
208     * @return array
209     */
210    public static function get_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.
211        return array(
212            'active'               => Jetpack::is_module_active( self::MODULE_SLUG ),
213            'url'                  => static::get_master_sitemap_url(),
214            'post_count'           => static::count_published( 'post' ),
215            'page_count'           => static::count_published( 'page' ),
216            'news_sitemap_enabled' => static::is_news_sitemap_enabled(),
217            'sitemaps'             => static::get_sitemap_entries(),
218        );
219    }
220
221    /**
222     * Execute: rebuild dispatch.
223     *
224     * Three-state idempotent dispatch:
225     *
226     * 1. If the state lock transient is set, a build step is currently
227     *    running. Return `dispatched=false`, `status=running`. We also surface
228     *    `already_running` as the alias the plan documents; this function
229     *    returns `running` as the canonical value so callers that branch on
230     *    one or the other both work — the output_schema enum permits both.
231     * 2. Else if a cron event is already scheduled in the future for our hook,
232     *    a build is queued. Return `dispatched=false`, `status=queued`.
233     * 3. Otherwise schedule a single-event cron tick to fire immediately and
234     *    return `dispatched=true`, `status=queued`.
235     *
236     * Every branch also returns `next_scheduled_at` (see
237     * `get_next_scheduled_at()`) so the caller learns when the queued/pending
238     * build will actually run without a follow-up status read.
239     *
240     * @param array|null $input Ability input (no parameters accepted).
241     * @return array
242     */
243    public static function request_rebuild( $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.
244        if ( static::is_build_running() ) {
245            return array(
246                'dispatched'        => false,
247                'status'            => 'running',
248                'next_scheduled_at' => static::get_next_scheduled_at(),
249            );
250        }
251
252        if ( static::is_build_queued() ) {
253            return array(
254                'dispatched'        => false,
255                'status'            => 'queued',
256                'next_scheduled_at' => static::get_next_scheduled_at(),
257            );
258        }
259
260        static::schedule_rebuild();
261
262        return array(
263            'dispatched'        => true,
264            'status'            => 'queued',
265            'next_scheduled_at' => static::get_next_scheduled_at(),
266        );
267    }
268
269    /**
270     * Public sitemap URL for the master sitemap.
271     *
272     * Extracted as a protected seam so tests can override without booting the
273     * rewrite/permalink stack.
274     */
275    protected static function get_master_sitemap_url(): string {
276        if ( function_exists( 'jetpack_sitemap_uri' ) ) {
277            return (string) jetpack_sitemap_uri( 'sitemap.xml' );
278        }
279        // Defensive: when the sitemaps module file is loaded the helper
280        // exists. This branch only runs if a caller invokes the ability
281        // outside the normal bootstrap path.
282        return (string) home_url( '/sitemap.xml' );
283    }
284
285    /**
286     * Raw master-sitemap XML — the exact document the public `sitemap.xml`
287     * router serves, read straight from storage via the librarian (no HTTP
288     * loopback). Returns an empty string when no master sitemap has been
289     * generated yet, or when the Sitemaps module helpers are unavailable.
290     *
291     * Extracted as a protected seam so tests can feed a known document without
292     * a librarian / wp_posts.
293     */
294    protected static function get_master_sitemap_xml(): string {
295        if (
296            ! class_exists( 'Jetpack_Sitemap_Librarian' )
297            || ! function_exists( 'jp_sitemap_filename' )
298            || ! defined( 'JP_MASTER_SITEMAP_TYPE' )
299        ) {
300            return '';
301        }
302
303        $librarian = new \Jetpack_Sitemap_Librarian();
304
305        // jp_sitemap_filename() is documented `@param string $number`; for the
306        // master type it returns 'sitemap.xml' and ignores the number, but it
307        // must be non-null and string-typed to satisfy the contract (the
308        // int-`0` router call site predates this and is Phan-baselined).
309        return (string) $librarian->get_sitemap_text(
310            \jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE, '0' ),
311            JP_MASTER_SITEMAP_TYPE
312        );
313    }
314
315    /**
316     * The child-sitemap entries actually present in the served master
317     * sitemap, as a list of `[ 'loc' => string, 'lastmod' => string|null ]`.
318     *
319     * Parses the same `<sitemapindex>` document `sitemap.xml` serves rather
320     * than deriving freshness from the `jetpack-sitemap-state` option: that
321     * option can read its initial/reset shape (no `max` projection) even while
322     * a fully-built sitemap.xml is being served, so it is not a reliable
323     * "what does the sitemap actually contain" source.
324     *
325     * Returns an empty array when no master sitemap exists yet or the stored
326     * document does not parse.
327     *
328     * @return array<int, array{loc:string, lastmod:string|null}>
329     */
330    protected static function get_sitemap_entries(): array {
331        $xml = static::get_master_sitemap_xml();
332        if ( '' === $xml ) {
333            return array();
334        }
335
336        $previous = libxml_use_internal_errors( true );
337        $document = new \DOMDocument();
338        // Source is Jetpack's own stored sitemap (not user input) and PHP 8+
339        // disables external-entity loading by default; LIBXML_NONET is belt-
340        // and-suspenders against any network/entity fetch during parsing.
341        $loaded = $document->loadXML( $xml, LIBXML_NONET );
342        libxml_clear_errors();
343        libxml_use_internal_errors( $previous );
344
345        if ( ! $loaded ) {
346            return array();
347        }
348
349        $entries = array();
350        foreach ( $document->getElementsByTagName( 'sitemap' ) as $sitemap_node ) {
351            $loc_nodes = $sitemap_node->getElementsByTagName( 'loc' );
352            if ( 0 === $loc_nodes->length ) {
353                continue;
354            }
355
356            $loc = trim( $loc_nodes->item( 0 )->textContent );
357            if ( '' === $loc ) {
358                continue;
359            }
360
361            $lastmod_nodes = $sitemap_node->getElementsByTagName( 'lastmod' );
362            $lastmod       = $lastmod_nodes->length > 0
363                ? trim( $lastmod_nodes->item( 0 )->textContent )
364                : '';
365
366            $entries[] = array(
367                'loc'     => $loc,
368                'lastmod' => '' === $lastmod ? null : $lastmod,
369            );
370        }
371
372        return $entries;
373    }
374
375    /**
376     * Whether news-sitemap inclusion is enabled.
377     *
378     * Mirrors the filter chain in `Jetpack_Sitemap_Manager::callback_action_do_robotstxt`
379     * but only resolves the modern filter — the deprecated 7.4.0 alias is
380     * already merged into the modern filter by the time it runs in production.
381     */
382    protected static function is_news_sitemap_enabled(): bool {
383        /** This filter is documented in modules/sitemaps/sitemaps.php */
384        return (bool) apply_filters( 'jetpack_news_sitemap_include_in_robotstxt', true );
385    }
386
387    /**
388     * Count published posts of a given post type.
389     *
390     * Wraps `wp_count_posts()` so tests can override without a real WP_Posts
391     * factory.
392     *
393     * @param string $post_type Post type slug.
394     */
395    protected static function count_published( string $post_type ): int {
396        $counts = wp_count_posts( $post_type );
397        if ( ! is_object( $counts ) || ! isset( $counts->publish ) ) {
398            return 0;
399        }
400        return (int) $counts->publish;
401    }
402
403    /**
404     * Whether a sitemap build step is currently running.
405     *
406     * The Sitemaps module sets a 15-minute transient lock at the start of
407     * `Jetpack_Sitemap_State::check_out()` and deletes it on `unlock()` /
408     * `reset()`. Presence of the transient is the canonical "in flight" signal.
409     */
410    protected static function is_build_running(): bool {
411        return true === get_transient( self::STATE_LOCK_TRANSIENT );
412    }
413
414    /**
415     * Whether a sitemap build is already scheduled for a future cron tick.
416     *
417     * Uses `wp_next_scheduled` so we don't stack duplicate single-event cron
418     * entries when the recurring `jp_sitemap_cron_hook` is already pending.
419     */
420    protected static function is_build_queued(): bool {
421        return false !== wp_next_scheduled( self::CRON_HOOK );
422    }
423
424    /**
425     * Schedule a single-event cron tick to drive the next build step.
426     *
427     * Matches the dispatch pattern used by
428     * `Jetpack_Sitemap_Manager::callback_action_purge_data` — `wp_schedule_single_event`
429     * with an immediate execution time. The recurring `sitemap-interval`
430     * schedule still fires on its normal cadence; this just front-runs the
431     * next tick.
432     */
433    protected static function schedule_rebuild(): void {
434        wp_schedule_single_event( time(), self::CRON_HOOK );
435    }
436
437    /**
438     * When the next `jp_sitemap_cron_hook` build tick is scheduled, as an
439     * ISO 8601 UTC string (e.g. `2026-05-19T19:33:20Z`), or null when nothing
440     * is scheduled.
441     *
442     * Returned alongside the dispatch result so callers immediately know when
443     * the build they queued (or the one already pending) will actually run,
444     * without a second round-trip. Null in the `running` case when the lock is
445     * held but no future tick is queued.
446     *
447     * ISO 8601 with the explicit `Z` zone designator (not `human_time_diff()`,
448     * not a bare "Y-m-d H:i:s") so the timezone is unambiguous and the value is
449     * locale-stable and machine-parseable — the same format the `sitemaps[]`
450     * `lastmod` values use in `get-status`.
451     */
452    protected static function get_next_scheduled_at(): ?string {
453        $timestamp = wp_next_scheduled( self::CRON_HOOK );
454        if ( false === $timestamp ) {
455            return null;
456        }
457        return gmdate( 'Y-m-d\TH:i:s\Z', $timestamp );
458    }
459}