infinity.php 53 KB

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