PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 7.2.2
Jetpack – WP Security, Backup, Speed, & Growth v7.2.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.2.2, at modules/infinite-scroll/infinity.php

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