Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
24.01% covered (danger)
24.01%
201 / 837
17.54% covered (danger)
17.54%
10 / 57
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
24.63% covered (danger)
24.63%
201 / 816
18.18% covered (danger)
18.18%
10 / 55
43610.15
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
 do_footer_and_get_duotone_svgs
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
5
 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 / 93
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     * Fire wp_footer, discarding its output except the duotone SVG filters the rendered blocks use.
1138     *
1139     * Block CSS points at these filters with `url(#id)`, so the page needs them alongside the posts.
1140     *
1141     * @since $$next-version$$
1142     *
1143     * @return string SVG markup, or an empty string.
1144     */
1145    public static function do_footer_and_get_duotone_svgs() {
1146        $svgs    = '';
1147        $swapped = array();
1148
1149        // The Gutenberg plugin replaces core's class with its own.
1150        foreach ( array( 'WP_Duotone', 'WP_Duotone_Gutenberg' ) as $class ) {
1151            $callback = array( $class, 'output_footer_assets' );
1152            $priority = has_action( 'wp_footer', $callback );
1153            if ( false === $priority ) {
1154                continue;
1155            }
1156
1157            $capture = static function () use ( $callback, &$svgs ) {
1158                ob_start();
1159                call_user_func( $callback );
1160                $svgs .= ob_get_clean();
1161            };
1162            remove_action( 'wp_footer', $callback, $priority );
1163            add_action( 'wp_footer', $capture, $priority );
1164            $swapped[] = array( $callback, $capture, $priority );
1165        }
1166
1167        $level = ob_get_level();
1168        ob_start();
1169        wp_footer();
1170        while ( ob_get_level() > $level ) {
1171            ob_end_clean();
1172        }
1173
1174        foreach ( $swapped as list( $callback, $capture, $priority ) ) {
1175            remove_action( 'wp_footer', $capture, $priority );
1176            add_action( 'wp_footer', $callback, $priority );
1177        }
1178
1179        return trim( $svgs );
1180    }
1181
1182    /**
1183     * Get the theme.json styles of core blocks whose stylesheets are in the given handles.
1184     *
1185     * Core adds these to `global-styles` only for core blocks rendered in the same request.
1186     *
1187     * @see wp_add_global_styles_for_blocks()
1188     * @since 16.5
1189     *
1190     * @param string[] $handles Style handles new to the page.
1191     * @return string CSS.
1192     */
1193    private static function get_theme_json_css_for_blocks( array $handles ) {
1194        $tree = WP_Theme_JSON_Resolver::resolve_theme_file_uris( WP_Theme_JSON_Resolver::get_merged_data() );
1195        $css  = '';
1196
1197        foreach ( $tree->get_styles_block_nodes() as $metadata ) {
1198            if ( isset( $metadata['name'] ) ) {
1199                $block_name = $metadata['name'];
1200            } else {
1201                $block_name = empty( $metadata['path'] ) ? '' : wp_get_block_name_from_theme_json_path( $metadata['path'] );
1202            }
1203
1204            if (
1205                is_string( $block_name )
1206                && str_starts_with( $block_name, 'core/' )
1207                && in_array( 'wp-block-' . substr( $block_name, 5 ), $handles, true )
1208            ) {
1209                $css .= $tree->get_styles_for_block( $metadata );
1210            }
1211        }
1212
1213        return $css;
1214    }
1215
1216    /**
1217     * Whether a style's handle stays the same while its inline CSS is rebuilt for each request's blocks.
1218     *
1219     * @since 16.5
1220     *
1221     * @param string $handle Style handle.
1222     * @return bool
1223     */
1224    private static function is_per_request_style( $handle ) {
1225        return 'block-style-variation-styles' === $handle
1226            || str_starts_with( $handle, 'core-block-supports' )
1227            || str_starts_with( $handle, 'wp-style-engine-' );
1228    }
1229
1230    /**
1231     * Point the printed markup of entries whose `src` a filter rewrote at the new URL.
1232     *
1233     * @since 16.5
1234     *
1235     * @param array $styles    Filtered style entries.
1236     * @param array $generated Entries as built by get_new_styles().
1237     * @return array
1238     */
1239    private static function prefer_rewritten_src( $styles, array $generated ) {
1240        $generated_src = array_column( $generated, 'src', 'handle' );
1241
1242        foreach ( $styles as $i => $style ) {
1243            if (
1244                isset( $style['handle'] )
1245                && isset( $style['html'] )
1246                && isset( $style['src'] )
1247                && isset( $generated_src[ $style['handle'] ] )
1248                && $style['src'] !== $generated_src[ $style['handle'] ]
1249            ) {
1250                // Swap the URL in the printed tag so the handle's inline CSS still loads.
1251                $html = str_replace( esc_url( $generated_src[ $style['handle'] ] ), esc_url( $style['src'] ), $style['html'], $count );
1252                if ( $count ) {
1253                    $styles[ $i ]['html'] = $html;
1254                } else {
1255                    unset( $styles[ $i ]['html'] );
1256                }
1257            }
1258        }
1259
1260        return $styles;
1261    }
1262
1263    /**
1264     * Provide IS with a list of the scripts and stylesheets already present on the page.
1265     * Since posts may contain require additional assets that haven't been loaded, this data will be used to track the additional assets.
1266     *
1267     * @global $wp_scripts, $wp_styles
1268     * @action wp_footer
1269     */
1270    public function action_wp_footer() {
1271        global $wp_scripts, $wp_styles;
1272
1273        $scripts = $wp_scripts instanceof \WP_Scripts ? $wp_scripts->done : array();
1274        /**
1275         * Filter the list of scripts already present on the page.
1276         *
1277         * @module infinite-scroll
1278         *
1279         * @since 2.1.2
1280         *
1281         * @param array $scripts Array of scripts present on the page.
1282         */
1283        $scripts = apply_filters( 'infinite_scroll_existing_scripts', $scripts );
1284
1285        $styles = $wp_styles instanceof \WP_Styles ? $wp_styles->done : array();
1286        /**
1287         * Filter the list of styles already present on the page.
1288         *
1289         * @module infinite-scroll
1290         *
1291         * @since 2.1.2
1292         *
1293         * @param array $styles Array of styles present on the page.
1294         */
1295        $styles = apply_filters( 'infinite_scroll_existing_stylesheets', $styles );
1296
1297        ?>
1298        <script type="text/javascript">
1299            (function() {
1300                var extend = function(out) {
1301                    out = out || {};
1302
1303                    for (var i = 1; i < arguments.length; i++) {
1304                        if (!arguments[i])
1305                        continue;
1306
1307                        for (var key in arguments[i]) {
1308                        if (arguments[i].hasOwnProperty(key))
1309                            out[key] = arguments[i][key];
1310                        }
1311                    }
1312
1313                    return out;
1314                };
1315                extend( window.infiniteScroll.settings.scripts, <?php echo wp_json_encode( $scripts, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?> );
1316                extend( window.infiniteScroll.settings.styles, <?php echo wp_json_encode( $styles, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?> );
1317            })();
1318        </script>
1319        <?php
1320        $aria_live = 'assertive';
1321        if ( 'scroll' === self::get_settings()->type ) {
1322            $aria_live = 'polite';
1323        }
1324        ?>
1325        <span id="infinite-aria" aria-live="<?php echo esc_attr( $aria_live ); ?>"></span>
1326        <?php
1327    }
1328
1329    /**
1330     * Identify additional scripts required by the latest set of IS posts and provide the necessary data to the IS response handler.
1331     *
1332     * @param array $results - the results.
1333     * @param array $query_args - Array of Query arguments.
1334     * @param array $wp_query - the WP query.
1335     * @global $wp_scripts
1336     * @uses sanitize_text_field, add_query_arg
1337     * @filter infinite_scroll_results
1338     * @return array
1339     */
1340    public function filter_infinite_scroll_results( $results, $query_args, $wp_query ) {
1341        // Don't bother unless there are posts to display
1342        if ( 'success' !== $results['type'] ) {
1343            return $results;
1344        }
1345
1346        // Parse and sanitize the script handles already output
1347        $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.
1348
1349        if ( is_array( $initial_scripts ) ) {
1350            global $wp_scripts;
1351
1352            // Identify new scripts needed by the latest set of IS posts
1353            $new_scripts = array_filter(
1354                $wp_scripts->done,
1355                function ( $script_name ) use ( $initial_scripts ) {
1356                    // Jetpack block scripts should always be sent, even if they've been
1357                    // sent before. These scripts only run once on when loaded, they don't
1358                    // watch for new blocks being added.
1359                    if ( str_starts_with( $script_name, 'jetpack-block-' ) ) {
1360                        return true;
1361                    }
1362
1363                    return ! in_array( $script_name, $initial_scripts, true );
1364                }
1365            );
1366
1367            // If new scripts are needed, extract relevant data from $wp_scripts
1368            if ( ! empty( $new_scripts ) ) {
1369                $results['scripts'] = array();
1370
1371                foreach ( $new_scripts as $handle ) {
1372                    // Abort if somehow the handle doesn't correspond to a registered script
1373                    // or if the script doesn't have `src` set.
1374                    $script_not_registered = ! isset( $wp_scripts->registered[ $handle ] );
1375                    $empty_src             = empty( $wp_scripts->registered[ $handle ]->src );
1376                    if ( $script_not_registered || $empty_src ) {
1377                        continue;
1378                    }
1379
1380                    $before_handle = $wp_scripts->get_inline_script_data( $handle, 'before' );
1381                    $after_handle  = $wp_scripts->get_inline_script_data( $handle, 'after' );
1382
1383                    // Provide basic script data
1384                    $script_data = array(
1385                        'handle'        => $handle,
1386                        'footer'        => ( is_array( $wp_scripts->in_footer ) && in_array( $handle, $wp_scripts->in_footer, true ) ),
1387                        'extra_data'    => $wp_scripts->print_extra_script( $handle, false ),
1388                        'before_handle' => $before_handle,
1389                        'after_handle'  => $after_handle,
1390                    );
1391
1392                    // Base source
1393                    $src = $wp_scripts->registered[ $handle ]->src;
1394
1395                    // Take base_url into account
1396                    if ( strpos( $src, 'http' ) !== 0 ) {
1397                        $src = $wp_scripts->base_url . $src;
1398                    }
1399
1400                    // Version and additional arguments
1401                    if ( null === $wp_scripts->registered[ $handle ]->ver ) {
1402                        $ver = '';
1403                    } else {
1404                        $ver = $wp_scripts->registered[ $handle ]->ver ? $wp_scripts->registered[ $handle ]->ver : $wp_scripts->default_version;
1405                    }
1406
1407                    if ( isset( $wp_scripts->args[ $handle ] ) ) {
1408                        $ver = $ver ? $ver . '&amp;' . $wp_scripts->args[ $handle ] : $wp_scripts->args[ $handle ];
1409                    }
1410
1411                    // Full script source with version info
1412                    $script_data['src'] = add_query_arg( 'ver', $ver, $src );
1413
1414                    // Add script to data that will be returned to IS JS
1415                    array_push( $results['scripts'], $script_data );
1416                }
1417            }
1418        }
1419
1420        // Expose additional script data to filters, but only include in final `$results` array if needed.
1421        if ( ! isset( $results['scripts'] ) ) {
1422            $results['scripts'] = array();
1423        }
1424
1425        /**
1426         * Filter the additional scripts required by the latest set of IS posts.
1427         *
1428         * @module infinite-scroll
1429         *
1430         * @since 2.1.2
1431         *
1432         * @param array $results['scripts'] Additional scripts required by the latest set of IS posts.
1433         * @param array|bool $initial_scripts Set of scripts loaded on each page.
1434         * @param array $results Array of Infinite Scroll results.
1435         * @param array $query_args Array of Query arguments.
1436         * @param WP_Query $wp_query WP Query.
1437         */
1438        $results['scripts'] = apply_filters(
1439            'infinite_scroll_additional_scripts',
1440            $results['scripts'],
1441            $initial_scripts,
1442            $results,
1443            $query_args,
1444            $wp_query
1445        );
1446
1447        if ( empty( $results['scripts'] ) ) {
1448            unset( $results['scripts'] );
1449        }
1450
1451        // Parse and sanitize the style handles already output
1452        $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
1453
1454        if ( is_array( $initial_styles ) ) {
1455            global $wp_styles;
1456
1457            $results['styles'] = self::get_new_styles( $wp_styles, $initial_styles );
1458        }
1459
1460        // Expose additional stylesheet data to filters, but only include in final `$results` array if needed.
1461        if ( ! isset( $results['styles'] ) ) {
1462            $results['styles'] = array();
1463        }
1464
1465        $generated_styles = $results['styles'];
1466
1467        /**
1468         * Filter the additional styles required by the latest set of IS posts.
1469         *
1470         * @module infinite-scroll
1471         *
1472         * @since 2.1.2
1473         *
1474         * @param array $results['styles'] Additional styles required by the latest set of IS posts.
1475         *                                 Each entry has `handle`, plus `html` (printed tags) and/or `src` and `media`.
1476         *                                 The client inserts `html` when present; rewriting `src` makes it load that URL instead.
1477         *                                 Entries with the IE-only `conditional` key are skipped.
1478         * @param array|bool $initial_styles Set of styles loaded on each page.
1479         * @param array $results Array of Infinite Scroll results.
1480         * @param array $query_args Array of Query arguments.
1481         * @param WP_Query $wp_query WP Query.
1482         */
1483        $results['styles'] = apply_filters(
1484            'infinite_scroll_additional_stylesheets',
1485            $results['styles'],
1486            $initial_styles,
1487            $results,
1488            $query_args,
1489            $wp_query
1490        );
1491
1492        if ( is_array( $results['styles'] ) ) {
1493            $results['styles'] = self::prefer_rewritten_src( $results['styles'], $generated_styles );
1494        }
1495
1496        if ( empty( $results['styles'] ) ) {
1497            unset( $results['styles'] );
1498        }
1499
1500        // Lastly, return the IS results array
1501        return $results;
1502    }
1503
1504    /**
1505     * Runs the query and returns the results via JSON.
1506     * Triggered by an AJAX request.
1507     *
1508     * @global $wp_query
1509     * @global $wp_the_query
1510     * @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
1511     */
1512    public function query() {
1513        if ( ! isset( $_REQUEST['page'] ) || ! current_theme_supports( 'infinite-scroll' ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no changes to the site.
1514            die( 0 );
1515        }
1516
1517        // @todo see if we should validate this nonce since we use it to form a query.
1518        $page = (int) $_REQUEST['page']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- we're casting this to an int and not making changes to the site.
1519
1520        // Sanitize and set $previousday. Expected format: dd.mm.yy
1521        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
1522            global $previousday;
1523            $previousday = $_REQUEST['currentday']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput
1524        }
1525
1526        $post_status = array( 'publish' );
1527        if ( current_user_can( 'read_private_posts' ) ) {
1528            array_push( $post_status, 'private' );
1529        }
1530
1531        $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.
1532
1533        $query_args = array_merge(
1534            self::wp_query()->query_vars,
1535            array(
1536                'paged'          => $page,
1537                'post_status'    => $post_status,
1538                'posts_per_page' => self::posts_per_page(),
1539                'order'          => $order,
1540            )
1541        );
1542
1543        // 4.0 ?s= compatibility, see https://core.trac.wordpress.org/ticket/11330#comment:50
1544        if ( empty( $query_args['s'] ) && ! isset( self::wp_query()->query['s'] ) ) {
1545            unset( $query_args['s'] );
1546        }
1547
1548        // By default, don't query for a specific page of a paged post object.
1549        // This argument can come from merging self::wp_query() into $query_args above.
1550        // Since IS is only used on archives, we should always display the first page of any paged content.
1551        unset( $query_args['page'] );
1552
1553        /**
1554         * Filter the array of main query arguments.
1555         *
1556         * @module infinite-scroll
1557         *
1558         * @since 2.0.1
1559         *
1560         * @param array $query_args Array of Query arguments.
1561         */
1562        $query_args = apply_filters( 'infinite_scroll_query_args', $query_args );
1563
1564        add_filter( 'posts_where', array( $this, 'query_time_filter' ), 10, 2 );
1565
1566        $infinite_scroll_query   = new WP_Query();
1567        $GLOBALS['wp_the_query'] = $infinite_scroll_query;
1568        $GLOBALS['wp_query']     = $infinite_scroll_query;
1569
1570        $infinite_scroll_query->query( $query_args );
1571
1572        remove_filter( 'posts_where', array( $this, 'query_time_filter' ), 10 );
1573
1574        $results = array();
1575
1576        if ( have_posts() ) {
1577            // Fire wp_head to ensure that all necessary scripts are enqueued. Output isn't used, but scripts are extracted in self::action_wp_footer.
1578            ob_start();
1579            wp_head();
1580            while ( ob_get_length() ) {
1581                ob_end_clean();
1582            }
1583
1584            $results['type'] = 'success';
1585
1586            /**
1587             * Fires when rendering Infinite Scroll posts.
1588             *
1589             * @module infinite-scroll
1590             *
1591             * @since 2.0.0
1592             */
1593            do_action( 'infinite_scroll_render' );
1594            $results['html'] = ob_get_clean();
1595            if ( empty( $results['html'] ) ) {
1596                /**
1597                 * 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.
1598                 *
1599                 * @module infinite-scroll
1600                 *
1601                 * @since 6.0.0
1602                 */
1603                $callbacks = apply_filters(
1604                    'infinite_scroll_render_callbacks',
1605                    array( self::get_settings()->render ) // This is the setting callback e.g. from add theme support.
1606                );
1607
1608                // Append fallback callback. That rhymes.
1609                $callbacks[] = array( $this, 'render' );
1610
1611                foreach ( $callbacks as $callback ) {
1612                    if ( false !== $callback && is_callable( $callback ) ) {
1613                        rewind_posts();
1614                        ob_start();
1615
1616                        add_action( 'infinite_scroll_render', $callback );
1617
1618                        /**
1619                         * This action is already documented above.
1620                         * See https://github.com/Automattic/jetpack/pull/16317/
1621                         * for more details as to why it was introduced.
1622                         */
1623                        do_action( 'infinite_scroll_render' );
1624
1625                        // Fire wp_head to ensure that all necessary scripts are enqueued. Output isn't used, but scripts are extracted in self::action_wp_footer.
1626                        wp_head();
1627
1628                        $results['html'] = ob_get_clean();
1629                        remove_action( 'infinite_scroll_render', $callback );
1630                    }
1631                    if ( ! empty( $results['html'] ) ) {
1632                        break;
1633                    }
1634                }
1635            }
1636
1637            // If primary and fallback rendering methods fail, prevent further IS rendering attempts. Otherwise, wrap the output if requested.
1638            if ( empty( $results['html'] ) ) {
1639                unset( $results['html'] );
1640                /**
1641                 * Fires when Infinite Scoll doesn't render any posts.
1642                 *
1643                 * @module infinite-scroll
1644                 *
1645                 * @since 2.0.0
1646                 */
1647                do_action( 'infinite_scroll_empty' );
1648                $results['type'] = 'empty';
1649            } elseif ( $this->has_wrapper() ) {
1650                $wrapper_classes  = is_string( self::get_settings()->wrapper ) ? self::get_settings()->wrapper : 'infinite-wrap';
1651                $wrapper_classes .= ' infinite-view-' . $page;
1652                $wrapper_classes  = trim( $wrapper_classes );
1653                $aria_label       = sprintf(
1654                    /* translators: %1$s is the page count */
1655                    __( 'Page: %1$d.', 'jetpack' ),
1656                    $page
1657                );
1658
1659                $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>';
1660            }
1661
1662            // Fire wp_footer so scripts are enqueued (extracted in self::action_wp_footer); only the duotone SVG filters are kept.
1663            $svg_filters = self::do_footer_and_get_duotone_svgs();
1664
1665            if ( 'success' === $results['type'] ) {
1666                global $currentday;
1667                $results['lastbatch']  = self::is_last_batch();
1668                $results['currentday'] = $currentday;
1669
1670                if ( '' !== $svg_filters ) {
1671                    $results['svg_filters'] = $svg_filters;
1672                }
1673            }
1674
1675            // Loop through posts to capture sharing data for new posts loaded via Infinite Scroll
1676            if ( 'success' === $results['type'] && function_exists( 'sharing_register_post_for_share_counts' ) ) {
1677                global $jetpack_sharing_counts;
1678
1679                while ( have_posts() ) {
1680                    the_post();
1681
1682                    sharing_register_post_for_share_counts( get_the_ID() );
1683                }
1684
1685                // If sharing counts are not initialized for any reason, we initialize them here.
1686                if ( ! is_array( $jetpack_sharing_counts ) ) {
1687                    $jetpack_sharing_counts = array();
1688                } else {
1689                    // Filter out non-string and non-integer values to avoid warnings with array_flip.
1690                    $flippable_jetpack_sharing_counts = array_filter(
1691                        $jetpack_sharing_counts,
1692                        function ( $value ) {
1693                            return is_string( $value ) || is_int( $value );
1694                        }
1695                    );
1696                }
1697
1698                $results['postflair'] = array_flip( $flippable_jetpack_sharing_counts ?? array() );
1699            }
1700        } else {
1701            /** This action is already documented in modules/infinite-scroll/infinity.php */
1702            do_action( 'infinite_scroll_empty' );
1703            $results['type'] = 'empty';
1704        }
1705
1706        wp_send_json(
1707            /**
1708             * Filter the Infinite Scroll results.
1709             *
1710             * @module infinite-scroll
1711             *
1712             * @since 2.0.0
1713             *
1714             * @param array $results Array of Infinite Scroll results.
1715             * @param array $query_args Array of main query arguments.
1716             * @param WP_Query $wp_query WP Query.
1717             */
1718            apply_filters( 'infinite_scroll_results', $results, $query_args, self::wp_query() ),
1719            null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
1720            JSON_UNESCAPED_SLASHES
1721        );
1722    }
1723
1724    /**
1725     * Update the $allowed_vars array with the standard WP public and private
1726     * query vars, as well as taxonomy vars
1727     *
1728     * @global $wp
1729     * @param array $allowed_vars - the allowed variables array.
1730     * @filter infinite_scroll_allowed_vars
1731     * @return array
1732     */
1733    public function allowed_query_vars( $allowed_vars ) {
1734        global $wp;
1735
1736        $allowed_vars += $wp->public_query_vars;
1737        $allowed_vars += $wp->private_query_vars;
1738        $allowed_vars += $this->get_taxonomy_vars();
1739
1740        foreach ( array_keys( $allowed_vars, 'paged', true ) as $key ) {
1741            unset( $allowed_vars[ $key ] );
1742        }
1743
1744        return array_unique( $allowed_vars );
1745    }
1746
1747    /**
1748     * Returns an array of stock and custom taxonomy query vars
1749     *
1750     * @global $wp_taxonomies
1751     * @return array
1752     */
1753    public function get_taxonomy_vars() {
1754        global $wp_taxonomies;
1755
1756        $taxonomy_vars = array();
1757        foreach ( $wp_taxonomies as $t ) {
1758            if ( $t->query_var ) {
1759                $taxonomy_vars[] = $t->query_var;
1760            }
1761        }
1762
1763        // still needed?
1764        $taxonomy_vars[] = 'tag_id';
1765
1766        return $taxonomy_vars;
1767    }
1768
1769    /**
1770     * Update the $query_args array with the parameters provided via AJAX/GET.
1771     *
1772     * @param array $query_args - the query args.
1773     * @filter infinite_scroll_query_args
1774     * @return array
1775     */
1776    public function inject_query_args( $query_args ) {
1777        /**
1778         * Filter the array of allowed Infinite Scroll query arguments.
1779         *
1780         * @module infinite-scroll
1781         *
1782         * @since 2.6.0
1783         *
1784         * @param array $args Array of allowed Infinite Scroll query arguments.
1785         * @param array $query_args Array of query arguments.
1786         */
1787        $allowed_vars = apply_filters( 'infinite_scroll_allowed_vars', array(), $query_args );
1788
1789        $query_args = array_merge(
1790            $query_args,
1791            array(
1792                'suppress_filters' => false,
1793            )
1794        );
1795
1796        if ( isset( $_REQUEST['query_args'] ) && is_array( $_REQUEST['query_args'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no site changes.
1797            foreach ( wp_unslash( $_REQUEST['query_args'] ) as $var => $value ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- no site changes, sanitized below.
1798                if ( ! in_array( $var, $allowed_vars, true ) || empty( $value ) ) {
1799                    continue;
1800                }
1801
1802                if ( 'post_type' === $var && ! self::is_queryable_post_type( $value ) ) {
1803                    continue;
1804                }
1805
1806                $query_args[ $var ] = filter_var( $value );
1807            }
1808        }
1809
1810        return $query_args;
1811    }
1812
1813    /**
1814     * Whether a post type supplied with the request may be queried on the front end.
1815     *
1816     * Core applies this test to the main query in WP::parse_request(), but the
1817     * Infinite Scroll query is a secondary one and never passes through it.
1818     *
1819     * @param mixed $post_type Post type name, or array of names, from the request.
1820     * @return bool
1821     */
1822    private static function is_queryable_post_type( $post_type ) {
1823        // WP_Query expands 'any' to the types that opted into search results.
1824        if ( 'any' === $post_type ) {
1825            return true;
1826        }
1827
1828        foreach ( (array) $post_type as $type ) {
1829            if ( ! is_string( $type ) || ! is_post_type_viewable( $type ) ) {
1830                return false;
1831            }
1832        }
1833
1834        return true;
1835    }
1836
1837    /**
1838     * Rendering fallback used when themes don't specify their own handler.
1839     *
1840     * @uses have_posts, the_post, get_template_part, get_post_format
1841     * @action infinite_scroll_render
1842     */
1843    public function render() {
1844        while ( have_posts() ) {
1845            the_post();
1846
1847            get_template_part( 'content', get_post_format() );
1848        }
1849    }
1850
1851    /**
1852     * Allow plugins to filter what archives Infinite Scroll supports
1853     *
1854     * @uses current_theme_supports, is_home, is_archive, apply_filters, self::get_settings
1855     * @return bool
1856     */
1857    public static function archive_supports_infinity() {
1858        $supported = current_theme_supports( 'infinite-scroll' ) && ( is_home() || is_archive() || is_search() );
1859
1860        // Disable when previewing a non-active theme in the customizer
1861        if ( is_customize_preview() && ! $GLOBALS['wp_customize']->is_theme_active() ) {
1862            return false;
1863        }
1864
1865        /**
1866         * Allow plugins to filter what archives Infinite Scroll supports.
1867         *
1868         * @module infinite-scroll
1869         *
1870         * @since 2.0.0
1871         *
1872         * @param bool $supported Does the Archive page support Infinite Scroll.
1873         * @param object self::get_settings() IS settings provided by theme.
1874         */
1875        return (bool) apply_filters( 'infinite_scroll_archive_supported', $supported, self::get_settings() );
1876    }
1877
1878    /**
1879     * The Infinite Blog Footer
1880     *
1881     * @uses self::get_settings, self::archive_supports_infinity, self::default_footer
1882     * @return string or null
1883     */
1884    public function footer() {
1885        if ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() ) {
1886            return;
1887        }
1888
1889        $settings = self::get_settings();
1890
1891        // Bail if theme requested footer not show
1892        if ( false === $settings->footer ) {
1893            return;
1894        }
1895
1896        // We only need the new footer for the 'scroll' type
1897        if ( 'scroll' !== $settings->type || ! self::archive_supports_infinity() ) {
1898            return;
1899        }
1900
1901        if ( self::is_last_batch() ) {
1902            return;
1903        }
1904
1905        // Display a footer, either user-specified or a default
1906        if ( false !== $settings->footer_callback && is_callable( $settings->footer_callback ) ) {
1907            call_user_func( $settings->footer_callback, $settings );
1908        } else {
1909            self::default_footer();
1910        }
1911    }
1912
1913    /**
1914     * Render default IS footer
1915     *
1916     * @uses __, wp_get_theme, apply_filters, home_url, esc_attr, get_bloginfo, bloginfo
1917     */
1918    private function default_footer() {
1919        if ( '' !== get_privacy_policy_url() ) {
1920            $credits = get_the_privacy_policy_link() . '<span role="separator" aria-hidden="true"> / </span>';
1921        } else {
1922            $credits = '';
1923        }
1924        $credits .= sprintf(
1925            '<a href="https://wordpress.org/" rel="noopener noreferrer" target="_blank" rel="generator">%1$s</a> ',
1926            __( 'Proudly powered by WordPress', 'jetpack' )
1927        );
1928        $credits .= sprintf(
1929            /* translators: %1$s is the name of a theme */
1930            __( 'Theme: %1$s.', 'jetpack' ),
1931            wp_get_theme()->Name
1932        );
1933        /**
1934         * Filter Infinite Scroll's credit text.
1935         *
1936         * @module infinite-scroll
1937         *
1938         * @since 2.0.0
1939         *
1940         * @param string $credits Infinite Scroll credits.
1941         */
1942        $credits = apply_filters( 'infinite_scroll_credit', $credits );
1943
1944        ?>
1945        <div id="infinite-footer">
1946            <div class="container">
1947                <div class="blog-info">
1948                    <a id="infinity-blog-title" href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
1949                        <?php bloginfo( 'name' ); ?>
1950                    </a>
1951                </div>
1952                <div class="blog-credits">
1953                    <?php echo $credits; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
1954                </div>
1955            </div>
1956        </div><!-- #infinite-footer -->
1957        <?php
1958    }
1959
1960    /**
1961     * Ensure that IS doesn't interfere with Grunion by stripping IS query arguments from the Grunion redirect URL.
1962     * When arguments are present, Grunion redirects to the IS AJAX endpoint.
1963     *
1964     * @param string $url - the Grunion redirect URL.
1965     * @uses remove_query_arg
1966     * @filter grunion_contact_form_redirect_url
1967     * @return string
1968     */
1969    public function filter_grunion_redirect_url( $url ) {
1970        // Remove IS query args, if present
1971        if ( str_contains( $url, 'infinity=scrolling' ) ) {
1972            $url = remove_query_arg(
1973                array(
1974                    'infinity',
1975                    'action',
1976                    'page',
1977                    'order',
1978                    'scripts',
1979                    'styles',
1980                ),
1981                $url
1982            );
1983        }
1984
1985        return $url;
1986    }
1987
1988    /**
1989     * When the MediaElement is loaded in dynamically, we need to enforce that
1990     * its settings are added to the page as well.
1991     *
1992     * @param array $scripts_data New scripts exposed to the infinite scroll.
1993     *
1994     * @since 8.4.0
1995     */
1996    public function add_mejs_config( $scripts_data ) {
1997        foreach ( $scripts_data as $key => $data ) {
1998            if ( 'mediaelement-core' === $data['handle'] ) {
1999                $mejs_settings = array(
2000                    'pluginPath'  => includes_url( 'js/mediaelement/', 'relative' ),
2001                    'classPrefix' => 'mejs-',
2002                    'stretching'  => 'responsive',
2003                );
2004
2005                $scripts_data[ $key ]['extra_data'] = sprintf(
2006                    'window.%s = %s',
2007                    '_wpmejsSettings',
2008                    wp_json_encode( apply_filters( 'mejs_settings', $mejs_settings ), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP )
2009                );
2010            }
2011        }
2012        return $scripts_data;
2013    }
2014
2015    /**
2016     * Determines whether the legacy AMP Reader post templates are being used.
2017     *
2018     * @return bool
2019     */
2020    private function is_exempted_amp_page() {
2021        if ( is_singular( 'web-story' ) ) {
2022            // Ensure that <amp-next-page> is not injected after <amp-story> as generated by the Web Stories plugin.
2023            return true;
2024        }
2025        if ( function_exists( 'amp_is_legacy' ) ) {
2026            // Available since AMP v2.0, this will return false if a theme like Twenty Twenty is selected as the Reader theme.
2027            return amp_is_legacy();
2028        }
2029        if ( method_exists( 'AMP_Options_Manager', 'get_option' ) ) {
2030            // In versions prior to v2.0, checking the template mode as being 'reader' is sufficient.
2031            return 'reader' === AMP_Options_Manager::get_option( 'theme_support' );
2032        }
2033        return false;
2034    }
2035
2036    /**
2037     * Load AMP specific hooks.
2038     *
2039     * @return void
2040     */
2041    public function amp_load_hooks() {
2042        if ( $this->is_exempted_amp_page() ) {
2043            return;
2044        }
2045
2046        if ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() ) {
2047            $template = self::get_settings()->render;
2048
2049            add_filter( 'jetpack_infinite_scroll_load_scripts_and_styles', '__return_false' );
2050
2051            add_action( 'template_redirect', array( $this, 'amp_start_output_buffering' ), 0 );
2052            add_action( 'shutdown', array( $this, 'amp_output_buffer' ), 1 );
2053
2054            if ( is_string( $template ) && strpos( $template, '::' ) === false && is_callable( "amp_{$template}_hooks" ) ) {
2055                call_user_func( "amp_{$template}_hooks" );
2056            }
2057
2058            // Warms up the amp next page markup.
2059            // This should be done outside the output buffering callback started in the template_redirect.
2060            $this->amp_get_footer_template();
2061        }
2062    }
2063
2064    /**
2065     * Start the AMP output buffering.
2066     *
2067     * @return void
2068     */
2069    public function amp_start_output_buffering() {
2070        ob_start( array( $this, 'amp_finish_output_buffering' ) );
2071    }
2072
2073    /**
2074     * Flush the AMP output buffer.
2075     *
2076     * @return void
2077     */
2078    public function amp_output_buffer() {
2079        if ( ob_get_contents() ) {
2080            ob_end_flush();
2081        }
2082    }
2083
2084    /**
2085     * Filter the AMP output buffer contents.
2086     *
2087     * @param string $buffer Contents of the output buffer.
2088     *
2089     * @return string|false
2090     */
2091    public function amp_finish_output_buffering( $buffer ) {
2092        // Hide WordPress admin bar on next page load.
2093        $buffer = preg_replace(
2094            '/id="wpadminbar"/',
2095            '$0 next-page-hide',
2096            $buffer
2097        );
2098
2099        /**
2100         * Get the theme footers.
2101         *
2102         * @module infinite-scroll
2103         *
2104         * @since 9.0.0
2105         *
2106         * @param array  array() An array to store multiple markup entries to be added to the footer.
2107         * @param string $buffer The contents of the output buffer.
2108         */
2109        $footers = apply_filters( 'jetpack_amp_infinite_footers', array(), $buffer );
2110
2111        /**
2112         * Filter the output buffer.
2113         * Themes can leverage this hook to add custom markup on next page load.
2114         *
2115         * @module infinite-scroll
2116         *
2117         * @since 9.0.0
2118         *
2119         * @param string $buffer The contents of the output buffer.
2120         */
2121        $buffer = apply_filters( 'jetpack_amp_infinite_output', $buffer );
2122
2123        // Add the amp next page markup.
2124        $buffer = preg_replace(
2125            '~</body>~',
2126            $this->amp_get_footer_template( $footers ) . '$0',
2127            $buffer
2128        );
2129
2130        return $buffer;
2131    }
2132
2133    /**
2134     * Get AMP next page markup with the custom footers.
2135     *
2136     * @param string[] $footers The theme footers.
2137     *
2138     * @return string
2139     */
2140    protected function amp_get_footer_template( $footers = array() ) {
2141        static $template = null;
2142
2143        if ( null === $template ) {
2144            $template = $this->amp_footer_template();
2145        }
2146
2147        if ( empty( $footers ) ) {
2148            return $template;
2149        }
2150
2151        return preg_replace(
2152            '/%%footer%%/',
2153            implode( '', $footers ),
2154            $template
2155        );
2156    }
2157
2158    /**
2159     * AMP Next Page markup.
2160     *
2161     * @return string
2162     */
2163    protected function amp_footer_template() {
2164        ob_start();
2165        ?>
2166<amp-next-page max-pages="<?php echo esc_attr( static::amp_get_max_pages() ); ?>">
2167    <script type="application/json">
2168        [
2169            <?php echo wp_json_encode( $this->amp_next_page(), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?>
2170        ]
2171    </script>
2172    <div separator>
2173        <?php
2174        echo wp_kses_post(
2175            /**
2176             * AMP infinite scroll separator.
2177             *
2178             * @module infinite-scroll
2179             *
2180             * @since 9.0.0
2181             *
2182             * @param string '' The markup for the next page separator.
2183             */
2184            apply_filters( 'jetpack_amp_infinite_separator', '' )
2185        );
2186        ?>
2187    </div>
2188    <div recommendation-box class="recommendation-box">
2189        <template type="amp-mustache">
2190            {{#pages}}
2191            <?php
2192            echo wp_kses_post(
2193                /**
2194                 * AMP infinite scroll older posts markup.
2195                 *
2196                 * @module infinite-scroll
2197                 *
2198                 * @since 9.0.0
2199                 *
2200                 * @param string '' The markup for the older posts/next page.
2201                 */
2202                apply_filters( 'jetpack_amp_infinite_older_posts', '' )
2203            );
2204            ?>
2205            {{/pages}}
2206        </template>
2207    </div>
2208    <div footer>
2209        %%footer%%
2210    </div>
2211</amp-next-page>
2212        <?php
2213        return ob_get_clean();
2214    }
2215
2216    /**
2217     * Get the AMP next page information.
2218     *
2219     * @return array
2220     */
2221    protected function amp_next_page() {
2222        $title = '';
2223        $url   = '';
2224        $image = '';
2225
2226        if ( ! static::amp_is_last_page() ) {
2227            $title = sprintf(
2228                '%s - %s %d - %s',
2229                wp_title( '', false ),
2230                __( 'Page', 'jetpack' ),
2231                max( get_query_var( 'paged', 1 ), 1 ) + 1,
2232                get_bloginfo( 'name' )
2233            );
2234            $url   = get_next_posts_page_link();
2235        }
2236
2237        $next_page = array(
2238            'title' => $title,
2239            'url'   => $url,
2240            'image' => $image,
2241        );
2242
2243        /**
2244         * The next page settings.
2245         * An array containing:
2246         *  - title => The title to be featured on the browser tab.
2247         *  - url   => The URL of next page.
2248         *  - image => The image URL. A required AMP setting, not in use currently. Themes are welcome to leverage.
2249         *
2250         * @module infinite-scroll
2251         *
2252         * @since 9.0.0
2253         *
2254         * @param array $next_page The contents of the output buffer.
2255         */
2256        return apply_filters( 'jetpack_amp_infinite_next_page_data', $next_page );
2257    }
2258
2259    /**
2260     * Get the number of pages left.
2261     *
2262     * @return int
2263     */
2264    protected static function amp_get_max_pages() {
2265        global $wp_query;
2266
2267        return (int) $wp_query->max_num_pages - (int) $wp_query->query_vars['paged'];
2268    }
2269
2270    /**
2271     * Is the last page.
2272     *
2273     * @return bool
2274     */
2275    protected static function amp_is_last_page() {
2276        return 0 === static::amp_get_max_pages();
2277    }
2278}
2279
2280/**
2281 * Initialize The_Neverending_Home_Page
2282 */
2283function the_neverending_home_page_init() {
2284    if ( ! current_theme_supports( 'infinite-scroll' ) ) {
2285        return;
2286    }
2287
2288    new The_Neverending_Home_Page();
2289}
2290add_action( 'init', 'the_neverending_home_page_init', 20 );
2291
2292/**
2293 * Check whether the current theme is infinite-scroll aware.
2294 * If so, include the files which add theme support.
2295 */
2296function the_neverending_home_page_theme_support() {
2297    if (
2298            defined( 'IS_WPCOM' ) && IS_WPCOM &&
2299            defined( 'REST_API_REQUEST' ) && REST_API_REQUEST &&
2300            ! doing_action( 'restapi_theme_after_setup_theme' )
2301    ) {
2302        // Don't source theme compat files until we're in the site's context
2303        return;
2304    }
2305    $theme_name = get_stylesheet();
2306
2307    /**
2308     * Filter the path to the Infinite Scroll compatibility file.
2309     *
2310     * @module infinite-scroll
2311     *
2312     * @since 2.0.0
2313     *
2314     * @param string $str IS compatibility file path.
2315     * @param string $theme_name Theme name.
2316     */
2317    $customization_file = apply_filters( 'infinite_scroll_customization_file', __DIR__ . "/themes/{$theme_name}.php", $theme_name );
2318
2319    if ( is_readable( $customization_file ) ) {
2320        require_once $customization_file;
2321    }
2322}
2323add_action( 'after_setup_theme', 'the_neverending_home_page_theme_support', 5 );
2324
2325/**
2326 * Early accommodation of the Infinite Scroll AJAX request
2327 */
2328if ( The_Neverending_Home_Page::got_infinity() ) {
2329    /**
2330     * If we're sure this is an AJAX request (i.e. the HTTP_X_REQUESTED_WITH header says so),
2331     * indicate it as early as possible for actions like init
2332     */
2333    if ( ! defined( 'DOING_AJAX' ) &&
2334        isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) &&
2335        strtoupper( sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ) ) === 'XMLHTTPREQUEST'
2336    ) {
2337        define( 'DOING_AJAX', true );
2338    }
2339
2340    // Don't load the admin bar when doing the AJAX response.
2341    show_admin_bar( false );
2342}