Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
86.96% covered (warning)
86.96%
140 / 161
70.59% covered (warning)
70.59%
12 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
Sitemaps_Abilities
88.05% covered (warning)
88.05%
140 / 159
70.59% covered (warning)
70.59%
12 / 17
34.86
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%
77 / 77
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                    'show_in_rest' => true,
126                    'mcp'          => array(
127                        'public' => true,
128                        'type'   => 'tool', // default is already "tool", but can be explicit.
129                    ),
130                ),
131            ),
132
133            'jetpack-sitemaps/request-rebuild' => array(
134                'label'               => __( 'Request a Jetpack Sitemaps rebuild', 'jetpack' ),
135                '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' ),
136                'input_schema'        => array(
137                    'type'                 => 'object',
138                    'additionalProperties' => false,
139                ),
140                'output_schema'       => array(
141                    'type'       => 'object',
142                    'properties' => array(
143                        'dispatched'        => array( 'type' => 'boolean' ),
144                        'status'            => array(
145                            'type' => 'string',
146                            'enum' => array( 'queued', 'running', 'already_running' ),
147                        ),
148                        'next_scheduled_at' => array( 'type' => array( 'string', 'null' ) ),
149                    ),
150                ),
151                'execute_callback'    => array( __CLASS__, 'request_rebuild' ),
152                'permission_callback' => array( __CLASS__, 'can_manage_sitemaps' ),
153                'meta'                => array(
154                    'annotations'  => array(
155                        'readonly'    => false,
156                        'destructive' => false,
157                        'idempotent'  => true,
158                    ),
159                    'show_in_rest' => true,
160                    'mcp'          => array(
161                        'public' => true,
162                        'type'   => 'tool', // default is already "tool", but can be explicit.
163                    ),
164                ),
165            ),
166        );
167    }
168
169    /**
170     * Permission check: can the current user read sitemap status?
171     *
172     * Sitemap status is metadata about publicly-served XML — anyone who can
173     * manage content (`edit_posts`) is allowed to see it. Reads do not modify
174     * state and do not expose secrets.
175     */
176    public static function can_view_sitemaps(): bool {
177        return current_user_can( 'edit_posts' );
178    }
179
180    /**
181     * Permission check: can the current user dispatch a sitemap rebuild?
182     *
183     * Rebuild scheduling writes to cron + transient state and can run for
184     * minutes on large sites, so it is gated on `manage_options` (admin only).
185     */
186    public static function can_manage_sitemaps(): bool {
187        return current_user_can( 'manage_options' );
188    }
189
190    /**
191     * Execute: status read.
192     *
193     * Surfaces an opinionated, agent-friendly projection of the module's state:
194     * - `active` from `Jetpack::is_module_active`.
195     * - `url` from `jetpack_sitemap_uri()`, the same helper the public sitemap
196     *   router uses.
197     * - `post_count` / `page_count` from `wp_count_posts()->publish`, the
198     *   same baseline used by the WordPress core sitemap. Cheap; no joins.
199     * - `news_sitemap_enabled` from the `jetpack_news_sitemap_include_in_robotstxt`
200     *   filter (the same filter that controls news-sitemap robots.txt inclusion).
201     * - `sitemaps` from the served master sitemap document itself (see
202     *   `get_sitemap_entries()`) — the real child-sitemap list with each
203     *   entry's own `lastmod`, rather than a synthetic last-build timestamp.
204     *
205     * @param array|null $input Ability input (no parameters accepted).
206     * @return array
207     */
208    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.
209        return array(
210            'active'               => Jetpack::is_module_active( self::MODULE_SLUG ),
211            'url'                  => static::get_master_sitemap_url(),
212            'post_count'           => static::count_published( 'post' ),
213            'page_count'           => static::count_published( 'page' ),
214            'news_sitemap_enabled' => static::is_news_sitemap_enabled(),
215            'sitemaps'             => static::get_sitemap_entries(),
216        );
217    }
218
219    /**
220     * Execute: rebuild dispatch.
221     *
222     * Three-state idempotent dispatch:
223     *
224     * 1. If the state lock transient is set, a build step is currently
225     *    running. Return `dispatched=false`, `status=running`. We also surface
226     *    `already_running` as the alias the plan documents; this function
227     *    returns `running` as the canonical value so callers that branch on
228     *    one or the other both work — the output_schema enum permits both.
229     * 2. Else if a cron event is already scheduled in the future for our hook,
230     *    a build is queued. Return `dispatched=false`, `status=queued`.
231     * 3. Otherwise schedule a single-event cron tick to fire immediately and
232     *    return `dispatched=true`, `status=queued`.
233     *
234     * Every branch also returns `next_scheduled_at` (see
235     * `get_next_scheduled_at()`) so the caller learns when the queued/pending
236     * build will actually run without a follow-up status read.
237     *
238     * @param array|null $input Ability input (no parameters accepted).
239     * @return array
240     */
241    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.
242        if ( static::is_build_running() ) {
243            return array(
244                'dispatched'        => false,
245                'status'            => 'running',
246                'next_scheduled_at' => static::get_next_scheduled_at(),
247            );
248        }
249
250        if ( static::is_build_queued() ) {
251            return array(
252                'dispatched'        => false,
253                'status'            => 'queued',
254                'next_scheduled_at' => static::get_next_scheduled_at(),
255            );
256        }
257
258        static::schedule_rebuild();
259
260        return array(
261            'dispatched'        => true,
262            'status'            => 'queued',
263            'next_scheduled_at' => static::get_next_scheduled_at(),
264        );
265    }
266
267    /**
268     * Public sitemap URL for the master sitemap.
269     *
270     * Extracted as a protected seam so tests can override without booting the
271     * rewrite/permalink stack.
272     */
273    protected static function get_master_sitemap_url(): string {
274        if ( function_exists( 'jetpack_sitemap_uri' ) ) {
275            return (string) jetpack_sitemap_uri( 'sitemap.xml' );
276        }
277        // Defensive: when the sitemaps module file is loaded the helper
278        // exists. This branch only runs if a caller invokes the ability
279        // outside the normal bootstrap path.
280        return (string) home_url( '/sitemap.xml' );
281    }
282
283    /**
284     * Raw master-sitemap XML — the exact document the public `sitemap.xml`
285     * router serves, read straight from storage via the librarian (no HTTP
286     * loopback). Returns an empty string when no master sitemap has been
287     * generated yet, or when the Sitemaps module helpers are unavailable.
288     *
289     * Extracted as a protected seam so tests can feed a known document without
290     * a librarian / wp_posts.
291     */
292    protected static function get_master_sitemap_xml(): string {
293        if (
294            ! class_exists( 'Jetpack_Sitemap_Librarian' )
295            || ! function_exists( 'jp_sitemap_filename' )
296            || ! defined( 'JP_MASTER_SITEMAP_TYPE' )
297        ) {
298            return '';
299        }
300
301        $librarian = new \Jetpack_Sitemap_Librarian();
302
303        // jp_sitemap_filename() is documented `@param string $number`; for the
304        // master type it returns 'sitemap.xml' and ignores the number, but it
305        // must be non-null and string-typed to satisfy the contract (the
306        // int-`0` router call site predates this and is Phan-baselined).
307        return (string) $librarian->get_sitemap_text(
308            \jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE, '0' ),
309            JP_MASTER_SITEMAP_TYPE
310        );
311    }
312
313    /**
314     * The child-sitemap entries actually present in the served master
315     * sitemap, as a list of `[ 'loc' => string, 'lastmod' => string|null ]`.
316     *
317     * Parses the same `<sitemapindex>` document `sitemap.xml` serves rather
318     * than deriving freshness from the `jetpack-sitemap-state` option: that
319     * option can read its initial/reset shape (no `max` projection) even while
320     * a fully-built sitemap.xml is being served, so it is not a reliable
321     * "what does the sitemap actually contain" source.
322     *
323     * Returns an empty array when no master sitemap exists yet or the stored
324     * document does not parse.
325     *
326     * @return array<int, array{loc:string, lastmod:string|null}>
327     */
328    protected static function get_sitemap_entries(): array {
329        $xml = static::get_master_sitemap_xml();
330        if ( '' === $xml ) {
331            return array();
332        }
333
334        $previous = libxml_use_internal_errors( true );
335        $document = new \DOMDocument();
336        // Source is Jetpack's own stored sitemap (not user input) and PHP 8+
337        // disables external-entity loading by default; LIBXML_NONET is belt-
338        // and-suspenders against any network/entity fetch during parsing.
339        $loaded = $document->loadXML( $xml, LIBXML_NONET );
340        libxml_clear_errors();
341        libxml_use_internal_errors( $previous );
342
343        if ( ! $loaded ) {
344            return array();
345        }
346
347        $entries = array();
348        foreach ( $document->getElementsByTagName( 'sitemap' ) as $sitemap_node ) {
349            $loc_nodes = $sitemap_node->getElementsByTagName( 'loc' );
350            if ( 0 === $loc_nodes->length ) {
351                continue;
352            }
353
354            $loc = trim( $loc_nodes->item( 0 )->textContent );
355            if ( '' === $loc ) {
356                continue;
357            }
358
359            $lastmod_nodes = $sitemap_node->getElementsByTagName( 'lastmod' );
360            $lastmod       = $lastmod_nodes->length > 0
361                ? trim( $lastmod_nodes->item( 0 )->textContent )
362                : '';
363
364            $entries[] = array(
365                'loc'     => $loc,
366                'lastmod' => '' === $lastmod ? null : $lastmod,
367            );
368        }
369
370        return $entries;
371    }
372
373    /**
374     * Whether news-sitemap inclusion is enabled.
375     *
376     * Mirrors the filter chain in `Jetpack_Sitemap_Manager::callback_action_do_robotstxt`
377     * but only resolves the modern filter — the deprecated 7.4.0 alias is
378     * already merged into the modern filter by the time it runs in production.
379     */
380    protected static function is_news_sitemap_enabled(): bool {
381        /** This filter is documented in modules/sitemaps/sitemaps.php */
382        return (bool) apply_filters( 'jetpack_news_sitemap_include_in_robotstxt', true );
383    }
384
385    /**
386     * Count published posts of a given post type.
387     *
388     * Wraps `wp_count_posts()` so tests can override without a real WP_Posts
389     * factory.
390     *
391     * @param string $post_type Post type slug.
392     */
393    protected static function count_published( string $post_type ): int {
394        $counts = wp_count_posts( $post_type );
395        if ( ! is_object( $counts ) || ! isset( $counts->publish ) ) {
396            return 0;
397        }
398        return (int) $counts->publish;
399    }
400
401    /**
402     * Whether a sitemap build step is currently running.
403     *
404     * The Sitemaps module sets a 15-minute transient lock at the start of
405     * `Jetpack_Sitemap_State::check_out()` and deletes it on `unlock()` /
406     * `reset()`. Presence of the transient is the canonical "in flight" signal.
407     */
408    protected static function is_build_running(): bool {
409        return true === get_transient( self::STATE_LOCK_TRANSIENT );
410    }
411
412    /**
413     * Whether a sitemap build is already scheduled for a future cron tick.
414     *
415     * Uses `wp_next_scheduled` so we don't stack duplicate single-event cron
416     * entries when the recurring `jp_sitemap_cron_hook` is already pending.
417     */
418    protected static function is_build_queued(): bool {
419        return false !== wp_next_scheduled( self::CRON_HOOK );
420    }
421
422    /**
423     * Schedule a single-event cron tick to drive the next build step.
424     *
425     * Matches the dispatch pattern used by
426     * `Jetpack_Sitemap_Manager::callback_action_purge_data` — `wp_schedule_single_event`
427     * with an immediate execution time. The recurring `sitemap-interval`
428     * schedule still fires on its normal cadence; this just front-runs the
429     * next tick.
430     */
431    protected static function schedule_rebuild(): void {
432        wp_schedule_single_event( time(), self::CRON_HOOK );
433    }
434
435    /**
436     * When the next `jp_sitemap_cron_hook` build tick is scheduled, as an
437     * ISO 8601 UTC string (e.g. `2026-05-19T19:33:20Z`), or null when nothing
438     * is scheduled.
439     *
440     * Returned alongside the dispatch result so callers immediately know when
441     * the build they queued (or the one already pending) will actually run,
442     * without a second round-trip. Null in the `running` case when the lock is
443     * held but no future tick is queued.
444     *
445     * ISO 8601 with the explicit `Z` zone designator (not `human_time_diff()`,
446     * not a bare "Y-m-d H:i:s") so the timezone is unambiguous and the value is
447     * locale-stable and machine-parseable — the same format the `sitemaps[]`
448     * `lastmod` values use in `get-status`.
449     */
450    protected static function get_next_scheduled_at(): ?string {
451        $timestamp = wp_next_scheduled( self::CRON_HOOK );
452        if ( false === $timestamp ) {
453            return null;
454        }
455        return gmdate( 'Y-m-d\TH:i:s\Z', $timestamp );
456    }
457}