PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 11.0.2
Jetpack – WP Security, Backup, Speed, & Growth v11.0.2
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / modules / infinite-scroll / infinity.php

infinity.php in Jetpack – WP Security, Backup, Speed, & Growth 11.0.2, at modules/infinite-scroll/infinity.php

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