PageRenderTime 54ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/files/jetpack/2.3.1/infinite-scroll/infinity.php

https://gitlab.com/Mirros/jsdelivr
PHP | 983 lines | 563 code | 167 blank | 253 comment | 100 complexity | 8a3195ad84b6ccc18cf34b7a2fa9cae8 MD5 | raw file
  1. <?php
  2. /*
  3. Plugin Name: The Neverending Home Page.
  4. Plugin URI: http://automattic.com/
  5. 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.
  6. Version: 1.1
  7. Author: Automattic
  8. Author URI: http://automattic.com/
  9. License: GNU General Public License v2 or later
  10. License URI: http://www.gnu.org/licenses/gpl-2.0.html
  11. */
  12. /**
  13. * Class: The_Neverending_Home_Page relies on add_theme_support, expects specific
  14. * styling from each theme; including fixed footer.
  15. */
  16. class The_Neverending_Home_Page {
  17. /**
  18. * Register actions and filters, plus parse IS settings
  19. *
  20. * @uses add_action, add_filter, self::get_settings
  21. * @return null
  22. */
  23. function __construct() {
  24. add_action( 'pre_get_posts', array( $this, 'posts_per_page_query' ) );
  25. add_action( 'admin_init', array( $this, 'settings_api_init' ) );
  26. add_action( 'template_redirect', array( $this, 'action_template_redirect' ) );
  27. add_action( 'template_redirect', array( $this, 'ajax_response' ) );
  28. add_action( 'custom_ajax_infinite_scroll', array( $this, 'query' ) );
  29. add_action( 'the_post', array( $this, 'preserve_more_tag' ) );
  30. add_action( 'wp_footer', array( $this, 'footer' ) );
  31. // Plugin compatibility
  32. add_filter( 'grunion_contact_form_redirect_url', array( $this, 'filter_grunion_redirect_url' ) );
  33. // Parse IS settings from theme
  34. self::get_settings();
  35. }
  36. /**
  37. * Initialize our static variables
  38. */
  39. static $the_time = null;
  40. static $settings = null; // Don't access directly, instead use self::get_settings().
  41. static $option_name_enabled = 'infinite_scroll';
  42. /**
  43. * Parse IS settings provided by theme
  44. *
  45. * @uses get_theme_support, infinite_scroll_has_footer_widgets, sanitize_title, add_action, get_option, wp_parse_args, is_active_sidebar
  46. * @return object
  47. */
  48. static function get_settings() {
  49. if ( is_null( self::$settings ) ) {
  50. $css_pattern = '#[^A-Z\d\-_]#i';
  51. $settings = $defaults = array(
  52. 'type' => 'scroll', // scroll | click
  53. 'requested_type' => 'scroll', // store the original type for use when logic overrides it
  54. 'footer_widgets' => false, // true | false | sidebar_id | array of sidebar_ids -- last two are checked with is_active_sidebar
  55. 'container' => 'content', // container html id
  56. 'wrapper' => true, // true | false | html class
  57. 'render' => false, // optional function, otherwise the `content` template part will be used
  58. 'footer' => true, // boolean to enable or disable the infinite footer | string to provide an html id to derive footer width from
  59. 'footer_callback' => false, // function to be called to render the IS footer, in place of the default
  60. 'posts_per_page' => false // int | false to set based on IS type
  61. );
  62. // Validate settings passed through add_theme_support()
  63. $_settings = get_theme_support( 'infinite-scroll' );
  64. if ( is_array( $_settings ) ) {
  65. // Preferred implementation, where theme provides an array of options
  66. if ( isset( $_settings[0] ) && is_array( $_settings[0] ) ) {
  67. foreach ( $_settings[0] as $key => $value ) {
  68. switch ( $key ) {
  69. case 'type' :
  70. if ( in_array( $value, array( 'scroll', 'click' ) ) )
  71. $settings[ $key ] = $settings['requested_type'] = $value;
  72. break;
  73. case 'footer_widgets' :
  74. if ( is_string( $value ) )
  75. $settings[ $key ] = sanitize_title( $value );
  76. elseif ( is_array( $value ) )
  77. $settings[ $key ] = array_map( 'sanitize_title', $value );
  78. elseif ( is_bool( $value ) )
  79. $settings[ $key ] = $value;
  80. break;
  81. case 'container' :
  82. case 'wrapper' :
  83. if ( 'wrapper' == $key && is_bool( $value ) ) {
  84. $settings[ $key ] = $value;
  85. } else {
  86. $value = preg_replace( $css_pattern, '', $value );
  87. if ( ! empty( $value ) )
  88. $settings[ $key ] = $value;
  89. }
  90. break;
  91. case 'render' :
  92. if ( false !== $value && is_callable( $value ) ) {
  93. $settings[ $key ] = $value;
  94. add_action( 'infinite_scroll_render', $value );
  95. }
  96. break;
  97. case 'footer' :
  98. if ( is_bool( $value ) ) {
  99. $settings[ $key ] = $value;
  100. } elseif ( is_string( $value ) ) {
  101. $value = preg_replace( $css_pattern, '', $value );
  102. if ( ! empty( $value ) )
  103. $settings[ $key ] = $value;
  104. }
  105. break;
  106. case 'footer_callback' :
  107. if ( is_callable( $value ) )
  108. $settings[ $key ] = $value;
  109. else
  110. $settings[ $key ] = false;
  111. break;
  112. case 'posts_per_page' :
  113. if ( is_numeric( $value ) )
  114. $settings[ $key ] = (int) $value;
  115. break;
  116. default:
  117. continue;
  118. break;
  119. }
  120. }
  121. } elseif ( is_string( $_settings[0] ) ) {
  122. // Checks below are for backwards compatibility
  123. // Container to append new posts to
  124. $settings['container'] = preg_replace( $css_pattern, '', $_settings[0] );
  125. // Wrap IS elements?
  126. if ( isset( $_settings[1] ) )
  127. $settings['wrapper'] = (bool) $_settings[1];
  128. }
  129. }
  130. // Always ensure all values are present in the final array
  131. $settings = wp_parse_args( $settings, $defaults );
  132. // Check if a legacy `infinite_scroll_has_footer_widgets()` function is defined and override the footer_widgets parameter's value.
  133. // Otherwise, if a widget area ID or array of IDs was provided in the footer_widgets parameter, check if any contains any widgets.
  134. // 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.
  135. if ( function_exists( 'infinite_scroll_has_footer_widgets' ) ) {
  136. $settings['footer_widgets'] = (bool) infinite_scroll_has_footer_widgets();
  137. } elseif ( is_array( $settings['footer_widgets'] ) ) {
  138. $sidebar_ids = $settings['footer_widgets'];
  139. $settings['footer_widgets'] = false;
  140. foreach ( $sidebar_ids as $sidebar_id ) {
  141. if ( is_active_sidebar( $sidebar_id ) ) {
  142. $settings['footer_widgets'] = true;
  143. break;
  144. }
  145. }
  146. unset( $sidebar_ids );
  147. unset( $sidebar_id );
  148. } elseif ( is_string( $settings['footer_widgets'] ) ) {
  149. $settings['footer_widgets'] = (bool) is_active_sidebar( $settings['footer_widgets'] );
  150. }
  151. // For complex logic, let themes filter the `footer_widgets` parameter.
  152. $settings['footer_widgets'] = apply_filters( 'infinite_scroll_has_footer_widgets', $settings['footer_widgets'] );
  153. // Finally, after all of the sidebar checks and filtering, ensure that a boolean value is present, otherwise set to default of `false`.
  154. if ( ! is_bool( $settings['footer_widgets'] ) )
  155. $settings['footer_widgets'] = false;
  156. // Ensure that IS is enabled and no footer widgets exist if the IS type isn't already "click".
  157. if ( 'click' != $settings['type'] ) {
  158. // Check the setting status
  159. $disabled = '' === get_option( self::$option_name_enabled ) ? true : false;
  160. // Footer content or Reading option check
  161. if ( $settings['footer_widgets'] || $disabled )
  162. $settings['type'] = 'click';
  163. }
  164. // Backwards compatibility for posts_per_page setting
  165. if ( false === $settings['posts_per_page'] )
  166. $settings['posts_per_page'] = 'click' == $settings['type'] ? (int) get_option( 'posts_per_page' ) : 7;
  167. // Store final settings in a class static to avoid reparsing
  168. self::$settings = apply_filters( 'infinite_scroll_settings', $settings );
  169. }
  170. return (object) self::$settings;
  171. }
  172. /**
  173. * Retrieve the query used with Infinite Scroll
  174. *
  175. * @global $wp_the_query
  176. * @uses apply_filters
  177. * @return object
  178. */
  179. static function wp_query() {
  180. global $wp_the_query;
  181. return apply_filters( 'infinite_scroll_query_object', $wp_the_query );
  182. }
  183. /**
  184. * Has infinite scroll been triggered?
  185. */
  186. static function got_infinity() {
  187. return isset( $_GET[ 'infinity' ] );
  188. }
  189. /**
  190. * The more tag will be ignored by default if the blog page isn't our homepage.
  191. * Let's force the $more global to false.
  192. */
  193. function preserve_more_tag( $array ) {
  194. global $more;
  195. if ( self::got_infinity() )
  196. $more = 0; //0 = show content up to the more tag. Add more link.
  197. return $array;
  198. }
  199. /**
  200. * Add a checkbox field to Settings > Reading
  201. * for enabling infinite scroll.
  202. *
  203. * Only show if the current theme supports infinity.
  204. *
  205. * @uses current_theme_supports, add_settings_field, __, register_setting
  206. * @action admin_init
  207. * @return null
  208. */
  209. function settings_api_init() {
  210. if ( ! current_theme_supports( 'infinite-scroll' ) )
  211. return;
  212. // Add the setting field [infinite_scroll] and place it in Settings > Reading
  213. add_settings_field( self::$option_name_enabled, '<span id="infinite-scroll-options">' . __( 'To infinity and beyond', 'jetpack' ) . '</span>', array( $this, 'infinite_setting_html' ), 'reading' );
  214. register_setting( 'reading', self::$option_name_enabled, 'esc_attr' );
  215. }
  216. /**
  217. * HTML code to display a checkbox true/false option
  218. * for the infinite_scroll setting.
  219. */
  220. function infinite_setting_html() {
  221. $notice = '<em>' . __( "We've disabled this option for you since you have footer widgets in Appearance &rarr; Widgets, or because your theme does not support infinite scroll.", 'jetpack' ) . '</em>';
  222. // If the blog has footer widgets, show a notice instead of the checkbox
  223. if ( self::get_settings()->footer_widgets || 'click' == self::get_settings()->requested_type ) {
  224. echo '<label>' . $notice . '</label>';
  225. } else {
  226. echo '<label><input name="infinite_scroll" type="checkbox" value="1" ' . checked( 1, '' !== get_option( self::$option_name_enabled ), false ) . ' /> ' . __( 'Scroll Infinitely', 'jetpack' ) . '</br><small>' . sprintf( __( '(Shows %s posts on each load)', 'jetpack' ), number_format_i18n( self::get_settings()->posts_per_page ) ) . '</small>' . '</label>';
  227. }
  228. }
  229. /**
  230. * Does the legwork to determine whether the feature is enabled.
  231. *
  232. * @uses current_theme_supports, self::archive_supports_infinity, self::get_settings, self::set_last_post_time, add_filter, wp_enqueue_script, plugins_url, wp_enqueue_style, add_action
  233. * @action template_redirect
  234. * @return null
  235. */
  236. function action_template_redirect() {
  237. // Check that we support infinite scroll, and are on the home page.
  238. if ( ! current_theme_supports( 'infinite-scroll' ) || ! self::archive_supports_infinity() )
  239. return;
  240. $id = self::get_settings()->container;
  241. // Check that we have an id.
  242. if ( empty( $id ) )
  243. return;
  244. // Bail if there are not enough posts for infinity.
  245. if ( ! self::set_last_post_time() )
  246. return;
  247. // Add a class to the body.
  248. add_filter( 'body_class', array( $this, 'body_class' ) );
  249. // Add our scripts.
  250. wp_enqueue_script( 'the-neverending-homepage', plugins_url( 'infinity.js', __FILE__ ), array( 'jquery' ), '20130523' );
  251. // Add our default styles.
  252. wp_enqueue_style( 'the-neverending-homepage', plugins_url( 'infinity.css', __FILE__ ), array(), '20120612' );
  253. add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_spinner_scripts' ) );
  254. add_action( 'wp_head', array( $this, 'action_wp_head' ), 2 );
  255. add_action( 'wp_footer', array( $this, 'action_wp_footer' ), 99999999 );
  256. add_filter( 'infinite_scroll_results', array( $this, 'filter_infinite_scroll_results' ), 10, 3 );
  257. }
  258. /**
  259. * Enqueue spinner scripts.
  260. */
  261. function enqueue_spinner_scripts() {
  262. wp_enqueue_script( 'jquery.spin' );
  263. }
  264. /**
  265. * Adds an 'infinite-scroll' class to the body.
  266. */
  267. function body_class( $classes ) {
  268. $classes[] = 'infinite-scroll';
  269. if ( 'scroll' == self::get_settings()->type )
  270. $classes[] = 'neverending';
  271. return $classes;
  272. }
  273. /**
  274. * Grab the timestamp for the last post.
  275. * @return string 'Y-m-d H:i:s' or null
  276. */
  277. function set_last_post_time( $date = false ) {
  278. $posts = self::wp_query()->posts;
  279. $count = count( $posts );
  280. if ( ! empty( $date ) && preg_match( '|\d{4}\-\d{2}\-\d{2}|', $_GET['date'] ) ) {
  281. self::$the_time = "$date 00:00:00";
  282. return self::$the_time;
  283. }
  284. // If we don't have enough posts for infinity, return early
  285. if ( ! $count || $count < self::get_settings()->posts_per_page )
  286. return self::$the_time;
  287. $last_post = end( $posts );
  288. // If the function is called again but we already have a value, return it
  289. if ( null != self::$the_time ) {
  290. return self::$the_time;
  291. } elseif ( isset( $last_post->post_date_gmt ) ) {
  292. // Grab the latest post time in Y-m-d H:i:s gmt format
  293. self::$the_time = $last_post->post_date_gmt;
  294. }
  295. return self::$the_time;
  296. }
  297. /**
  298. * Create a where clause that will make sure post queries
  299. * will always return results prior to (descending sort)
  300. * or before (ascending sort) the last post date.
  301. *
  302. * @global $wpdb
  303. * @param string $where
  304. * @param object $query
  305. * @uses apply_filters
  306. * @uses self::set_last_post_time
  307. * @filter posts_where
  308. * @return string
  309. */
  310. function query_time_filter( $where, $query ) {
  311. global $wpdb;
  312. $operator = 'ASC' == $query->get( 'order' ) ? '>' : '<';
  313. // Construct the date query using our timestamp
  314. $clause = $wpdb->prepare( " AND {$wpdb->posts}.post_date_gmt {$operator} %s", self::set_last_post_time() );
  315. $where .= apply_filters( 'infinite_scroll_posts_where', $clause, $query, $operator, self::set_last_post_time() );
  316. return $where;
  317. }
  318. /**
  319. * Let's overwrite the default post_per_page setting to always display a fixed amount.
  320. *
  321. * @param object $query
  322. * @uses is_admin, self::archive_supports_infinity, self::get_settings
  323. * @return null
  324. */
  325. function posts_per_page_query( $query ) {
  326. if ( ! is_admin() && self::archive_supports_infinity() && $query->is_main_query() )
  327. $query->set( 'posts_per_page', self::get_settings()->posts_per_page );
  328. }
  329. /**
  330. * Check if the IS output should be wrapped in a div.
  331. * Setting value can be a boolean or a string specifying the class applied to the div.
  332. *
  333. * @uses self::get_settings
  334. * @return bool
  335. */
  336. function has_wrapper() {
  337. return (bool) self::get_settings()->wrapper;
  338. }
  339. /**
  340. * Returns the Ajax url
  341. *
  342. * @global $wp
  343. * @uses home_url, is_ssl, add_query_arg, trailingslashit, apply_filters
  344. * @return string
  345. */
  346. function ajax_url() {
  347. global $wp;
  348. // When using default permalinks, $wp->request will be null, so we reconstruct the request from the query arguments WP parsed.
  349. if ( is_null( $wp->request ) ) {
  350. $base_url = home_url( '/', is_ssl() ? 'https' : 'http' );
  351. $base_url = add_query_arg( $wp->query_vars, $base_url );
  352. } else {
  353. $base_url = home_url( trailingslashit( $wp->request ), is_ssl() ? 'https' : 'http' );
  354. }
  355. $ajaxurl = add_query_arg( array( 'infinity' => 'scrolling' ), $base_url );
  356. return apply_filters( 'infinite_scroll_ajax_url', $ajaxurl );
  357. }
  358. /**
  359. * Our own Ajax response, avoiding calling admin-ajax
  360. */
  361. function ajax_response() {
  362. // Only proceed if the url query has a key of "Infinity"
  363. if ( ! self::got_infinity() )
  364. return false;
  365. define( 'DOING_AJAX', true );
  366. @header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
  367. send_nosniff_header();
  368. do_action( 'custom_ajax_infinite_scroll' );
  369. die( '0' );
  370. }
  371. /**
  372. * Prints the relevant infinite scroll settings in JS.
  373. *
  374. * @global $wp_rewrite
  375. * @uses self::get_settings, esc_js, esc_url_raw, self::has_wrapper, __, apply_filters, do_action
  376. * @action wp_head
  377. * @return string
  378. */
  379. function action_wp_head() {
  380. global $wp_rewrite;
  381. // Base JS settings
  382. $js_settings = array(
  383. 'id' => self::get_settings()->container,
  384. 'ajaxurl' => esc_url_raw( self::ajax_url() ),
  385. 'type' => esc_js( self::get_settings()->type ),
  386. 'wrapper' => self::has_wrapper(),
  387. 'wrapper_class' => is_string( self::get_settings()->wrapper ) ? esc_js( self::get_settings()->wrapper ) : 'infinite-wrap',
  388. 'footer' => is_string( self::get_settings()->footer ) ? esc_js( self::get_settings()->footer ) : self::get_settings()->footer,
  389. 'text' => esc_js( __( 'Older posts', 'jetpack' ) ),
  390. 'totop' => esc_js( __( 'Scroll back to top', 'jetpack' ) ),
  391. 'order' => 'DESC',
  392. 'scripts' => array(),
  393. 'styles' => array(),
  394. 'google_analytics' => false,
  395. 'offset' => self::wp_query()->get( 'paged' ),
  396. 'history' => array(
  397. 'host' => preg_replace( '#^http(s)?://#i', '', untrailingslashit( get_option( 'home' ) ) ),
  398. 'path' => self::get_request_path(),
  399. 'use_trailing_slashes' => $wp_rewrite->use_trailing_slashes
  400. )
  401. );
  402. // Optional order param
  403. if ( isset( $_GET['order'] ) ) {
  404. $order = strtoupper( $_GET['order'] );
  405. if ( in_array( $order, array( 'ASC', 'DESC' ) ) )
  406. $js_settings['order'] = $order;
  407. }
  408. $js_settings = apply_filters( 'infinite_scroll_js_settings', $js_settings );
  409. do_action( 'infinite_scroll_wp_head' );
  410. ?>
  411. <script type="text/javascript">
  412. //<![CDATA[
  413. var infiniteScroll = <?php echo json_encode( array( 'settings' => $js_settings ) ); ?>;
  414. //]]>
  415. </script>
  416. <?php
  417. }
  418. /**
  419. * Build path data for current request.
  420. * Used for Google Analytics and pushState history tracking.
  421. *
  422. * @global $wp_rewrite
  423. * @global $wp
  424. * @uses user_trailingslashit, sanitize_text_field, add_query_arg
  425. * @return string|bool
  426. */
  427. private function get_request_path() {
  428. global $wp_rewrite;
  429. if ( $wp_rewrite->using_permalinks() ) {
  430. global $wp;
  431. // If called too early, bail
  432. if ( ! isset( $wp->request ) )
  433. return false;
  434. // Determine path for paginated version of current request
  435. if ( false != preg_match( '#' . $wp_rewrite->pagination_base . '/\d+/?$#i', $wp->request ) )
  436. $path = preg_replace( '#' . $wp_rewrite->pagination_base . '/\d+$#i', $wp_rewrite->pagination_base . '/%d', $wp->request );
  437. else
  438. $path = $wp->request . '/' . $wp_rewrite->pagination_base . '/%d';
  439. // Slashes everywhere we need them
  440. if ( 0 !== strpos( $path, '/' ) )
  441. $path = '/' . $path;
  442. $path = user_trailingslashit( $path );
  443. } else {
  444. // Clean up raw $_GET input
  445. $path = array_map( 'sanitize_text_field', $_GET );
  446. $path = array_filter( $path );
  447. $path['paged'] = '%d';
  448. $path = add_query_arg( $path, '/' );
  449. }
  450. return empty( $path ) ? false : $path;
  451. }
  452. /**
  453. * Provide IS with a list of the scripts and stylesheets already present on the page.
  454. * Since posts may contain require additional assets that haven't been loaded, this data will be used to track the additional assets.
  455. *
  456. * @global $wp_scripts, $wp_styles
  457. * @action wp_footer
  458. * @return string
  459. */
  460. function action_wp_footer() {
  461. global $wp_scripts, $wp_styles;
  462. $scripts = is_a( $wp_scripts, 'WP_Scripts' ) ? $wp_scripts->done : array();
  463. $scripts = apply_filters( 'infinite_scroll_existing_scripts', $scripts );
  464. $styles = is_a( $wp_styles, 'WP_Styles' ) ? $wp_styles->done : array();
  465. $styles = apply_filters( 'infinite_scroll_existing_stylesheets', $styles );
  466. ?><script type="text/javascript">
  467. jQuery.extend( infiniteScroll.settings.scripts, <?php echo json_encode( $scripts ); ?> );
  468. jQuery.extend( infiniteScroll.settings.styles, <?php echo json_encode( $styles ); ?> );
  469. </script><?php
  470. }
  471. /**
  472. * Identify additional scripts required by the latest set of IS posts and provide the necessary data to the IS response handler.
  473. *
  474. * @global $wp_scripts
  475. * @uses sanitize_text_field, add_query_arg
  476. * @filter infinite_scroll_results
  477. * @return array
  478. */
  479. function filter_infinite_scroll_results( $results, $query_args, $wp_query ) {
  480. // Don't bother unless there are posts to display
  481. if ( 'success' != $results['type'] )
  482. return $results;
  483. // Parse and sanitize the script handles already output
  484. $initial_scripts = isset( $_GET['scripts'] ) && is_array( $_GET['scripts'] ) ? array_map( 'sanitize_text_field', $_GET['scripts'] ) : false;
  485. if ( is_array( $initial_scripts ) ) {
  486. global $wp_scripts;
  487. // Identify new scripts needed by the latest set of IS posts
  488. $new_scripts = array_diff( $wp_scripts->done, $initial_scripts );
  489. // If new scripts are needed, extract relevant data from $wp_scripts
  490. if ( ! empty( $new_scripts ) ) {
  491. $results['scripts'] = array();
  492. foreach ( $new_scripts as $handle ) {
  493. // Abort if somehow the handle doesn't correspond to a registered script
  494. if ( ! isset( $wp_scripts->registered[ $handle ] ) )
  495. continue;
  496. // Provide basic script data
  497. $script_data = array(
  498. 'handle' => $handle,
  499. 'footer' => ( is_array( $wp_scripts->in_footer ) && in_array( $handle, $wp_scripts->in_footer ) ),
  500. 'extra_data' => $wp_scripts->print_extra_script( $handle, false )
  501. );
  502. // Base source
  503. $src = $wp_scripts->registered[ $handle ]->src;
  504. // Take base_url into account
  505. if ( strpos( $src, 'http' ) !== 0 )
  506. $src = $wp_scripts->base_url . $src;
  507. // Version and additional arguments
  508. if ( null === $wp_scripts->registered[ $handle ]->ver )
  509. $ver = '';
  510. else
  511. $ver = $wp_scripts->registered[ $handle ]->ver ? $wp_scripts->registered[ $handle ]->ver : $wp_scripts->default_version;
  512. if ( isset( $wp_scripts->args[ $handle ] ) )
  513. $ver = $ver ? $ver . '&amp;' . $wp_scripts->args[$handle] : $wp_scripts->args[$handle];
  514. // Full script source with version info
  515. $script_data['src'] = add_query_arg( 'ver', $ver, $src );
  516. // Add script to data that will be returned to IS JS
  517. array_push( $results['scripts'], $script_data );
  518. }
  519. }
  520. }
  521. // Expose additional script data to filters, but only include in final `$results` array if needed.
  522. if ( ! isset( $results['scripts'] ) )
  523. $results['scripts'] = array();
  524. $results['scripts'] = apply_filters( 'infinite_scroll_additional_scripts', $results['scripts'], $initial_scripts, $results, $query_args, $wp_query );
  525. if ( empty( $results['scripts'] ) )
  526. unset( $results['scripts' ] );
  527. // Parse and sanitize the style handles already output
  528. $initial_styles = isset( $_GET['styles'] ) && is_array( $_GET['styles'] ) ? array_map( 'sanitize_text_field', $_GET['styles'] ) : false;
  529. if ( is_array( $initial_styles ) ) {
  530. global $wp_styles;
  531. // Identify new styles needed by the latest set of IS posts
  532. $new_styles = array_diff( $wp_styles->done, $initial_styles );
  533. // If new styles are needed, extract relevant data from $wp_styles
  534. if ( ! empty( $new_styles ) ) {
  535. $results['styles'] = array();
  536. foreach ( $new_styles as $handle ) {
  537. // Abort if somehow the handle doesn't correspond to a registered stylesheet
  538. if ( ! isset( $wp_styles->registered[ $handle ] ) )
  539. continue;
  540. // Provide basic style data
  541. $style_data = array(
  542. 'handle' => $handle,
  543. 'media' => 'all'
  544. );
  545. // Base source
  546. $src = $wp_styles->registered[ $handle ]->src;
  547. // Take base_url into account
  548. if ( strpos( $src, 'http' ) !== 0 )
  549. $src = $wp_styles->base_url . $src;
  550. // Version and additional arguments
  551. if ( null === $wp_styles->registered[ $handle ]->ver )
  552. $ver = '';
  553. else
  554. $ver = $wp_styles->registered[ $handle ]->ver ? $wp_styles->registered[ $handle ]->ver : $wp_styles->default_version;
  555. if ( isset($wp_styles->args[ $handle ] ) )
  556. $ver = $ver ? $ver . '&amp;' . $wp_styles->args[$handle] : $wp_styles->args[$handle];
  557. // Full stylesheet source with version info
  558. $style_data['src'] = add_query_arg( 'ver', $ver, $src );
  559. // Parse stylesheet's conditional comments if present, converting to logic executable in JS
  560. if ( isset( $wp_styles->registered[ $handle ]->extra['conditional'] ) && $wp_styles->registered[ $handle ]->extra['conditional'] ) {
  561. // First, convert conditional comment operators to standard logical operators. %ver is replaced in JS with the IE version
  562. $style_data['conditional'] = str_replace( array(
  563. 'lte',
  564. 'lt',
  565. 'gte',
  566. 'gt'
  567. ), array(
  568. '%ver <=',
  569. '%ver <',
  570. '%ver >=',
  571. '%ver >',
  572. ), $wp_styles->registered[ $handle ]->extra['conditional'] );
  573. // 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().
  574. $style_data['conditional'] = preg_replace( '#!\s*IE(\s*\d+){0}#i', '1==2', $style_data['conditional'] );
  575. // Lastly, remove the IE strings
  576. $style_data['conditional'] = str_replace( 'IE', '', $style_data['conditional'] );
  577. }
  578. // Parse requested media context for stylesheet
  579. if ( isset( $wp_styles->registered[ $handle ]->args ) )
  580. $style_data['media'] = esc_attr( $wp_styles->registered[ $handle ]->args );
  581. // Add stylesheet to data that will be returned to IS JS
  582. array_push( $results['styles'], $style_data );
  583. }
  584. }
  585. }
  586. // Expose additional stylesheet data to filters, but only include in final `$results` array if needed.
  587. if ( ! isset( $results['styles'] ) )
  588. $results['styles'] = array();
  589. $results['styles'] = apply_filters( 'infinite_scroll_additional_stylesheets', $results['styles'], $initial_styles, $results, $query_args, $wp_query );
  590. if ( empty( $results['styles'] ) )
  591. unset( $results['styles' ] );
  592. // Lastly, return the IS results array
  593. return $results;
  594. }
  595. /**
  596. * Runs the query and returns the results via JSON.
  597. * Triggered by an AJAX request.
  598. *
  599. * @global $wp_query
  600. * @global $wp_the_query
  601. * @uses current_theme_supports, get_option, self::wp_query, self::set_last_post_time, 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
  602. * @return string or null
  603. */
  604. function query() {
  605. if ( ! isset( $_GET['page'] ) || ! current_theme_supports( 'infinite-scroll' ) )
  606. die;
  607. $page = (int) $_GET['page'];
  608. $sticky = get_option( 'sticky_posts' );
  609. $post__not_in = self::wp_query()->get( 'post__not_in' );
  610. if ( ! empty( $post__not_in ) )
  611. $sticky = array_unique( array_merge( $sticky, $post__not_in ) );
  612. if ( ! empty( $_GET['date'] ) )
  613. self::set_last_post_time( $_GET['date'] );
  614. $post_status = array( 'publish' );
  615. if ( current_user_can( 'read_private_posts' ) )
  616. array_push( $post_status, 'private' );
  617. $order = in_array( $_GET['order'], array( 'ASC', 'DESC' ) ) ? $_GET['order'] : 'DESC';
  618. $query_args = array_merge( self::wp_query()->query_vars, array(
  619. 'paged' => $page,
  620. 'post_status' => $post_status,
  621. 'posts_per_page' => self::get_settings()->posts_per_page,
  622. 'post__not_in' => ( array ) $sticky,
  623. 'order' => $order
  624. ) );
  625. // By default, don't query for a specific page of a paged post object.
  626. // This argument can come from merging self::wp_query() into $query_args above.
  627. // Since IS is only used on archives, we should always display the first page of any paged content.
  628. unset( $query_args['page'] );
  629. $query_args = apply_filters( 'infinite_scroll_query_args', $query_args );
  630. // Add query filter that checks for posts below the date
  631. add_filter( 'posts_where', array( $this, 'query_time_filter' ), 10, 2 );
  632. $GLOBALS['wp_the_query'] = $GLOBALS['wp_query'] = new WP_Query( $query_args );
  633. remove_filter( 'posts_where', array( $this, 'query_time_filter' ), 10, 2 );
  634. $results = array();
  635. if ( have_posts() ) {
  636. // Fire wp_head to ensure that all necessary scripts are enqueued. Output isn't used, but scripts are extracted in self::action_wp_footer.
  637. ob_start();
  638. wp_head();
  639. ob_end_clean();
  640. $results['type'] = 'success';
  641. // First, try theme's specified rendering handler, either specified via `add_theme_support` or by hooking to this action directly.
  642. ob_start();
  643. do_action( 'infinite_scroll_render' );
  644. $results['html'] = ob_get_clean();
  645. // Fall back if a theme doesn't specify a rendering function. Because themes may hook additional functions to the `infinite_scroll_render` action, `has_action()` is ineffective here.
  646. if ( empty( $results['html'] ) ) {
  647. add_action( 'infinite_scroll_render', array( $this, 'render' ) );
  648. rewind_posts();
  649. ob_start();
  650. do_action( 'infinite_scroll_render' );
  651. $results['html'] = ob_get_clean();
  652. }
  653. // If primary and fallback rendering methods fail, prevent further IS rendering attempts. Otherwise, wrap the output if requested.
  654. if ( empty( $results['html'] ) ) {
  655. unset( $results['html'] );
  656. do_action( 'infinite_scroll_empty' );
  657. $results['type'] = 'empty';
  658. } elseif ( $this->has_wrapper() ) {
  659. $wrapper_classes = is_string( self::get_settings()->wrapper ) ? self::get_settings()->wrapper : 'infinite-wrap';
  660. $wrapper_classes .= ' infinite-view-' . $page;
  661. $wrapper_classes = trim( $wrapper_classes );
  662. $results['html'] = '<div class="' . esc_attr( $wrapper_classes ) . '" id="infinite-view-' . $page . '" data-page-num="' . $page . '">' . $results['html'] . '</div>';
  663. }
  664. // Fire wp_footer to ensure that all necessary scripts are enqueued. Output isn't used, but scripts are extracted in self::action_wp_footer.
  665. ob_start();
  666. wp_footer();
  667. ob_end_clean();
  668. // Loop through posts to capture sharing data for new posts loaded via Infinite Scroll
  669. if ( 'success' == $results['type'] && function_exists( 'sharing_register_post_for_share_counts' ) ) {
  670. global $jetpack_sharing_counts;
  671. while( have_posts() ) {
  672. the_post();
  673. sharing_register_post_for_share_counts( get_the_ID() );
  674. }
  675. $results['postflair'] = array_flip( $jetpack_sharing_counts );
  676. }
  677. } else {
  678. do_action( 'infinite_scroll_empty' );
  679. $results['type'] = 'empty';
  680. }
  681. echo json_encode( apply_filters( 'infinite_scroll_results', $results, $query_args, self::wp_query() ) );
  682. die;
  683. }
  684. /**
  685. * Rendering fallback used when themes don't specify their own handler.
  686. *
  687. * @uses have_posts, the_post, get_template_part, get_post_format
  688. * @action infinite_scroll_render
  689. * @return string
  690. */
  691. function render() {
  692. while ( have_posts() ) {
  693. the_post();
  694. get_template_part( 'content', get_post_format() );
  695. }
  696. }
  697. /**
  698. * Allow plugins to filter what archives Infinite Scroll supports
  699. *
  700. * @uses current_theme_supports, is_home, is_archive, apply_filters, self::get_settings
  701. * @return bool
  702. */
  703. public static function archive_supports_infinity() {
  704. $supported = current_theme_supports( 'infinite-scroll' ) && ( is_home() || is_archive() );
  705. return (bool) apply_filters( 'infinite_scroll_archive_supported', $supported, self::get_settings() );
  706. }
  707. /**
  708. * The Infinite Blog Footer
  709. *
  710. * @uses self::get_settings, self::set_last_post_time, self::archive_supports_infinity, self::default_footer
  711. * @return string or null
  712. */
  713. function footer() {
  714. // Bail if theme requested footer not show
  715. if ( false == self::get_settings()->footer )
  716. return;
  717. // Bail if there are not enough posts for infinity.
  718. if ( ! self::set_last_post_time() )
  719. return;
  720. // We only need the new footer for the 'scroll' type
  721. if ( 'scroll' != self::get_settings()->type || ! self::archive_supports_infinity() )
  722. return;
  723. // Display a footer, either user-specified or a default
  724. if ( false !== self::get_settings()->footer_callback && is_callable( self::get_settings()->footer_callback ) )
  725. call_user_func( self::get_settings()->footer_callback, self::get_settings() );
  726. else
  727. self::default_footer();
  728. }
  729. /**
  730. * Render default IS footer
  731. *
  732. * @uses __, wp_get_theme, get_current_theme, apply_filters, home_url, esc_attr, get_bloginfo, bloginfo
  733. * @return string
  734. */
  735. private function default_footer() {
  736. $credits = '<a href="http://wordpress.org/" rel="generator">Proudly powered by WordPress</a> ';
  737. $credits .= sprintf( __( 'Theme: %1$s.', 'jetpack' ), function_exists( 'wp_get_theme' ) ? wp_get_theme()->Name : get_current_theme() );
  738. $credits = apply_filters( 'infinite_scroll_credit', $credits );
  739. ?>
  740. <div id="infinite-footer">
  741. <div class="container">
  742. <div class="blog-info">
  743. <a id="infinity-blog-title" href="<?php echo home_url( '/' ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home">
  744. <?php bloginfo( 'name' ); ?>
  745. </a>
  746. </div>
  747. <div class="blog-credits">
  748. <?php echo $credits; ?>
  749. </div>
  750. </div>
  751. </div><!-- #infinite-footer -->
  752. <?php
  753. }
  754. /**
  755. * Ensure that IS doesn't interfere with Grunion by stripping IS query arguments from the Grunion redirect URL.
  756. * When arguments are present, Grunion redirects to the IS AJAX endpoint.
  757. *
  758. * @param string $url
  759. * @uses remove_query_arg
  760. * @filter grunion_contact_form_redirect_url
  761. * @return string
  762. */
  763. public function filter_grunion_redirect_url( $url ) {
  764. // Remove IS query args, if present
  765. if ( false !== strpos( $url, 'infinity=scrolling' ) ) {
  766. $url = remove_query_arg( array(
  767. 'infinity',
  768. 'action',
  769. 'page',
  770. 'order',
  771. 'scripts',
  772. 'styles'
  773. ), $url );
  774. }
  775. return $url;
  776. }
  777. };
  778. /**
  779. * Initialize The_Neverending_Home_Page
  780. */
  781. function the_neverending_home_page_init() {
  782. if ( ! current_theme_supports( 'infinite-scroll' ) )
  783. return;
  784. new The_Neverending_Home_Page;
  785. }
  786. add_action( 'init', 'the_neverending_home_page_init', 20 );
  787. /**
  788. * Check whether the current theme is infinite-scroll aware.
  789. * If so, include the files which add theme support.
  790. */
  791. function the_neverending_home_page_theme_support() {
  792. $theme_name = get_stylesheet();
  793. $customization_file = apply_filters( 'infinite_scroll_customization_file', dirname( __FILE__ ) . "/themes/{$theme_name}.php", $theme_name );
  794. if ( is_readable( $customization_file ) )
  795. require_once( $customization_file );
  796. }
  797. add_action( 'after_setup_theme', 'the_neverending_home_page_theme_support', 5 );