Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
68.70% covered (warning)
68.70%
496 / 722
32.00% covered (danger)
32.00%
8 / 25
CRAP
0.00% covered (danger)
0.00%
0 / 2
Jetpack_Sitemap_Buffer_Empty
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 2
20
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 get_root_element
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
Jetpack_Sitemap_Builder
72.51% covered (warning)
72.51%
496 / 684
34.78% covered (danger)
34.78%
8 / 23
581.56
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 update_sitemap
65.00% covered (warning)
65.00%
13 / 20
0.00% covered (danger)
0.00%
0 / 1
7.54
 build_next_sitemap_file
89.47% covered (warning)
89.47%
51 / 57
0.00% covered (danger)
0.00%
0 / 1
11.14
 build_next_sitemap_of_type
100.00% covered (success)
100.00%
48 / 48
100.00% covered (success)
100.00%
1 / 1
5
 build_next_sitemap_index_of_type
75.00% covered (warning)
75.00%
48 / 64
0.00% covered (danger)
0.00%
0 / 1
10.27
 build_master_sitemap
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
6
 create_master_buffer
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 build_flat_master_buffer
90.48% covered (success)
90.48%
19 / 21
0.00% covered (danger)
0.00%
0 / 1
10.09
 build_nested_master_buffer
69.23% covered (warning)
69.23%
18 / 26
0.00% covered (danger)
0.00%
0 / 1
14.52
 sitemap_count_of
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 stored_sitemap_timestamps
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 append_sitemap_to_master
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 build_one_page_sitemap
91.36% covered (success)
91.36%
74 / 81
0.00% covered (danger)
0.00%
0 / 1
21.28
 build_one_image_sitemap
53.85% covered (warning)
53.85%
21 / 39
0.00% covered (danger)
0.00%
0 / 1
14.29
 build_one_video_sitemap
52.50% covered (warning)
52.50%
21 / 40
0.00% covered (danger)
0.00%
0 / 1
17.68
 build_one_sitemap_index
74.55% covered (warning)
74.55%
41 / 55
0.00% covered (danger)
0.00%
0 / 1
10.34
 sitemap_row_to_index_item
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 empty_sitemap_xml
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 news_sitemap_xml
90.91% covered (success)
90.91%
30 / 33
0.00% covered (danger)
0.00%
0 / 1
8.05
 post_to_sitemap_item
64.00% covered (warning)
64.00%
16 / 25
0.00% covered (danger)
0.00%
0 / 1
4.75
 image_post_to_sitemap_item
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
20
 video_post_to_sitemap_item
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
42
 post_to_news_sitemap_item
85.71% covered (warning)
85.71%
30 / 35
0.00% covered (danger)
0.00%
0 / 1
4.05
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * Build the sitemap tree.
4 *
5 * @package automattic/jetpack
6 * @since 4.8.0
7 * @author Automattic
8 */
9
10if ( ! defined( 'ABSPATH' ) ) {
11    exit( 0 );
12}
13
14/* Include sitemap subclasses, if not already, and include proper buffer based on phpxml's availability. */
15require_once __DIR__ . '/sitemap-constants.php';
16require_once __DIR__ . '/sitemap-buffer.php';
17
18if ( ! class_exists( 'DOMDocument' ) ) {
19    require_once __DIR__ . '/sitemap-buffer-fallback.php';
20    require_once __DIR__ . '/sitemap-buffer-image-fallback.php';
21    require_once __DIR__ . '/sitemap-buffer-master-fallback.php';
22    require_once __DIR__ . '/sitemap-buffer-news-fallback.php';
23    require_once __DIR__ . '/sitemap-buffer-page-fallback.php';
24    require_once __DIR__ . '/sitemap-buffer-video-fallback.php';
25} else {
26    require_once __DIR__ . '/sitemap-buffer-image.php';
27    require_once __DIR__ . '/sitemap-buffer-master.php';
28    require_once __DIR__ . '/sitemap-buffer-news.php';
29    require_once __DIR__ . '/sitemap-buffer-page.php';
30    require_once __DIR__ . '/sitemap-buffer-video.php';
31}
32
33require_once __DIR__ . '/sitemap-librarian.php';
34require_once __DIR__ . '/sitemap-finder.php';
35require_once __DIR__ . '/sitemap-state.php';
36
37if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
38    require_once __DIR__ . '/sitemap-logger.php';
39}
40
41/**
42 * Simple class for rendering an empty sitemap with a short TTL
43 */
44class Jetpack_Sitemap_Buffer_Empty extends Jetpack_Sitemap_Buffer {
45    /**
46     * Jetpack_Sitemap_Buffer_Empty constructor.
47     */
48    public function __construct() {
49        parent::__construct( JP_SITEMAP_MAX_ITEMS, JP_SITEMAP_MAX_BYTES, '1970-01-01 00:00:00' );
50
51        $this->doc->appendChild(
52            $this->doc->createComment( "generator='jetpack-" . JETPACK__VERSION . "'" )
53        );
54
55        $this->doc->appendChild(
56            $this->doc->createComment( 'Jetpack_Sitemap_Buffer_Empty' )
57        );
58
59        foreach ( Jetpack_Sitemap_Stylist::sitemap_stylesheet_urls() as $url ) {
60            $this->doc->appendChild(
61                $this->doc->createProcessingInstruction( 'xml-stylesheet', 'type="text/css" href="' . esc_xml( $url ) . '"' )
62            );
63        }
64    }
65
66    /**
67     * Returns a DOM element for an empty sitemap.
68     */
69    protected function get_root_element() {
70        if ( ! isset( $this->root ) ) {
71            $this->root = $this->doc->createElement( 'sitemapindex' );
72            $this->root->setAttribute( 'xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9' );
73            $this->doc->appendChild( $this->root );
74            $this->byte_capacity -= strlen( $this->doc->saveXML( $this->root ) );
75        }
76
77        return $this->root;
78    }
79}
80
81/**
82 * The Jetpack_Sitemap_Builder object handles the construction of
83 * all sitemap files (except the XSL files, which are handled by
84 * Jetpack_Sitemap_Stylist.) Other than the constructor, there are
85 * only two public functions: build_all_sitemaps and news_sitemap_xml.
86 *
87 * @since 4.8.0
88 */
89class Jetpack_Sitemap_Builder { // phpcs:ignore Generic.Files.OneObjectStructurePerFile.MultipleFound,Generic.Classes.OpeningBraceSameLine.ContentAfterBrace
90
91    /**
92     * Returned by the master sitemap builders when the entries do not fit in one
93     * buffer, so the flat listing has to give way to the nested indexes.
94     *
95     * @since 16.2
96     */
97    const MASTER_OVERFLOW = 'overflow';
98
99    /**
100     * Returned by the master sitemap builders when a sitemap file they would link
101     * is missing, so any master built now would reach fewer URLs than the last one.
102     *
103     * @since 16.2
104     */
105    const MASTER_INCOMPLETE = 'incomplete';
106
107    /**
108     * Librarian object for storing and retrieving sitemap data.
109     *
110     * @access private
111     * @since 4.8.0
112     * @var $librarian Jetpack_Sitemap_Librarian
113     */
114    private $librarian;
115
116    /**
117     * Logger object for reporting debug messages.
118     *
119     * @access private
120     * @since 4.8.0
121     * @var $logger Jetpack_Sitemap_Logger
122     */
123    private $logger = false;
124
125    /**
126     * Finder object for dealing with sitemap URIs.
127     *
128     * @access private
129     * @since 4.8.0
130     * @var $finder Jetpack_Sitemap_Finder
131     */
132    private $finder;
133
134    /**
135     * Construct a new Jetpack_Sitemap_Builder object.
136     *
137     * @access public
138     * @since 4.8.0
139     */
140    public function __construct() {
141        $this->librarian = new Jetpack_Sitemap_Librarian();
142        $this->finder    = new Jetpack_Sitemap_Finder();
143
144        if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
145            $this->logger = new Jetpack_Sitemap_Logger();
146        }
147
148        update_option(
149            'jetpack_sitemap_post_types',
150            /**
151             * The array of post types to be included in the sitemap.
152             *
153             * Add your custom post type name to the array to have posts of
154             * that type included in the sitemap. The default array includes
155             * 'page' and 'post'.
156             *
157             * The result of this filter is cached in an option, 'jetpack_sitemap_post_types',
158             * so this filter only has to be applied once per generation.
159             *
160             * @since 4.8.0
161             */
162            apply_filters(
163                'jetpack_sitemap_post_types',
164                array( 'post', 'page' )
165            )
166        );
167    }
168
169    /**
170     * Update the sitemap.
171     *
172     * All we do here is call build_next_sitemap_file a bunch of times.
173     *
174     * @since 4.8.0
175     */
176    public function update_sitemap() {
177        if ( $this->logger ) {
178            $this->logger->report( '-- Updating...' );
179            if ( ! class_exists( 'DOMDocument' ) ) {
180                $this->logger->report(
181                    __(
182                        'Jetpack cannot load necessary XML manipulation libraries. Please ask your hosting provider to refer to our server requirements at https://jetpack.com/support/server-requirements/ .',
183                        'jetpack'
184                    ),
185                    true
186                );
187            }
188        }
189
190        /**
191         * Filters whether to suspend cache addition for the entire sitemap generation.
192         *
193         * @since 15.0
194         *
195         * @param bool|null $suspend_addition Whether to suspend cache addition. Defaults to null.
196         * @return bool|null Whether to suspend cache addition.
197         */
198        $suspend_addition = apply_filters( 'jetpack_sitemap_suspend_cache_addition', null );
199
200        // Cache the previous state in case something else changed it.
201        $prev_suspend_addition = wp_suspend_cache_addition();
202
203        wp_suspend_cache_addition( $suspend_addition );
204
205        for ( $i = 1; $i <= JP_SITEMAP_UPDATE_SIZE; $i++ ) {
206            if ( true === $this->build_next_sitemap_file() ) {
207                break; // All finished!
208            }
209        }
210
211        // Restore previous state.
212        wp_suspend_cache_addition( $prev_suspend_addition );
213
214        if ( $this->logger ) {
215            $this->logger->report( '-- ...done for now.' );
216            $this->logger->time();
217        }
218    }
219
220    /**
221     * Generate the next sitemap file.
222     *
223     * Reads the most recent state of the sitemap generation phase,
224     * constructs the next file, and updates the state.
225     *
226     * @since 4.8.0
227     *
228     * @return bool True when finished.
229     */
230    private function build_next_sitemap_file() {
231        $finished = false; // Initialize finished flag.
232
233        // Get the most recent state, and lock the state.
234        $state = Jetpack_Sitemap_State::check_out();
235
236        // Do nothing if the state was locked.
237        if ( false === $state ) {
238            return false;
239        }
240
241        // Otherwise, branch on the sitemap-type key of $state.
242        switch ( $state['sitemap-type'] ) {
243            case JP_PAGE_SITEMAP_TYPE:
244                $this->build_next_sitemap_of_type(
245                    JP_PAGE_SITEMAP_TYPE,
246                    array( $this, 'build_one_page_sitemap' ),
247                    $state
248                );
249                break;
250
251            case JP_PAGE_SITEMAP_INDEX_TYPE:
252                $this->build_next_sitemap_index_of_type(
253                    JP_PAGE_SITEMAP_INDEX_TYPE,
254                    JP_IMAGE_SITEMAP_TYPE,
255                    $state
256                );
257                break;
258
259            case JP_IMAGE_SITEMAP_TYPE:
260                $this->build_next_sitemap_of_type(
261                    JP_IMAGE_SITEMAP_TYPE,
262                    array( $this, 'build_one_image_sitemap' ),
263                    $state
264                );
265                break;
266
267            case JP_IMAGE_SITEMAP_INDEX_TYPE:
268                $this->build_next_sitemap_index_of_type(
269                    JP_IMAGE_SITEMAP_INDEX_TYPE,
270                    JP_VIDEO_SITEMAP_TYPE,
271                    $state
272                );
273                break;
274
275            case JP_VIDEO_SITEMAP_TYPE:
276                $this->build_next_sitemap_of_type(
277                    JP_VIDEO_SITEMAP_TYPE,
278                    array( $this, 'build_one_video_sitemap' ),
279                    $state
280                );
281                break;
282
283            case JP_VIDEO_SITEMAP_INDEX_TYPE:
284                $this->build_next_sitemap_index_of_type(
285                    JP_VIDEO_SITEMAP_INDEX_TYPE,
286                    JP_MASTER_SITEMAP_TYPE,
287                    $state
288                );
289                break;
290
291            case JP_MASTER_SITEMAP_TYPE:
292                $this->build_master_sitemap( $state['max'] );
293
294                // Reset the state and quit.
295                Jetpack_Sitemap_State::reset(
296                    JP_PAGE_SITEMAP_TYPE
297                );
298
299                if ( $this->logger ) {
300                    $this->logger->report( '-- Finished.' );
301                    $this->logger->time();
302                }
303                $finished = true;
304
305                break;
306
307            default:
308                Jetpack_Sitemap_State::reset(
309                    JP_PAGE_SITEMAP_TYPE
310                );
311                $finished = true;
312
313                break;
314        } // End switch.
315
316        // Unlock the state.
317        Jetpack_Sitemap_State::unlock();
318
319        return $finished;
320    }
321
322    /**
323     * Build the next sitemap of a given type and update the sitemap state.
324     *
325     * @since 4.8.0
326     *
327     * @param string   $sitemap_type The type of the sitemap being generated.
328     * @param callback $build_one    A callback which builds a single sitemap file.
329     * @param array    $state        A sitemap state.
330     */
331    private function build_next_sitemap_of_type( $sitemap_type, $build_one, $state ) {
332        $index_type = jp_sitemap_index_type_of( $sitemap_type );
333
334        // Try to build a sitemap.
335        $result = call_user_func_array(
336            $build_one,
337            array(
338                $state['number'] + 1,
339                $state['last-added'],
340            )
341        );
342
343        if ( false === $result ) {
344            // If no sitemap was generated, advance to the next type.
345            Jetpack_Sitemap_State::check_in(
346                array(
347                    'sitemap-type'  => $index_type,
348                    'last-added'    => 0,
349                    'number'        => 0,
350                    'last-modified' => '1970-01-01 00:00:00',
351                )
352            );
353
354            if ( $this->logger ) {
355                $this->logger->report( "-- Cleaning Up $sitemap_type" );
356            }
357
358            // Clean up old files.
359            $this->librarian->delete_numbered_sitemap_rows_after(
360                $state['number'],
361                $sitemap_type
362            );
363
364            return;
365        }
366
367        // Otherwise, update the state.
368        Jetpack_Sitemap_State::check_in(
369            array(
370                'sitemap-type'  => $state['sitemap-type'],
371                'last-added'    => $result['last_id'],
372                'number'        => $state['number'] + 1,
373                'last-modified' => $result['last_modified'],
374            )
375        );
376
377        if ( true === $result['any_left'] ) {
378            // If there's more work to be done with this type, return.
379            return;
380        }
381
382        // Otherwise, advance state to the next sitemap type.
383        Jetpack_Sitemap_State::check_in(
384            array(
385                'sitemap-type'  => $index_type,
386                'last-added'    => 0,
387                'number'        => 0,
388                'last-modified' => '1970-01-01 00:00:00',
389            )
390        );
391
392        if ( $this->logger ) {
393            $this->logger->report( "-- Cleaning Up $sitemap_type" );
394        }
395
396        // Clean up old files.
397        $this->librarian->delete_numbered_sitemap_rows_after(
398            $state['number'] + 1,
399            $sitemap_type
400        );
401    }
402
403    /**
404     * Build the next sitemap index of a given type and update the state.
405     *
406     * @since 4.8.0
407     *
408     * @param string $index_type The type of index being generated.
409     * @param string $next_type  The next type to generate after this one.
410     * @param array  $state      A sitemap state.
411     */
412    private function build_next_sitemap_index_of_type( $index_type, $next_type, $state ) {
413        $sitemap_type = jp_sitemap_child_type_of( $index_type );
414
415        $sitemap_type_exists = isset( $state['max'][ $sitemap_type ] ) && is_array( $state['max'][ $sitemap_type ] );
416
417        // If only 0 or 1 sitemaps were built, advance to the next type and return.
418        if ( $sitemap_type_exists && 1 >= $state['max'][ $sitemap_type ]['number'] ) {
419            Jetpack_Sitemap_State::check_in(
420                array(
421                    'sitemap-type'  => $next_type,
422                    'last-added'    => 0,
423                    'number'        => 0,
424                    'last-modified' => '1970-01-01 00:00:00',
425                )
426            );
427
428            if ( $this->logger ) {
429                $this->logger->report( "-- Cleaning Up $index_type" );
430            }
431
432            // There are no indices of this type.
433            $this->librarian->delete_numbered_sitemap_rows_after(
434                0,
435                $index_type
436            );
437
438            return;
439        }
440
441        // Otherwise, try to build a sitemap index.
442        $result = $this->build_one_sitemap_index(
443            $state['number'] + 1,
444            $state['last-added'],
445            $state['last-modified'],
446            $index_type
447        );
448
449        // If no index was built, advance to the next type and return.
450        if ( false === $result ) {
451            Jetpack_Sitemap_State::check_in(
452                array(
453                    'sitemap-type'  => $next_type,
454                    'last-added'    => 0,
455                    'number'        => 0,
456                    'last-modified' => '1970-01-01 00:00:00',
457                )
458            );
459
460            if ( $this->logger ) {
461                $this->logger->report( "-- Cleaning Up $index_type" );
462            }
463
464            // Clean up old files.
465            $this->librarian->delete_numbered_sitemap_rows_after(
466                $state['number'],
467                $index_type
468            );
469
470            return;
471        }
472
473        // Otherwise, check in the state.
474        Jetpack_Sitemap_State::check_in(
475            array(
476                'sitemap-type'  => $index_type,
477                'last-added'    => $result['last_id'],
478                'number'        => $state['number'] + 1,
479                'last-modified' => $result['last_modified'],
480            )
481        );
482
483        // If there are still sitemaps left to index, return.
484        if ( true === $result['any_left'] ) {
485            return;
486        }
487
488        // Otherwise, advance to the next type.
489        Jetpack_Sitemap_State::check_in(
490            array(
491                'sitemap-type'  => $next_type,
492                'last-added'    => 0,
493                'number'        => 0,
494                'last-modified' => '1970-01-01 00:00:00',
495            )
496        );
497
498        if ( $this->logger ) {
499            $this->logger->report( "-- Cleaning Up $index_type" );
500        }
501
502        // We're done generating indices of this type.
503        $this->librarian->delete_numbered_sitemap_rows_after(
504            $state['number'] + 1,
505            $index_type
506        );
507    }
508
509    /**
510     * Builds the master sitemap index.
511     *
512     * A sitemap index file may not list other sitemap index files, so with the
513     * `jetpack_sitemap_flat_master_index` filter on, the master lists every
514     * individual sitemap file directly whenever they all fit in one buffer. They
515     * no longer fit somewhere north of a million URLs, and only then does it fall
516     * back to linking the per-type `*-sitemap-index-N.xml` files. With the filter
517     * off, which is still the default, it always links them.
518     *
519     * Either way the buffer is only stored once every sitemap this generation
520     * cycle recorded is accounted for. If one is missing, the master the previous
521     * cycle stored is left in place: it reaches more URLs than anything that
522     * could be built right now.
523     *
524     * @link https://www.sitemaps.org/protocol.html#index
525     *
526     * @param array $max Array of sitemap types with max index and datetime.
527     *
528     * @since 4.8.0
529     */
530    private function build_master_sitemap( $max ) {
531        if ( $this->logger ) {
532            $this->logger->report( '-- Building Master Sitemap.' );
533        }
534
535        $sitemap_types = array(
536            JP_PAGE_SITEMAP_TYPE,
537            JP_IMAGE_SITEMAP_TYPE,
538            JP_VIDEO_SITEMAP_TYPE,
539        );
540
541        $buffer = null;
542
543        /**
544         * Whether the master sitemap lists each individual sitemap file directly.
545         *
546         * A sitemap index file may not list other sitemap index files, and Google
547         * Search Console reports the nested layout as "Nested indexing". Listing
548         * the files directly is what fixes that.
549         *
550         * Off by default so the flat layout can be rolled out a site at a time.
551         * The default is expected to flip once it has been verified in production,
552         * at which point this filter goes away.
553         *
554         * @module sitemaps
555         *
556         * @since 16.2
557         *
558         * @param bool $flat_master_index Whether to list sitemap files directly. Default false.
559         */
560        if ( apply_filters( 'jetpack_sitemap_flat_master_index', false ) ) {
561            $buffer = $this->build_flat_master_buffer( $sitemap_types, $max );
562        }
563
564        if ( null === $buffer || self::MASTER_OVERFLOW === $buffer ) {
565            /*
566             * Either the flat layout is off, or the files did not fit in one
567             * buffer. Nesting is invalid and Google flags it, but a complete
568             * invalid tree beats a valid one that drops URLs, and a sitemap
569             * index cannot be paginated to make the flat layout scale further.
570             */
571            $buffer = $this->build_nested_master_buffer( $sitemap_types, $max );
572        }
573
574        if ( ! is_object( $buffer ) ) {
575            return;
576        }
577
578        $this->librarian->store_sitemap_data(
579            0,
580            JP_MASTER_SITEMAP_TYPE,
581            $buffer->contents(),
582            ''
583        );
584    }
585
586    /**
587     * Create the buffer a master sitemap is assembled in.
588     *
589     * Extracted as a protected seam so a test can hand back a buffer small
590     * enough to overflow without generating a million URLs.
591     *
592     * @access protected
593     * @since 16.2
594     *
595     * @return Jetpack_Sitemap_Buffer|Jetpack_Sitemap_Buffer_XMLWriter|false The buffer, or false if one cannot be created.
596     */
597    protected function create_master_buffer() {
598        return Jetpack_Sitemap_Buffer_Factory::create(
599            'master',
600            JP_SITEMAP_MAX_ITEMS,
601            JP_SITEMAP_MAX_BYTES
602        );
603    }
604
605    /**
606     * Build a master sitemap buffer listing every individual sitemap file.
607     *
608     * The buffer's item and byte limits can both stop this short, and how soon
609     * the byte limit bites depends on how long this site's URLs are, so the
610     * partial buffer is discarded and MASTER_OVERFLOW returned rather than
611     * storing a master that omits sitemaps. Every type is still checked over
612     * once the buffer overflows, so a missing file is reported as
613     * MASTER_INCOMPLETE instead of sending the caller off to build a nested
614     * master out of the same broken state.
615     *
616     * @access private
617     * @since 16.2
618     *
619     * @param array $sitemap_types The sitemap types to list, in order.
620     * @param array $max           Array of sitemap types with max index and datetime.
621     *
622     * @return Jetpack_Sitemap_Buffer|Jetpack_Sitemap_Buffer_XMLWriter|string The buffer, or MASTER_OVERFLOW / MASTER_INCOMPLETE.
623     */
624    private function build_flat_master_buffer( $sitemap_types, $max ) {
625        $buffer = $this->create_master_buffer();
626
627        if ( ! $buffer ) {
628            return self::MASTER_INCOMPLETE;
629        }
630
631        $overflowed = false;
632
633        foreach ( $sitemap_types as $sitemap_type ) {
634            $expected = $this->sitemap_count_of( $max, $sitemap_type );
635
636            if ( $expected < 1 ) {
637                continue;
638            }
639
640            $timestamps = $this->stored_sitemap_timestamps( $sitemap_type, $expected );
641
642            if ( false === $timestamps ) {
643                return self::MASTER_INCOMPLETE;
644            }
645
646            if ( $overflowed ) {
647                continue;
648            }
649
650            for ( $number = 1; $number <= $expected; $number++ ) {
651                $filename = jp_sitemap_filename( $sitemap_type, $number );
652
653                if ( ! $this->append_sitemap_to_master( $buffer, $filename, $timestamps[ $filename ] ) ) {
654                    if ( $this->logger ) {
655                        $this->logger->report( '-- Master Sitemap is full; falling back to nested indexes.' );
656                    }
657
658                    $overflowed = true;
659                    break;
660                }
661            }
662        }
663
664        return $overflowed ? self::MASTER_OVERFLOW : $buffer;
665    }
666
667    /**
668     * Build a master sitemap buffer linking one file per sitemap type: the single
669     * sitemap when there is only one, otherwise that type's newest index file.
670     *
671     * Only used when the individual files do not all fit. The whole index chain
672     * has to be intact, because the newest index reaches the older ones only by
673     * linking back through them, so every index of a type is checked and not just
674     * the one the master names.
675     *
676     * @access private
677     * @since 16.2
678     *
679     * @param array $sitemap_types The sitemap types to list, in order.
680     * @param array $max           Array of sitemap types with max index and datetime.
681     *
682     * @return Jetpack_Sitemap_Buffer|Jetpack_Sitemap_Buffer_XMLWriter|string The buffer, or MASTER_INCOMPLETE.
683     */
684    private function build_nested_master_buffer( $sitemap_types, $max ) {
685        $buffer = $this->create_master_buffer();
686
687        if ( ! $buffer ) {
688            return self::MASTER_INCOMPLETE;
689        }
690
691        foreach ( $sitemap_types as $sitemap_type ) {
692            $expected = $this->sitemap_count_of( $max, $sitemap_type );
693
694            if ( $expected < 1 ) {
695                continue;
696            }
697
698            // The files reached through the index still have to be there.
699            $timestamps = $this->stored_sitemap_timestamps( $sitemap_type, $expected );
700
701            if ( false === $timestamps ) {
702                return self::MASTER_INCOMPLETE;
703            }
704
705            $linked_type  = $sitemap_type;
706            $linked_count = $expected;
707
708            if ( 1 !== $expected ) {
709                // Only a type with a single sitemap has no index to link.
710                $linked_type  = jp_sitemap_index_type_of( $sitemap_type );
711                $linked_count = $this->sitemap_count_of( $max, $linked_type );
712                $timestamps   = $this->stored_sitemap_timestamps( $linked_type, $linked_count );
713
714                if ( $linked_count < 1 || false === $timestamps ) {
715                    if ( $this->logger ) {
716                        $this->logger->report( "-- No usable index for $sitemap_type; keeping the previous Master Sitemap." );
717                    }
718
719                    return self::MASTER_INCOMPLETE;
720                }
721            }
722
723            $linked_name = jp_sitemap_filename( $linked_type, $linked_count );
724
725            if ( ! $this->append_sitemap_to_master( $buffer, $linked_name, $timestamps[ $linked_name ] ) ) {
726                if ( $this->logger ) {
727                    $this->logger->report( "-- No room for $linked_name; keeping the previous Master Sitemap." );
728                }
729
730                return self::MASTER_INCOMPLETE;
731            }
732        }
733
734        return $buffer;
735    }
736
737    /**
738     * The number of sitemap files of a type the current generation cycle recorded.
739     *
740     * @access private
741     * @since 16.2
742     *
743     * @param array  $max  Array of sitemap types with max index and datetime.
744     * @param string $type A sitemap or sitemap index type.
745     *
746     * @return int The count, or 0 if the type produced nothing.
747     */
748    private function sitemap_count_of( $max, $type ) {
749        return isset( $max[ $type ]['number'] ) ? (int) $max[ $type ]['number'] : 0;
750    }
751
752    /**
753     * Look up the timestamps of files 1..$count of a sitemap type, by filename.
754     *
755     * Filenames rather than row order, because a row rewritten by an interrupted
756     * cleanup no longer sorts where its number says it should.
757     *
758     * @access private
759     * @since 16.2
760     *
761     * @param string $type  A sitemap or sitemap index type.
762     * @param int    $count How many files of that type to expect.
763     *
764     * @return array|false Map of filename to timestamp, or false if any is missing.
765     */
766    private function stored_sitemap_timestamps( $type, $count ) {
767        $names = array();
768
769        for ( $number = 1; $number <= $count; $number++ ) {
770            $names[] = jp_sitemap_filename( $type, $number );
771        }
772
773        $timestamps = $this->librarian->query_sitemap_timestamps( $type, $names );
774
775        foreach ( $names as $name ) {
776            if ( ! isset( $timestamps[ $name ] ) ) {
777                if ( $this->logger ) {
778                    $this->logger->report( "-- $name is missing; keeping the previous Master Sitemap." );
779                }
780
781                return false;
782            }
783        }
784
785        return $timestamps;
786    }
787
788    /**
789     * Append one <sitemap> entry to a master sitemap buffer.
790     *
791     * @access private
792     * @since 16.2
793     *
794     * @param Jetpack_Sitemap_Buffer|Jetpack_Sitemap_Buffer_XMLWriter $buffer   The master sitemap buffer.
795     * @param string                                                  $filename The sitemap filename to link.
796     * @param string                                                  $lastmod  Its timestamp, in 'YYYY-MM-DD hh:mm:ss' format.
797     *
798     * @return bool Whether the entry fit.
799     */
800    private function append_sitemap_to_master( $buffer, $filename, $lastmod ) {
801        return true === $buffer->append(
802            array(
803                'sitemap' => array(
804                    'loc'     => $this->finder->construct_sitemap_url( $filename ),
805                    'lastmod' => jp_sitemap_datetime( $lastmod ),
806                ),
807            )
808        );
809    }
810
811    /**
812     * Build and store a single page sitemap. Returns false if no sitemap is built.
813     *
814     * Side effect: Create/update a sitemap row.
815     *
816     * @access private
817     * @since 4.8.0
818     *
819     * @param int $number The number of the current sitemap.
820     * @param int $from_id The greatest lower bound of the IDs of the posts to be included.
821     *
822     * @return bool|array @args {
823     *   @type int    $last_id       The ID of the last item to be successfully added to the buffer.
824     *   @type bool   $any_left      'true' if there are items which haven't been saved to a sitemap, 'false' otherwise.
825     *   @type string $last_modified The most recent timestamp to appear on the sitemap.
826     * }
827     */
828    public function build_one_page_sitemap( $number, $from_id ) {
829        $last_post_id   = $from_id;
830        $any_posts_left = true;
831
832        if ( $this->logger ) {
833            $debug_name = jp_sitemap_filename( JP_PAGE_SITEMAP_TYPE, $number );
834            $this->logger->report( "-- Building $debug_name" );
835        }
836
837        $buffer = Jetpack_Sitemap_Buffer_Factory::create(
838            'page',
839            JP_SITEMAP_MAX_ITEMS,
840            JP_SITEMAP_MAX_BYTES
841        );
842
843        if ( ! $buffer ) {
844            return false;
845        }
846
847        // Add entry for the main page (only if we're at the first one) and it isn't already going to be included as a page.
848        if ( 1 === $number && 'page' !== get_option( 'show_on_front' ) ) {
849            $item_array = array(
850                'url' => array(
851                    'loc' => home_url( '/' ),
852                ),
853            );
854
855            /**
856             * Filter associative array with data to build <url> node
857             * and its descendants for site home.
858             *
859             * @module sitemaps
860             *
861             * @since 3.9.0
862             *
863             * @param array $blog_home Data to build parent and children nodes for site home.
864             */
865            $item_array = apply_filters( 'jetpack_sitemap_url_home', $item_array );
866
867            $buffer->append( $item_array );
868        }
869
870        // Add as many items to the buffer as possible.
871        while ( $last_post_id >= 0 && false === $buffer->is_full() ) {
872            $posts = $this->librarian->query_posts_after_id(
873                $last_post_id,
874                JP_SITEMAP_BATCH_SIZE
875            );
876
877            if ( null == $posts ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual -- WPCS: loose comparison ok.
878                $any_posts_left = false;
879                break;
880            }
881
882            foreach ( $posts as $post ) {
883                $current_item = $this->post_to_sitemap_item( $post );
884
885                if ( true === $buffer->append( $current_item['xml'] ) ) {
886                    $last_post_id = $post->ID;
887                    $buffer->view_time( $current_item['last_modified'] );
888                } else {
889                    break;
890                }
891            }
892        }
893
894        // Handle other page sitemap URLs.
895        if ( ! $any_posts_left || $last_post_id < 0 ) {
896            // Negative IDs are used to track URL indexes.
897            $last_post_id   = min( 0, $last_post_id );
898            $any_posts_left = true; // Reinitialize.
899
900            /**
901             * Filter other page sitemap URLs.
902             *
903             * @module sitemaps
904             *
905             * @since 6.1.0
906             *
907             * @param array $urls An array of other URLs.
908             */
909            $other_urls = apply_filters( 'jetpack_page_sitemap_other_urls', array() );
910
911            if ( $other_urls ) { // Start with index [1].
912                $other_urls = array_values( $other_urls );
913                array_unshift( $other_urls, $other_urls[0] );
914                unset( $other_urls[0] );
915            }
916
917            // Add as many items to the buffer as possible.
918            while ( false === $buffer->is_full() ) {
919                // The URLs are keyed from 1, so the last key written is also the offset of the next URL.
920                $last_post_id_index = abs( $last_post_id );
921                $urls               = array_slice(
922                    $other_urls,
923                    $last_post_id_index,
924                    JP_SITEMAP_BATCH_SIZE,
925                    true
926                );
927
928                if ( ! $urls ) {
929                    $any_posts_left = false;
930                    break;
931                }
932
933                foreach ( $urls as $index => $url ) {
934                    if ( ! is_array( $url ) ) {
935                        $url = array( 'loc' => $url );
936                    }
937                    $item = array( 'xml' => compact( 'url' ) );
938
939                    if ( true === $buffer->append( $item['xml'] ) ) {
940                        $last_post_id = -$index;
941                        if ( isset( $url['lastmod'] ) ) {
942                            $buffer->view_time( jp_sitemap_datetime( $url['lastmod'] ) );
943                        }
944                    } else {
945                        break;
946                    }
947                }
948            }
949        }
950
951        // If no items were added, return false.
952        if ( true === $buffer->is_empty() ) {
953            return false;
954        }
955
956        /**
957         * Filter sitemap before rendering it as XML.
958         *
959         * @module sitemaps
960         *
961         * @since 3.9.0
962         * @since 5.3.0 returns an element of DOMDocument type instead of SimpleXMLElement
963         *
964         * @param DOMDocument      $doc Data tree for sitemap.
965         * @param string           $last_modified Date of last modification.
966         */
967        if ( has_filter( 'jetpack_print_sitemap' ) ) {
968            apply_filters(
969                'jetpack_print_sitemap',
970                $buffer->get_document(),
971                $buffer->last_modified()
972            );
973        }
974
975        // Store the buffer as the content of a sitemap row.
976        $this->librarian->store_sitemap_data(
977            $number,
978            JP_PAGE_SITEMAP_TYPE,
979            $buffer->contents(),
980            $buffer->last_modified()
981        );
982
983        /*
984         * Now report back with the ID of the last post ID to be
985         * successfully added and whether there are any posts left.
986         */
987        return array(
988            'last_id'       => $last_post_id,
989            'any_left'      => $any_posts_left,
990            'last_modified' => $buffer->last_modified(),
991        );
992    }
993
994    /**
995     * Build and store a single image sitemap. Returns false if no sitemap is built.
996     *
997     * Side effect: Create/update an image sitemap row.
998     *
999     * @access private
1000     * @since 4.8.0
1001     *
1002     * @param int $number The number of the current sitemap.
1003     * @param int $from_id The greatest lower bound of the IDs of the posts to be included.
1004     *
1005     * @return bool|array @args {
1006     *   @type int    $last_id       The ID of the last item to be successfully added to the buffer.
1007     *   @type bool   $any_left      'true' if there are items which haven't been saved to a sitemap, 'false' otherwise.
1008     *   @type string $last_modified The most recent timestamp to appear on the sitemap.
1009     * }
1010     */
1011    public function build_one_image_sitemap( $number, $from_id ) {
1012        $last_post_id   = $from_id;
1013        $any_posts_left = true;
1014
1015        if ( $this->logger ) {
1016            $debug_name = jp_sitemap_filename( JP_IMAGE_SITEMAP_TYPE, $number );
1017            $this->logger->report( "-- Building $debug_name" );
1018        }
1019
1020        $buffer = Jetpack_Sitemap_Buffer_Factory::create(
1021            'image',
1022            JP_SITEMAP_MAX_ITEMS,
1023            JP_SITEMAP_MAX_BYTES
1024        );
1025
1026        if ( ! $buffer ) {
1027            return false;
1028        }
1029
1030        // Add as many items to the buffer as possible.
1031        while ( false === $buffer->is_full() ) {
1032            $posts = $this->librarian->query_images_after_id(
1033                $last_post_id,
1034                JP_SITEMAP_BATCH_SIZE
1035            );
1036
1037            if ( null == $posts ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual -- WPCS: loose comparison ok.
1038                $any_posts_left = false;
1039                break;
1040            }
1041
1042            foreach ( $posts as $post ) {
1043                $current_item = $this->image_post_to_sitemap_item( $post );
1044
1045                if ( true === $buffer->append( $current_item['xml'] ) ) {
1046                    $last_post_id = $post->ID;
1047                    $buffer->view_time( $current_item['last_modified'] );
1048                } else {
1049                    break;
1050                }
1051            }
1052        }
1053
1054        // If no items were added, return false.
1055        if ( true === $buffer->is_empty() ) {
1056            return false;
1057        }
1058
1059        // Store the buffer as the content of a jp_sitemap post.
1060        $this->librarian->store_sitemap_data(
1061            $number,
1062            JP_IMAGE_SITEMAP_TYPE,
1063            $buffer->contents(),
1064            $buffer->last_modified()
1065        );
1066
1067        /*
1068         * Now report back with the ID of the last post to be
1069         * successfully added and whether there are any posts left.
1070         */
1071        return array(
1072            'last_id'       => $last_post_id,
1073            'any_left'      => $any_posts_left,
1074            'last_modified' => $buffer->last_modified(),
1075        );
1076    }
1077
1078    /**
1079     * Build and store a single video sitemap. Returns false if no sitemap is built.
1080     *
1081     * Side effect: Create/update an video sitemap row.
1082     *
1083     * @access private
1084     * @since 4.8.0
1085     *
1086     * @param int $number The number of the current sitemap.
1087     * @param int $from_id The greatest lower bound of the IDs of the posts to be included.
1088     *
1089     * @return bool|array @args {
1090     *   @type int    $last_id       The ID of the last item to be successfully added to the buffer.
1091     *   @type bool   $any_left      'true' if there are items which haven't been saved to a sitemap, 'false' otherwise.
1092     *   @type string $last_modified The most recent timestamp to appear on the sitemap.
1093     * }
1094     */
1095    public function build_one_video_sitemap( $number, $from_id ) {
1096        $last_post_id   = $from_id;
1097        $any_posts_left = true;
1098
1099        if ( $this->logger ) {
1100            $debug_name = jp_sitemap_filename( JP_VIDEO_SITEMAP_TYPE, $number );
1101            $this->logger->report( "-- Building $debug_name" );
1102        }
1103
1104        $buffer = Jetpack_Sitemap_Buffer_Factory::create(
1105            'video',
1106            JP_SITEMAP_MAX_ITEMS,
1107            JP_SITEMAP_MAX_BYTES
1108        );
1109
1110        if ( ! $buffer ) {
1111            return false;
1112        }
1113
1114        // Add as many items to the buffer as possible.
1115        while ( false === $buffer->is_full() ) {
1116            $posts = $this->librarian->query_videos_after_id(
1117                $last_post_id,
1118                JP_SITEMAP_BATCH_SIZE
1119            );
1120
1121            if ( null == $posts ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual -- WPCS: loose comparison ok.
1122                $any_posts_left = false;
1123                break;
1124            }
1125
1126            foreach ( $posts as $post ) {
1127                $current_item = $this->video_post_to_sitemap_item( $post );
1128
1129                if ( true === $buffer->append( $current_item['xml'] ) ) {
1130                    $last_post_id = $post->ID;
1131                    $buffer->view_time( $current_item['last_modified'] );
1132                } else {
1133                    break;
1134                }
1135            }
1136        }
1137
1138        // If no items were added, return false.
1139        if ( true === $buffer->is_empty() ) {
1140            return false;
1141        }
1142
1143        if ( false === $buffer->is_empty() ) {
1144            $this->librarian->store_sitemap_data(
1145                $number,
1146                JP_VIDEO_SITEMAP_TYPE,
1147                $buffer->contents(),
1148                $buffer->last_modified()
1149            );
1150        }
1151
1152        /*
1153         * Now report back with the ID of the last post to be
1154         * successfully added and whether there are any posts left.
1155         */
1156        return array(
1157            'last_id'       => $last_post_id,
1158            'any_left'      => $any_posts_left,
1159            'last_modified' => $buffer->last_modified(),
1160        );
1161    }
1162
1163    /**
1164     * Build and store a single page sitemap index. Return false if no index is built.
1165     *
1166     * Side effect: Create/update a sitemap index row.
1167     *
1168     * @access private
1169     * @since 4.8.0
1170     *
1171     * @param int    $number     The number of the current sitemap index.
1172     * @param int    $from_id    The greatest lower bound of the IDs of the sitemaps to be included.
1173     * @param string $datetime   Datetime of previous sitemap in 'YYYY-MM-DD hh:mm:ss' format.
1174     * @param string $index_type Sitemap index type.
1175     *
1176     * @return bool|array @args {
1177     *   @type int    $last_id       The ID of the last item to be successfully added to the buffer.
1178     *   @type bool   $any_left      'true' if there are items which haven't been saved to a sitemap, 'false' otherwise.
1179     *   @type string $last_modified The most recent timestamp to appear on the sitemap.
1180     * }
1181     */
1182    private function build_one_sitemap_index( $number, $from_id, $datetime, $index_type ) {
1183        $last_sitemap_id   = $from_id;
1184        $any_sitemaps_left = true;
1185
1186        // Check the datetime format.
1187        $datetime = jp_sitemap_datetime( $datetime );
1188
1189        $sitemap_type = jp_sitemap_child_type_of( $index_type );
1190
1191        if ( $this->logger ) {
1192            $index_debug_name = jp_sitemap_filename( $index_type, $number );
1193            $this->logger->report( "-- Building $index_debug_name" );
1194        }
1195
1196        $buffer = Jetpack_Sitemap_Buffer_Factory::create(
1197            'master',
1198            JP_SITEMAP_MAX_ITEMS,
1199            JP_SITEMAP_MAX_BYTES,
1200            $datetime
1201        );
1202        if ( ! $buffer ) {
1203            return false;
1204        }
1205
1206        // Add pointer to the previous sitemap index (unless we're at the first one).
1207        if ( 1 !== $number ) {
1208            $i              = $number - 1;
1209            $prev_index_url = $this->finder->construct_sitemap_url(
1210                jp_sitemap_filename( $index_type, $i )
1211            );
1212
1213            $item_array = array(
1214                'sitemap' => array(
1215                    'loc'     => $prev_index_url,
1216                    'lastmod' => $datetime,
1217                ),
1218            );
1219
1220            $buffer->append( $item_array );
1221        }
1222
1223        // Add as many items to the buffer as possible.
1224        while ( false === $buffer->is_full() ) {
1225            // Retrieve a batch of posts (in order).
1226            $posts = $this->librarian->query_sitemaps_after_id(
1227                $sitemap_type,
1228                $last_sitemap_id,
1229                JP_SITEMAP_BATCH_SIZE
1230            );
1231
1232            // If there were no posts to get, make a note.
1233            if ( null == $posts ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual -- WPCS: loose comparison ok.
1234                $any_sitemaps_left = false;
1235                break;
1236            }
1237
1238            // Otherwise, loop through each post in the batch.
1239            foreach ( $posts as $post ) {
1240                // Generate the sitemap XML for the post.
1241                $current_item = $this->sitemap_row_to_index_item( (array) $post );
1242
1243                // Try adding this item to the buffer.
1244                if ( true === $buffer->append( $current_item['xml'] ) ) {
1245                    $last_sitemap_id = $post['ID'];
1246                    $buffer->view_time( $current_item['last_modified'] );
1247                } else {
1248                    // Otherwise stop looping through posts.
1249                    break;
1250                }
1251            }
1252        }
1253
1254        // If no items were added, return false.
1255        if ( true === $buffer->is_empty() ) {
1256            return false;
1257        }
1258
1259        $this->librarian->store_sitemap_data(
1260            $number,
1261            $index_type,
1262            $buffer->contents(),
1263            $buffer->last_modified()
1264        );
1265
1266        /*
1267         * Now report back with the ID of the last sitemap post ID to
1268         * be successfully added, whether there are any sitemap posts
1269         * left, and the most recent modification time seen.
1270         */
1271        return array(
1272            'last_id'       => $last_sitemap_id,
1273            'any_left'      => $any_sitemaps_left,
1274            'last_modified' => $buffer->last_modified(),
1275        );
1276    }
1277
1278    /**
1279     * Construct the sitemap index url entry for a sitemap row.
1280     *
1281     * @link https://www.sitemaps.org/protocol.html#sitemapIndex_sitemap
1282     *
1283     * @access private
1284     * @since 4.8.0
1285     *
1286     * @param array $row The sitemap data to be processed.
1287     *
1288     * @return string An XML fragment representing the post URL.
1289     */
1290    private function sitemap_row_to_index_item( $row ) {
1291        $url = $this->finder->construct_sitemap_url( $row['post_title'] );
1292
1293        $item_array = array(
1294            'sitemap' => array(
1295                'loc'     => $url,
1296                'lastmod' => jp_sitemap_datetime( $row['post_date'] ),
1297            ),
1298        );
1299
1300        return array(
1301            'xml'           => $item_array,
1302            'last_modified' => $row['post_date'],
1303        );
1304    }
1305
1306    /**
1307     * This is served instead of a 404 when the master sitemap is requested
1308     * but not yet generated.
1309     *
1310     * @access public
1311     * @since 6.7.0
1312     *
1313     * @return string The empty sitemap xml.
1314     */
1315    public function empty_sitemap_xml() {
1316        $empty_sitemap = new Jetpack_Sitemap_Buffer_Empty();
1317        return $empty_sitemap->contents();
1318    }
1319
1320    /**
1321     * Build and return the news sitemap xml. Note that the result of this
1322     * function is cached in the transient 'jetpack_news_sitemap_xml_v2'.
1323     *
1324     * @access public
1325     * @since 4.8.0
1326     *
1327     * @return string The news sitemap xml.
1328     */
1329    public function news_sitemap_xml() {
1330        $buffer = Jetpack_Sitemap_Buffer_Factory::create(
1331            'news',
1332            JP_SITEMAP_MAX_ITEMS,
1333            JP_SITEMAP_MAX_BYTES
1334        );
1335
1336        if ( ! $buffer ) {
1337            return '';
1338        }
1339
1340        $the_stored_news_sitemap = get_transient( 'jetpack_news_sitemap_xml_v2' );
1341
1342        if ( false === $the_stored_news_sitemap ) {
1343
1344            if ( $this->logger ) {
1345                $this->logger->report( 'Beginning news sitemap generation.' );
1346            }
1347
1348            /**
1349             * Filter limit of entries to include in news sitemap.
1350             *
1351             * @module sitemaps
1352             *
1353             * @since 3.9.0
1354             *
1355             * @param int $count Number of entries to include in news sitemap.
1356             */
1357            $item_limit = apply_filters(
1358                'jetpack_sitemap_news_sitemap_count',
1359                JP_NEWS_SITEMAP_MAX_ITEMS
1360            );
1361
1362            $expires_at = time() + JP_NEWS_SITEMAP_INTERVAL;
1363            $posts      = $this->librarian->query_most_recent_posts( $item_limit );
1364            foreach ( (array) $posts as $post ) {
1365                $current_item = $this->post_to_news_sitemap_item( $post );
1366                if ( null === $current_item['xml'] ) {
1367                    continue;
1368                }
1369                if ( false === $buffer->append( $current_item['xml'] ) ) {
1370                    break;
1371                }
1372                $expires_at = min( $expires_at, strtotime( $post->post_date_gmt . ' UTC' ) + 2 * DAY_IN_SECONDS );
1373            }
1374
1375            if ( $this->logger ) {
1376                $this->logger->time( 'End news sitemap generation.' );
1377            }
1378
1379            $the_stored_news_sitemap = $buffer->contents();
1380
1381            set_transient(
1382                'jetpack_news_sitemap_xml_v2',
1383                $the_stored_news_sitemap,
1384                max( 1, $expires_at - time() )
1385            );
1386        } // End if.
1387
1388        return $the_stored_news_sitemap;
1389    }
1390
1391    /**
1392     * Construct the sitemap url entry for a WP_Post.
1393     *
1394     * @link https://www.sitemaps.org/protocol.html#urldef
1395     * @access private
1396     * @since 4.8.0
1397     *
1398     * @param object $post The post to be processed. Similar to WP_Post, but without post_content and post_content_filtered.
1399     *
1400     * @return array
1401     *              @type array  $xml An XML fragment representing the post URL.
1402     *              @type string $last_modified Date post was last modified.
1403     */
1404    private function post_to_sitemap_item( $post ) {
1405
1406        /**
1407         * Filter condition to allow skipping specific posts in sitemap.
1408         *
1409         * @module sitemaps
1410         *
1411         * @since 3.9.0
1412         *
1413         * @param bool   $skip Current boolean. False by default, so no post is skipped.
1414         * @param object $post Current post in the form of a $wpdb result object. Not WP_Post.
1415         *                     Doesn't have all the properties of a WP_Post.
1416         */
1417        if ( true === apply_filters( 'jetpack_sitemap_skip_post', false, $post ) ) {
1418            return array(
1419                'xml'           => null,
1420                'last_modified' => null,
1421            );
1422        }
1423
1424        $url = esc_url( get_permalink( $post ) );
1425
1426        /*
1427         * Spec requires the URL to be <=2048 bytes.
1428         * In practice this constraint is unlikely to be violated.
1429         */
1430        if ( 2048 < strlen( $url ) ) {
1431            $url = home_url() . '/?p=' . $post->ID;
1432        }
1433
1434        $last_modified = $post->post_modified_gmt;
1435
1436        // Check for more recent comments.
1437        // Note that 'Y-m-d h:i:s' strings sort lexicographically.
1438        if ( 0 < $post->comment_count ) {
1439            $last_modified = max(
1440                $last_modified,
1441                $this->librarian->query_latest_approved_comment_time_on_post( $post->ID )
1442            );
1443        }
1444
1445        $item_array = array(
1446            'url' => array(
1447                'loc'     => $url,
1448                'lastmod' => jp_sitemap_datetime( $last_modified ),
1449            ),
1450        );
1451
1452        /**
1453         * Filter sitemap URL item before rendering it as XML.
1454         *
1455         * @module sitemaps
1456         *
1457         * @since 3.9.0
1458         *
1459         * @param array $tree Associative array representing sitemap URL element.
1460         * @param int   $post_id ID of the post being processed.
1461         */
1462        $item_array = apply_filters( 'jetpack_sitemap_url', $item_array, $post->ID );
1463
1464        return array(
1465            'xml'           => $item_array,
1466            'last_modified' => $last_modified,
1467        );
1468    }
1469
1470    /**
1471     * Construct the image sitemap url entry for a WP_Post of image type.
1472     *
1473     * @link https://www.sitemaps.org/protocol.html#urldef
1474     *
1475     * @access private
1476     * @since 4.8.0
1477     *
1478     * @param WP_Post $post The image post to be processed.
1479     *
1480     * @return array
1481     *              @type array  $xml An XML fragment representing the post URL.
1482     *              @type string $last_modified Date post was last modified.
1483     */
1484    private function image_post_to_sitemap_item( $post ) {
1485
1486        /**
1487         * Filter condition to allow skipping specific image posts in the sitemap.
1488         *
1489         * @module sitemaps
1490         *
1491         * @since 4.8.0
1492         *
1493         * @param bool    $skip Current boolean. False by default, so no post is skipped.
1494         * @param WP_POST $post Current post object.
1495         */
1496        if ( apply_filters( 'jetpack_sitemap_image_skip_post', false, $post ) ) {
1497            return array(
1498                'xml'           => null,
1499                'last_modified' => null,
1500            );
1501        }
1502
1503        $url = wp_get_attachment_url( $post->ID );
1504
1505        // Do not include the image if the attached parent is not published.
1506        // Unattached will be published. Otherwise, will inherit parent status.
1507        if ( 'publish' !== get_post_status( $post ) ) {
1508            return array(
1509                'xml'           => null,
1510                'last_modified' => null,
1511            );
1512        }
1513
1514        $parent_url = get_permalink( get_post( $post->post_parent ) );
1515        if ( '' == $parent_url ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual -- WPCS: loose comparison ok.
1516            $parent_url = get_permalink( $post );
1517        }
1518
1519        $item_array = array(
1520            'url' => array(
1521                'loc'         => $parent_url,
1522                'lastmod'     => jp_sitemap_datetime( $post->post_modified_gmt ),
1523                'image:image' => array(
1524                    'image:loc' => $url,
1525                ),
1526            ),
1527        );
1528
1529        /**
1530         * Filter associative array with data to build <url> node
1531         * and its descendants for current post in image sitemap.
1532         *
1533         * @module sitemaps
1534         *
1535         * @since 4.8.0
1536         *
1537         * @param array $item_array Data to build parent and children nodes for current post.
1538         * @param int   $post_id Current image post ID.
1539         */
1540        $item_array = apply_filters(
1541            'jetpack_sitemap_image_sitemap_item',
1542            $item_array,
1543            $post->ID
1544        );
1545
1546        return array(
1547            'xml'           => $item_array,
1548            'last_modified' => $post->post_modified_gmt,
1549        );
1550    }
1551
1552    /**
1553     * Construct the video sitemap url entry for a WP_Post of video type.
1554     *
1555     * @link https://www.sitemaps.org/protocol.html#urldef
1556     * @link https://developers.google.com/webmasters/videosearch/sitemaps
1557     *
1558     * @access private
1559     * @since 4.8.0
1560     *
1561     * @param WP_Post $post The video post to be processed.
1562     *
1563     * @return array
1564     *              @type array  $xml An XML fragment representing the post URL.
1565     *              @type string $last_modified Date post was last modified.
1566     */
1567    private function video_post_to_sitemap_item( $post ) {
1568
1569        /**
1570         * Filter condition to allow skipping specific video posts in the sitemap.
1571         *
1572         * @module sitemaps
1573         *
1574         * @since 4.8.0
1575         *
1576         * @param bool    $skip Current boolean. False by default, so no post is skipped.
1577         * @param WP_POST $post Current post object.
1578         */
1579        if ( apply_filters( 'jetpack_sitemap_video_skip_post', false, $post ) ) {
1580            return array(
1581                'xml'           => null,
1582                'last_modified' => null,
1583            );
1584        }
1585
1586        // Do not include the video if the attached parent is not published.
1587        // Unattached will be published. Otherwise, will inherit parent status.
1588        if ( 'publish' !== get_post_status( $post ) ) {
1589            return array(
1590                'xml'           => null,
1591                'last_modified' => null,
1592            );
1593        }
1594
1595        $parent_url = esc_url( get_permalink( get_post( $post->post_parent ) ) );
1596        if ( '' == $parent_url ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual -- WPCS: loose comparison ok.
1597            $parent_url = esc_url( get_permalink( $post ) );
1598        }
1599
1600        // Prepare the content like get_the_content_feed().
1601        $content = $post->post_content;
1602        /** This filter is already documented in core/wp-includes/post-template.php */
1603        $content = apply_filters( 'the_content', $content );
1604
1605        /** This filter is already documented in core/wp-includes/feed.php */
1606        $content = apply_filters( 'the_content_feed', $content, 'rss2' );
1607
1608        // Include thumbnails for VideoPress videos, use blank image for others.
1609        if ( 'complete' === get_post_meta( $post->ID, 'videopress_status', true ) && has_post_thumbnail( $post ) ) {
1610            $video_thumbnail_url = get_the_post_thumbnail_url( $post );
1611        } else {
1612            /**
1613             * Filter the thumbnail image used in the video sitemap for non-VideoPress videos.
1614             *
1615             * @since 7.2.0
1616             *
1617             * @param string $str Image URL.
1618             */
1619            $video_thumbnail_url = apply_filters( 'jetpack_video_sitemap_default_thumbnail', 'https://s0.wp.com/i/blank.jpg' );
1620        }
1621
1622        $item_array = array(
1623            'url' => array(
1624                'loc'         => $parent_url,
1625                'lastmod'     => jp_sitemap_datetime( $post->post_modified_gmt ),
1626                'video:video' => array(
1627                    /** This filter is already documented in core/wp-includes/feed.php */
1628                    'video:title'         => apply_filters( 'the_title_rss', $post->post_title ),
1629                    'video:thumbnail_loc' => esc_url( $video_thumbnail_url ),
1630                    'video:description'   => $content,
1631                    'video:content_loc'   => esc_url( wp_get_attachment_url( $post->ID ) ),
1632                ),
1633            ),
1634        );
1635
1636        // TODO: Integrate with VideoPress here.
1637        // cf. video:player_loc tag in video sitemap spec.
1638
1639        /**
1640         * Filter associative array with data to build <url> node
1641         * and its descendants for current post in video sitemap.
1642         *
1643         * @module sitemaps
1644         *
1645         * @since 4.8.0
1646         *
1647         * @param array $item_array Data to build parent and children nodes for current post.
1648         * @param int   $post_id Current video post ID.
1649         */
1650        $item_array = apply_filters(
1651            'jetpack_sitemap_video_sitemap_item',
1652            $item_array,
1653            $post->ID
1654        );
1655
1656        return array(
1657            'xml'           => $item_array,
1658            'last_modified' => $post->post_modified_gmt,
1659        );
1660    }
1661
1662    /**
1663     * Construct the news sitemap url entry for a WP_Post.
1664     *
1665     * @link https://www.sitemaps.org/protocol.html#urldef
1666     *
1667     * @access private
1668     * @since 4.8.0
1669     *
1670     * @param object $post The post to be processed. Similar to WP_Post, but without post_content and post_content_filtered.
1671     *
1672     * @return string An XML fragment representing the post URL.
1673     */
1674    private function post_to_news_sitemap_item( $post ) {
1675
1676        // Exclude posts with meta 'jetpack_seo_noindex' set true from the Jetpack news sitemap.
1677        add_filter( 'jetpack_sitemap_news_skip_post', array( 'Jetpack_SEO_Posts', 'exclude_noindex_posts_from_jetpack_sitemap' ), 10, 2 );
1678
1679        /**
1680         * Filter condition to allow skipping specific posts in news sitemap.
1681         *
1682         * @module sitemaps
1683         *
1684         * @since 3.9.0
1685         *
1686         * @param bool   $skip Current boolean. False by default, so no post is skipped.
1687         * @param object $post Current post in the form of a $wpdb result object. Not WP_Post.
1688         *                     Doesn't have all the properties of a WP_Post.
1689         */
1690        if ( apply_filters( 'jetpack_sitemap_news_skip_post', false, $post ) ) {
1691            return array(
1692                'xml' => null,
1693            );
1694        }
1695
1696        $url = get_permalink( $post );
1697
1698        /*
1699         * Spec requires the URL to be <=2048 bytes.
1700         * In practice this constraint is unlikely to be violated.
1701         */
1702        if ( 2048 < strlen( $url ) ) {
1703            $url = home_url() . '/?p=' . $post->ID;
1704        }
1705
1706        /*
1707         * Trim the locale to an ISO 639 language code as required by Google.
1708         * Special cases are zh-cn (Simplified Chinese) and zh-tw (Traditional Chinese).
1709         * @link https://www.loc.gov/standards/iso639-2/php/code_list.php
1710         */
1711        $language = strtolower( get_locale() );
1712
1713        if ( in_array( $language, array( 'zh_tw', 'zh_cn' ), true ) ) {
1714            $language = str_replace( '_', '-', $language );
1715        } else {
1716            $language = preg_replace( '/(_.*)$/i', '', $language );
1717        }
1718
1719        $item_array = array(
1720            'url' => array(
1721                'loc'       => $url,
1722                'lastmod'   => jp_sitemap_datetime( $post->post_modified_gmt ),
1723                'news:news' => array(
1724                    'news:publication'      => array(
1725                        'news:name'     => html_entity_decode( get_bloginfo( 'name' ), ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 ),
1726                        'news:language' => $language,
1727                    ),
1728                    /** This filter is already documented in core/wp-includes/feed.php */
1729                    'news:title'            => apply_filters( 'the_title_rss', $post->post_title ),
1730                    'news:publication_date' => jp_sitemap_datetime( $post->post_date_gmt ),
1731                    'news:genres'           => 'Blog',
1732                ),
1733            ),
1734        );
1735
1736        /**
1737         * Filter associative array with data to build <url> node
1738         * and its descendants for current post in news sitemap.
1739         *
1740         * @module sitemaps
1741         *
1742         * @since 3.9.0
1743         *
1744         * @param array $item_array Data to build parent and children nodes for current post.
1745         * @param int   $post_id Current post ID.
1746         */
1747        $item_array = apply_filters(
1748            'jetpack_sitemap_news_sitemap_item',
1749            $item_array,
1750            $post->ID
1751        );
1752
1753        return array(
1754            'xml' => $item_array,
1755        );
1756    }
1757}