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