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