Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
53.50% covered (warning)
53.50%
176 / 329
73.91% covered (warning)
73.91%
17 / 23
CRAP
0.00% covered (danger)
0.00%
0 / 1
jetpack_sitemap_uri
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
Jetpack_Sitemap_Manager
58.47% covered (warning)
58.47%
176 / 301
77.27% covered (warning)
77.27%
17 / 22
656.30
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
40 / 40
100.00% covered (success)
100.00%
1 / 1
5
 is_sitemap_ready
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 callback_redirect_core_index
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 callback_filter_core_robots
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 callback_filter_core_query
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
4
 callback_filter_core_posts
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
 callback_invalidate_index_cache
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
13
 callback_sitemap_saved
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
9
 callback_purge_pending_index_cache
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
7
 callback_sitemap_deleted
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 prevent_caching
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 serve_raw_and_die
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
12
 callback_action_catch_sitemap_urls
12.61% covered (danger)
12.61%
14 / 111
0.00% covered (danger)
0.00%
0 / 1
234.22
 callback_add_sitemap_schedule
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 callback_sitemap_cron_hook
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 schedule_sitemap_generation
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
2
 callback_action_do_robotstxt
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
 callback_action_news_publication_changed
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 callback_action_news_post_deleted
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 callback_action_flush_news_sitemap_cache
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 callback_action_purge_data
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 callback_action_filter_sitemap_location
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * Generate sitemap files in base XML as well as some namespace extensions.
4 *
5 * This module generates two different base sitemaps.
6 *
7 * 1. sitemap.xml
8 *    The basic sitemap is updated regularly by wp-cron. It is stored in the
9 *    database and retrieved when requested. This sitemap aims to include canonical
10 *    URLs for all published content and abide by the sitemap spec. This is the root
11 *    of a tree of sitemap and sitemap index xml files, depending on the number of URLs.
12 *
13 *    By default the sitemap contains published posts of type 'post' and 'page', as
14 *    well as the home url. To include other post types use the 'jetpack_sitemap_post_types'
15 *    filter.
16 *
17 * @link https://www.sitemaps.org/protocol.html Base sitemaps protocol.
18 * @link https://support.google.com/webmasters/answer/178636 Image sitemap extension.
19 * @link https://developers.google.com/webmasters/videosearch/sitemaps Video sitemap extension.
20 *
21 * 2. news-sitemap.xml
22 *    The news sitemap is generated on the fly when requested. It does not aim for
23 *    completeness, instead including at most 1000 of the most recent published posts
24 *    from the previous 2 days, per the news-sitemap spec.
25 *
26 * @link https://support.google.com/webmasters/answer/74288 News sitemap extension.
27 *
28 * @package automattic/jetpack
29 * @since 3.9.0
30 * @since 4.8.0 Remove 1000 post limit.
31 * @author Automattic
32 */
33
34if ( ! defined( 'ABSPATH' ) ) {
35    exit( 0 );
36}
37
38/* Include all of the sitemap subclasses. */
39require_once __DIR__ . '/sitemap-constants.php';
40require_once __DIR__ . '/sitemap-buffer.php';
41require_once __DIR__ . '/sitemap-buffer-fallback.php';
42require_once __DIR__ . '/sitemap-buffer-xmlwriter.php';
43require_once __DIR__ . '/sitemap-buffer-page-xmlwriter.php';
44require_once __DIR__ . '/sitemap-buffer-image-xmlwriter.php';
45require_once __DIR__ . '/sitemap-buffer-video-xmlwriter.php';
46require_once __DIR__ . '/sitemap-buffer-news-xmlwriter.php';
47require_once __DIR__ . '/sitemap-buffer-master-xmlwriter.php';
48require_once __DIR__ . '/sitemap-buffer-factory.php';
49require_once __DIR__ . '/sitemap-stylist.php';
50require_once __DIR__ . '/sitemap-librarian.php';
51require_once __DIR__ . '/sitemap-finder.php';
52require_once __DIR__ . '/sitemap-builder.php';
53
54if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
55    require_once __DIR__ . '/sitemap-logger.php';
56}
57
58// phpcs:disable Universal.Files.SeparateFunctionsFromOO.Mixed -- TODO: Move classes to appropriately-named class files.
59
60/**
61 * Governs the generation, storage, and serving of sitemaps.
62 *
63 * @since 4.8.0
64 *
65 * @phan-constructor-used-for-side-effects
66 */
67class Jetpack_Sitemap_Manager {
68
69    /**
70     * Librarian object for storing and retrieving sitemap data.
71     *
72     * @see Jetpack_Sitemap_Librarian
73     * @since 4.8.0
74     * @var Jetpack_Sitemap_Librarian $librarian Librarian object for storing and retrieving sitemap data.
75     */
76    private $librarian;
77
78    /**
79     * Logger object for reporting debug messages.
80     *
81     * @see Jetpack_Sitemap_Logger
82     * @since 4.8.0
83     * @var Jetpack_Sitemap_Logger $logger Logger object for reporting debug messages.
84     */
85    private $logger;
86
87    /**
88     * Finder object for handling sitemap URIs.
89     *
90     * @see Jetpack_Sitemap_Finder
91     * @since 4.8.0
92     * @var Jetpack_Sitemap_Finder $finder Finder object for handling with sitemap URIs.
93     */
94    private $finder;
95
96    /**
97     * Construct a new Jetpack_Sitemap_Manager.
98     *
99     * @access public
100     * @since 4.8.0
101     */
102    public function __construct() {
103        $this->librarian = new Jetpack_Sitemap_Librarian();
104        $this->finder    = new Jetpack_Sitemap_Finder();
105
106        if ( defined( 'WP_DEBUG' ) && ( true === WP_DEBUG ) ) {
107            $this->logger = new Jetpack_Sitemap_Logger();
108        }
109
110        // Add callback for sitemap URL handler.
111        add_action(
112            'wp_loaded',
113            array( $this, 'callback_action_catch_sitemap_urls' ),
114            defined( 'IS_WPCOM' ) && IS_WPCOM ? 100 : 10
115        );
116
117        add_action( 'template_redirect', array( $this, 'callback_redirect_core_index' ), 0 );
118        add_filter( 'robots_txt', array( $this, 'callback_filter_core_robots' ), 1 );
119        add_filter( 'wp_sitemaps_posts_query_args', array( $this, 'callback_filter_core_query' ) );
120        add_filter( 'the_posts', array( $this, 'callback_filter_core_posts' ), 10, 2 );
121        add_action( 'wp_loaded', array( __CLASS__, 'callback_purge_pending_index_cache' ), 20 );
122        add_action( 'wp_after_insert_post', array( __CLASS__, 'callback_sitemap_saved' ), 10, 4 );
123        add_action( 'jetpack_activate_module_sitemaps', array( __CLASS__, 'callback_invalidate_index_cache' ) );
124        add_action( 'jetpack_deactivate_module_sitemaps', array( __CLASS__, 'callback_invalidate_index_cache' ) );
125        add_action( 'deleted_post', array( __CLASS__, 'callback_sitemap_deleted' ), 10, 2 );
126        add_action( 'deleted_post', array( $this, 'callback_action_news_post_deleted' ), 10, 2 );
127
128        // Add generator to wp_cron task list.
129        $this->schedule_sitemap_generation();
130
131        // Add sitemap to robots.txt.
132        add_action(
133            'do_robotstxt',
134            array( $this, 'callback_action_do_robotstxt' ),
135            20
136        );
137
138        // Keep cached news entries in sync with publication changes.
139        add_action(
140            'transition_post_status',
141            array( $this, 'callback_action_news_publication_changed' ),
142            10,
143            3
144        );
145
146        // In case we need to purge all sitemaps, we do this.
147        add_action(
148            'jetpack_sitemaps_purge_data',
149            array( $this, 'callback_action_purge_data' )
150        );
151
152        /*
153         * Module parameters are stored as options in the database.
154         * This allows us to avoid having to process all of init
155         * before serving the sitemap data. The following actions
156         * process and store these filters.
157         */
158
159        // Process filters and store location string for sitemap.
160        add_action(
161            'init',
162            array( $this, 'callback_action_filter_sitemap_location' ),
163            999
164        );
165    }
166
167    /**
168     * Whether Jetpack has stored a generated master index.
169     *
170     * @since 16.5
171     * @return bool
172     */
173    public function is_sitemap_ready() {
174        return '' !== $this->librarian->get_sitemap_text(
175            jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE, '0' ),
176            JP_MASTER_SITEMAP_TYPE
177        );
178    }
179
180    /**
181     * Redirect submitted core indexes without breaking their child sitemap URLs.
182     *
183     * @since 16.5
184     */
185    public function callback_redirect_core_index() {
186        if ( 'index' !== get_query_var( 'sitemap' ) || ! $this->is_sitemap_ready() || ! wp_sitemaps_get_server()->sitemaps_enabled() ) {
187            return;
188        }
189
190        $this->prevent_caching();
191        wp_safe_redirect( jetpack_sitemap_uri(), 301, 'Jetpack' );
192        exit;
193    }
194
195    /**
196     * Advertise only Jetpack's index once it is available.
197     *
198     * @since 16.5
199     * @param string $output Robots.txt contents.
200     * @return string
201     */
202    public function callback_filter_core_robots( $output ) {
203        if ( ! $this->is_sitemap_ready() ) {
204            return $output;
205        }
206
207        $core_line = 'Sitemap: ' . esc_url( get_sitemap_url( 'index' ) );
208        return preg_replace( '/^' . preg_quote( $core_line, '/' ) . '\r?(?:\n|$)/m', '', $output );
209    }
210
211    /**
212     * Apply SEO exclusions to core's fallback queries, including their page counts.
213     *
214     * @since 16.5
215     * @param array $args Core sitemap query arguments.
216     * @return array
217     */
218    public function callback_filter_core_query( $args ) {
219        $args['jetpack_sitemap_fallback'] = true;
220        if ( has_filter( 'jetpack_sitemap_skip_post', array( 'Jetpack_SEO_Posts', 'exclude_noindex_posts_from_jetpack_sitemap' ) ) && Jetpack_SEO_Utils::is_enabled_jetpack_seo() ) {
221            $indexable          = array(
222                'relation'         => 'OR',
223                'noindex_missing'  => array(
224                    'key'     => 'jetpack_seo_noindex',
225                    'compare' => 'NOT EXISTS',
226                ),
227                'noindex_disabled' => array(
228                    'key'     => 'jetpack_seo_noindex',
229                    'value'   => array( '', '0' ),
230                    'compare' => 'IN',
231                ),
232            );
233            $args['meta_query'] = empty( $args['meta_query'] ) ? $indexable : array(
234                'relation'          => 'AND',
235                'existing'          => $args['meta_query'],
236                'jetpack_indexable' => $indexable,
237            ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Scoped sitemap queries must exclude noindex posts before pagination.
238        }
239        return $args;
240    }
241
242    /**
243     * Preserve custom Jetpack post exclusions on core's fallback sitemap pages.
244     *
245     * @since 16.5
246     * @param WP_Post[] $posts Query results.
247     * @param WP_Query  $query Current query.
248     * @return WP_Post[]
249     */
250    public function callback_filter_core_posts( $posts, $query ) {
251        if ( ! $query->get( 'jetpack_sitemap_fallback' ) ) {
252            return $posts;
253        }
254        update_meta_cache( 'post', wp_list_pluck( $posts, 'ID' ) );
255        return array_values(
256            array_filter(
257                $posts,
258                static function ( $post ) {
259                    return true !== apply_filters( 'jetpack_sitemap_skip_post', false, $post );
260                }
261            )
262        );
263    }
264
265    /**
266     * Invalidate only the index and discovery URLs after a stored index changes.
267     *
268     * @since 16.5
269     * @return string[] Discovery URLs supplied to cache adapters.
270     */
271    public static function callback_invalidate_index_cache() {
272        $url       = jetpack_sitemap_uri();
273        $urls      = array_unique( array( $url, get_sitemap_url( 'index' ), home_url( '/robots.txt' ) ) );
274        $clear_url = function_exists( 'batcache_clear_url' ) ? 'batcache_clear_url' : null;
275        if ( ! $clear_url && function_exists( 'pcm_flush_batcache_url' ) ) {
276            $clear_url = 'pcm_flush_batcache_url';
277        }
278        if ( $clear_url && defined( 'WP_CLI' ) && WP_CLI && ! get_option( 'jetpack_sitemap_pending_cache_purge' ) ) {
279            update_option( 'jetpack_sitemap_pending_cache_purge', 'urls', true );
280        }
281        if ( $clear_url && ! ( defined( 'WP_CLI' ) && WP_CLI ) ) {
282            // Batcache shares a URL version across query variants, except for the "p" parameter.
283            $cache_urls = array();
284            foreach ( $urls as $cached_url ) {
285                $query = array();
286                wp_parse_str( (string) wp_parse_url( $cached_url, PHP_URL_QUERY ), $query );
287                $cache_urls[] = remove_query_arg( array_diff( array_keys( $query ), array( 'p' ) ), $cached_url );
288            }
289            foreach ( array_unique( $cache_urls ) as $cached_url ) {
290                $clear_url( $cached_url );
291            }
292        }
293
294        /**
295         * Invalidate sitemap discovery responses in additional page caches.
296         *
297         * @since 16.5
298         * @param string   $url  Jetpack sitemap index URL.
299         * @param string[] $urls Sitemap index and discovery URLs to invalidate.
300         */
301        do_action( 'jetpack_sitemap_index_updated', $url, $urls );
302        return $urls;
303    }
304
305    /**
306     * Purge cached pending responses when the first usable index is stored.
307     *
308     * @since 16.5
309     * @param int           $post_id Stored post ID.
310     * @param \WP_Post|null $post Stored sitemap post.
311     * @param bool          $update Whether this updates an existing post.
312     * @param \WP_Post|null $post_before Previously stored post, if any.
313     */
314    public static function callback_sitemap_saved( $post_id, $post, $update, $post_before ) {
315        if ( ! $post instanceof \WP_Post || JP_MASTER_SITEMAP_TYPE !== $post->post_type || jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE, '0' ) !== $post->post_title ) {
316            return;
317        }
318
319        if ( '' !== $post->post_content && ( ! $post_before || '' === $post_before->post_content ) ) {
320            update_option( 'jetpack_sitemap_pending_cache_purge', 'first-build', true );
321            if ( ! ( defined( 'WP_CLI' ) && WP_CLI ) ) {
322                self::callback_purge_pending_index_cache();
323                return;
324            }
325        }
326        self::callback_invalidate_index_cache();
327    }
328
329    /**
330     * Finish deferred cache recovery in a web bootstrap with host cache APIs.
331     *
332     * @since 16.5
333     */
334    public static function callback_purge_pending_index_cache() {
335        $pending = get_option( 'jetpack_sitemap_pending_cache_purge' );
336        if ( ( defined( 'WP_CLI' ) && WP_CLI ) || ! $pending ) {
337            if ( false === $pending ) {
338                add_option( 'jetpack_sitemap_pending_cache_purge', '', '', true );
339            }
340            return;
341        }
342        if ( ! update_option( 'jetpack_sitemap_pending_cache_purge', '', true ) ) {
343            return;
344        }
345        $urls = self::callback_invalidate_index_cache();
346        if ( 'first-build' === $pending ) {
347            // Some hosts also flush the whole origin; avoid doing that on routine rebuilds.
348            do_action( 'edge_cache_purge_uris', $urls );
349        }
350    }
351
352    /**
353     * Invalidate discovery responses when the generated index is removed.
354     *
355     * @since 16.5
356     * @param int           $post_id Deleted post ID.
357     * @param \WP_Post|null $post Deleted post.
358     */
359    public static function callback_sitemap_deleted( $post_id, $post ) {
360        if ( $post instanceof \WP_Post && JP_MASTER_SITEMAP_TYPE === $post->post_type ) {
361            self::callback_invalidate_index_cache();
362        }
363    }
364
365    /**
366     * Keep pending sitemap responses and reversible redirects out of page caches.
367     *
368     * @since 16.5
369     */
370    private function prevent_caching() {
371        nocache_headers();
372        if ( function_exists( 'batcache_cancel' ) ) {
373            // @phan-suppress-next-line PhanUndeclaredFunction -- Optional Batcache API, guarded above.
374            batcache_cancel();
375        }
376    }
377
378    /**
379     * Echo a raw string of given content-type.
380     *
381     * @access private
382     * @since 4.8.0
383     *
384     * @param string $the_content_type The content type to be served.
385     * @param string $the_content The string to be echoed.
386     * @return never
387     */
388    private function serve_raw_and_die( $the_content_type, $the_content ) {
389        header( 'Content-Type: ' . $the_content_type . '; charset=UTF-8' );
390
391        global $wp_query;
392        $wp_query->is_feed = true;
393        set_query_var( 'feed', 'sitemap' );
394
395        if ( '' === $the_content ) {
396            $this->prevent_caching();
397            $error = __( 'No sitemap found. Please try again later.', 'jetpack' );
398            if ( current_user_can( 'manage_options' ) ) {
399                $next = human_time_diff( wp_next_scheduled( 'jp_sitemap_cron_hook' ) );
400                /* translators: %s is a human_time_diff until next sitemap generation. */
401                $error = sprintf( __( 'No sitemap found. The system will try to build it again in %s.', 'jetpack' ), $next );
402            }
403
404            wp_die(
405                esc_html( $error ),
406                esc_html__( 'Sitemaps', 'jetpack' ),
407                array(
408                    'response' => 404,
409                )
410            );
411        }
412
413        echo $the_content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- All content created by Jetpack.
414
415        die( 0 );
416    }
417
418    /**
419     * Callback to intercept sitemap url requests and serve sitemap files.
420     *
421     * @access public
422     * @since 4.8.0
423     */
424    public function callback_action_catch_sitemap_urls() {
425        // Regular expressions for sitemap URL routing.
426        $regex = array(
427            'sitemap'     => '/^sitemap-[1-9][0-9]*\.xml$/',
428            'index'       => '/^sitemap-index-[1-9][0-9]*\.xml$/',
429            'image'       => '/^image-sitemap-[1-9][0-9]*\.xml$/',
430            'image-index' => '/^image-sitemap-index-[1-9][0-9]*\.xml$/',
431            'video'       => '/^video-sitemap-[1-9][0-9]*\.xml$/',
432            'video-index' => '/^video-sitemap-index-[1-9][0-9]*\.xml$/',
433        );
434
435        // The raw path(+query) of the requested URI.
436        if ( isset( $_SERVER['REQUEST_URI'] ) ) { // WPCS: Input var okay.
437            $raw_uri = sanitize_text_field(
438                wp_unslash( $_SERVER['REQUEST_URI'] ) // WPCS: Input var okay.
439            );
440        } else {
441            $raw_uri = '';
442        }
443
444        $request = $this->finder->recognize_sitemap_uri( $raw_uri );
445
446        if ( isset( $request['sitemap_name'] ) ) {
447
448            /**
449             * Filter the content type used to serve the sitemap XML files.
450             *
451             * @module sitemaps
452             *
453             * @since 3.9.0
454             *
455             * @param string $xml_content_type By default, it's 'text/xml'.
456             */
457            $xml_content_type = apply_filters( 'jetpack_sitemap_content_type', 'text/xml' );
458
459            // Catch master sitemap xml.
460            if ( 'sitemap.xml' === $request['sitemap_name'] ) {
461                $sitemap_content = $this->librarian->get_sitemap_text(
462                    jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE, '0' ),
463                    JP_MASTER_SITEMAP_TYPE
464                );
465
466                if ( empty( $sitemap_content ) ) {
467                    $this->prevent_caching();
468                    if ( wp_sitemaps_get_server()->sitemaps_enabled() ) {
469                        wp_safe_redirect( get_sitemap_url( 'index' ), 302, 'Jetpack' );
470                        exit;
471                    }
472                    $builder         = new Jetpack_Sitemap_Builder();
473                    $sitemap_content = $builder->empty_sitemap_xml();
474                }
475
476                $this->serve_raw_and_die(
477                    $xml_content_type,
478                    $sitemap_content
479                );
480            }
481
482            // Catch sitemap xsl.
483            if ( 'sitemap.xsl' === $request['sitemap_name'] ) {
484                $this->serve_raw_and_die(
485                    'application/xml',
486                    Jetpack_Sitemap_Stylist::sitemap_xsl()
487                );
488            }
489
490            // Catch sitemap index xsl.
491            if ( 'sitemap-index.xsl' === $request['sitemap_name'] ) {
492                $this->serve_raw_and_die(
493                    'application/xml',
494                    Jetpack_Sitemap_Stylist::sitemap_index_xsl()
495                );
496            }
497
498            // Catch image sitemap xsl.
499            if ( 'image-sitemap.xsl' === $request['sitemap_name'] ) {
500                $this->serve_raw_and_die(
501                    'application/xml',
502                    Jetpack_Sitemap_Stylist::image_sitemap_xsl()
503                );
504            }
505
506            // Catch video sitemap xsl.
507            if ( 'video-sitemap.xsl' === $request['sitemap_name'] ) {
508                $this->serve_raw_and_die(
509                    'application/xml',
510                    Jetpack_Sitemap_Stylist::video_sitemap_xsl()
511                );
512            }
513
514            // Catch news sitemap xml.
515            if ( 'news-sitemap.xml' === $request['sitemap_name'] ) {
516                $sitemap_builder = new Jetpack_Sitemap_Builder();
517                $this->serve_raw_and_die(
518                    $xml_content_type,
519                    $sitemap_builder->news_sitemap_xml()
520                );
521            }
522
523            // Catch news sitemap xsl.
524            if ( 'news-sitemap.xsl' === $request['sitemap_name'] ) {
525                $this->serve_raw_and_die(
526                    'application/xml',
527                    Jetpack_Sitemap_Stylist::news_sitemap_xsl()
528                );
529            }
530
531            // Catch sitemap xml.
532            if ( preg_match( $regex['sitemap'], $request['sitemap_name'] ) ) {
533                $this->serve_raw_and_die(
534                    $xml_content_type,
535                    $this->librarian->get_sitemap_text(
536                        $request['sitemap_name'],
537                        JP_PAGE_SITEMAP_TYPE
538                    )
539                );
540            }
541
542            // Catch sitemap index xml.
543            if ( preg_match( $regex['index'], $request['sitemap_name'] ) ) {
544                $this->serve_raw_and_die(
545                    $xml_content_type,
546                    $this->librarian->get_sitemap_text(
547                        $request['sitemap_name'],
548                        JP_PAGE_SITEMAP_INDEX_TYPE
549                    )
550                );
551            }
552
553            // Catch image sitemap xml.
554            if ( preg_match( $regex['image'], $request['sitemap_name'] ) ) {
555                $this->serve_raw_and_die(
556                    $xml_content_type,
557                    $this->librarian->get_sitemap_text(
558                        $request['sitemap_name'],
559                        JP_IMAGE_SITEMAP_TYPE
560                    )
561                );
562            }
563
564            // Catch image sitemap index xml.
565            if ( preg_match( $regex['image-index'], $request['sitemap_name'] ) ) {
566                $this->serve_raw_and_die(
567                    $xml_content_type,
568                    $this->librarian->get_sitemap_text(
569                        $request['sitemap_name'],
570                        JP_IMAGE_SITEMAP_INDEX_TYPE
571                    )
572                );
573            }
574
575            // Catch video sitemap xml.
576            if ( preg_match( $regex['video'], $request['sitemap_name'] ) ) {
577                $this->serve_raw_and_die(
578                    $xml_content_type,
579                    $this->librarian->get_sitemap_text(
580                        $request['sitemap_name'],
581                        JP_VIDEO_SITEMAP_TYPE
582                    )
583                );
584            }
585
586            // Catch video sitemap index xml.
587            if ( preg_match( $regex['video-index'], $request['sitemap_name'] ) ) {
588                $this->serve_raw_and_die(
589                    $xml_content_type,
590                    $this->librarian->get_sitemap_text(
591                        $request['sitemap_name'],
592                        JP_VIDEO_SITEMAP_INDEX_TYPE
593                    )
594                );
595            }
596        }
597    }
598
599    /**
600     * Callback for adding sitemap-interval to the list of schedules.
601     *
602     * @access public
603     * @since 4.8.0
604     *
605     * @param array $schedules The array of WP_Cron schedules.
606     *
607     * @return array The updated array of WP_Cron schedules.
608     */
609    public function callback_add_sitemap_schedule( $schedules ) {
610        $schedules['sitemap-interval'] = array(
611            'interval' => JP_SITEMAP_INTERVAL,
612            'display'  => __( 'Sitemap Interval', 'jetpack' ),
613        );
614        return $schedules;
615    }
616
617    /**
618     * Callback handler for sitemap cron hook
619     *
620     * @access public
621     */
622    public function callback_sitemap_cron_hook() {
623        $sitemap_builder = new Jetpack_Sitemap_Builder();
624        $sitemap_builder->update_sitemap();
625    }
626
627    /**
628     * Add actions to schedule sitemap generation.
629     * Should only be called once, in the constructor.
630     *
631     * @access private
632     * @since 4.8.0
633     */
634    private function schedule_sitemap_generation() {
635        // Add cron schedule.
636        add_filter( 'cron_schedules', array( $this, 'callback_add_sitemap_schedule' ) ); // phpcs:ignore WordPress.WP.CronInterval.ChangeDetected
637
638        add_action(
639            'jp_sitemap_cron_hook',
640            array( $this, 'callback_sitemap_cron_hook' )
641        );
642
643        if ( ! wp_next_scheduled( 'jp_sitemap_cron_hook' ) ) {
644            /**
645             * Filter the delay in seconds until sitemap generation cron job is started.
646             *
647             * This filter allows a site operator or hosting provider to potentialy spread out sitemap generation for a
648             * lot of sites over time. By default, it will be randomly done over 15 minutes.
649             *
650             * @module sitemaps
651             * @since 6.6.1
652             *
653             * @param int $delay Time to delay in seconds.
654             */
655            $delay = apply_filters( 'jetpack_sitemap_generation_delay', MINUTE_IN_SECONDS * wp_rand( 1, 15 ) ); // Randomly space it out to start within next fifteen minutes.
656            wp_schedule_event(
657                time() + $delay,
658                'sitemap-interval',
659                'jp_sitemap_cron_hook'
660            );
661        }
662    }
663
664    /**
665     * Callback to add sitemap to robots.txt.
666     *
667     * @access public
668     * @since 4.8.0
669     */
670    public function callback_action_do_robotstxt() {
671
672        /**
673         * Filter whether to make the default sitemap discoverable to robots or not. Default true.
674         *
675         * @module sitemaps
676         * @since 3.9.0
677         * @deprecated 7.4.0
678         *
679         * @param bool $discover_sitemap Make default sitemap discoverable to robots.
680         */
681        $discover_sitemap = apply_filters_deprecated( 'jetpack_sitemap_generate', array( true ), 'jetpack-7.4.0', 'jetpack_sitemap_include_in_robotstxt' );
682
683        /**
684         * Filter whether to make the default sitemap discoverable to robots or not. Default true.
685         *
686         * @module sitemaps
687         * @since 7.4.0
688         *
689         * @param bool $discover_sitemap Make default sitemap discoverable to robots.
690         */
691        $discover_sitemap = apply_filters( 'jetpack_sitemap_include_in_robotstxt', $discover_sitemap );
692
693        if ( true === $discover_sitemap && $this->is_sitemap_ready() ) {
694            $sitemap_url = $this->finder->construct_sitemap_url( 'sitemap.xml' );
695            echo 'Sitemap: ' . esc_url( $sitemap_url ) . "\n";
696        }
697
698        /**
699         * Filter whether to make the news sitemap discoverable to robots or not. Default true.
700         *
701         * @module sitemaps
702         * @since 3.9.0
703         * @deprecated 7.4.0
704         *
705         * @param bool $discover_news_sitemap Make default news sitemap discoverable to robots.
706         */
707        $discover_news_sitemap = apply_filters_deprecated( 'jetpack_news_sitemap_generate', array( true ), 'jetpack-7.4.0', 'jetpack_news_sitemap_include_in_robotstxt' );
708
709        /**
710         * Filter whether to make the news sitemap discoverable to robots or not. Default true.
711         *
712         * @module sitemaps
713         * @since 7.4.0
714         *
715         * @param bool $discover_news_sitemap Make default news sitemap discoverable to robots.
716         */
717        $discover_news_sitemap = apply_filters( 'jetpack_news_sitemap_include_in_robotstxt', $discover_news_sitemap );
718
719        if ( true === $discover_news_sitemap ) {
720            $news_sitemap_url = $this->finder->construct_sitemap_url( 'news-sitemap.xml' );
721            echo 'Sitemap: ' . esc_url( $news_sitemap_url ) . "\n";
722        }
723    }
724
725    /**
726     * Invalidate news when an included post enters, leaves, or updates publication.
727     *
728     * @since $$next-version$$
729     * @param string  $new_status New post status.
730     * @param string  $old_status Previous post status.
731     * @param WP_Post $post Updated post.
732     */
733    public function callback_action_news_publication_changed( $new_status, $old_status, $post ) {
734        if ( 'publish' !== $new_status && 'publish' !== $old_status ) {
735            return;
736        }
737        /** This filter is documented in modules/sitemaps/sitemap-librarian.php. */
738        $post_types = apply_filters( 'jetpack_sitemap_news_sitemap_post_types', array( 'page', 'post' ) );
739        if ( in_array( $post->post_type, (array) $post_types, true ) ) {
740            $this->callback_action_flush_news_sitemap_cache();
741        }
742    }
743
744    /**
745     * Invalidate news after an included published post is permanently deleted.
746     *
747     * @since $$next-version$$
748     * @param int     $post_id Deleted post ID.
749     * @param WP_Post $post Deleted post.
750     */
751    public function callback_action_news_post_deleted( $post_id, $post ) {
752        $this->callback_action_news_publication_changed( 'delete', $post->post_status, $post );
753    }
754
755    /**
756     * Callback to delete the news sitemap cache.
757     *
758     * @access public
759     * @since 4.8.0
760     */
761    public function callback_action_flush_news_sitemap_cache() {
762        delete_transient( 'jetpack_news_sitemap_xml' );
763        delete_transient( 'jetpack_news_sitemap_xml_v2' );
764    }
765
766    /**
767     * Callback for resetting stored sitemap data.
768     *
769     * @access public
770     * @since 5.3.0
771     * @since 6.7.0 Schedules a regeneration.
772     */
773    public function callback_action_purge_data() {
774        $this->callback_action_flush_news_sitemap_cache();
775        $this->librarian->delete_all_stored_sitemap_data();
776        /** This filter is documented in modules/sitemaps/sitemaps.php */
777        $delay = apply_filters( 'jetpack_sitemap_generation_delay', MINUTE_IN_SECONDS * wp_rand( 1, 15 ) ); // Randomly space it out to start within next fifteen minutes.
778        wp_schedule_single_event( time() + $delay, 'jp_sitemap_cron_hook' );
779    }
780
781    /**
782     * Callback to set the sitemap location.
783     *
784     * @access public
785     * @since 4.8.0
786     */
787    public function callback_action_filter_sitemap_location() {
788        update_option(
789            'jetpack_sitemap_location',
790            /**
791             * Additional path for sitemap URIs. Default value is empty.
792             *
793             * This string is any additional path fragment you want included between
794             * the home URL and the sitemap filenames. Exactly how this fragment is
795             * interpreted depends on your permalink settings. For example:
796             *
797             *   Pretty permalinks:
798             *     home_url() . jetpack_sitemap_location . '/sitemap.xml'
799             *
800             *   Plain ("ugly") permalinks:
801             *     home_url() . jetpack_sitemap_location . '/?jetpack-sitemap=sitemap.xml'
802             *
803             *   PATHINFO permalinks:
804             *     home_url() . '/index.php' . jetpack_sitemap_location . '/sitemap.xml'
805             *
806             * where 'sitemap.xml' is the name of a specific sitemap file.
807             * The value of this filter must be a valid path fragment per RFC 3986;
808             * in particular it must either be empty or begin with a '/'.
809             * Also take care that any restrictions on sitemap location imposed by
810             * the sitemap protocol are satisfied.
811             *
812             * The result of this filter is stored in an option, 'jetpack_sitemap_location';
813             * that option is what gets read when the sitemap location is needed.
814             * This way we don't have to wait for init to finish before building sitemaps.
815             *
816             * @link https://tools.ietf.org/html/rfc3986#section-3.3 RFC 3986
817             * @link https://www.sitemaps.org/ The sitemap protocol
818             *
819             * @since 4.8.0
820             */
821            apply_filters(
822                'jetpack_sitemap_location',
823                ''
824            )
825        );
826    }
827} // End Jetpack_Sitemap_Manager class.
828
829new Jetpack_Sitemap_Manager();
830
831/**
832 * Absolute URL of the current blog's sitemap.
833 *
834 * @module sitemaps
835 *
836 * @since  3.9.0
837 * @since  4.8.1 Code uses method found in Jetpack_Sitemap_Finder::construct_sitemap_url in 4.8.0.
838 *                It has been moved here to avoid fatal errors with other plugins that were expecting to find this function.
839 *
840 * @param string $filename Sitemap file name. Defaults to 'sitemap.xml', the initial sitemaps page.
841 *
842 * @return string Sitemap URL.
843 */
844function jetpack_sitemap_uri( $filename = 'sitemap.xml' ) {
845    global $wp_rewrite;
846
847    $location = Jetpack_Options::get_option_and_ensure_autoload( 'jetpack_sitemap_location', '' );
848
849    if ( $wp_rewrite->using_index_permalinks() ) {
850        $sitemap_url = home_url( '/index.php' . $location . '/' . $filename );
851    } elseif ( $wp_rewrite->using_permalinks() ) {
852        $sitemap_url = home_url( $location . '/' . $filename );
853    } else {
854        $sitemap_url = home_url( $location . '/?jetpack-sitemap=' . $filename );
855    }
856
857    /**
858     * Filter sitemap URL relative to home URL.
859     *
860     * @module sitemaps
861     *
862     * @since 3.9.0
863     *
864     * @param string $sitemap_url Sitemap URL.
865     */
866    return apply_filters( 'jetpack_sitemap_location', $sitemap_url );
867}
868
869// Register Jetpack Sitemaps abilities (WordPress Abilities API, WP 6.9+).
870require_once __DIR__ . '/abilities/class-sitemaps-abilities.php';
871\Automattic\Jetpack\Plugin\Abilities\Sitemaps_Abilities::init();