Nav apraksta

infinity.php 63KB

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