Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
21.65% covered (danger)
21.65%
176 / 813
14.55% covered (danger)
14.55%
8 / 55
CRAP
0.00% covered (danger)
0.00%
0 / 1
the_neverending_home_page_init
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
the_neverending_home_page_theme_support
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
56
The_Neverending_Home_Page
22.22% covered (danger)
22.22%
176 / 792
15.09% covered (danger)
15.09%
8 / 53
46113.09
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
1
 get_settings
15.62% covered (danger)
15.62%
15 / 96
0.00% covered (danger)
0.00%
0 / 1
1153.65
 posts_per_page
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
7.04
 wp_query
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 got_infinity
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 is_last_batch
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
56
 preserve_more_tag
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 settings_api_init
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 infinite_setting_html
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 action_template_redirect
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
56
 init_customizer_assets
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
2
 body_class
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 get_excluded_posts
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
90
 get_query_vars
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 has_only_title_matching_posts
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
90
 get_last_post_date
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
110
 get_query_sort_field
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
42
 query_time_filter
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
72
 posts_per_page_query
50.00% covered (danger)
50.00%
1 / 2
0.00% covered (danger)
0.00%
0 / 1
6.00
 has_wrapper
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 ajax_url
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 ajax_response
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 action_wp_head
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 action_wp_footer_settings
0.00% covered (danger)
0.00%
0 / 58
0.00% covered (danger)
0.00%
0 / 1
306
 get_request_path
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
42
 get_request_parameters
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 get_new_styles
100.00% covered (success)
100.00%
33 / 33
100.00% covered (success)
100.00%
1 / 1
13
 get_theme_json_css_for_blocks
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
7.04
 is_per_request_style
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 prefer_rewritten_src
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
8.04
 action_wp_footer
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
20
 filter_infinite_scroll_results
47.83% covered (danger)
47.83%
33 / 69
0.00% covered (danger)
0.00%
0 / 1
105.81
 query
0.00% covered (danger)
0.00%
0 / 94
0.00% covered (danger)
0.00%
0 / 1
812
 allowed_query_vars
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 get_taxonomy_vars
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 inject_query_args
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
8.02
 is_queryable_post_type
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 render
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 archive_supports_infinity
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
6.56
 footer
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
90
 default_footer
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
6
 filter_grunion_redirect_url
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
6
 add_mejs_config
15.38% covered (danger)
15.38%
2 / 13
0.00% covered (danger)
0.00%
0 / 1
8.45
 is_exempted_amp_page
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 amp_load_hooks
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
56
 amp_start_output_buffering
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 amp_output_buffer
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 amp_finish_output_buffering
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
2
 amp_get_footer_template
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 amp_footer_template
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
2
 amp_next_page
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
6
 amp_get_max_pages
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 amp_is_last_page
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2
3// phpcs:disable Universal.Files.SeparateFunctionsFromOO.Mixed -- TODO: Move classes to appropriately-named class files.
4
5use Automattic\Jetpack\Assets;
6
7if ( ! defined( 'ABSPATH' ) ) {
8    exit( 0 );
9}
10
11/*
12Plugin Name: The Neverending Home Page.
13Plugin URI: https://automattic.com/
14Description: Adds infinite scrolling support to the front-end blog post view for themes, pulling the next set of posts automatically into view when the reader approaches the bottom of the page.
15Version: 1.1
16Author: Automattic
17Author URI: https://automattic.com/
18License: GNU General Public License v2 or later
19License URI: https://www.gnu.org/licenses/gpl-2.0.html
20Text Domain: jetpack
21*/
22
23/**
24 * Class: The_Neverending_Home_Page relies on add_theme_support, expects specific
25 * styling from each theme; including fixed footer.
26 *
27 * @phan-constructor-used-for-side-effects
28 */
29class The_Neverending_Home_Page {
30    /**
31    * Maximum allowed number of posts per page in $_REQUEST.
32    */
33    const MAX_ALLOWED_POSTS_PER_PAGE_ΙΝ_REQUEST = 5000;
34
35    /**
36     * Register actions and filters, plus parse IS settings
37     *
38     * @uses add_action, add_filter, self::get_settings
39     */
40    public function __construct() {
41        add_action( 'pre_get_posts', array( $this, 'posts_per_page_query' ) );
42        add_action( 'admin_init', array( $this, 'settings_api_init' ) );
43        add_action( 'template_redirect', array( $this, 'action_template_redirect' ) );
44        add_action( 'customize_preview_init', array( $this, 'init_customizer_assets' ) );
45        add_action( 'template_redirect', array( $this, 'ajax_response' ) );
46        add_action( 'custom_ajax_infinite_scroll', array( $this, 'query' ) );
47        add_filter( 'infinite_scroll_query_args', array( $this, 'inject_query_args' ) );
48        add_filter( 'infinite_scroll_allowed_vars', array( $this, 'allowed_query_vars' ) );
49        add_action( 'the_post', array( $this, 'preserve_more_tag' ) );
50        add_action( 'wp_footer', array( $this, 'footer' ) );
51        add_filter( 'infinite_scroll_additional_scripts', array( $this, 'add_mejs_config' ) );
52
53        // Plugin compatibility
54        add_filter( 'grunion_contact_form_redirect_url', array( $this, 'filter_grunion_redirect_url' ) );
55
56        // AMP compatibility
57        // needs to happen after parse_query so that Jetpack_AMP_Support::is_amp_request() is ready.
58        add_action( 'wp', array( $this, 'amp_load_hooks' ) );
59
60        // Parse IS settings from theme
61        self::get_settings();
62    }
63
64    /**
65     * Initialize our static variables
66     */
67
68    /**
69     * The time.
70     *
71     * @var null - I don't think this is used?
72     */
73    public static $the_time = null;
74
75    /**
76     * Settings.
77     *
78     * Don't access directly, instead use self::get_settings().
79     *
80     * @var array
81     */
82    public static $settings = null;
83
84    /**
85     * The enabled option name.
86     *
87     * @var string
88     */
89    public static $option_name_enabled = 'infinite_scroll';
90
91    /**
92     * Parse IS settings provided by theme
93     *
94     * @uses get_theme_support, infinite_scroll_has_footer_widgets, sanitize_title, add_action, get_option, wp_parse_args, is_active_sidebar
95     * @return object
96     */
97    public static function get_settings() {
98        $defaults = array(
99            'type'            => 'scroll', // scroll | click
100            'requested_type'  => 'scroll', // store the original type for use when logic overrides it
101            'footer_widgets'  => false, // true | false | sidebar_id | array of sidebar_ids -- last two are checked with is_active_sidebar
102            'container'       => 'content', // container html id
103            'wrapper'         => true, // true | false | html class -- the html class.
104            'render'          => false, // optional function, otherwise the `content` template part will be used
105            'footer'          => true, // boolean to enable or disable the infinite footer | string to provide an html id to derive footer width from
106            'footer_callback' => false, // function to be called to render the IS footer, in place of the default
107            'posts_per_page'  => false,
108            'click_handle'    => true, // boolean to enable or disable rendering the click handler div. If type is click and this is false, page must include its own trigger with the HTML ID `infinite-handle`.
109        );
110
111        if ( self::$settings === null ) {
112            $css_pattern = '#[^A-Z\d\-_]#i';
113
114            $settings = $defaults;
115            // Validate settings passed through add_theme_support()
116            $_settings = get_theme_support( 'infinite-scroll' );
117
118            if ( is_array( $_settings ) ) {
119                // Preferred implementation, where theme provides an array of options
120                if ( isset( $_settings[0] ) && is_array( $_settings[0] ) ) {
121                    foreach ( $_settings[0] as $key => $value ) {
122                        switch ( $key ) {
123                            case 'type':
124                                if ( in_array( $value, array( 'scroll', 'click' ), true ) ) {
125                                    $settings['requested_type'] = $value;
126                                    $settings[ $key ]           = $settings['requested_type'];
127                                }
128
129                                break;
130
131                            case 'footer_widgets':
132                                if ( is_string( $value ) ) {
133                                    $settings[ $key ] = sanitize_title( $value );
134                                } elseif ( is_array( $value ) ) {
135                                    $settings[ $key ] = array_map( 'sanitize_title', $value );
136                                } elseif ( is_bool( $value ) ) {
137                                    $settings[ $key ] = $value;
138                                }
139
140                                break;
141
142                            case 'container':
143                            case 'wrapper':
144                                if ( 'wrapper' === $key && is_bool( $value ) ) {
145                                    $settings[ $key ] = $value;
146                                } else {
147                                    $value = preg_replace( $css_pattern, '', $value );
148
149                                    if ( ! empty( $value ) ) {
150                                        $settings[ $key ] = $value;
151                                    }
152                                }
153
154                                break;
155
156                            case 'render':
157                                if ( false !== $value && is_callable( $value ) ) {
158                                    $settings[ $key ] = $value;
159                                }
160
161                                break;
162
163                            case 'footer':
164                                if ( is_bool( $value ) ) {
165                                    $settings[ $key ] = $value;
166                                } elseif ( is_string( $value ) ) {
167                                    $value = preg_replace( $css_pattern, '', $value );
168
169                                    if ( ! empty( $value ) ) {
170                                        $settings[ $key ] = $value;
171                                    }
172                                }
173
174                                break;
175
176                            case 'footer_callback':
177                                if ( is_callable( $value ) ) {
178                                    $settings[ $key ] = $value;
179                                } else {
180                                    $settings[ $key ] = false;
181                                }
182
183                                break;
184
185                            case 'posts_per_page':
186                                if ( is_numeric( $value ) ) {
187                                    $settings[ $key ] = (int) $value;
188                                }
189
190                                break;
191
192                            case 'click_handle':
193                                if ( is_bool( $value ) ) {
194                                    $settings[ $key ] = $value;
195                                }
196
197                                break;
198
199                            default:
200                                break;
201                        }
202                    }
203                } elseif ( is_string( $_settings[0] ) ) {
204                    // Checks below are for backwards compatibility
205
206                    // Container to append new posts to
207                    $settings['container'] = preg_replace( $css_pattern, '', $_settings[0] );
208
209                    // Wrap IS elements?
210                    if ( isset( $_settings[1] ) ) {
211                        $settings['wrapper'] = (bool) $_settings[1];
212                    }
213                }
214            }
215
216            // Always ensure all values are present in the final array
217            $settings = wp_parse_args( $settings, $defaults );
218
219            // Check if a legacy `infinite_scroll_has_footer_widgets()` function is defined and override the footer_widgets parameter's value.
220            // Otherwise, if a widget area ID or array of IDs was provided in the footer_widgets parameter, check if any contains any widgets.
221            // It is safe to use `is_active_sidebar()` before the sidebar is registered as this function doesn't check for a sidebar's existence when determining if it contains any widgets.
222            if ( function_exists( 'infinite_scroll_has_footer_widgets' ) ) {
223                // @phan-suppress-next-line PhanUndeclaredFunction -- Checked above. See also https://github.com/phan/phan/issues/1204.
224                $settings['footer_widgets'] = (bool) infinite_scroll_has_footer_widgets();
225            } elseif ( is_array( $settings['footer_widgets'] ) ) {
226                $sidebar_ids                = $settings['footer_widgets'];
227                $settings['footer_widgets'] = false;
228
229                foreach ( $sidebar_ids as $sidebar_id ) {
230                    if ( is_active_sidebar( $sidebar_id ) ) {
231                        $settings['footer_widgets'] = true;
232                        break;
233                    }
234                }
235
236                unset( $sidebar_ids );
237                unset( $sidebar_id );
238            } elseif ( is_string( $settings['footer_widgets'] ) ) {
239                $settings['footer_widgets'] = (bool) is_active_sidebar( $settings['footer_widgets'] );
240            }
241
242            /**
243             * Filter Infinite Scroll's `footer_widgets` parameter.
244             *
245             * @module infinite-scroll
246             *
247             * @since 2.0.0
248             *
249             * @param bool $settings['footer_widgets'] Does the current theme have Footer Widgets.
250             */
251            $settings['footer_widgets'] = apply_filters( 'infinite_scroll_has_footer_widgets', $settings['footer_widgets'] );
252
253            // Finally, after all of the sidebar checks and filtering, ensure that a boolean value is present, otherwise set to default of `false`.
254            if ( ! is_bool( $settings['footer_widgets'] ) ) {
255                $settings['footer_widgets'] = false;
256            }
257
258            // Ensure that IS is enabled and no footer widgets exist if the IS type isn't already "click".
259            if ( 'click' !== $settings['type'] ) {
260                // Check the setting status
261                $disabled = '' === get_option( self::$option_name_enabled );
262
263                // Footer content or Reading option check
264                if ( $settings['footer_widgets'] || $disabled ) {
265                    $settings['type'] = 'click';
266                }
267            }
268
269            // Force display of the click handler and attendant bits when the type isn't `click`
270            if ( 'click' !== $settings['type'] ) {
271                $settings['click_handle'] = true;
272            }
273
274            // Store final settings in a class static to avoid reparsing
275            self::$settings = $settings;
276        }
277
278        /**
279         * Filter the array of Infinite Scroll settings.
280         *
281         * @module infinite-scroll
282         *
283         * @since 2.0.0
284         *
285         * @param array $settings Array of Infinite Scroll settings.
286         */
287        $filtered_settings = apply_filters( 'infinite_scroll_settings', self::$settings );
288
289        // Ensure all properties are still set.
290        return (object) wp_parse_args( $filtered_settings, $defaults );
291    }
292
293    /**
294     * Number of posts per page.
295     *
296     * @uses self::wp_query, self::get_settings, apply_filters
297     * @return int
298     */
299    public static function posts_per_page() {
300        $settings                   = self::get_settings();
301        $posts_per_page             = $settings->posts_per_page ? $settings->posts_per_page : self::wp_query()->get( 'posts_per_page' );
302        $posts_per_page_core_option = get_option( 'posts_per_page' );
303
304        // If Infinite Scroll is set to click, and if the site owner changed posts_per_page, let's use that.
305        if (
306            'click' === $settings->type
307                && ( '10' !== $posts_per_page_core_option )
308        ) {
309            $posts_per_page = $posts_per_page_core_option;
310        }
311
312        // Take JS query into consideration here.
313        $posts_per_page_in_request = isset( $_REQUEST['query_args']['posts_per_page'] ) ? (int) $_REQUEST['query_args']['posts_per_page'] : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
314        if ( $posts_per_page_in_request > 0 &&
315            self::MAX_ALLOWED_POSTS_PER_PAGE_ΙΝ_REQUEST >= $posts_per_page_in_request
316        ) {
317            $posts_per_page = $posts_per_page_in_request;
318        }
319
320        /**
321         * Filter the number of posts per page.
322         *
323         * @module infinite-scroll
324         *
325         * @since 6.0.0
326         *
327         * @param int $posts_per_page The number of posts to display per page.
328         */
329        return (int) apply_filters( 'infinite_scroll_posts_per_page', $posts_per_page );
330    }
331
332    /**
333     * Retrieve the query used with Infinite Scroll
334     *
335     * @global $wp_the_query
336     * @uses apply_filters
337     * @return object
338     */
339    public static function wp_query() {
340        global $wp_the_query;
341        /**
342         * Filter the Infinite Scroll query object.
343         *
344         * @module infinite-scroll
345         *
346         * @since 2.2.1
347         *
348         * @param WP_Query $wp_the_query WP Query.
349         */
350        return apply_filters( 'infinite_scroll_query_object', $wp_the_query );
351    }
352
353    /**
354     * Has infinite scroll been triggered?
355     */
356    public static function got_infinity() {
357        /**
358         * Filter the parameter used to check if Infinite Scroll has been triggered.
359         *
360         * @module infinite-scroll
361         *
362         * @since 3.9.0
363         *
364         * @param bool isset( $_GET[ 'infinity' ] ) Return true if the "infinity" parameter is set.
365         */
366        return apply_filters( 'infinite_scroll_got_infinity', isset( $_GET['infinity'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no changes made to the site.
367    }
368
369    /**
370     * Is this guaranteed to be the last batch of posts?
371     */
372    public static function is_last_batch() {
373        /**
374         * Override whether or not this is the last batch for a request
375         *
376         * @module infinite-scroll
377         *
378         * @since 4.8.0
379         *
380         * @param bool|null null                 Bool if value should be overridden, null to determine from query
381         * @param object    self::wp_query()     WP_Query object for current request
382         * @param object    self::get_settings() Infinite Scroll settings
383         */
384        $override = apply_filters( 'infinite_scroll_is_last_batch', null, self::wp_query(), self::get_settings() );
385        if ( is_bool( $override ) ) {
386            return $override;
387        }
388
389        $entries        = (int) self::wp_query()->found_posts;
390        $posts_per_page = self::posts_per_page();
391
392        // This is to cope with an issue in certain themes or setups where posts are returned but found_posts is 0.
393        if ( 0 === $entries ) {
394            return ( ! is_countable( self::wp_query()->posts ) || ( count( self::wp_query()->posts ) < $posts_per_page ) );
395        }
396        $paged = max( 1, (int) self::wp_query()->get( 'paged' ) );
397
398        // Are there enough posts for more than the first page?
399        if ( $entries <= $posts_per_page ) {
400            return true;
401        }
402
403        // Calculate entries left after a certain number of pages
404        if ( $paged && $paged > 1 ) {
405            $entries -= $posts_per_page * $paged;
406        }
407
408        // Are there some entries left to display?
409        return $entries <= 0;
410    }
411
412    /**
413     * The more tag will be ignored by default if the blog page isn't our homepage.
414     * Let's force the $more global to false.
415     *
416     * @param array $array - the_post array.
417     * @return array
418     */
419    public function preserve_more_tag( $array ) {
420        global $more;
421
422        if ( self::got_infinity() ) {
423            $more = 0; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- 0 = show content up to the more tag. Add more link.
424        }
425
426        return $array;
427    }
428
429    /**
430     * Add a checkbox field to Settings > Reading
431     * for enabling infinite scroll.
432     *
433     * Only show if the current theme supports infinity.
434     *
435     * @uses current_theme_supports, add_settings_field, __, register_setting
436     * @action admin_init
437     * @return null
438     */
439    public function settings_api_init() {
440        if ( ! current_theme_supports( 'infinite-scroll' ) ) {
441            return;
442        }
443
444        // Add the setting field [infinite_scroll] and place it in Settings > Reading
445        add_settings_field( self::$option_name_enabled, '<span id="infinite-scroll-options">' . esc_html__( 'Infinite Scroll Behavior', 'jetpack' ) . '</span>', array( $this, 'infinite_setting_html' ), 'reading' );
446        register_setting( 'reading', self::$option_name_enabled, 'esc_attr' );
447    }
448
449    /**
450     * HTML code to display a checkbox true/false option
451     * for the infinite_scroll setting.
452     */
453    public function infinite_setting_html() {
454        $settings = self::get_settings();
455
456        // If the blog has footer widgets, show a notice instead of the checkbox
457        if ( $settings->footer_widgets || 'click' === $settings->requested_type ) {
458            echo '<label><em>' . esc_html__( 'We&rsquo;ve changed this option to a click-to-scroll version for you since you have footer widgets in Appearance &rarr; Widgets, or your theme uses click-to-scroll as the default behavior.', 'jetpack' ) . '</em></label>';
459        } else {
460            echo '<label><input name="infinite_scroll" type="checkbox" value="1" ' . checked( 1, '' !== get_option( self::$option_name_enabled ), false ) . ' /> ' . esc_html__( 'Check to load posts as you scroll. Uncheck to show clickable button to load posts', 'jetpack' ) . '</label>';
461            // translators: the number of posts to show on each page load.
462            echo '<p class="description">' . esc_html( sprintf( _n( 'Shows %s post on each load.', 'Shows %s posts on each load.', self::posts_per_page(), 'jetpack' ), number_format_i18n( self::posts_per_page() ) ) ) . '</p>';
463        }
464    }
465
466    /**
467     * Does the legwork to determine whether the feature is enabled.
468     *
469     * @uses current_theme_supports, self::archive_supports_infinity, self::get_settings, add_filter, wp_enqueue_script, plugins_url, wp_enqueue_style, add_action
470     * @action template_redirect
471     * @return null
472     */
473    public function action_template_redirect() {
474        // Check that we support infinite scroll, and are on the home page.
475        if ( ! current_theme_supports( 'infinite-scroll' ) || ! self::archive_supports_infinity() ) {
476            return;
477        }
478
479        $id = self::get_settings()->container;
480
481        // Check that we have an id.
482        if ( empty( $id ) ) {
483            return;
484        }
485
486        // AMP infinite scroll functionality will start on amp_load_hooks().
487        if ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() ) {
488            return;
489        }
490
491        // Add our scripts.
492        wp_register_script(
493            'the-neverending-homepage',
494            Assets::get_file_url_for_environment(
495                '_inc/build/infinite-scroll/infinity.min.js',
496                'modules/infinite-scroll/infinity.js'
497            ),
498            array(),
499            JETPACK__VERSION . '-is5.0.1', // Added for ability to cachebust on WP.com.
500            true
501        );
502
503        // Add our default styles.
504        wp_register_style( 'the-neverending-homepage', plugins_url( 'infinity.css', __FILE__ ), array(), '20140422' );
505
506        // Make sure there are enough posts for IS
507        if ( self::is_last_batch() ) {
508            return;
509        }
510
511        // Add our scripts.
512        wp_enqueue_script( 'the-neverending-homepage' );
513
514        // Add our default styles.
515        wp_enqueue_style( 'the-neverending-homepage' );
516
517        add_action( 'wp_footer', array( $this, 'action_wp_footer_settings' ), 2 );
518
519        add_action( 'wp_footer', array( $this, 'action_wp_footer' ), 21 ); // Core prints footer scripts at priority 20, so we just need to be one later than that
520
521        add_filter( 'infinite_scroll_results', array( $this, 'filter_infinite_scroll_results' ), 10, 3 );
522    }
523
524    /**
525     * Initialize the Customizer logic separately from the main JS.
526     *
527     * @since 8.4.0
528     */
529    public function init_customizer_assets() {
530        // Add our scripts.
531        wp_register_script(
532            'the-neverending-homepage-customizer',
533            Assets::get_file_url_for_environment(
534                '_inc/build/infinite-scroll/infinity-customizer.min.js',
535                'modules/infinite-scroll/infinity-customizer.js'
536            ),
537            array( 'jquery', 'customize-base' ),
538            JETPACK__VERSION . '-is5.0.0', // Added for ability to cachebust on WP.com.
539            true
540        );
541
542        wp_enqueue_script( 'the-neverending-homepage-customizer' );
543    }
544
545    /**
546     * Returns classes to be added to <body>. If it's enabled, 'infinite-scroll'. If set to continuous scroll, adds 'neverending' too.
547     *
548     * @since 4.7.0 No longer added as a 'body_class' filter but passed to JS environment and added using JS.
549     *
550     * @return string
551     */
552    public function body_class() {
553        $settings = self::get_settings();
554        $classes  = '';
555        // Do not add infinity-scroll class if disabled through the Reading page
556        $disabled = '' === get_option( self::$option_name_enabled );
557        if ( ! $disabled || 'click' === $settings->type ) {
558            $classes = 'infinite-scroll';
559
560            if ( 'scroll' === $settings->type ) {
561                $classes .= ' neverending';
562            }
563        }
564
565        return $classes;
566    }
567
568    /**
569     * In case IS is activated on search page, we have to exclude initially loaded posts which match the keyword by title, not the content as they are displayed before content-matching ones
570     *
571     * @uses self::wp_query
572     * @uses self::get_last_post_date
573     * @uses self::has_only_title_matching_posts
574     * @return array
575     */
576    public function get_excluded_posts() {
577
578        $excluded_posts = array();
579        // loop through posts returned by wp_query call
580        foreach ( self::wp_query()->get_posts() as $post ) {
581            if ( ! $post instanceof \WP_Post ) {
582                continue;
583            }
584
585            // @phan-suppress-next-line PhanPluginDuplicateConditionalNullCoalescing -- probably would be safe to collapse, but not changing just in case.
586            $orderby   = isset( self::wp_query()->query_vars['orderby'] ) ? self::wp_query()->query_vars['orderby'] : '';
587            $post_date = ( ! empty( $post->post_date ) ? $post->post_date : false );
588            if ( 'modified' === $orderby || false === $post_date ) {
589                $post_date = $post->post_modified;
590            }
591
592            // in case all posts initially displayed match the keyword by title we add em all to excluded posts array
593            // else, we add only posts which are older than last_post_date param as newer are natually excluded by last_post_date condition in the SQL query
594            if ( self::has_only_title_matching_posts() || $post_date <= self::get_last_post_date() ) {
595                array_push( $excluded_posts, $post->ID );
596            }
597        }
598        return $excluded_posts;
599    }
600
601    /**
602     * In case IS is active on search, we have to exclude posts matched by title rather than by post_content in order to prevent dupes on next pages
603     *
604     * @uses self::wp_query
605     * @uses self::get_excluded_posts
606     * @return array
607     */
608    public function get_query_vars() {
609
610        $query_vars = self::wp_query()->query_vars;
611        // applies to search page only
612        if ( true === self::wp_query()->is_search() ) {
613            // set post__not_in array in query_vars in case it does not exists
614            if ( ! isset( $query_vars['post__not_in'] ) ) {
615                $query_vars['post__not_in'] = array();
616            }
617            // get excluded posts
618            $excluded = self::get_excluded_posts();
619            // merge them with other post__not_in posts (eg.: sticky posts)
620            $query_vars['post__not_in'] = array_merge( $query_vars['post__not_in'], $excluded );
621        }
622        return $query_vars;
623    }
624
625    /**
626     * This function checks whether all posts returned by initial wp_query match the keyword by title
627     * The code used in this function is borrowed from WP_Query class where it is used to construct like conditions for keywords
628     *
629     * @uses self::wp_query
630     * @return bool
631     */
632    public function has_only_title_matching_posts() {
633
634        // apply following logic for search page results only
635        if ( false === self::wp_query()->is_search() ) {
636            return false;
637        }
638
639        // grab the last posts in the stack as if the last one is title-matching the rest is title-matching as well
640        $post = end( self::wp_query()->posts );
641        if ( ! $post instanceof WP_Post ) {
642            return false;
643        }
644
645        // code inspired by WP_Query class
646        if ( preg_match_all( '/".*?("|$)|((?<=[\t ",+])|^)[^\t ",+]+/', self::wp_query()->get( 's' ), $matches ) ) {
647            $search_terms = self::wp_query()->query_vars['search_terms'] ?? null;
648            // if the search string has only short terms or stopwords, or is 10+ terms long, match it as sentence
649            if ( empty( $search_terms ) || ! is_countable( $search_terms ) || count( $search_terms ) > 9 ) {
650                $search_terms = array( self::wp_query()->get( 's' ) );
651            }
652        } else {
653            $search_terms = array( self::wp_query()->get( 's' ) );
654        }
655
656        // actual testing. As search query combines multiple keywords with AND, it's enough to check if any of the keywords is present in the title
657        $term = current( $search_terms );
658        if ( ! empty( $term ) && str_contains( $post->post_title, $term ) ) {
659            return true;
660        }
661
662        return false;
663    }
664
665    /**
666     * Grab the timestamp for the initial query's last post.
667     *
668     * This takes into account the query's 'orderby' parameter and returns
669     * false if the posts are not ordered by date.
670     *
671     * @uses self::got_infinity
672     * @uses self::has_only_title_matching_posts
673     * @uses self::wp_query
674     * @return string 'Y-m-d H:i:s' or false
675     */
676    public function get_last_post_date() {
677        if ( self::got_infinity() ) {
678            return;
679        }
680
681        if ( ! self::wp_query()->have_posts() ) {
682            return null;
683        }
684
685        // In case there are only title-matching posts in the initial WP_Query result, we don't want to use the last_post_date param yet
686        if ( true === self::has_only_title_matching_posts() ) {
687            return false;
688        }
689
690        $post = end( self::wp_query()->posts );
691        // @phan-suppress-next-line PhanPluginDuplicateConditionalNullCoalescing -- probably would be safe to collapse, but not changing just in case.
692        $orderby   = isset( self::wp_query()->query_vars['orderby'] ) ? self::wp_query()->query_vars['orderby'] : '';
693        $post_date = ( ! empty( $post->post_date ) ? $post->post_date : false );
694        switch ( $orderby ) {
695            case 'modified':
696                return $post->post_modified;
697            case 'date':
698            case '':
699                return $post_date;
700            default:
701                return false;
702        }
703    }
704
705    /**
706     * Returns the appropriate `wp_posts` table field for a given query's
707     * 'orderby' parameter, if applicable.
708     *
709     * @param object $query - an optional query object.
710     * @uses self::wp_query
711     * @return string or false
712     */
713    public function get_query_sort_field( $query = null ) {
714        if ( empty( $query ) ) {
715            $query = self::wp_query();
716        }
717
718        $orderby = $query->query_vars['orderby'] ?? '';
719
720        switch ( $orderby ) {
721            case 'modified':
722                return 'post_modified';
723            case 'date':
724            case '':
725                return 'post_date';
726            default:
727                return false;
728        }
729    }
730
731    /**
732     * Create a where clause that will make sure post queries return posts
733     * in the correct order, without duplicates, if a new post is added
734     * and we're sorting by post date.
735     *
736     * @global $wpdb
737     * @param string $where - the where clause.
738     * @param object $query - the query.
739     * @uses apply_filters
740     * @filter posts_where
741     * @return string
742     */
743    public function query_time_filter( $where, $query ) {
744        if ( self::got_infinity() ) {
745            global $wpdb;
746
747            $sort_field = self::get_query_sort_field( $query );
748
749            if ( 'post_date' !== $sort_field ||
750            ! isset( $_REQUEST['query_args']['order'] ) || 'DESC' !== $_REQUEST['query_args']['order'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no changes made to the site.
751                return $where;
752            }
753
754            $query_before = isset( $_REQUEST['query_before'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['query_before'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no changes made to the site.
755
756            if ( empty( $query_before ) ) {
757                return $where;
758            }
759
760            // Construct the date query using our timestamp
761            $clause = $wpdb->prepare( " AND {$wpdb->posts}.post_date <= %s", $query_before );
762
763            /**
764             * Filter Infinite Scroll's SQL date query making sure post queries
765             * will always return results prior to (descending sort)
766             * or before (ascending sort) the last post date.
767             *
768             * @deprecated 14.0
769             *
770             * @module infinite-scroll
771             *
772             * @param string $clause SQL Date query.
773             * @param object $query Query.
774             * @param string $operator @deprecated Query operator.
775             * @param string $last_post_date @deprecated Last Post Date timestamp.
776             */
777            $operator       = '<';
778            $last_post_date = isset( $_REQUEST['last_post_date'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['last_post_date'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no changes to the site
779            $where         .= apply_filters_deprecated( 'infinite_scroll_posts_where', array( $clause, $query, $operator, $last_post_date ), '14.0', '' );
780        }
781
782        return $where;
783    }
784
785    /**
786     * Let's overwrite the default post_per_page setting to always display a fixed amount.
787     *
788     * @param object $query - the query.
789     * @uses is_admin, self::archive_supports_infinity, self::get_settings
790     */
791    public function posts_per_page_query( $query ) {
792        if ( ! is_admin() && self::archive_supports_infinity() && $query->is_main_query() ) {
793            $query->set( 'posts_per_page', self::posts_per_page() );
794        }
795    }
796
797    /**
798     * Check if the IS output should be wrapped in a div.
799     * Setting value can be a boolean or a string specifying the class applied to the div.
800     *
801     * @uses self::get_settings
802     * @return bool
803     */
804    public function has_wrapper() {
805        return (bool) self::get_settings()->wrapper;
806    }
807
808    /**
809     * Returns the Ajax url
810     *
811     * @global $wp
812     * @uses home_url, add_query_arg, apply_filters
813     * @return string
814     */
815    public function ajax_url() {
816        $base_url = set_url_scheme( home_url( '/' ) );
817
818        $ajaxurl = add_query_arg( array( 'infinity' => 'scrolling' ), $base_url );
819
820        /**
821         * Filter the Infinite Scroll Ajax URL.
822         *
823         * @module infinite-scroll
824         *
825         * @since 2.0.0
826         *
827         * @param string $ajaxurl Infinite Scroll Ajax URL.
828         */
829        return apply_filters( 'infinite_scroll_ajax_url', $ajaxurl );
830    }
831
832    /**
833     * Our own Ajax response, avoiding calling admin-ajax
834     */
835    public function ajax_response() {
836        // Only proceed if the url query has a key of "Infinity"
837        if ( ! self::got_infinity() ) {
838            return false;
839        }
840
841        // This should already be defined below, but make sure.
842        if ( ! defined( 'DOING_AJAX' ) ) {
843            define( 'DOING_AJAX', true );
844        }
845
846        @header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
847        send_nosniff_header();
848
849        /**
850         * Fires at the end of the Infinite Scroll Ajax response.
851         *
852         * @module infinite-scroll
853         *
854         * @since 2.0.0
855         */
856        do_action( 'custom_ajax_infinite_scroll' );
857        die( '0' );
858    }
859
860    /**
861     * Alias for renamed class method.
862     *
863     * Previously, JS settings object was unnecessarily output in the document head.
864     * When the hook was changed, the method name no longer made sense.
865     */
866    public function action_wp_head() {
867        $this->action_wp_footer_settings();
868    }
869
870    /**
871     * Prints the relevant infinite scroll settings in JS.
872     *
873     * @global $wp_rewrite
874     * @uses self::get_settings, esc_js, esc_url_raw, self::has_wrapper, __, apply_filters, do_action, self::get_query_vars
875     * @action wp_footer
876     */
877    public function action_wp_footer_settings() {
878        global $wp_rewrite;
879        global $currentday;
880
881        $settings = self::get_settings();
882
883        // Default click handle text
884        $click_handle_text = __( 'Older posts', 'jetpack' );
885
886        // If a single CPT is displayed, use its plural name instead of "posts"
887        // Could be empty (posts) or an array of multiple post types.
888        // In the latter two cases cases, the default text is used, leaving the `infinite_scroll_js_settings` filter for further customization.
889        $post_type = self::wp_query()->get( 'post_type' );
890
891        // If it's a taxonomy, try to change the button text.
892        if ( is_tax() ) {
893            // Get current taxonomy slug.
894            $taxonomy_slug = self::wp_query()->get( 'taxonomy' );
895
896            // Get taxonomy settings.
897            $taxonomy = get_taxonomy( $taxonomy_slug );
898
899            // Check if the taxonomy is attached to one post type only and use its plural name.
900            // If not, use "Posts" without confusing the users.
901            if (
902                $taxonomy instanceof \WP_Taxonomy
903                && is_countable( $taxonomy->object_type )
904                && ! empty( $taxonomy->object_type )
905                && count( $taxonomy->object_type ) < 2
906            ) {
907                // It seems [0] doesn't work, as sometimes plugins can deregister a taxonomy but not reindex.
908                $post_type = reset( $taxonomy->object_type );
909            }
910        }
911
912        if ( is_string( $post_type ) && ! empty( $post_type ) ) {
913            $post_type = get_post_type_object( $post_type );
914
915            if ( is_object( $post_type ) && ! is_wp_error( $post_type ) ) {
916                if ( isset( $post_type->labels->name ) ) {
917                    $cpt_text = $post_type->labels->name;
918                } elseif ( isset( $post_type->label ) ) {
919                    $cpt_text = $post_type->label;
920                }
921
922                if ( isset( $cpt_text ) ) {
923                    /* translators: %s is the name of a custom post type */
924                    $click_handle_text = sprintf( __( 'More %s', 'jetpack' ), $cpt_text );
925                    unset( $cpt_text );
926                }
927            }
928        }
929
930        unset( $post_type );
931
932        // Base JS settings
933        $js_settings = array(
934            'id'               => $settings->container,
935            'ajaxurl'          => esc_url_raw( self::ajax_url() ),
936            'type'             => esc_js( $settings->type ),
937            'wrapper'          => self::has_wrapper(),
938            'wrapper_class'    => is_string( $settings->wrapper ) ? esc_js( $settings->wrapper ) : 'infinite-wrap',
939            'footer'           => is_string( $settings->footer ) ? esc_js( $settings->footer ) : $settings->footer,
940            'click_handle'     => esc_js( $settings->click_handle ),
941            'text'             => $click_handle_text,
942            'totop'            => __( 'Scroll back to top', 'jetpack' ),
943            'currentday'       => $currentday,
944            'order'            => 'DESC',
945            'scripts'          => array(),
946            'styles'           => array(),
947            'google_analytics' => false,
948            'offset'           => max( 1, self::wp_query()->get( 'paged' ) ), // Pass through the current page so we can use that to offset the first load.
949            'history'          => array(
950                'host'                 => preg_replace( '#^http(s)?://#i', '', untrailingslashit( esc_url( get_home_url() ) ) ),
951                'path'                 => self::get_request_path(),
952                'use_trailing_slashes' => $wp_rewrite->use_trailing_slashes,
953                'parameters'           => self::get_request_parameters(),
954            ),
955            'query_args'       => self::get_query_vars(),
956            'query_before'     => current_time( 'mysql' ),
957            'last_post_date'   => self::get_last_post_date(),
958            'body_class'       => self::body_class(),
959            'loading_text'     => __( 'Loading new page', 'jetpack' ),
960        );
961
962        // Optional order param
963        if ( isset( $_REQUEST['order'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no changes made to the site.
964            $order = strtoupper( sanitize_text_field( wp_unslash( $_REQUEST['order'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no changes made to the site.
965
966            if ( in_array( $order, array( 'ASC', 'DESC' ), true ) ) {
967                $js_settings['order'] = $order;
968            }
969        }
970
971        /**
972         * Filter the Infinite Scroll JS settings outputted in the head.
973         *
974         * @module infinite-scroll
975         *
976         * @since 2.0.0
977         *
978         * @param array $js_settings Infinite Scroll JS settings.
979         */
980        $js_settings = apply_filters( 'infinite_scroll_js_settings', $js_settings );
981
982        /**
983         * Fires before Infinite Scroll outputs inline JavaScript in the head.
984         *
985         * @module infinite-scroll
986         *
987         * @since 2.0.0
988         */
989        do_action( 'infinite_scroll_wp_head' );
990
991        ?>
992        <script type="text/javascript">
993        var infiniteScroll = <?php echo wp_json_encode( array( 'settings' => $js_settings ), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?>;
994        </script>
995        <?php
996    }
997
998    // phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
999
1000    /**
1001     * Build path data for current request.
1002     * Used for Google Analytics and pushState history tracking.
1003     *
1004     * @global $wp_rewrite
1005     * @global $wp
1006     * @uses user_trailingslashit, sanitize_text_field, add_query_arg
1007     * @return string|bool
1008     */
1009    private function get_request_path() {
1010        global $wp_rewrite;
1011
1012        if ( $wp_rewrite->using_permalinks() ) {
1013            global $wp;
1014
1015            // If called too early, bail
1016            if ( ! isset( $wp->request ) ) {
1017                return false;
1018            }
1019
1020            // Determine path for paginated version of current request
1021            if ( preg_match( '#' . preg_quote( $wp_rewrite->pagination_base, '#' ) . '/\d+/?$#i', $wp->request ) ) {
1022                $path = preg_replace( '#' . preg_quote( $wp_rewrite->pagination_base, '#' ) . '/\d+$#i', $wp_rewrite->pagination_base . '/%d', $wp->request );
1023            } else {
1024                $path = $wp->request . '/' . $wp_rewrite->pagination_base . '/%d';
1025            }
1026
1027            // Slashes everywhere we need them
1028            if ( ! str_starts_with( $path, '/' ) ) {
1029                $path = '/' . $path;
1030            }
1031
1032            $path = user_trailingslashit( $path );
1033        } else {
1034            // Clean up raw $_REQUEST input
1035            $path = array_map( 'sanitize_text_field', wp_unslash( $_REQUEST ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- seems this is used for Google Analytics and browser history tracking.
1036            $path = array_filter( $path );
1037
1038            $path['paged'] = '%d';
1039
1040            $path = add_query_arg( $path, '/' );
1041        }
1042
1043        return empty( $path ) ? false : $path;
1044    }
1045
1046    /**
1047     * Return query string for current request, prefixed with '?'.
1048     *
1049     * @return string
1050     */
1051    private function get_request_parameters() {
1052        $uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
1053        $uri = preg_replace( '/^[^?]*(\?.*$)/', '$1', $uri, 1, $count );
1054        if ( $count !== 1 ) {
1055            return '';
1056        }
1057        return $uri;
1058    }
1059
1060    /**
1061     * Get the markup for styles printed since the initial page load.
1062     *
1063     * @since $$next-version$$
1064     *
1065     * @param WP_Styles $wp_styles      Styles registry.
1066     * @param string[]  $initial_styles Handles already present on the page.
1067     * @return array[] List of arrays with `handle` and `html` keys, plus `src` and `media` for stylesheet files.
1068     */
1069    public static function get_new_styles( $wp_styles, array $initial_styles ) {
1070        $styles    = array();
1071        $do_concat = $wp_styles->do_concat;
1072
1073        $wp_styles->do_concat = false;
1074        foreach ( array_unique( $wp_styles->done ) as $handle ) {
1075            $is_on_page = in_array( $handle, $initial_styles, true );
1076            if ( $is_on_page && ! self::is_per_request_style( $handle ) ) {
1077                continue;
1078            }
1079
1080            ob_start();
1081            $wp_styles->do_item( $handle );
1082            $html = ob_get_clean();
1083
1084            if ( '' === trim( $html ) ) {
1085                continue;
1086            }
1087
1088            // The page already has a tag with this ID, so drop it to keep IDs unique.
1089            if ( $is_on_page ) {
1090                $html = preg_replace( '/(<style\b[^>]*?)\s+id=([\'"])[^\'"]*\2/i', '$1', $html );
1091            }
1092
1093            $style = array(
1094                'handle' => $handle,
1095                'html'   => $html,
1096            );
1097
1098            $registered = $wp_styles->registered[ $handle ];
1099            if ( is_string( $registered->src ) && '' !== $registered->src ) {
1100                $ver            = null === $registered->ver ? '' : ( $registered->ver ? $registered->ver : $wp_styles->default_version );
1101                $style['src']   = wp_specialchars_decode( $wp_styles->_css_href( $registered->src, $ver, $handle ), ENT_QUOTES );
1102                $style['media'] = $registered->args ? $registered->args : 'all';
1103            }
1104
1105            $styles[] = $style;
1106        }
1107        $wp_styles->do_concat = $do_concat;
1108
1109        // `global-styles` is already on the page, so send the theme.json CSS of blocks it does not cover yet.
1110        if ( in_array( 'global-styles', $initial_styles, true ) ) {
1111            $block_css = self::get_theme_json_css_for_blocks( array_diff( $wp_styles->done, $initial_styles ) );
1112            if ( '' !== $block_css ) {
1113                $styles[] = array(
1114                    'handle' => 'global-styles',
1115                    'html'   => "<style>\n" . $block_css . "\n</style>\n",
1116                );
1117            }
1118        }
1119
1120        return $styles;
1121    }
1122
1123    /**
1124     * Get the theme.json styles of core blocks whose stylesheets are in the given handles.
1125     *
1126     * Core adds these to `global-styles` only for core blocks rendered in the same request.
1127     *
1128     * @see wp_add_global_styles_for_blocks()
1129     * @since $$next-version$$
1130     *
1131     * @param string[] $handles Style handles new to the page.
1132     * @return string CSS.
1133     */
1134    private static function get_theme_json_css_for_blocks( array $handles ) {
1135        $tree = WP_Theme_JSON_Resolver::resolve_theme_file_uris( WP_Theme_JSON_Resolver::get_merged_data() );
1136        $css  = '';
1137
1138        foreach ( $tree->get_styles_block_nodes() as $metadata ) {
1139            if ( isset( $metadata['name'] ) ) {
1140                $block_name = $metadata['name'];
1141            } else {
1142                $block_name = empty( $metadata['path'] ) ? '' : wp_get_block_name_from_theme_json_path( $metadata['path'] );
1143            }
1144
1145            if (
1146                is_string( $block_name )
1147                && str_starts_with( $block_name, 'core/' )
1148                && in_array( 'wp-block-' . substr( $block_name, 5 ), $handles, true )
1149            ) {
1150                $css .= $tree->get_styles_for_block( $metadata );
1151            }
1152        }
1153
1154        return $css;
1155    }
1156
1157    /**
1158     * Whether a style's handle stays the same while its inline CSS is rebuilt for each request's blocks.
1159     *
1160     * @since $$next-version$$
1161     *
1162     * @param string $handle Style handle.
1163     * @return bool
1164     */
1165    private static function is_per_request_style( $handle ) {
1166        return 'block-style-variation-styles' === $handle
1167            || str_starts_with( $handle, 'core-block-supports' )
1168            || str_starts_with( $handle, 'wp-style-engine-' );
1169    }
1170
1171    /**
1172     * Point the printed markup of entries whose `src` a filter rewrote at the new URL.
1173     *
1174     * @since $$next-version$$
1175     *
1176     * @param array $styles    Filtered style entries.
1177     * @param array $generated Entries as built by get_new_styles().
1178     * @return array
1179     */
1180    private static function prefer_rewritten_src( $styles, array $generated ) {
1181        $generated_src = array_column( $generated, 'src', 'handle' );
1182
1183        foreach ( $styles as $i => $style ) {
1184            if (
1185                isset( $style['handle'] )
1186                && isset( $style['html'] )
1187                && isset( $style['src'] )
1188                && isset( $generated_src[ $style['handle'] ] )
1189                && $style['src'] !== $generated_src[ $style['handle'] ]
1190            ) {
1191                // Swap the URL in the printed tag so the handle's inline CSS still loads.
1192                $html = str_replace( esc_url( $generated_src[ $style['handle'] ] ), esc_url( $style['src'] ), $style['html'], $count );
1193                if ( $count ) {
1194                    $styles[ $i ]['html'] = $html;
1195                } else {
1196                    unset( $styles[ $i ]['html'] );
1197                }
1198            }
1199        }
1200
1201        return $styles;
1202    }
1203
1204    /**
1205     * Provide IS with a list of the scripts and stylesheets already present on the page.
1206     * Since posts may contain require additional assets that haven't been loaded, this data will be used to track the additional assets.
1207     *
1208     * @global $wp_scripts, $wp_styles
1209     * @action wp_footer
1210     */
1211    public function action_wp_footer() {
1212        global $wp_scripts, $wp_styles;
1213
1214        $scripts = $wp_scripts instanceof \WP_Scripts ? $wp_scripts->done : array();
1215        /**
1216         * Filter the list of scripts already present on the page.
1217         *
1218         * @module infinite-scroll
1219         *
1220         * @since 2.1.2
1221         *
1222         * @param array $scripts Array of scripts present on the page.
1223         */
1224        $scripts = apply_filters( 'infinite_scroll_existing_scripts', $scripts );
1225
1226        $styles = $wp_styles instanceof \WP_Styles ? $wp_styles->done : array();
1227        /**
1228         * Filter the list of styles already present on the page.
1229         *
1230         * @module infinite-scroll
1231         *
1232         * @since 2.1.2
1233         *
1234         * @param array $styles Array of styles present on the page.
1235         */
1236        $styles = apply_filters( 'infinite_scroll_existing_stylesheets', $styles );
1237
1238        ?>
1239        <script type="text/javascript">
1240            (function() {
1241                var extend = function(out) {
1242                    out = out || {};
1243
1244                    for (var i = 1; i < arguments.length; i++) {
1245                        if (!arguments[i])
1246                        continue;
1247
1248                        for (var key in arguments[i]) {
1249                        if (arguments[i].hasOwnProperty(key))
1250                            out[key] = arguments[i][key];
1251                        }
1252                    }
1253
1254                    return out;
1255                };
1256                extend( window.infiniteScroll.settings.scripts, <?php echo wp_json_encode( $scripts, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?> );
1257                extend( window.infiniteScroll.settings.styles, <?php echo wp_json_encode( $styles, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?> );
1258            })();
1259        </script>
1260        <?php
1261        $aria_live = 'assertive';
1262        if ( 'scroll' === self::get_settings()->type ) {
1263            $aria_live = 'polite';
1264        }
1265        ?>
1266        <span id="infinite-aria" aria-live="<?php echo esc_attr( $aria_live ); ?>"></span>
1267        <?php
1268    }
1269
1270    /**
1271     * Identify additional scripts required by the latest set of IS posts and provide the necessary data to the IS response handler.
1272     *
1273     * @param array $results - the results.
1274     * @param array $query_args - Array of Query arguments.
1275     * @param array $wp_query - the WP query.
1276     * @global $wp_scripts
1277     * @uses sanitize_text_field, add_query_arg
1278     * @filter infinite_scroll_results
1279     * @return array
1280     */
1281    public function filter_infinite_scroll_results( $results, $query_args, $wp_query ) {
1282        // Don't bother unless there are posts to display
1283        if ( 'success' !== $results['type'] ) {
1284            return $results;
1285        }
1286
1287        // Parse and sanitize the script handles already output
1288        $initial_scripts = isset( $_REQUEST['scripts'] ) && is_array( $_REQUEST['scripts'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_REQUEST['scripts'] ) ) : false; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no site changes made.
1289
1290        if ( is_array( $initial_scripts ) ) {
1291            global $wp_scripts;
1292
1293            // Identify new scripts needed by the latest set of IS posts
1294            $new_scripts = array_filter(
1295                $wp_scripts->done,
1296                function ( $script_name ) use ( $initial_scripts ) {
1297                    // Jetpack block scripts should always be sent, even if they've been
1298                    // sent before. These scripts only run once on when loaded, they don't
1299                    // watch for new blocks being added.
1300                    if ( str_starts_with( $script_name, 'jetpack-block-' ) ) {
1301                        return true;
1302                    }
1303
1304                    return ! in_array( $script_name, $initial_scripts, true );
1305                }
1306            );
1307
1308            // If new scripts are needed, extract relevant data from $wp_scripts
1309            if ( ! empty( $new_scripts ) ) {
1310                $results['scripts'] = array();
1311
1312                foreach ( $new_scripts as $handle ) {
1313                    // Abort if somehow the handle doesn't correspond to a registered script
1314                    // or if the script doesn't have `src` set.
1315                    $script_not_registered = ! isset( $wp_scripts->registered[ $handle ] );
1316                    $empty_src             = empty( $wp_scripts->registered[ $handle ]->src );
1317                    if ( $script_not_registered || $empty_src ) {
1318                        continue;
1319                    }
1320
1321                    $before_handle = $wp_scripts->get_inline_script_data( $handle, 'before' );
1322                    $after_handle  = $wp_scripts->get_inline_script_data( $handle, 'after' );
1323
1324                    // Provide basic script data
1325                    $script_data = array(
1326                        'handle'        => $handle,
1327                        'footer'        => ( is_array( $wp_scripts->in_footer ) && in_array( $handle, $wp_scripts->in_footer, true ) ),
1328                        'extra_data'    => $wp_scripts->print_extra_script( $handle, false ),
1329                        'before_handle' => $before_handle,
1330                        'after_handle'  => $after_handle,
1331                    );
1332
1333                    // Base source
1334                    $src = $wp_scripts->registered[ $handle ]->src;
1335
1336                    // Take base_url into account
1337                    if ( strpos( $src, 'http' ) !== 0 ) {
1338                        $src = $wp_scripts->base_url . $src;
1339                    }
1340
1341                    // Version and additional arguments
1342                    if ( null === $wp_scripts->registered[ $handle ]->ver ) {
1343                        $ver = '';
1344                    } else {
1345                        $ver = $wp_scripts->registered[ $handle ]->ver ? $wp_scripts->registered[ $handle ]->ver : $wp_scripts->default_version;
1346                    }
1347
1348                    if ( isset( $wp_scripts->args[ $handle ] ) ) {
1349                        $ver = $ver ? $ver . '&amp;' . $wp_scripts->args[ $handle ] : $wp_scripts->args[ $handle ];
1350                    }
1351
1352                    // Full script source with version info
1353                    $script_data['src'] = add_query_arg( 'ver', $ver, $src );
1354
1355                    // Add script to data that will be returned to IS JS
1356                    array_push( $results['scripts'], $script_data );
1357                }
1358            }
1359        }
1360
1361        // Expose additional script data to filters, but only include in final `$results` array if needed.
1362        if ( ! isset( $results['scripts'] ) ) {
1363            $results['scripts'] = array();
1364        }
1365
1366        /**
1367         * Filter the additional scripts required by the latest set of IS posts.
1368         *
1369         * @module infinite-scroll
1370         *
1371         * @since 2.1.2
1372         *
1373         * @param array $results['scripts'] Additional scripts required by the latest set of IS posts.
1374         * @param array|bool $initial_scripts Set of scripts loaded on each page.
1375         * @param array $results Array of Infinite Scroll results.
1376         * @param array $query_args Array of Query arguments.
1377         * @param WP_Query $wp_query WP Query.
1378         */
1379        $results['scripts'] = apply_filters(
1380            'infinite_scroll_additional_scripts',
1381            $results['scripts'],
1382            $initial_scripts,
1383            $results,
1384            $query_args,
1385            $wp_query
1386        );
1387
1388        if ( empty( $results['scripts'] ) ) {
1389            unset( $results['scripts'] );
1390        }
1391
1392        // Parse and sanitize the style handles already output
1393        $initial_styles = isset( $_REQUEST['styles'] ) && is_array( $_REQUEST['styles'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_REQUEST['styles'] ) ) : false; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1394
1395        if ( is_array( $initial_styles ) ) {
1396            global $wp_styles;
1397
1398            $results['styles'] = self::get_new_styles( $wp_styles, $initial_styles );
1399        }
1400
1401        // Expose additional stylesheet data to filters, but only include in final `$results` array if needed.
1402        if ( ! isset( $results['styles'] ) ) {
1403            $results['styles'] = array();
1404        }
1405
1406        $generated_styles = $results['styles'];
1407
1408        /**
1409         * Filter the additional styles required by the latest set of IS posts.
1410         *
1411         * @module infinite-scroll
1412         *
1413         * @since 2.1.2
1414         *
1415         * @param array $results['styles'] Additional styles required by the latest set of IS posts.
1416         *                                 Each entry has `handle`, plus `html` (printed tags) and/or `src` and `media`.
1417         *                                 The client inserts `html` when present; rewriting `src` makes it load that URL instead.
1418         *                                 Entries with the IE-only `conditional` key are skipped.
1419         * @param array|bool $initial_styles Set of styles loaded on each page.
1420         * @param array $results Array of Infinite Scroll results.
1421         * @param array $query_args Array of Query arguments.
1422         * @param WP_Query $wp_query WP Query.
1423         */
1424        $results['styles'] = apply_filters(
1425            'infinite_scroll_additional_stylesheets',
1426            $results['styles'],
1427            $initial_styles,
1428            $results,
1429            $query_args,
1430            $wp_query
1431        );
1432
1433        if ( is_array( $results['styles'] ) ) {
1434            $results['styles'] = self::prefer_rewritten_src( $results['styles'], $generated_styles );
1435        }
1436
1437        if ( empty( $results['styles'] ) ) {
1438            unset( $results['styles'] );
1439        }
1440
1441        // Lastly, return the IS results array
1442        return $results;
1443    }
1444
1445    /**
1446     * Runs the query and returns the results via JSON.
1447     * Triggered by an AJAX request.
1448     *
1449     * @global $wp_query
1450     * @global $wp_the_query
1451     * @uses current_theme_supports, get_option, self::wp_query, current_user_can, apply_filters, self::get_settings, add_filter, WP_Query, remove_filter, have_posts, wp_head, do_action, add_action, this::render, this::has_wrapper, esc_attr, wp_footer, sharing_register_post_for_share_counts, get_the_id
1452     */
1453    public function query() {
1454        if ( ! isset( $_REQUEST['page'] ) || ! current_theme_supports( 'infinite-scroll' ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no changes to the site.
1455            die( 0 );
1456        }
1457
1458        // @todo see if we should validate this nonce since we use it to form a query.
1459        $page = (int) $_REQUEST['page']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- we're casting this to an int and not making changes to the site.
1460
1461        // Sanitize and set $previousday. Expected format: dd.mm.yy
1462        if ( isset( $_REQUEST['currentday'] ) && is_string( $_REQUEST['currentday'] ) && preg_match( '/^\d{2}\.\d{2}\.\d{2}$/', $_REQUEST['currentday'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput, WordPress.Security.NonceVerification.Recommended -- manually validating, no changes to site
1463            global $previousday;
1464            $previousday = $_REQUEST['currentday']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput
1465        }
1466
1467        $post_status = array( 'publish' );
1468        if ( current_user_can( 'read_private_posts' ) ) {
1469            array_push( $post_status, 'private' );
1470        }
1471
1472        $order = isset( $_REQUEST['order'] ) && in_array( $_REQUEST['order'], array( 'ASC', 'DESC' ), true ) ? sanitize_text_field( wp_unslash( $_REQUEST['order'] ) ) : 'DESC'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no changes made to the site.
1473
1474        $query_args = array_merge(
1475            self::wp_query()->query_vars,
1476            array(
1477                'paged'          => $page,
1478                'post_status'    => $post_status,
1479                'posts_per_page' => self::posts_per_page(),
1480                'order'          => $order,
1481            )
1482        );
1483
1484        // 4.0 ?s= compatibility, see https://core.trac.wordpress.org/ticket/11330#comment:50
1485        if ( empty( $query_args['s'] ) && ! isset( self::wp_query()->query['s'] ) ) {
1486            unset( $query_args['s'] );
1487        }
1488
1489        // By default, don't query for a specific page of a paged post object.
1490        // This argument can come from merging self::wp_query() into $query_args above.
1491        // Since IS is only used on archives, we should always display the first page of any paged content.
1492        unset( $query_args['page'] );
1493
1494        /**
1495         * Filter the array of main query arguments.
1496         *
1497         * @module infinite-scroll
1498         *
1499         * @since 2.0.1
1500         *
1501         * @param array $query_args Array of Query arguments.
1502         */
1503        $query_args = apply_filters( 'infinite_scroll_query_args', $query_args );
1504
1505        add_filter( 'posts_where', array( $this, 'query_time_filter' ), 10, 2 );
1506
1507        $infinite_scroll_query   = new WP_Query();
1508        $GLOBALS['wp_the_query'] = $infinite_scroll_query;
1509        $GLOBALS['wp_query']     = $infinite_scroll_query;
1510
1511        $infinite_scroll_query->query( $query_args );
1512
1513        remove_filter( 'posts_where', array( $this, 'query_time_filter' ), 10 );
1514
1515        $results = array();
1516
1517        if ( have_posts() ) {
1518            // Fire wp_head to ensure that all necessary scripts are enqueued. Output isn't used, but scripts are extracted in self::action_wp_footer.
1519            ob_start();
1520            wp_head();
1521            while ( ob_get_length() ) {
1522                ob_end_clean();
1523            }
1524
1525            $results['type'] = 'success';
1526
1527            /**
1528             * Fires when rendering Infinite Scroll posts.
1529             *
1530             * @module infinite-scroll
1531             *
1532             * @since 2.0.0
1533             */
1534            do_action( 'infinite_scroll_render' );
1535            $results['html'] = ob_get_clean();
1536            if ( empty( $results['html'] ) ) {
1537                /**
1538                 * Gather renderer callbacks. These will be called in order and allow multiple callbacks to be queued. Once content is found, no futher callbacks will run.
1539                 *
1540                 * @module infinite-scroll
1541                 *
1542                 * @since 6.0.0
1543                 */
1544                $callbacks = apply_filters(
1545                    'infinite_scroll_render_callbacks',
1546                    array( self::get_settings()->render ) // This is the setting callback e.g. from add theme support.
1547                );
1548
1549                // Append fallback callback. That rhymes.
1550                $callbacks[] = array( $this, 'render' );
1551
1552                foreach ( $callbacks as $callback ) {
1553                    if ( false !== $callback && is_callable( $callback ) ) {
1554                        rewind_posts();
1555                        ob_start();
1556
1557                        add_action( 'infinite_scroll_render', $callback );
1558
1559                        /**
1560                         * This action is already documented above.
1561                         * See https://github.com/Automattic/jetpack/pull/16317/
1562                         * for more details as to why it was introduced.
1563                         */
1564                        do_action( 'infinite_scroll_render' );
1565
1566                        // Fire wp_head to ensure that all necessary scripts are enqueued. Output isn't used, but scripts are extracted in self::action_wp_footer.
1567                        wp_head();
1568
1569                        $results['html'] = ob_get_clean();
1570                        remove_action( 'infinite_scroll_render', $callback );
1571                    }
1572                    if ( ! empty( $results['html'] ) ) {
1573                        break;
1574                    }
1575                }
1576            }
1577
1578            // If primary and fallback rendering methods fail, prevent further IS rendering attempts. Otherwise, wrap the output if requested.
1579            if ( empty( $results['html'] ) ) {
1580                unset( $results['html'] );
1581                /**
1582                 * Fires when Infinite Scoll doesn't render any posts.
1583                 *
1584                 * @module infinite-scroll
1585                 *
1586                 * @since 2.0.0
1587                 */
1588                do_action( 'infinite_scroll_empty' );
1589                $results['type'] = 'empty';
1590            } elseif ( $this->has_wrapper() ) {
1591                $wrapper_classes  = is_string( self::get_settings()->wrapper ) ? self::get_settings()->wrapper : 'infinite-wrap';
1592                $wrapper_classes .= ' infinite-view-' . $page;
1593                $wrapper_classes  = trim( $wrapper_classes );
1594                $aria_label       = sprintf(
1595                    /* translators: %1$s is the page count */
1596                    __( 'Page: %1$d.', 'jetpack' ),
1597                    $page
1598                );
1599
1600                $results['html'] = '<div class="' . esc_attr( $wrapper_classes ) . '" id="infinite-view-' . $page . '" data-page-num="' . $page . '" role="region" aria-label="' . esc_attr( $aria_label ) . '">' . $results['html'] . '</div>';
1601            }
1602
1603            // Fire wp_footer to ensure that all necessary scripts are enqueued. Output isn't used, but scripts are extracted in self::action_wp_footer.
1604            ob_start();
1605            wp_footer();
1606            while ( ob_get_length() ) {
1607                ob_end_clean();
1608            }
1609
1610            if ( 'success' === $results['type'] ) {
1611                global $currentday;
1612                $results['lastbatch']  = self::is_last_batch();
1613                $results['currentday'] = $currentday;
1614            }
1615
1616            // Loop through posts to capture sharing data for new posts loaded via Infinite Scroll
1617            if ( 'success' === $results['type'] && function_exists( 'sharing_register_post_for_share_counts' ) ) {
1618                global $jetpack_sharing_counts;
1619
1620                while ( have_posts() ) {
1621                    the_post();
1622
1623                    sharing_register_post_for_share_counts( get_the_ID() );
1624                }
1625
1626                // If sharing counts are not initialized for any reason, we initialize them here.
1627                if ( ! is_array( $jetpack_sharing_counts ) ) {
1628                    $jetpack_sharing_counts = array();
1629                } else {
1630                    // Filter out non-string and non-integer values to avoid warnings with array_flip.
1631                    $flippable_jetpack_sharing_counts = array_filter(
1632                        $jetpack_sharing_counts,
1633                        function ( $value ) {
1634                            return is_string( $value ) || is_int( $value );
1635                        }
1636                    );
1637                }
1638
1639                $results['postflair'] = array_flip( $flippable_jetpack_sharing_counts ?? array() );
1640            }
1641        } else {
1642            /** This action is already documented in modules/infinite-scroll/infinity.php */
1643            do_action( 'infinite_scroll_empty' );
1644            $results['type'] = 'empty';
1645        }
1646
1647        wp_send_json(
1648            /**
1649             * Filter the Infinite Scroll results.
1650             *
1651             * @module infinite-scroll
1652             *
1653             * @since 2.0.0
1654             *
1655             * @param array $results Array of Infinite Scroll results.
1656             * @param array $query_args Array of main query arguments.
1657             * @param WP_Query $wp_query WP Query.
1658             */
1659            apply_filters( 'infinite_scroll_results', $results, $query_args, self::wp_query() ),
1660            null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
1661            JSON_UNESCAPED_SLASHES
1662        );
1663    }
1664
1665    /**
1666     * Update the $allowed_vars array with the standard WP public and private
1667     * query vars, as well as taxonomy vars
1668     *
1669     * @global $wp
1670     * @param array $allowed_vars - the allowed variables array.
1671     * @filter infinite_scroll_allowed_vars
1672     * @return array
1673     */
1674    public function allowed_query_vars( $allowed_vars ) {
1675        global $wp;
1676
1677        $allowed_vars += $wp->public_query_vars;
1678        $allowed_vars += $wp->private_query_vars;
1679        $allowed_vars += $this->get_taxonomy_vars();
1680
1681        foreach ( array_keys( $allowed_vars, 'paged', true ) as $key ) {
1682            unset( $allowed_vars[ $key ] );
1683        }
1684
1685        return array_unique( $allowed_vars );
1686    }
1687
1688    /**
1689     * Returns an array of stock and custom taxonomy query vars
1690     *
1691     * @global $wp_taxonomies
1692     * @return array
1693     */
1694    public function get_taxonomy_vars() {
1695        global $wp_taxonomies;
1696
1697        $taxonomy_vars = array();
1698        foreach ( $wp_taxonomies as $t ) {
1699            if ( $t->query_var ) {
1700                $taxonomy_vars[] = $t->query_var;
1701            }
1702        }
1703
1704        // still needed?
1705        $taxonomy_vars[] = 'tag_id';
1706
1707        return $taxonomy_vars;
1708    }
1709
1710    /**
1711     * Update the $query_args array with the parameters provided via AJAX/GET.
1712     *
1713     * @param array $query_args - the query args.
1714     * @filter infinite_scroll_query_args
1715     * @return array
1716     */
1717    public function inject_query_args( $query_args ) {
1718        /**
1719         * Filter the array of allowed Infinite Scroll query arguments.
1720         *
1721         * @module infinite-scroll
1722         *
1723         * @since 2.6.0
1724         *
1725         * @param array $args Array of allowed Infinite Scroll query arguments.
1726         * @param array $query_args Array of query arguments.
1727         */
1728        $allowed_vars = apply_filters( 'infinite_scroll_allowed_vars', array(), $query_args );
1729
1730        $query_args = array_merge(
1731            $query_args,
1732            array(
1733                'suppress_filters' => false,
1734            )
1735        );
1736
1737        if ( isset( $_REQUEST['query_args'] ) && is_array( $_REQUEST['query_args'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no site changes.
1738            foreach ( wp_unslash( $_REQUEST['query_args'] ) as $var => $value ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- no site changes, sanitized below.
1739                if ( ! in_array( $var, $allowed_vars, true ) || empty( $value ) ) {
1740                    continue;
1741                }
1742
1743                if ( 'post_type' === $var && ! self::is_queryable_post_type( $value ) ) {
1744                    continue;
1745                }
1746
1747                $query_args[ $var ] = filter_var( $value );
1748            }
1749        }
1750
1751        return $query_args;
1752    }
1753
1754    /**
1755     * Whether a post type supplied with the request may be queried on the front end.
1756     *
1757     * Core applies this test to the main query in WP::parse_request(), but the
1758     * Infinite Scroll query is a secondary one and never passes through it.
1759     *
1760     * @param mixed $post_type Post type name, or array of names, from the request.
1761     * @return bool
1762     */
1763    private static function is_queryable_post_type( $post_type ) {
1764        // WP_Query expands 'any' to the types that opted into search results.
1765        if ( 'any' === $post_type ) {
1766            return true;
1767        }
1768
1769        foreach ( (array) $post_type as $type ) {
1770            if ( ! is_string( $type ) || ! is_post_type_viewable( $type ) ) {
1771                return false;
1772            }
1773        }
1774
1775        return true;
1776    }
1777
1778    /**
1779     * Rendering fallback used when themes don't specify their own handler.
1780     *
1781     * @uses have_posts, the_post, get_template_part, get_post_format
1782     * @action infinite_scroll_render
1783     */
1784    public function render() {
1785        while ( have_posts() ) {
1786            the_post();
1787
1788            get_template_part( 'content', get_post_format() );
1789        }
1790    }
1791
1792    /**
1793     * Allow plugins to filter what archives Infinite Scroll supports
1794     *
1795     * @uses current_theme_supports, is_home, is_archive, apply_filters, self::get_settings
1796     * @return bool
1797     */
1798    public static function archive_supports_infinity() {
1799        $supported = current_theme_supports( 'infinite-scroll' ) && ( is_home() || is_archive() || is_search() );
1800
1801        // Disable when previewing a non-active theme in the customizer
1802        if ( is_customize_preview() && ! $GLOBALS['wp_customize']->is_theme_active() ) {
1803            return false;
1804        }
1805
1806        /**
1807         * Allow plugins to filter what archives Infinite Scroll supports.
1808         *
1809         * @module infinite-scroll
1810         *
1811         * @since 2.0.0
1812         *
1813         * @param bool $supported Does the Archive page support Infinite Scroll.
1814         * @param object self::get_settings() IS settings provided by theme.
1815         */
1816        return (bool) apply_filters( 'infinite_scroll_archive_supported', $supported, self::get_settings() );
1817    }
1818
1819    /**
1820     * The Infinite Blog Footer
1821     *
1822     * @uses self::get_settings, self::archive_supports_infinity, self::default_footer
1823     * @return string or null
1824     */
1825    public function footer() {
1826        if ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() ) {
1827            return;
1828        }
1829
1830        $settings = self::get_settings();
1831
1832        // Bail if theme requested footer not show
1833        if ( false === $settings->footer ) {
1834            return;
1835        }
1836
1837        // We only need the new footer for the 'scroll' type
1838        if ( 'scroll' !== $settings->type || ! self::archive_supports_infinity() ) {
1839            return;
1840        }
1841
1842        if ( self::is_last_batch() ) {
1843            return;
1844        }
1845
1846        // Display a footer, either user-specified or a default
1847        if ( false !== $settings->footer_callback && is_callable( $settings->footer_callback ) ) {
1848            call_user_func( $settings->footer_callback, $settings );
1849        } else {
1850            self::default_footer();
1851        }
1852    }
1853
1854    /**
1855     * Render default IS footer
1856     *
1857     * @uses __, wp_get_theme, apply_filters, home_url, esc_attr, get_bloginfo, bloginfo
1858     */
1859    private function default_footer() {
1860        if ( '' !== get_privacy_policy_url() ) {
1861            $credits = get_the_privacy_policy_link() . '<span role="separator" aria-hidden="true"> / </span>';
1862        } else {
1863            $credits = '';
1864        }
1865        $credits .= sprintf(
1866            '<a href="https://wordpress.org/" rel="noopener noreferrer" target="_blank" rel="generator">%1$s</a> ',
1867            __( 'Proudly powered by WordPress', 'jetpack' )
1868        );
1869        $credits .= sprintf(
1870            /* translators: %1$s is the name of a theme */
1871            __( 'Theme: %1$s.', 'jetpack' ),
1872            wp_get_theme()->Name
1873        );
1874        /**
1875         * Filter Infinite Scroll's credit text.
1876         *
1877         * @module infinite-scroll
1878         *
1879         * @since 2.0.0
1880         *
1881         * @param string $credits Infinite Scroll credits.
1882         */
1883        $credits = apply_filters( 'infinite_scroll_credit', $credits );
1884
1885        ?>
1886        <div id="infinite-footer">
1887            <div class="container">
1888                <div class="blog-info">
1889                    <a id="infinity-blog-title" href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
1890                        <?php bloginfo( 'name' ); ?>
1891                    </a>
1892                </div>
1893                <div class="blog-credits">
1894                    <?php echo $credits; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
1895                </div>
1896            </div>
1897        </div><!-- #infinite-footer -->
1898        <?php
1899    }
1900
1901    /**
1902     * Ensure that IS doesn't interfere with Grunion by stripping IS query arguments from the Grunion redirect URL.
1903     * When arguments are present, Grunion redirects to the IS AJAX endpoint.
1904     *
1905     * @param string $url - the Grunion redirect URL.
1906     * @uses remove_query_arg
1907     * @filter grunion_contact_form_redirect_url
1908     * @return string
1909     */
1910    public function filter_grunion_redirect_url( $url ) {
1911        // Remove IS query args, if present
1912        if ( str_contains( $url, 'infinity=scrolling' ) ) {
1913            $url = remove_query_arg(
1914                array(
1915                    'infinity',
1916                    'action',
1917                    'page',
1918                    'order',
1919                    'scripts',
1920                    'styles',
1921                ),
1922                $url
1923            );
1924        }
1925
1926        return $url;
1927    }
1928
1929    /**
1930     * When the MediaElement is loaded in dynamically, we need to enforce that
1931     * its settings are added to the page as well.
1932     *
1933     * @param array $scripts_data New scripts exposed to the infinite scroll.
1934     *
1935     * @since 8.4.0
1936     */
1937    public function add_mejs_config( $scripts_data ) {
1938        foreach ( $scripts_data as $key => $data ) {
1939            if ( 'mediaelement-core' === $data['handle'] ) {
1940                $mejs_settings = array(
1941                    'pluginPath'  => includes_url( 'js/mediaelement/', 'relative' ),
1942                    'classPrefix' => 'mejs-',
1943                    'stretching'  => 'responsive',
1944                );
1945
1946                $scripts_data[ $key ]['extra_data'] = sprintf(
1947                    'window.%s = %s',
1948                    '_wpmejsSettings',
1949                    wp_json_encode( apply_filters( 'mejs_settings', $mejs_settings ), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP )
1950                );
1951            }
1952        }
1953        return $scripts_data;
1954    }
1955
1956    /**
1957     * Determines whether the legacy AMP Reader post templates are being used.
1958     *
1959     * @return bool
1960     */
1961    private function is_exempted_amp_page() {
1962        if ( is_singular( 'web-story' ) ) {
1963            // Ensure that <amp-next-page> is not injected after <amp-story> as generated by the Web Stories plugin.
1964            return true;
1965        }
1966        if ( function_exists( 'amp_is_legacy' ) ) {
1967            // Available since AMP v2.0, this will return false if a theme like Twenty Twenty is selected as the Reader theme.
1968            return amp_is_legacy();
1969        }
1970        if ( method_exists( 'AMP_Options_Manager', 'get_option' ) ) {
1971            // In versions prior to v2.0, checking the template mode as being 'reader' is sufficient.
1972            return 'reader' === AMP_Options_Manager::get_option( 'theme_support' );
1973        }
1974        return false;
1975    }
1976
1977    /**
1978     * Load AMP specific hooks.
1979     *
1980     * @return void
1981     */
1982    public function amp_load_hooks() {
1983        if ( $this->is_exempted_amp_page() ) {
1984            return;
1985        }
1986
1987        if ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() ) {
1988            $template = self::get_settings()->render;
1989
1990            add_filter( 'jetpack_infinite_scroll_load_scripts_and_styles', '__return_false' );
1991
1992            add_action( 'template_redirect', array( $this, 'amp_start_output_buffering' ), 0 );
1993            add_action( 'shutdown', array( $this, 'amp_output_buffer' ), 1 );
1994
1995            if ( is_string( $template ) && strpos( $template, '::' ) === false && is_callable( "amp_{$template}_hooks" ) ) {
1996                call_user_func( "amp_{$template}_hooks" );
1997            }
1998
1999            // Warms up the amp next page markup.
2000            // This should be done outside the output buffering callback started in the template_redirect.
2001            $this->amp_get_footer_template();
2002        }
2003    }
2004
2005    /**
2006     * Start the AMP output buffering.
2007     *
2008     * @return void
2009     */
2010    public function amp_start_output_buffering() {
2011        ob_start( array( $this, 'amp_finish_output_buffering' ) );
2012    }
2013
2014    /**
2015     * Flush the AMP output buffer.
2016     *
2017     * @return void
2018     */
2019    public function amp_output_buffer() {
2020        if ( ob_get_contents() ) {
2021            ob_end_flush();
2022        }
2023    }
2024
2025    /**
2026     * Filter the AMP output buffer contents.
2027     *
2028     * @param string $buffer Contents of the output buffer.
2029     *
2030     * @return string|false
2031     */
2032    public function amp_finish_output_buffering( $buffer ) {
2033        // Hide WordPress admin bar on next page load.
2034        $buffer = preg_replace(
2035            '/id="wpadminbar"/',
2036            '$0 next-page-hide',
2037            $buffer
2038        );
2039
2040        /**
2041         * Get the theme footers.
2042         *
2043         * @module infinite-scroll
2044         *
2045         * @since 9.0.0
2046         *
2047         * @param array  array() An array to store multiple markup entries to be added to the footer.
2048         * @param string $buffer The contents of the output buffer.
2049         */
2050        $footers = apply_filters( 'jetpack_amp_infinite_footers', array(), $buffer );
2051
2052        /**
2053         * Filter the output buffer.
2054         * Themes can leverage this hook to add custom markup on next page load.
2055         *
2056         * @module infinite-scroll
2057         *
2058         * @since 9.0.0
2059         *
2060         * @param string $buffer The contents of the output buffer.
2061         */
2062        $buffer = apply_filters( 'jetpack_amp_infinite_output', $buffer );
2063
2064        // Add the amp next page markup.
2065        $buffer = preg_replace(
2066            '~</body>~',
2067            $this->amp_get_footer_template( $footers ) . '$0',
2068            $buffer
2069        );
2070
2071        return $buffer;
2072    }
2073
2074    /**
2075     * Get AMP next page markup with the custom footers.
2076     *
2077     * @param string[] $footers The theme footers.
2078     *
2079     * @return string
2080     */
2081    protected function amp_get_footer_template( $footers = array() ) {
2082        static $template = null;
2083
2084        if ( null === $template ) {
2085            $template = $this->amp_footer_template();
2086        }
2087
2088        if ( empty( $footers ) ) {
2089            return $template;
2090        }
2091
2092        return preg_replace(
2093            '/%%footer%%/',
2094            implode( '', $footers ),
2095            $template
2096        );
2097    }
2098
2099    /**
2100     * AMP Next Page markup.
2101     *
2102     * @return string
2103     */
2104    protected function amp_footer_template() {
2105        ob_start();
2106        ?>
2107<amp-next-page max-pages="<?php echo esc_attr( static::amp_get_max_pages() ); ?>">
2108    <script type="application/json">
2109        [
2110            <?php echo wp_json_encode( $this->amp_next_page(), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?>
2111        ]
2112    </script>
2113    <div separator>
2114        <?php
2115        echo wp_kses_post(
2116            /**
2117             * AMP infinite scroll separator.
2118             *
2119             * @module infinite-scroll
2120             *
2121             * @since 9.0.0
2122             *
2123             * @param string '' The markup for the next page separator.
2124             */
2125            apply_filters( 'jetpack_amp_infinite_separator', '' )
2126        );
2127        ?>
2128    </div>
2129    <div recommendation-box class="recommendation-box">
2130        <template type="amp-mustache">
2131            {{#pages}}
2132            <?php
2133            echo wp_kses_post(
2134                /**
2135                 * AMP infinite scroll older posts markup.
2136                 *
2137                 * @module infinite-scroll
2138                 *
2139                 * @since 9.0.0
2140                 *
2141                 * @param string '' The markup for the older posts/next page.
2142                 */
2143                apply_filters( 'jetpack_amp_infinite_older_posts', '' )
2144            );
2145            ?>
2146            {{/pages}}
2147        </template>
2148    </div>
2149    <div footer>
2150        %%footer%%
2151    </div>
2152</amp-next-page>
2153        <?php
2154        return ob_get_clean();
2155    }
2156
2157    /**
2158     * Get the AMP next page information.
2159     *
2160     * @return array
2161     */
2162    protected function amp_next_page() {
2163        $title = '';
2164        $url   = '';
2165        $image = '';
2166
2167        if ( ! static::amp_is_last_page() ) {
2168            $title = sprintf(
2169                '%s - %s %d - %s',
2170                wp_title( '', false ),
2171                __( 'Page', 'jetpack' ),
2172                max( get_query_var( 'paged', 1 ), 1 ) + 1,
2173                get_bloginfo( 'name' )
2174            );
2175            $url   = get_next_posts_page_link();
2176        }
2177
2178        $next_page = array(
2179            'title' => $title,
2180            'url'   => $url,
2181            'image' => $image,
2182        );
2183
2184        /**
2185         * The next page settings.
2186         * An array containing:
2187         *  - title => The title to be featured on the browser tab.
2188         *  - url   => The URL of next page.
2189         *  - image => The image URL. A required AMP setting, not in use currently. Themes are welcome to leverage.
2190         *
2191         * @module infinite-scroll
2192         *
2193         * @since 9.0.0
2194         *
2195         * @param array $next_page The contents of the output buffer.
2196         */
2197        return apply_filters( 'jetpack_amp_infinite_next_page_data', $next_page );
2198    }
2199
2200    /**
2201     * Get the number of pages left.
2202     *
2203     * @return int
2204     */
2205    protected static function amp_get_max_pages() {
2206        global $wp_query;
2207
2208        return (int) $wp_query->max_num_pages - (int) $wp_query->query_vars['paged'];
2209    }
2210
2211    /**
2212     * Is the last page.
2213     *
2214     * @return bool
2215     */
2216    protected static function amp_is_last_page() {
2217        return 0 === static::amp_get_max_pages();
2218    }
2219}
2220
2221/**
2222 * Initialize The_Neverending_Home_Page
2223 */
2224function the_neverending_home_page_init() {
2225    if ( ! current_theme_supports( 'infinite-scroll' ) ) {
2226        return;
2227    }
2228
2229    new The_Neverending_Home_Page();
2230}
2231add_action( 'init', 'the_neverending_home_page_init', 20 );
2232
2233/**
2234 * Check whether the current theme is infinite-scroll aware.
2235 * If so, include the files which add theme support.
2236 */
2237function the_neverending_home_page_theme_support() {
2238    if (
2239            defined( 'IS_WPCOM' ) && IS_WPCOM &&
2240            defined( 'REST_API_REQUEST' ) && REST_API_REQUEST &&
2241            ! doing_action( 'restapi_theme_after_setup_theme' )
2242    ) {
2243        // Don't source theme compat files until we're in the site's context
2244        return;
2245    }
2246    $theme_name = get_stylesheet();
2247
2248    /**
2249     * Filter the path to the Infinite Scroll compatibility file.
2250     *
2251     * @module infinite-scroll
2252     *
2253     * @since 2.0.0
2254     *
2255     * @param string $str IS compatibility file path.
2256     * @param string $theme_name Theme name.
2257     */
2258    $customization_file = apply_filters( 'infinite_scroll_customization_file', __DIR__ . "/themes/{$theme_name}.php", $theme_name );
2259
2260    if ( is_readable( $customization_file ) ) {
2261        require_once $customization_file;
2262    }
2263}
2264add_action( 'after_setup_theme', 'the_neverending_home_page_theme_support', 5 );
2265
2266/**
2267 * Early accommodation of the Infinite Scroll AJAX request
2268 */
2269if ( The_Neverending_Home_Page::got_infinity() ) {
2270    /**
2271     * If we're sure this is an AJAX request (i.e. the HTTP_X_REQUESTED_WITH header says so),
2272     * indicate it as early as possible for actions like init
2273     */
2274    if ( ! defined( 'DOING_AJAX' ) &&
2275        isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) &&
2276        strtoupper( sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ) ) === 'XMLHTTPREQUEST'
2277    ) {
2278        define( 'DOING_AJAX', true );
2279    }
2280
2281    // Don't load the admin bar when doing the AJAX response.
2282    show_admin_bar( false );
2283}