Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
66.27% covered (warning)
66.27%
112 / 169
60.00% covered (warning)
60.00%
9 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Sitemap_Librarian
67.47% covered (warning)
67.47%
112 / 166
60.00% covered (warning)
60.00%
9 / 15
52.09
0.00% covered (danger)
0.00%
0 / 1
 read_sitemap_data
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
2
 store_sitemap_data
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
2
 get_current_sitemap_post_id
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 delete_sitemap_data
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 get_sitemap_text
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 delete_numbered_sitemap_rows_after
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 delete_all_stored_sitemap_data
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 delete_sitemap_type_data
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 query_sitemaps_after_id
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 query_posts_after_id
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
2
 query_latest_approved_comment_time_on_post
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 query_images_after_id
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 query_videos_after_id
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
2
 query_most_recent_posts
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
6
 get_sanitized_post_columns
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * Sitemaps are stored in the database using a custom table. This class
4 * provides a small API for storing and retrieving sitemap data so we can
5 * avoid lots of explicit SQL juggling while building sitemaps. This file
6 * also includes the SQL used to retrieve posts and images to be included
7 * in the sitemaps.
8 *
9 * @since 4.8.0
10 * @package automattic/jetpack
11 */
12
13if ( ! defined( 'ABSPATH' ) ) {
14    exit( 0 );
15}
16
17/* Ensure sitemap constants are available. */
18require_once __DIR__ . '/sitemap-constants.php';
19
20/**
21 * This object handles any database interaction required
22 * for sitemap generation.
23 *
24 * @since 4.8.0
25 */
26class Jetpack_Sitemap_Librarian {
27
28    /**
29     * Sanitized posts table column lists, keyed by table name.
30     *
31     * Keying by table name keeps a process that switches blogs from reusing
32     * one site's column list against another site's posts table. The cache
33     * is static because the librarian is constructed fresh on every request
34     * that builds a sitemap, while the underlying schema is not.
35     *
36     * @var array
37     */
38    private static $post_columns_cache = array();
39
40    /**
41     * Retrieve a single sitemap with given name and type.
42     * Returns null if no such sitemap exists.
43     *
44     * @access public
45     * @since 4.8.0
46     *
47     * @param string $name Name of the sitemap to be retrieved.
48     * @param string $type Type of the sitemap to be retrieved.
49     *
50     * @return array $args {
51     *   @type int    $id        ID number of the sitemap in the database.
52     *   @type string $timestamp Most recent timestamp of the resources pointed to.
53     *   @type string $name      Name of the sitemap in the database.
54     *   @type string $type      Type of the sitemap in the database.
55     *   @type string $text      The content of the sitemap.
56     * }
57     */
58    public function read_sitemap_data( $name, $type ) {
59        $post_array = get_posts(
60            array(
61                'numberposts' => 1,
62                'title'       => $name,
63                'post_type'   => $type,
64                'post_status' => 'draft',
65            )
66        );
67
68        $the_post = array_shift( $post_array );
69
70        if ( null === $the_post ) {
71            return null;
72        } else {
73            return array(
74                'id'        => $the_post->ID,
75                'timestamp' => $the_post->post_date,
76                'name'      => $the_post->post_title,
77                'type'      => $the_post->post_type,
78                'text'      => base64_decode( $the_post->post_content ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
79            );
80        }
81    }
82
83    /**
84     * Store a sitemap of given type and index in the database.
85     * Note that the timestamp is reencoded as 'Y-m-d H:i:s'.
86     *
87     * If a sitemap with that type and name does not exist, create it.
88     * If a sitemap with that type and name does exist, update it.
89     *
90     * This method uses get_current_sitemap_post_id() for efficiency,
91     * as it only retrieves the post ID, which will be typically cached in the persistent object cache.
92     * This approach avoids loading unnecessary data (like post content) into memory,
93     * unlike using read_sitemap_data() which would retrieve the full post object.
94     *
95     * @access public
96     * @since 4.8.0
97     *
98     * @param string $index     Index of the sitemap to be stored.
99     * @param string $type      Type of the sitemap to be stored.
100     * @param string $contents  Contents of the sitemap to be stored.
101     * @param string $timestamp Timestamp of the sitemap to be stored, in 'YYYY-MM-DD hh:mm:ss' format.
102     */
103    public function store_sitemap_data( $index, $type, $contents, $timestamp ) {
104        $name = jp_sitemap_filename( $type, $index );
105
106        $post_id = $this->get_current_sitemap_post_id( $name, $type );
107
108        if ( null === $post_id ) {
109            // Post does not exist.
110            wp_insert_post(
111                array(
112                    'post_title'   => $name,
113                    'post_content' => base64_encode( $contents ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
114                    'post_type'    => $type,
115                    'post_date'    => gmdate( 'Y-m-d H:i:s', strtotime( $timestamp ) ),
116                )
117            );
118        } else {
119            // Post does exist.
120            wp_insert_post(
121                array(
122                    'ID'           => $post_id,
123                    'post_title'   => $name,
124                    'post_content' => base64_encode( $contents ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
125                    'post_type'    => $type,
126                    'post_date'    => gmdate( 'Y-m-d H:i:s', strtotime( $timestamp ) ),
127                )
128            );
129        }
130    }
131
132    /**
133     * Get the current sitemap post ID.
134     *
135     * @param string $name The name of the sitemap.
136     * @param string $type The type of the sitemap.
137     * @return int|null The post ID if it exists, null otherwise.
138     */
139    private function get_current_sitemap_post_id( $name, $type ) {
140        $args = array(
141            'post_type'      => $type,
142            'post_status'    => 'draft',
143            'posts_per_page' => 1,
144            'title'          => $name,
145            'fields'         => 'ids',
146        );
147
148        $query = new WP_Query( $args );
149        $posts = $query->posts;
150        return is_array( $posts ) && $posts ? $posts[0] : null;
151    }
152    /**
153     * Delete a sitemap by name and type.
154     *
155     * @access public
156     * @since 4.8.0
157     *
158     * @param string $name Row name.
159     * @param string $type Row type.
160     *
161     * @return bool 'true' if a row was deleted, 'false' otherwise.
162     */
163    public function delete_sitemap_data( $name, $type ) {
164        $the_post = $this->read_sitemap_data( $name, $type );
165
166        if ( null === $the_post ) {
167            return false;
168        } else {
169            wp_delete_post( $the_post['id'] );
170            return true;
171        }
172    }
173
174    /**
175     * Retrieve the contents of a sitemap with given name and type.
176     * If no such sitemap exists, return the empty string. Note that the
177     * returned string is run through wp_specialchars_decode.
178     *
179     * @access public
180     * @since 4.8.0
181     *
182     * @param string $name Row name.
183     * @param string $type Row type.
184     *
185     * @return string Text of the specified sitemap, or the empty string.
186     */
187    public function get_sitemap_text( $name, $type ) {
188        $row = $this->read_sitemap_data( $name, $type );
189
190        if ( null === $row ) {
191            return '';
192        } else {
193            return $row['text'];
194        }
195    }
196
197    /**
198     * Delete numbered sitemaps named prefix-(p+1), prefix-(p+2), ...
199     * until the first nonexistent sitemap is found.
200     *
201     * @access public
202     * @since 4.8.0
203     *
204     * @param int    $position Number before the first sitemap to be deleted.
205     * @param string $type Sitemap type.
206     */
207    public function delete_numbered_sitemap_rows_after( $position, $type ) {
208        $any_left = true;
209
210        while ( true === $any_left ) {
211            ++$position;
212            $name     = jp_sitemap_filename( $type, $position );
213            $any_left = $this->delete_sitemap_data( $name, $type );
214        }
215    }
216
217    /**
218     * Deletes all stored sitemap data.
219     *
220     * @access public
221     * @since 4.8.0
222     */
223    public function delete_all_stored_sitemap_data() {
224        $this->delete_sitemap_type_data( JP_MASTER_SITEMAP_TYPE );
225        $this->delete_sitemap_type_data( JP_PAGE_SITEMAP_TYPE );
226        $this->delete_sitemap_type_data( JP_PAGE_SITEMAP_INDEX_TYPE );
227        $this->delete_sitemap_type_data( JP_IMAGE_SITEMAP_TYPE );
228        $this->delete_sitemap_type_data( JP_IMAGE_SITEMAP_INDEX_TYPE );
229        $this->delete_sitemap_type_data( JP_VIDEO_SITEMAP_TYPE );
230        $this->delete_sitemap_type_data( JP_VIDEO_SITEMAP_INDEX_TYPE );
231    }
232
233    /**
234     * Deletes all sitemap data of specific type
235     *
236     * @access protected
237     * @since 5.3.0
238     *
239     * @param String $type Type of sitemap.
240     */
241    protected function delete_sitemap_type_data( $type ) {
242        $ids = get_posts(
243            array(
244                'post_type'   => $type,
245                'post_status' => 'draft',
246                'fields'      => 'ids',
247            )
248        );
249
250        foreach ( $ids as $id ) {
251            wp_trash_post( $id );
252        }
253    }
254
255    /**
256     * Retrieve an array of sitemap rows (of a given type) sorted by ID.
257     *
258     * Returns the smallest $num_posts sitemap rows (measured by ID)
259     * of the given type which are larger than $from_id.
260     *
261     * @access public
262     * @since 4.8.0
263     *
264     * @param string $type Type of the sitemap rows to retrieve.
265     * @param int    $from_id Greatest lower bound of retrieved sitemap post IDs.
266     * @param int    $num_posts Largest number of sitemap posts to retrieve.
267     *
268     * @return array The sitemaps, as an array of associative arrays with
269     *               keys ID, post_title, and post_date. The post content is
270     *               deliberately excluded to keep memory usage low.
271     */
272    public function query_sitemaps_after_id( $type, $from_id, $num_posts ) {
273        global $wpdb;
274
275        return $wpdb->get_results(
276            $wpdb->prepare(
277                "SELECT ID, post_title, post_date
278                    FROM $wpdb->posts
279                    WHERE post_type=%s
280                        AND post_status=%s
281                        AND ID>%d
282                    ORDER BY ID ASC
283                    LIMIT %d;",
284                $type,
285                'draft',
286                $from_id,
287                $num_posts
288            ),
289            ARRAY_A
290        ); // WPCS: db call ok; no-cache ok.
291    }
292
293    /**
294     * Retrieve an array of posts sorted by ID.
295     *
296     * More precisely, returns the smallest $num_posts posts
297     * (measured by ID) which are larger than $from_id.
298     *
299     * @access public
300     * @since 4.8.0
301     *
302     * @param int $from_id Greatest lower bound of retrieved post IDs.
303     * @param int $num_posts Largest number of posts to retrieve.
304     *
305     * @return array The posts.
306     */
307    public function query_posts_after_id( $from_id, $num_posts ) {
308        global $wpdb;
309
310        // Get the list of post types to include and prepare for query.
311        $post_types = Jetpack_Options::get_option_and_ensure_autoload(
312            'jetpack_sitemap_post_types',
313            array( 'page', 'post' )
314        );
315        foreach ( (array) $post_types as $i => $post_type ) {
316            $post_types[ $i ] = $wpdb->prepare( '%s', $post_type );
317        }
318        $post_types_list = implode( ',', $post_types );
319
320        $columns_list = $this->get_sanitized_post_columns( $wpdb );
321
322        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- WPCS: db call ok; no-cache ok.
323        return $wpdb->get_results(
324            $wpdb->prepare(
325                "SELECT $columns_list
326                    FROM $wpdb->posts
327                    WHERE post_status='publish'
328                        AND post_type IN ($post_types_list)
329                        AND ID>%d
330                    ORDER BY ID ASC
331                    LIMIT %d;",
332                $from_id,
333                $num_posts
334            )
335        );
336        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
337    }
338
339    /**
340     * Get the most recent timestamp among approved comments for the given post_id.
341     *
342     * @access public
343     * @since 4.8.0
344     *
345     * @param int $post_id Post identifier.
346     *
347     * @return string Timestamp in 'Y-m-d h:i:s' format (UTC) of the most recent comment on the given post, or null if no such comments exist.
348     */
349    public function query_latest_approved_comment_time_on_post( $post_id ) {
350        global $wpdb;
351
352        return $wpdb->get_var(
353            $wpdb->prepare(
354                "SELECT MAX(comment_date_gmt)
355                    FROM $wpdb->comments
356                    WHERE comment_post_ID = %d AND comment_approved = '1' AND comment_type in ( '', 'comment' )",
357                $post_id
358            )
359        );
360    }
361
362    /**
363     * Retrieve an array of image posts sorted by ID.
364     *
365     * More precisely, returns the smallest $num_posts image posts
366     * (measured by ID) which are larger than $from_id.
367     *
368     * @access public
369     * @since 4.8.0
370     *
371     * @param int $from_id Greatest lower bound of retrieved image post IDs.
372     * @param int $num_posts Largest number of image posts to retrieve.
373     *
374     * @return array The posts, without the post_content and
375     *               post_content_filtered columns.
376     */
377    public function query_images_after_id( $from_id, $num_posts ) {
378        global $wpdb;
379
380        $columns_list = $this->get_sanitized_post_columns( $wpdb );
381
382        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- WPCS: db call ok; no-cache ok.
383        return $wpdb->get_results(
384            $wpdb->prepare(
385                "SELECT $columns_list
386                    FROM $wpdb->posts
387                    WHERE post_type='attachment'
388                        AND post_mime_type LIKE %s
389                        AND ID>%d
390                    ORDER BY ID ASC
391                    LIMIT %d;",
392                'image/%',
393                $from_id,
394                $num_posts
395            )
396        );
397        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
398    }
399
400    /**
401     * Retrieve an array of video posts sorted by ID.
402     *
403     * More precisely, returns the smallest $num_posts video posts
404     * (measured by ID) which are larger than $from_id.
405     *
406     * @access public
407     * @since 4.8.0
408     *
409     * @param int $from_id Greatest lower bound of retrieved video post IDs.
410     * @param int $num_posts Largest number of video posts to retrieve.
411     *
412     * @return array The posts.
413     */
414    public function query_videos_after_id( $from_id, $num_posts ) {
415        global $wpdb;
416
417        return $wpdb->get_results(
418            $wpdb->prepare(
419                "SELECT *
420                    FROM $wpdb->posts
421                    WHERE post_type='attachment'
422                        AND post_mime_type LIKE %s
423                        AND ID>%d
424                    ORDER BY ID ASC
425                    LIMIT %d;",
426                'video/%',
427                $from_id,
428                $num_posts
429            )
430        ); // WPCS: db call ok; no-cache ok.
431    }
432
433    /**
434     * Retrieve an array of published posts from the last 2 days.
435     *
436     * @access public
437     * @since 4.8.0
438     *
439     * @param int $num_posts Largest number of posts to retrieve.
440     *
441     * @return array The posts.
442     */
443    public function query_most_recent_posts( $num_posts ) {
444        global $wpdb;
445
446        $two_days_ago = gmdate( 'Y-m-d', strtotime( '-2 days' ) );
447
448        /**
449         * Filter post types to be included in news sitemap.
450         *
451         * @module sitemaps
452         *
453         * @since 3.9.0
454         *
455         * @param array $post_types Array with post types to include in news sitemap.
456         */
457        $post_types = apply_filters(
458            'jetpack_sitemap_news_sitemap_post_types',
459            array( 'page', 'post' )
460        );
461
462        foreach ( (array) $post_types as $i => $post_type ) {
463            $post_types[ $i ] = $wpdb->prepare( '%s', $post_type );
464        }
465
466        $post_types_list = implode( ',', $post_types );
467
468        $columns_list = $this->get_sanitized_post_columns( $wpdb );
469
470        // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.QuotedSimplePlaceholder,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- WPCS: db call ok; no-cache ok.
471        return $wpdb->get_results(
472            $wpdb->prepare(
473                "SELECT $columns_list
474                    FROM $wpdb->posts
475                    WHERE post_status='publish'
476                        AND post_date >= '%s'
477                        AND post_type IN ($post_types_list)
478                    ORDER BY post_date DESC
479                    LIMIT %d;",
480                $two_days_ago,
481                $num_posts
482            )
483        );
484        // phpcs:enable WordPress.DB.PreparedSQLPlaceholders.QuotedSimplePlaceholder,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
485    }
486
487    /**
488     * Returns all columns from the posts table,
489     * except post_content and post_content_filtered.
490     *
491     * The column list is memoized in self::$post_columns_cache, since this is
492     * called once per batch while building sitemaps.
493     *
494     * A cached entry is only used when it is non-empty. SHOW COLUMNS returns
495     * no rows when the query fails, and treating that as a cache hit would
496     * leave every later query in the process with an empty column list.
497     *
498     * @param object $wpdb The WordPress database object.
499     * @return string The sanitized post columns.
500     */
501    private function get_sanitized_post_columns( $wpdb ) {
502        $table = $wpdb->posts;
503
504        if ( empty( self::$post_columns_cache[ $table ] ) ) {
505            $columns = array_filter(
506                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
507                $wpdb->get_col( "SHOW COLUMNS FROM $wpdb->posts" ),
508                function ( $column ) {
509                    return $column !== 'post_content' && $column !== 'post_content_filtered';
510                }
511            );
512
513            self::$post_columns_cache[ $table ] = implode( ',', array_map( 'esc_sql', $columns ) );
514        }
515
516        return self::$post_columns_cache[ $table ];
517    }
518}