PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 7.6.2
Jetpack – WP Security, Backup, Speed, & Growth v7.6.2
16.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 All 502 releases
jetpack / modules / infinite-scroll / infinity.php

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

1,668 lines 52.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 use Automattic\Jetpack\Assets;
4
5 /*
6 Plugin Name: The Neverending Home Page.
7 Plugin URI: http://automattic.com/
8 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.
9 Version: 1.1
10 Author: Automattic
11 Author URI: http://automattic.com/
12 License: GNU General Public License v2 or later
13 License URI: http://www.gnu.org/licenses/gpl-2.0.html
14 */
15
16 /**
17 * Class: The_Neverending_Home_Page relies on add_theme_support, expects specific
18 * styling from each theme; including fixed footer.
19 */
20 class The_Neverending_Home_Page {
21
22 /**
23 * Register actions and filters, plus parse IS settings
24 *
25 * @uses add_action, add_filter, self::get_settings
26 * @return null
27 */
28 function __construct() {
29 add_action( 'pre_get_posts', array( $this, 'posts_per_page_query' ) );
30
31 add_action( 'admin_init', array( $this, 'settings_api_init' ) );
32 add_action( 'template_redirect', array( $this, 'action_template_redirect' ) );
33 add_action( 'template_redirect', array( $this, 'ajax_response' ) );
34 add_action( 'custom_ajax_infinite_scroll', array( $this, 'query' ) );
35 add_filter( 'infinite_scroll_query_args', array( $this, 'inject_query_args' ) );
36 add_filter( 'infinite_scroll_allowed_vars', array( $this, 'allowed_query_vars' ) );
37 add_action( 'the_post', array( $this, 'preserve_more_tag' ) );
38 add_action( 'wp_footer', array( $this, 'footer' ) );
39
40 // Plugin compatibility
41 add_filter( 'grunion_contact_form_redirect_url', array( $this, 'filter_grunion_redirect_url' ) );
42
43 // Parse IS settings from theme
44 self::get_settings();
45 }
46
47 /**
48 * Initialize our static variables
49 */
50 static $the_time = null;
51 static $settings = null; // Don't access directly, instead use self::get_settings().
52
53 static $option_name_enabled = 'infinite_scroll';
54
55 /**
56 * Parse IS settings provided by theme
57 *
58 * @uses get_theme_support, infinite_scroll_has_footer_widgets, sanitize_title, add_action, get_option, wp_parse_args, is_active_sidebar
59 * @return object
60 */
61 static function get_settings() {
62 if ( is_null( self::$settings ) ) {
63 $css_pattern = '#[^A-Z\d\-_]#i';
64
65 $settings = $defaults = array(
66 'type' => 'scroll', // scroll | click
67 'requested_type' => 'scroll', // store the original type for use when logic overrides it
68 'footer_widgets' => false, // true | false | sidebar_id | array of sidebar_ids -- last two are checked with is_active_sidebar
69 'container' => 'content', // container html id
70 'wrapper' => true, // true | false | html class
71 'render' => false, // optional function, otherwise the `content` template part will be used
72 'footer' => true, // boolean to enable or disable the infinite footer | string to provide an html id to derive footer width from
73 'footer_callback' => false, // function to be called to render the IS footer, in place of the default
74 'posts_per_page' => false, // int | false to set based on IS type
75 '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`.
76 );
77
78 // Validate settings passed through add_theme_support()
79 $_settings = get_theme_support( 'infinite-scroll' );
80
81 if ( is_array( $_settings ) ) {
82 // Preferred implementation, where theme provides an array of options
83 if ( isset( $_settings[0] ) && is_array( $_settings[0] ) ) {
84 foreach ( $_settings[0] as $key => $value ) {
85 switch ( $key ) {
86 case 'type' :
87 if ( in_array( $value, array( 'scroll', 'click' ) ) )
88 $settings[ $key ] = $settings['requested_type'] = $value;
89
90 break;
91
92 case 'footer_widgets' :
93 if ( is_string( $value ) )
94 $settings[ $key ] = sanitize_title( $value );
95 elseif ( is_array( $value ) )
96 $settings[ $key ] = array_map( 'sanitize_title', $value );
97 elseif ( is_bool( $value ) )
98 $settings[ $key ] = $value;
99
100 break;
101
102 case 'container' :
103 case 'wrapper' :
104 if ( 'wrapper' == $key && is_bool( $value ) ) {
105 $settings[ $key ] = $value;
106 } else {
107 $value = preg_replace( $css_pattern, '', $value );
108
109 if ( ! empty( $value ) )
110 $settings[ $key ] = $value;
111 }
112
113 break;
114
115 case 'render' :
116 if ( false !== $value && is_callable( $value ) ) {
117 $settings[ $key ] = $value;
118 }
119
120 break;
121
122 case 'footer' :
123 if ( is_bool( $value ) ) {
124 $settings[ $key ] = $value;
125 } elseif ( is_string( $value ) ) {
126 $value = preg_replace( $css_pattern, '', $value );
127
128 if ( ! empty( $value ) )
129 $settings[ $key ] = $value;
130 }
131
132 break;
133
134 case 'footer_callback' :
135 if ( is_callable( $value ) )
136 $settings[ $key ] = $value;
137 else
138 $settings[ $key ] = false;
139
140 break;
141
142 case 'posts_per_page' :
143 if ( is_numeric( $value ) )
144 $settings[ $key ] = (int) $value;
145
146 break;
147
148 case 'click_handle' :
149 if ( is_bool( $value ) ) {
150 $settings[ $key ] = $value;
151 }
152
153 break;
154
155 default:
156 break;
157 }
158 }
159 } elseif ( is_string( $_settings[0] ) ) {
160 // Checks below are for backwards compatibility
161
162 // Container to append new posts to
163 $settings['container'] = preg_replace( $css_pattern, '', $_settings[0] );
164
165 // Wrap IS elements?
166 if ( isset( $_settings[1] ) )
167 $settings['wrapper'] = (bool) $_settings[1];
168 }
169 }
170
171 // Always ensure all values are present in the final array
172 $settings = wp_parse_args( $settings, $defaults );
173
174 // Check if a legacy `infinite_scroll_has_footer_widgets()` function is defined and override the footer_widgets parameter's value.
175 // Otherwise, if a widget area ID or array of IDs was provided in the footer_widgets parameter, check if any contains any widgets.
176 // 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.
177 if ( function_exists( 'infinite_scroll_has_footer_widgets' ) ) {
178 $settings['footer_widgets'] = (bool) infinite_scroll_has_footer_widgets();
179 } elseif ( is_array( $settings['footer_widgets'] ) ) {
180 $sidebar_ids = $settings['footer_widgets'];
181 $settings['footer_widgets'] = false;
182
183 foreach ( $sidebar_ids as $sidebar_id ) {
184 if ( is_active_sidebar( $sidebar_id ) ) {
185 $settings['footer_widgets'] = true;
186 break;
187 }
188 }
189
190 unset( $sidebar_ids );
191 unset( $sidebar_id );
192 } elseif ( is_string( $settings['footer_widgets'] ) ) {
193 $settings['footer_widgets'] = (bool) is_active_sidebar( $settings['footer_widgets'] );
194 }
195
196 /**
197 * Filter Infinite Scroll's `footer_widgets` parameter.
198 *
199 * @module infinite-scroll
200 *
201 * @since 2.0.0
202 *
203 * @param bool $settings['footer_widgets'] Does the current theme have Footer Widgets.
204 */
205 $settings['footer_widgets'] = apply_filters( 'infinite_scroll_has_footer_widgets', $settings['footer_widgets'] );
206
207 // Finally, after all of the sidebar checks and filtering, ensure that a boolean value is present, otherwise set to default of `false`.
208 if ( ! is_bool( $settings['footer_widgets'] ) )
209 $settings['footer_widgets'] = false;
210
211 // Ensure that IS is enabled and no footer widgets exist if the IS type isn't already "click".
212 if ( 'click' != $settings['type'] ) {
213 // Check the setting status
214 $disabled = '' === get_option( self::$option_name_enabled ) ? true : false;
215
216 // Footer content or Reading option check
217 if ( $settings['footer_widgets'] || $disabled )
218 $settings['type'] = 'click';
219 }
220
221 // Force display of the click handler and attendant bits when the type isn't `click`
222 if ( 'click' !== $settings['type'] ) {
223 $settings['click_handle'] = true;
224 }
225
226 // Store final settings in a class static to avoid reparsing
227 /**
228 * Filter the array of Infinite Scroll settings.
229 *
230 * @module infinite-scroll
231 *
232 * @since 2.0.0
233 *
234 * @param array $settings Array of Infinite Scroll settings.
235 */
236 self::$settings = apply_filters( 'infinite_scroll_settings', $settings );
237 }
238
239 /** This filter is already documented in modules/infinite-scroll/infinity.php */
240 return (object) apply_filters( 'infinite_scroll_settings', self::$settings );
241 }
242
243 /**
244 * Number of posts per page.
245 *
246 * @uses self::wp_query, self::get_settings, apply_filters
247 * @return int
248 */
249 static function posts_per_page() {
250 $posts_per_page = self::get_settings()->posts_per_page ? self::get_settings()->posts_per_page : self::wp_query()->get( 'posts_per_page' );
251
252 // Take JS query into consideration here
253 if ( true === isset( $_REQUEST['query_args']['posts_per_page'] ) ) {
254 $posts_per_page = $_REQUEST['query_args']['posts_per_page'];
255 }
256
257 /**
258 * Filter the number of posts per page.
259 *
260 * @module infinite-scroll
261 *
262 * @since 6.0.0
263 *
264 * @param int $posts_per_page The number of posts to display per page.
265 */
266 return (int) apply_filters( 'infinite_scroll_posts_per_page', $posts_per_page );
267 }
268
269 /**
270 * Retrieve the query used with Infinite Scroll
271 *
272 * @global $wp_the_query
273 * @uses apply_filters
274 * @return object
275 */
276 static function wp_query() {
277 global $wp_the_query;
278 /**
279 * Filter the Infinite Scroll query object.
280 *
281 * @module infinite-scroll
282 *
283 * @since 2.2.1
284 *
285 * @param WP_Query $wp_the_query WP Query.
286 */
287 return apply_filters( 'infinite_scroll_query_object', $wp_the_query );
288 }
289
290 /**
291 * Has infinite scroll been triggered?
292 */
293 static function got_infinity() {
294 /**
295 * Filter the parameter used to check if Infinite Scroll has been triggered.
296 *
297 * @module infinite-scroll
298 *
299 * @since 3.9.0
300 *
301 * @param bool isset( $_GET[ 'infinity' ] ) Return true if the "infinity" parameter is set.
302 */
303 return apply_filters( 'infinite_scroll_got_infinity', isset( $_GET[ 'infinity' ] ) );
304 }
305
306 /**
307 * Is this guaranteed to be the last batch of posts?
308 */
309 static function is_last_batch() {
310 /**
311 * Override whether or not this is the last batch for a request
312 *
313 * @module infinite-scroll
314 *
315 * @since 4.8.0
316 *
317 * @param bool|null null Bool if value should be overridden, null to determine from query
318 * @param object self::wp_query() WP_Query object for current request
319 * @param object self::get_settings() Infinite Scroll settings
320 */
321 $override = apply_filters( 'infinite_scroll_is_last_batch', null, self::wp_query(), self::get_settings() );
322 if ( is_bool( $override ) ) {
323 return $override;
324 }
325
326 $entries = (int) self::wp_query()->found_posts;
327 $posts_per_page = self::posts_per_page();
328
329 // This is to cope with an issue in certain themes or setups where posts are returned but found_posts is 0.
330 if ( 0 == $entries ) {
331 return (bool) ( count( self::wp_query()->posts ) < $posts_per_page );
332 }
333 $paged = max( 1, self::wp_query()->get( 'paged' ) );
334
335 // Are there enough posts for more than the first page?
336 if ( $entries <= $posts_per_page ) {
337 return true;
338 }
339
340 // Calculate entries left after a certain number of pages
341 if ( $paged && $paged > 1 ) {
342 $entries -= $posts_per_page * $paged;
343 }
344
345 // Are there some entries left to display?
346 return $entries <= 0;
347 }
348
349 /**
350 * The more tag will be ignored by default if the blog page isn't our homepage.
351 * Let's force the $more global to false.
352 */
353 function preserve_more_tag( $array ) {
354 global $more;
355
356 if ( self::got_infinity() )
357 $more = 0; //0 = show content up to the more tag. Add more link.
358
359 return $array;
360 }
361
362 /**
363 * Add a checkbox field to Settings > Reading
364 * for enabling infinite scroll.
365 *
366 * Only show if the current theme supports infinity.
367 *
368 * @uses current_theme_supports, add_settings_field, __, register_setting
369 * @action admin_init
370 * @return null
371 */
372 function settings_api_init() {
373 if ( ! current_theme_supports( 'infinite-scroll' ) )
374 return;
375
376 if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
377 // This setting is no longer configurable in wp-admin on WordPress.com -- leave a pointer
378 add_settings_field( self::$option_name_enabled,
379 '<span id="infinite-scroll-options">' . esc_html__( 'Infinite Scroll Behavior', 'jetpack' ) . '</span>',
380 array( $this, 'infinite_setting_html_calypso_placeholder' ),
381 'reading'
382 );
383 return;
384 }
385
386 // Add the setting field [infinite_scroll] and place it in Settings > Reading
387 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' );
388 register_setting( 'reading', self::$option_name_enabled, 'esc_attr' );
389 }
390
391 function infinite_setting_html_calypso_placeholder() {
392 $details = get_blog_details();
393 echo '<span>' . sprintf(
394 /* translators: Variables are the enclosing link to the settings page */
395 esc_html__( 'This option has moved. You can now manage it %1$shere%2$s.' ),
396 '<a href="' . esc_url( 'https://wordpress.com/settings/writing/' . $details->domain ) . '">',
397 '</a>'
398 ) . '</span>';
399 }
400
401 /**
402 * HTML code to display a checkbox true/false option
403 * for the infinite_scroll setting.
404 */
405 function infinite_setting_html() {
406 $notice = '<em>' . __( '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>';
407
408 // If the blog has footer widgets, show a notice instead of the checkbox
409 if ( self::get_settings()->footer_widgets || 'click' == self::get_settings()->requested_type ) {
410 echo '<label>' . $notice . '</label>';
411 } else {
412 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>';
413 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>';
414 }
415 }
416
417 /**
418 * Does the legwork to determine whether the feature is enabled.
419 *
420 * @uses current_theme_supports, self::archive_supports_infinity, self::get_settings, add_filter, wp_enqueue_script, plugins_url, wp_enqueue_style, add_action
421 * @action template_redirect
422 * @return null
423 */
424 function action_template_redirect() {
425 // Check that we support infinite scroll, and are on the home page.
426 if ( ! current_theme_supports( 'infinite-scroll' ) || ! self::archive_supports_infinity() )
427 return;
428
429 $id = self::get_settings()->container;
430
431 // Check that we have an id.
432 if ( empty( $id ) )
433 return;
434
435 // Add our scripts.
436 wp_register_script(
437 'the-neverending-homepage',
438 Assets::get_file_url_for_environment(
439 '_inc/build/infinite-scroll/infinity.min.js',
440 'modules/infinite-scroll/infinity.js'
441 ),
442 array( 'jquery' ),
443 '4.0.0',
444 true
445 );
446
447 // Add our default styles.
448 wp_register_style( 'the-neverending-homepage', plugins_url( 'infinity.css', __FILE__ ), array(), '20140422' );
449
450 // Make sure there are enough posts for IS
451 if ( self::is_last_batch() ) {
452 return;
453 }
454
455 // Add our scripts.
456 wp_enqueue_script( 'the-neverending-homepage' );
457
458 // Add our default styles.
459 wp_enqueue_style( 'the-neverending-homepage' );
460
461 add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_spinner_scripts' ) );
462
463 add_action( 'wp_footer', array( $this, 'action_wp_footer_settings' ), 2 );
464
465 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
466
467 add_filter( 'infinite_scroll_results', array( $this, 'filter_infinite_scroll_results' ), 10, 3 );
468 }
469
470 /**
471 * Enqueue spinner scripts.
472 */
473 function enqueue_spinner_scripts() {
474 wp_enqueue_script( 'jquery.spin' );
475 }
476
477 /**
478 * Returns classes to be added to <body>. If it's enabled, 'infinite-scroll'. If set to continuous scroll, adds 'neverending' too.
479 *
480 * @since 4.7.0 No longer added as a 'body_class' filter but passed to JS environment and added using JS.
481 *
482 * @return string
483 */
484 function body_class() {
485 $classes = '';
486 // Do not add infinity-scroll class if disabled through the Reading page
487 $disabled = '' === get_option( self::$option_name_enabled ) ? true : false;
488 if ( ! $disabled || 'click' == self::get_settings()->type ) {
489 $classes = 'infinite-scroll';
490
491 if ( 'scroll' == self::get_settings()->type )
492 $classes .= ' neverending';
493 }
494
495 return $classes;
496 }
497
498 /**
499 * 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
500 *
501 * @uses self::wp_query
502 * @uses self::get_last_post_date
503 * @uses self::has_only_title_matching_posts
504 * @return array
505 */
506 function get_excluded_posts() {
507
508 $excluded_posts = array();
509 //loop through posts returned by wp_query call
510 foreach( self::wp_query()->get_posts() as $post ) {
511
512 $orderby = isset( self::wp_query()->query_vars['orderby'] ) ? self::wp_query()->query_vars['orderby'] : '';
513 $post_date = ( ! empty( $post->post_date ) ? $post->post_date : false );
514 if ( 'modified' === $orderby || false === $post_date ) {
515 $post_date = $post->post_modified;
516 }
517
518 //in case all posts initially displayed match the keyword by title we add em all to excluded posts array
519 //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
520 if ( self::has_only_title_matching_posts() || $post_date <= self::get_last_post_date() ) {
521 array_push( $excluded_posts, $post->ID );
522 }
523 }
524 return $excluded_posts;
525 }
526
527 /**
528 * 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
529 *
530 * @uses self::wp_query
531 * @uses self::get_excluded_posts
532 * @return array
533 */
534 function get_query_vars() {
535
536 $query_vars = self::wp_query()->query_vars;
537 //applies to search page only
538 if ( true === self::wp_query()->is_search() ) {
539 //set post__not_in array in query_vars in case it does not exists
540 if ( false === isset( $query_vars['post__not_in'] ) ) {
541 $query_vars['post__not_in'] = array();
542 }
543 //get excluded posts
544 $excluded = self::get_excluded_posts();
545 //merge them with other post__not_in posts (eg.: sticky posts)
546 $query_vars['post__not_in'] = array_merge( $query_vars['post__not_in'], $excluded );
547 }
548 return $query_vars;
549 }
550
551 /**
552 * This function checks whether all posts returned by initial wp_query match the keyword by title
553 * The code used in this function is borrowed from WP_Query class where it is used to construct like conditions for keywords
554 *
555 * @uses self::wp_query
556 * @return bool
557 */
558 function has_only_title_matching_posts() {
559
560 //apply following logic for search page results only
561 if ( false === self::wp_query()->is_search() ) {
562 return false;
563 }
564
565 //grab the last posts in the stack as if the last one is title-matching the rest is title-matching as well
566 $post = end( self::wp_query()->posts );
567
568 //code inspired by WP_Query class
569 if ( preg_match_all( '/".*?("|$)|((?<=[\t ",+])|^)[^\t ",+]+/', self::wp_query()->get( 's' ), $matches ) ) {
570 $search_terms = self::wp_query()->query_vars['search_terms'];
571 // if the search string has only short terms or stopwords, or is 10+ terms long, match it as sentence
572 if ( empty( $search_terms ) || count( $search_terms ) > 9 ) {
573 $search_terms = array( self::wp_query()->get( 's' ) );
574 }
575 } else {
576 $search_terms = array( self::wp_query()->get( 's' ) );
577 }
578
579 //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
580 $term = current( $search_terms );
581 if ( ! empty( $term ) && false !== strpos( $post->post_title, $term ) ) {
582 return true;
583 }
584
585 return false;
586 }
587
588 /**
589 * Grab the timestamp for the initial query's last post.
590 *
591 * This takes into account the query's 'orderby' parameter and returns
592 * false if the posts are not ordered by date.
593 *
594 * @uses self::got_infinity
595 * @uses self::has_only_title_matching_posts
596 * @uses self::wp_query
597 * @return string 'Y-m-d H:i:s' or false
598 */
599 function get_last_post_date() {
600 if ( self::got_infinity() )
601 return;
602
603 if ( ! self::wp_query()->have_posts() ) {
604 return null;
605 }
606
607 //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
608 if ( true === self::has_only_title_matching_posts() ) {
609 return false;
610 }
611
612 $post = end( self::wp_query()->posts );
613 $orderby = isset( self::wp_query()->query_vars['orderby'] ) ?
614 self::wp_query()->query_vars['orderby'] : '';
615 $post_date = ( ! empty( $post->post_date ) ? $post->post_date : false );
616 switch ( $orderby ) {
617 case 'modified':
618 return $post->post_modified;
619 case 'date':
620 case '':
621 return $post_date;
622 default:
623 return false;
624 }
625 }
626
627 /**
628 * Returns the appropriate `wp_posts` table field for a given query's
629 * 'orderby' parameter, if applicable.
630 *
631 * @param optional object $query
632 * @uses self::wp_query
633 * @return string or false
634 */
635 function get_query_sort_field( $query = null ) {
636 if ( empty( $query ) )
637 $query = self::wp_query();
638
639 $orderby = isset( $query->query_vars['orderby'] ) ? $query->query_vars['orderby'] : '';
640
641 switch ( $orderby ) {
642 case 'modified':
643 return 'post_modified';
644 case 'date':
645 case '':
646 return 'post_date';
647 default:
648 return false;
649 }
650 }
651
652 /**
653 * Create a where clause that will make sure post queries return posts
654 * in the correct order, without duplicates, if a new post is added
655 * and we're sorting by post date.
656 *
657 * @global $wpdb
658 * @param string $where
659 * @param object $query
660 * @uses apply_filters
661 * @filter posts_where
662 * @return string
663 */
664 function query_time_filter( $where, $query ) {
665 if ( self::got_infinity() ) {
666 global $wpdb;
667
668 $sort_field = self::get_query_sort_field( $query );
669
670 if ( 'post_date' !== $sort_field || 'DESC' !== $_REQUEST['query_args']['order'] ) {
671 return $where;
672 }
673
674 $query_before = sanitize_text_field( wp_unslash( $_REQUEST['query_before'] ) );
675
676 if ( empty( $query_before ) ) {
677 return $where;
678 }
679
680 // Construct the date query using our timestamp
681 $clause = $wpdb->prepare( " AND {$wpdb->posts}.post_date <= %s", $query_before );
682
683 /**
684 * Filter Infinite Scroll's SQL date query making sure post queries
685 * will always return results prior to (descending sort)
686 * or before (ascending sort) the last post date.
687 *
688 * @module infinite-scroll
689 *
690 * @param string $clause SQL Date query.
691 * @param object $query Query.
692 * @param string $operator @deprecated Query operator.
693 * @param string $last_post_date @deprecated Last Post Date timestamp.
694 */
695 $operator = 'ASC' === $_REQUEST['query_args']['order'] ? '>' : '<';
696 $last_post_date = sanitize_text_field( wp_unslash( $_REQUEST['last_post_date'] ) );
697 $where .= apply_filters( 'infinite_scroll_posts_where', $clause, $query, $operator, $last_post_date );
698 }
699
700 return $where;
701 }
702
703 /**
704 * Let's overwrite the default post_per_page setting to always display a fixed amount.
705 *
706 * @param object $query
707 * @uses is_admin, self::archive_supports_infinity, self::get_settings
708 * @return null
709 */
710 function posts_per_page_query( $query ) {
711 if ( ! is_admin() && self::archive_supports_infinity() && $query->is_main_query() )
712 $query->set( 'posts_per_page', self::posts_per_page() );
713 }
714
715 /**
716 * Check if the IS output should be wrapped in a div.
717 * Setting value can be a boolean or a string specifying the class applied to the div.
718 *
719 * @uses self::get_settings
720 * @return bool
721 */
722 function has_wrapper() {
723 return (bool) self::get_settings()->wrapper;
724 }
725
726 /**
727 * Returns the Ajax url
728 *
729 * @global $wp
730 * @uses home_url, add_query_arg, apply_filters
731 * @return string
732 */
733 function ajax_url() {
734 $base_url = set_url_scheme( home_url( '/' ) );
735
736 $ajaxurl = add_query_arg( array( 'infinity' => 'scrolling' ), $base_url );
737
738 /**
739 * Filter the Infinite Scroll Ajax URL.
740 *
741 * @module infinite-scroll
742 *
743 * @since 2.0.0
744 *
745 * @param string $ajaxurl Infinite Scroll Ajax URL.
746 */
747 return apply_filters( 'infinite_scroll_ajax_url', $ajaxurl );
748 }
749
750 /**
751 * Our own Ajax response, avoiding calling admin-ajax
752 */
753 function ajax_response() {
754 // Only proceed if the url query has a key of "Infinity"
755 if ( ! self::got_infinity() )
756 return false;
757
758 // This should already be defined below, but make sure.
759 if ( ! defined( 'DOING_AJAX' ) ) {
760 define( 'DOING_AJAX', true );
761 }
762
763 @header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
764 send_nosniff_header();
765
766 /**
767 * Fires at the end of the Infinite Scroll Ajax response.
768 *
769 * @module infinite-scroll
770 *
771 * @since 2.0.0
772 */
773 do_action( 'custom_ajax_infinite_scroll' );
774 die( '0' );
775 }
776
777 /**
778 * Alias for renamed class method.
779 *
780 * Previously, JS settings object was unnecessarily output in the document head.
781 * When the hook was changed, the method name no longer made sense.
782 */
783 function action_wp_head() {
784 $this->action_wp_footer_settings();
785 }
786
787 /**
788 * Prints the relevant infinite scroll settings in JS.
789 *
790 * @global $wp_rewrite
791 * @uses self::get_settings, esc_js, esc_url_raw, self::has_wrapper, __, apply_filters, do_action, self::get_query_vars
792 * @action wp_footer
793 * @return string
794 */
795 function action_wp_footer_settings() {
796 global $wp_rewrite;
797 global $currentday;
798
799 // Default click handle text
800 $click_handle_text = __( 'Older posts', 'jetpack' );
801
802 // If a single CPT is displayed, use its plural name instead of "posts"
803 // Could be empty (posts) or an array of multiple post types.
804 // In the latter two cases cases, the default text is used, leaving the `infinite_scroll_js_settings` filter for further customization.
805 $post_type = self::wp_query()->get( 'post_type' );
806
807 // If it's a taxonomy, try to change the button text.
808 if ( is_tax() ) {
809 // Get current taxonomy slug.
810 $taxonomy_slug = self::wp_query()->get( 'taxonomy' );
811
812 // Get taxonomy settings.
813 $taxonomy = get_taxonomy( $taxonomy_slug );
814
815 // Check if the taxonomy is attached to one post type only and use its plural name.
816 // If not, use "Posts" without confusing the users.
817 if ( count( $taxonomy->object_type ) < 2 ) {
818 $post_type = $taxonomy->object_type[0];
819 }
820 }
821
822 if ( is_string( $post_type ) && ! empty( $post_type ) ) {
823 $post_type = get_post_type_object( $post_type );
824
825 if ( is_object( $post_type ) && ! is_wp_error( $post_type ) ) {
826 if ( isset( $post_type->labels->name ) ) {
827 $cpt_text = $post_type->labels->name;
828 } elseif ( isset( $post_type->label ) ) {
829 $cpt_text = $post_type->label;
830 }
831
832 if ( isset( $cpt_text ) ) {
833 /* translators: %s is the name of a custom post type */
834 $click_handle_text = sprintf( __( 'More %s', 'jetpack' ), $cpt_text );
835 unset( $cpt_text );
836 }
837 }
838 }
839
840 unset( $post_type );
841
842 // Base JS settings
843 $js_settings = array(
844 'id' => self::get_settings()->container,
845 'ajaxurl' => esc_url_raw( self::ajax_url() ),
846 'type' => esc_js( self::get_settings()->type ),
847 'wrapper' => self::has_wrapper(),
848 'wrapper_class' => is_string( self::get_settings()->wrapper ) ? esc_js( self::get_settings()->wrapper ) : 'infinite-wrap',
849 'footer' => is_string( self::get_settings()->footer ) ? esc_js( self::get_settings()->footer ) : self::get_settings()->footer,
850 'click_handle' => esc_js( self::get_settings()->click_handle ),
851 'text' => esc_js( $click_handle_text ),
852 'totop' => esc_js( __( 'Scroll back to top', 'jetpack' ) ),
853 'currentday' => $currentday,
854 'order' => 'DESC',
855 'scripts' => array(),
856 'styles' => array(),
857 'google_analytics' => false,
858 'offset' => max( 1, self::wp_query()->get( 'paged' ) ), // Pass through the current page so we can use that to offset the first load.
859 'history' => array(
860 'host' => preg_replace( '#^http(s)?://#i', '', untrailingslashit( esc_url( get_home_url() ) ) ),
861 'path' => self::get_request_path(),
862 'use_trailing_slashes' => $wp_rewrite->use_trailing_slashes,
863 'parameters' => self::get_request_parameters(),
864 ),
865 'query_args' => self::get_query_vars(),
866 'query_before' => current_time( 'mysql' ),
867 'last_post_date' => self::get_last_post_date(),
868 'body_class' => self::body_class(),
869 );
870
871 // Optional order param
872 if ( isset( $_REQUEST['order'] ) ) {
873 $order = strtoupper( $_REQUEST['order'] );
874
875 if ( in_array( $order, array( 'ASC', 'DESC' ) ) )
876 $js_settings['order'] = $order;
877 }
878
879 /**
880 * Filter the Infinite Scroll JS settings outputted in the head.
881 *
882 * @module infinite-scroll
883 *
884 * @since 2.0.0
885 *
886 * @param array $js_settings Infinite Scroll JS settings.
887 */
888 $js_settings = apply_filters( 'infinite_scroll_js_settings', $js_settings );
889
890 /**
891 * Fires before Infinite Scroll outputs inline JavaScript in the head.
892 *
893 * @module infinite-scroll
894 *
895 * @since 2.0.0
896 */
897 do_action( 'infinite_scroll_wp_head' );
898
899 ?>
900 <script type="text/javascript">
901 //<![CDATA[
902 var infiniteScroll = JSON.parse( decodeURIComponent( '<?php echo
903 rawurlencode( json_encode( array( 'settings' => $js_settings ) ) );
904 ?>' ) );
905 //]]>
906 </script>
907 <?php
908 }
909
910 /**
911 * Build path data for current request.
912 * Used for Google Analytics and pushState history tracking.
913 *
914 * @global $wp_rewrite
915 * @global $wp
916 * @uses user_trailingslashit, sanitize_text_field, add_query_arg
917 * @return string|bool
918 */
919 private function get_request_path() {
920 global $wp_rewrite;
921
922 if ( $wp_rewrite->using_permalinks() ) {
923 global $wp;
924
925 // If called too early, bail
926 if ( ! isset( $wp->request ) )
927 return false;
928
929 // Determine path for paginated version of current request
930 if ( false != preg_match( '#' . $wp_rewrite->pagination_base . '/\d+/?$#i', $wp->request ) )
931 $path = preg_replace( '#' . $wp_rewrite->pagination_base . '/\d+$#i', $wp_rewrite->pagination_base . '/%d', $wp->request );
932 else
933 $path = $wp->request . '/' . $wp_rewrite->pagination_base . '/%d';
934
935 // Slashes everywhere we need them
936 if ( 0 !== strpos( $path, '/' ) )
937 $path = '/' . $path;
938
939 $path = user_trailingslashit( $path );
940 } else {
941 // Clean up raw $_REQUEST input
942 $path = array_map( 'sanitize_text_field', $_REQUEST );
943 $path = array_filter( $path );
944
945 $path['paged'] = '%d';
946
947 $path = add_query_arg( $path, '/' );
948 }
949
950 return empty( $path ) ? false : $path;
951 }
952
953 /**
954 * Return query string for current request, prefixed with '?'.
955 *
956 * @return string
957 */
958 private function get_request_parameters() {
959 $uri = $_SERVER[ 'REQUEST_URI' ];
960 $uri = preg_replace( '/^[^?]*(\?.*$)/', '$1', $uri, 1, $count );
961 if ( $count != 1 )
962 return '';
963 return $uri;
964 }
965
966 /**
967 * Provide IS with a list of the scripts and stylesheets already present on the page.
968 * Since posts may contain require additional assets that haven't been loaded, this data will be used to track the additional assets.
969 *
970 * @global $wp_scripts, $wp_styles
971 * @action wp_footer
972 * @return string
973 */
974 function action_wp_footer() {
975 global $wp_scripts, $wp_styles;
976
977 $scripts = is_a( $wp_scripts, 'WP_Scripts' ) ? $wp_scripts->done : array();
978 /**
979 * Filter the list of scripts already present on the page.
980 *
981 * @module infinite-scroll
982 *
983 * @since 2.1.2
984 *
985 * @param array $scripts Array of scripts present on the page.
986 */
987 $scripts = apply_filters( 'infinite_scroll_existing_scripts', $scripts );
988
989 $styles = is_a( $wp_styles, 'WP_Styles' ) ? $wp_styles->done : array();
990 /**
991 * Filter the list of styles already present on the page.
992 *
993 * @module infinite-scroll
994 *
995 * @since 2.1.2
996 *
997 * @param array $styles Array of styles present on the page.
998 */
999 $styles = apply_filters( 'infinite_scroll_existing_stylesheets', $styles );
1000
1001 ?><script type="text/javascript">
1002 jQuery.extend( infiniteScroll.settings.scripts, <?php echo json_encode( $scripts ); ?> );
1003 jQuery.extend( infiniteScroll.settings.styles, <?php echo json_encode( $styles ); ?> );
1004 </script><?php
1005 }
1006
1007 /**
1008 * Identify additional scripts required by the latest set of IS posts and provide the necessary data to the IS response handler.
1009 *
1010 * @global $wp_scripts
1011 * @uses sanitize_text_field, add_query_arg
1012 * @filter infinite_scroll_results
1013 * @return array
1014 */
1015 function filter_infinite_scroll_results( $results, $query_args, $wp_query ) {
1016 // Don't bother unless there are posts to display
1017 if ( 'success' != $results['type'] )
1018 return $results;
1019
1020 // Parse and sanitize the script handles already output
1021 $initial_scripts = isset( $_REQUEST['scripts'] ) && is_array( $_REQUEST['scripts'] ) ? array_map( 'sanitize_text_field', $_REQUEST['scripts'] ) : false;
1022
1023 if ( is_array( $initial_scripts ) ) {
1024 global $wp_scripts;
1025
1026 // Identify new scripts needed by the latest set of IS posts
1027 $new_scripts = array_diff( $wp_scripts->done, $initial_scripts );
1028
1029 // If new scripts are needed, extract relevant data from $wp_scripts
1030 if ( ! empty( $new_scripts ) ) {
1031 $results['scripts'] = array();
1032
1033 foreach ( $new_scripts as $handle ) {
1034 // Abort if somehow the handle doesn't correspond to a registered script
1035 if ( ! isset( $wp_scripts->registered[ $handle ] ) )
1036 continue;
1037
1038 // Provide basic script data
1039 $script_data = array(
1040 'handle' => $handle,
1041 'footer' => ( is_array( $wp_scripts->in_footer ) && in_array( $handle, $wp_scripts->in_footer ) ),
1042 'extra_data' => $wp_scripts->print_extra_script( $handle, false )
1043 );
1044
1045 // Base source
1046 $src = $wp_scripts->registered[ $handle ]->src;
1047
1048 // Take base_url into account
1049 if ( strpos( $src, 'http' ) !== 0 )
1050 $src = $wp_scripts->base_url . $src;
1051
1052 // Version and additional arguments
1053 if ( null === $wp_scripts->registered[ $handle ]->ver )
1054 $ver = '';
1055 else
1056 $ver = $wp_scripts->registered[ $handle ]->ver ? $wp_scripts->registered[ $handle ]->ver : $wp_scripts->default_version;
1057
1058 if ( isset( $wp_scripts->args[ $handle ] ) )
1059 $ver = $ver ? $ver . '&amp;' . $wp_scripts->args[$handle] : $wp_scripts->args[$handle];
1060
1061 // Full script source with version info
1062 $script_data['src'] = add_query_arg( 'ver', $ver, $src );
1063
1064 // Add script to data that will be returned to IS JS
1065 array_push( $results['scripts'], $script_data );
1066 }
1067 }
1068 }
1069
1070 // Expose additional script data to filters, but only include in final `$results` array if needed.
1071 if ( ! isset( $results['scripts'] ) )
1072 $results['scripts'] = array();
1073
1074 /**
1075 * Filter the additional scripts required by the latest set of IS posts.
1076 *
1077 * @module infinite-scroll
1078 *
1079 * @since 2.1.2
1080 *
1081 * @param array $results['scripts'] Additional scripts required by the latest set of IS posts.
1082 * @param array|bool $initial_scripts Set of scripts loaded on each page.
1083 * @param array $results Array of Infinite Scroll results.
1084 * @param array $query_args Array of Query arguments.
1085 * @param WP_Query $wp_query WP Query.
1086 */
1087 $results['scripts'] = apply_filters(
1088 'infinite_scroll_additional_scripts',
1089 $results['scripts'],
1090 $initial_scripts,
1091 $results,
1092 $query_args,
1093 $wp_query
1094 );
1095
1096 if ( empty( $results['scripts'] ) )
1097 unset( $results['scripts' ] );
1098
1099 // Parse and sanitize the style handles already output
1100 $initial_styles = isset( $_REQUEST['styles'] ) && is_array( $_REQUEST['styles'] ) ? array_map( 'sanitize_text_field', $_REQUEST['styles'] ) : false;
1101
1102 if ( is_array( $initial_styles ) ) {
1103 global $wp_styles;
1104
1105 // Identify new styles needed by the latest set of IS posts
1106 $new_styles = array_diff( $wp_styles->done, $initial_styles );
1107
1108 // If new styles are needed, extract relevant data from $wp_styles
1109 if ( ! empty( $new_styles ) ) {
1110 $results['styles'] = array();
1111
1112 foreach ( $new_styles as $handle ) {
1113 // Abort if somehow the handle doesn't correspond to a registered stylesheet
1114 if ( ! isset( $wp_styles->registered[ $handle ] ) )
1115 continue;
1116
1117 // Provide basic style data
1118 $style_data = array(
1119 'handle' => $handle,
1120 'media' => 'all'
1121 );
1122
1123 // Base source
1124 $src = $wp_styles->registered[ $handle ]->src;
1125
1126 // Take base_url into account
1127 if ( strpos( $src, 'http' ) !== 0 )
1128 $src = $wp_styles->base_url . $src;
1129
1130 // Version and additional arguments
1131 if ( null === $wp_styles->registered[ $handle ]->ver )
1132 $ver = '';
1133 else
1134 $ver = $wp_styles->registered[ $handle ]->ver ? $wp_styles->registered[ $handle ]->ver : $wp_styles->default_version;
1135
1136 if ( isset($wp_styles->args[ $handle ] ) )
1137 $ver = $ver ? $ver . '&amp;' . $wp_styles->args[$handle] : $wp_styles->args[$handle];
1138
1139 // Full stylesheet source with version info
1140 $style_data['src'] = add_query_arg( 'ver', $ver, $src );
1141
1142 // Parse stylesheet's conditional comments if present, converting to logic executable in JS
1143 if ( isset( $wp_styles->registered[ $handle ]->extra['conditional'] ) && $wp_styles->registered[ $handle ]->extra['conditional'] ) {
1144 // First, convert conditional comment operators to standard logical operators. %ver is replaced in JS with the IE version
1145 $style_data['conditional'] = str_replace( array(
1146 'lte',
1147 'lt',
1148 'gte',
1149 'gt'
1150 ), array(
1151 '%ver <=',
1152 '%ver <',
1153 '%ver >=',
1154 '%ver >',
1155 ), $wp_styles->registered[ $handle ]->extra['conditional'] );
1156
1157 // 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().
1158 $style_data['conditional'] = preg_replace( '#!\s*IE(\s*\d+){0}#i', '1==2', $style_data['conditional'] );
1159
1160 // Lastly, remove the IE strings
1161 $style_data['conditional'] = str_replace( 'IE', '', $style_data['conditional'] );
1162 }
1163
1164 // Parse requested media context for stylesheet
1165 if ( isset( $wp_styles->registered[ $handle ]->args ) )
1166 $style_data['media'] = esc_attr( $wp_styles->registered[ $handle ]->args );
1167
1168 // Add stylesheet to data that will be returned to IS JS
1169 array_push( $results['styles'], $style_data );
1170 }
1171 }
1172 }
1173
1174 // Expose additional stylesheet data to filters, but only include in final `$results` array if needed.
1175 if ( ! isset( $results['styles'] ) )
1176 $results['styles'] = array();
1177
1178 /**
1179 * Filter the additional styles required by the latest set of IS posts.
1180 *
1181 * @module infinite-scroll
1182 *
1183 * @since 2.1.2
1184 *
1185 * @param array $results['styles'] Additional styles required by the latest set of IS posts.
1186 * @param array|bool $initial_styles Set of styles loaded on each page.
1187 * @param array $results Array of Infinite Scroll results.
1188 * @param array $query_args Array of Query arguments.
1189 * @param WP_Query $wp_query WP Query.
1190 */
1191 $results['styles'] = apply_filters(
1192 'infinite_scroll_additional_stylesheets',
1193 $results['styles'],
1194 $initial_styles,
1195 $results,
1196 $query_args,
1197 $wp_query
1198 );
1199
1200 if ( empty( $results['styles'] ) )
1201 unset( $results['styles' ] );
1202
1203 // Lastly, return the IS results array
1204 return $results;
1205 }
1206
1207 /**
1208 * Runs the query and returns the results via JSON.
1209 * Triggered by an AJAX request.
1210 *
1211 * @global $wp_query
1212 * @global $wp_the_query
1213 * @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
1214 * @return string or null
1215 */
1216 function query() {
1217 if ( ! isset( $_REQUEST['page'] ) || ! current_theme_supports( 'infinite-scroll' ) )
1218 die;
1219
1220 $page = (int) $_REQUEST['page'];
1221
1222 // Sanitize and set $previousday. Expected format: dd.mm.yy
1223 if ( preg_match( '/^\d{2}\.\d{2}\.\d{2}$/', $_REQUEST['currentday'] ) ) {
1224 global $previousday;
1225 $previousday = $_REQUEST['currentday'];
1226 }
1227
1228 $post_status = array( 'publish' );
1229 if ( current_user_can( 'read_private_posts' ) )
1230 array_push( $post_status, 'private' );
1231
1232 $order = in_array( $_REQUEST['order'], array( 'ASC', 'DESC' ) ) ? $_REQUEST['order'] : 'DESC';
1233
1234 $query_args = array_merge( self::wp_query()->query_vars, array(
1235 'paged' => $page,
1236 'post_status' => $post_status,
1237 'posts_per_page' => self::posts_per_page(),
1238 'order' => $order
1239 ) );
1240
1241 // 4.0 ?s= compatibility, see https://core.trac.wordpress.org/ticket/11330#comment:50
1242 if ( empty( $query_args['s'] ) && ! isset( self::wp_query()->query['s'] ) ) {
1243 unset( $query_args['s'] );
1244 }
1245
1246 // By default, don't query for a specific page of a paged post object.
1247 // This argument can come from merging self::wp_query() into $query_args above.
1248 // Since IS is only used on archives, we should always display the first page of any paged content.
1249 unset( $query_args['page'] );
1250
1251 /**
1252 * Filter the array of main query arguments.
1253 *
1254 * @module infinite-scroll
1255 *
1256 * @since 2.0.1
1257 *
1258 * @param array $query_args Array of Query arguments.
1259 */
1260 $query_args = apply_filters( 'infinite_scroll_query_args', $query_args );
1261
1262 add_filter( 'posts_where', array( $this, 'query_time_filter' ), 10, 2 );
1263
1264 $GLOBALS['wp_the_query'] = $GLOBALS['wp_query'] = $infinite_scroll_query = new WP_Query();
1265
1266 $infinite_scroll_query->query( $query_args );
1267
1268 remove_filter( 'posts_where', array( $this, 'query_time_filter' ), 10, 2 );
1269
1270 $results = array();
1271
1272 if ( have_posts() ) {
1273 // Fire wp_head to ensure that all necessary scripts are enqueued. Output isn't used, but scripts are extracted in self::action_wp_footer.
1274 ob_start();
1275 wp_head();
1276 while ( ob_get_length() ) {
1277 ob_end_clean();
1278 }
1279
1280 $results['type'] = 'success';
1281
1282 /**
1283 * 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.
1284 *
1285 * @module infinite-scroll
1286 *
1287 * @since 6.0.0
1288 */
1289 $callbacks = apply_filters( 'infinite_scroll_render_callbacks', array(
1290 self::get_settings()->render, // This is the setting callback e.g. from add theme support.
1291 ) );
1292
1293 // Append fallback callback. That rhymes.
1294 $callbacks[] = array( $this, 'render' );
1295
1296 foreach ( $callbacks as $callback ) {
1297 if ( false !== $callback && is_callable( $callback ) ) {
1298 rewind_posts();
1299 ob_start();
1300 add_action( 'infinite_scroll_render', $callback );
1301
1302 /**
1303 * Fires when rendering Infinite Scroll posts.
1304 *
1305 * @module infinite-scroll
1306 *
1307 * @since 2.0.0
1308 */
1309 do_action( 'infinite_scroll_render' );
1310
1311 $results['html'] = ob_get_clean();
1312 remove_action( 'infinite_scroll_render', $callback );
1313 }
1314 if ( ! empty( $results['html'] ) ) {
1315 break;
1316 }
1317 }
1318
1319 // If primary and fallback rendering methods fail, prevent further IS rendering attempts. Otherwise, wrap the output if requested.
1320 if ( empty( $results['html'] ) ) {
1321 unset( $results['html'] );
1322 /**
1323 * Fires when Infinite Scoll doesn't render any posts.
1324 *
1325 * @module infinite-scroll
1326 *
1327 * @since 2.0.0
1328 */
1329 do_action( 'infinite_scroll_empty' );
1330 $results['type'] = 'empty';
1331 } elseif ( $this->has_wrapper() ) {
1332 $wrapper_classes = is_string( self::get_settings()->wrapper ) ? self::get_settings()->wrapper : 'infinite-wrap';
1333 $wrapper_classes .= ' infinite-view-' . $page;
1334 $wrapper_classes = trim( $wrapper_classes );
1335
1336 $results['html'] = '<div class="' . esc_attr( $wrapper_classes ) . '" id="infinite-view-' . $page . '" data-page-num="' . $page . '">' . $results['html'] . '</div>';
1337 }
1338
1339 // Fire wp_footer to ensure that all necessary scripts are enqueued. Output isn't used, but scripts are extracted in self::action_wp_footer.
1340 ob_start();
1341 wp_footer();
1342 while ( ob_get_length() ) {
1343 ob_end_clean();
1344 }
1345
1346 if ( 'success' == $results['type'] ) {
1347 global $currentday;
1348 $results['lastbatch'] = self::is_last_batch();
1349 $results['currentday'] = $currentday;
1350 }
1351
1352 // Loop through posts to capture sharing data for new posts loaded via Infinite Scroll
1353 if ( 'success' == $results['type'] && function_exists( 'sharing_register_post_for_share_counts' ) ) {
1354 global $jetpack_sharing_counts;
1355
1356 while( have_posts() ) {
1357 the_post();
1358
1359 sharing_register_post_for_share_counts( get_the_ID() );
1360 }
1361
1362 $results['postflair'] = array_flip( $jetpack_sharing_counts );
1363 }
1364 } else {
1365 /** This action is already documented in modules/infinite-scroll/infinity.php */
1366 do_action( 'infinite_scroll_empty' );
1367 $results['type'] = 'empty';
1368 }
1369
1370 wp_send_json(
1371 /**
1372 * Filter the Infinite Scroll results.
1373 *
1374 * @module infinite-scroll
1375 *
1376 * @since 2.0.0
1377 *
1378 * @param array $results Array of Infinite Scroll results.
1379 * @param array $query_args Array of main query arguments.
1380 * @param WP_Query $wp_query WP Query.
1381 */
1382 apply_filters( 'infinite_scroll_results', $results, $query_args, self::wp_query() )
1383 );
1384 }
1385
1386 /**
1387 * Update the $allowed_vars array with the standard WP public and private
1388 * query vars, as well as taxonomy vars
1389 *
1390 * @global $wp
1391 * @param array $allowed_vars
1392 * @filter infinite_scroll_allowed_vars
1393 * @return array
1394 */
1395 function allowed_query_vars( $allowed_vars ) {
1396 global $wp;
1397
1398 $allowed_vars += $wp->public_query_vars;
1399 $allowed_vars += $wp->private_query_vars;
1400 $allowed_vars += $this->get_taxonomy_vars();
1401
1402 foreach ( array_keys( $allowed_vars, 'paged' ) as $key ) {
1403 unset( $allowed_vars[ $key ] );
1404 }
1405
1406 return array_unique( $allowed_vars );
1407 }
1408
1409 /**
1410 * Returns an array of stock and custom taxonomy query vars
1411 *
1412 * @global $wp_taxonomies
1413 * @return array
1414 */
1415 function get_taxonomy_vars() {
1416 global $wp_taxonomies;
1417
1418 $taxonomy_vars = array();
1419 foreach ( $wp_taxonomies as $taxonomy => $t ) {
1420 if ( $t->query_var )
1421 $taxonomy_vars[] = $t->query_var;
1422 }
1423
1424 // still needed?
1425 $taxonomy_vars[] = 'tag_id';
1426
1427 return $taxonomy_vars;
1428 }
1429
1430 /**
1431 * Update the $query_args array with the parameters provided via AJAX/GET.
1432 *
1433 * @param array $query_args
1434 * @filter infinite_scroll_query_args
1435 * @return array
1436 */
1437 function inject_query_args( $query_args ) {
1438 /**
1439 * Filter the array of allowed Infinite Scroll query arguments.
1440 *
1441 * @module infinite-scroll
1442 *
1443 * @since 2.6.0
1444 *
1445 * @param array $args Array of allowed Infinite Scroll query arguments.
1446 * @param array $query_args Array of query arguments.
1447 */
1448 $allowed_vars = apply_filters( 'infinite_scroll_allowed_vars', array(), $query_args );
1449
1450 $query_args = array_merge( $query_args, array(
1451 'suppress_filters' => false,
1452 ) );
1453
1454 if ( is_array( $_REQUEST[ 'query_args' ] ) ) {
1455 foreach ( $_REQUEST[ 'query_args' ] as $var => $value ) {
1456 if ( in_array( $var, $allowed_vars ) && ! empty( $value ) )
1457 $query_args[ $var ] = $value;
1458 }
1459 }
1460
1461 return $query_args;
1462 }
1463
1464 /**
1465 * Rendering fallback used when themes don't specify their own handler.
1466 *
1467 * @uses have_posts, the_post, get_template_part, get_post_format
1468 * @action infinite_scroll_render
1469 * @return string
1470 */
1471 function render() {
1472 while ( have_posts() ) {
1473 the_post();
1474
1475 get_template_part( 'content', get_post_format() );
1476 }
1477 }
1478
1479 /**
1480 * Allow plugins to filter what archives Infinite Scroll supports
1481 *
1482 * @uses current_theme_supports, is_home, is_archive, apply_filters, self::get_settings
1483 * @return bool
1484 */
1485 public static function archive_supports_infinity() {
1486 $supported = current_theme_supports( 'infinite-scroll' ) && ( is_home() || is_archive() || is_search() );
1487
1488 // Disable when previewing a non-active theme in the customizer
1489 if ( is_customize_preview() && ! $GLOBALS['wp_customize']->is_theme_active() ) {
1490 return false;
1491 }
1492
1493 /**
1494 * Allow plugins to filter what archives Infinite Scroll supports.
1495 *
1496 * @module infinite-scroll
1497 *
1498 * @since 2.0.0
1499 *
1500 * @param bool $supported Does the Archive page support Infinite Scroll.
1501 * @param object self::get_settings() IS settings provided by theme.
1502 */
1503 return (bool) apply_filters( 'infinite_scroll_archive_supported', $supported, self::get_settings() );
1504 }
1505
1506 /**
1507 * The Infinite Blog Footer
1508 *
1509 * @uses self::get_settings, self::archive_supports_infinity, self::default_footer
1510 * @return string or null
1511 */
1512 function footer() {
1513 // Bail if theme requested footer not show
1514 if ( false == self::get_settings()->footer )
1515 return;
1516
1517 // We only need the new footer for the 'scroll' type
1518 if ( 'scroll' != self::get_settings()->type || ! self::archive_supports_infinity() )
1519 return;
1520
1521 if ( self::is_last_batch() ) {
1522 return;
1523 }
1524
1525 // Display a footer, either user-specified or a default
1526 if ( false !== self::get_settings()->footer_callback && is_callable( self::get_settings()->footer_callback ) )
1527 call_user_func( self::get_settings()->footer_callback, self::get_settings() );
1528 else
1529 self::default_footer();
1530 }
1531
1532 /**
1533 * Render default IS footer
1534 *
1535 * @uses __, wp_get_theme, apply_filters, home_url, esc_attr, get_bloginfo, bloginfo
1536 * @return string
1537 *
1538 */
1539 private function default_footer() {
1540 if ( '' !== get_privacy_policy_url() ) {
1541 $credits = get_the_privacy_policy_link() . '<span role="separator" aria-hidden="true"> / </span>';
1542 } else {
1543 $credits = '';
1544 }
1545 $credits .= sprintf(
1546 '<a href="https://wordpress.org/" rel="noopener noreferrer" target="_blank" rel="generator">%1$s</a> ',
1547 __( 'Proudly powered by WordPress', 'jetpack' )
1548 );
1549 $credits .= sprintf(
1550 /* translators: %1$s is the name of a theme */
1551 __( 'Theme: %1$s.', 'jetpack' ),
1552 wp_get_theme()->Name
1553 );
1554 /**
1555 * Filter Infinite Scroll's credit text.
1556 *
1557 * @module infinite-scroll
1558 *
1559 * @since 2.0.0
1560 *
1561 * @param string $credits Infinite Scroll credits.
1562 */
1563 $credits = apply_filters( 'infinite_scroll_credit', $credits );
1564
1565 ?>
1566 <div id="infinite-footer">
1567 <div class="container">
1568 <div class="blog-info">
1569 <a id="infinity-blog-title" href="<?php echo home_url( '/' ); ?>" rel="home">
1570 <?php bloginfo( 'name' ); ?>
1571 </a>
1572 </div>
1573 <div class="blog-credits">
1574 <?php echo $credits; ?>
1575 </div>
1576 </div>
1577 </div><!-- #infinite-footer -->
1578 <?php
1579 }
1580
1581 /**
1582 * Ensure that IS doesn't interfere with Grunion by stripping IS query arguments from the Grunion redirect URL.
1583 * When arguments are present, Grunion redirects to the IS AJAX endpoint.
1584 *
1585 * @param string $url
1586 * @uses remove_query_arg
1587 * @filter grunion_contact_form_redirect_url
1588 * @return string
1589 */
1590 public function filter_grunion_redirect_url( $url ) {
1591 // Remove IS query args, if present
1592 if ( false !== strpos( $url, 'infinity=scrolling' ) ) {
1593 $url = remove_query_arg( array(
1594 'infinity',
1595 'action',
1596 'page',
1597 'order',
1598 'scripts',
1599 'styles'
1600 ), $url );
1601 }
1602
1603 return $url;
1604 }
1605 };
1606
1607 /**
1608 * Initialize The_Neverending_Home_Page
1609 */
1610 function the_neverending_home_page_init() {
1611 if ( ! current_theme_supports( 'infinite-scroll' ) )
1612 return;
1613
1614 new The_Neverending_Home_Page();
1615 }
1616 add_action( 'init', 'the_neverending_home_page_init', 20 );
1617
1618 /**
1619 * Check whether the current theme is infinite-scroll aware.
1620 * If so, include the files which add theme support.
1621 */
1622 function the_neverending_home_page_theme_support() {
1623 if (
1624 defined( 'IS_WPCOM' ) && IS_WPCOM &&
1625 defined( 'REST_API_REQUEST' ) && REST_API_REQUEST &&
1626 ! doing_action( 'restapi_theme_after_setup_theme' )
1627 ) {
1628 // Don't source theme compat files until we're in the site's context
1629 return;
1630 }
1631 $theme_name = get_stylesheet();
1632
1633 /**
1634 * Filter the path to the Infinite Scroll compatibility file.
1635 *
1636 * @module infinite-scroll
1637 *
1638 * @since 2.0.0
1639 *
1640 * @param string $str IS compatibility file path.
1641 * @param string $theme_name Theme name.
1642 */
1643 $customization_file = apply_filters( 'infinite_scroll_customization_file', dirname( __FILE__ ) . "/themes/{$theme_name}.php", $theme_name );
1644
1645 if ( is_readable( $customization_file ) )
1646 require_once( $customization_file );
1647 }
1648 add_action( 'after_setup_theme', 'the_neverending_home_page_theme_support', 5 );
1649
1650 /**
1651 * Early accommodation of the Infinite Scroll AJAX request
1652 */
1653 if ( The_Neverending_Home_Page::got_infinity() ) {
1654 /**
1655 * If we're sure this is an AJAX request (i.e. the HTTP_X_REQUESTED_WITH header says so),
1656 * indicate it as early as possible for actions like init
1657 */
1658 if ( ! defined( 'DOING_AJAX' ) &&
1659 isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) &&
1660 strtoupper( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'XMLHTTPREQUEST'
1661 ) {
1662 define( 'DOING_AJAX', true );
1663 }
1664
1665 // Don't load the admin bar when doing the AJAX response.
1666 show_admin_bar( false );
1667 }
1668