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