jetpack-related-posts.php 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608
  1. <?php
  2. class Jetpack_RelatedPosts {
  3. const VERSION = '20150408';
  4. const SHORTCODE = 'jetpack-related-posts';
  5. private static $instance = null;
  6. private static $instance_raw = null;
  7. /**
  8. * Creates and returns a static instance of Jetpack_RelatedPosts.
  9. *
  10. * @return Jetpack_RelatedPosts
  11. */
  12. public static function init() {
  13. if ( ! self::$instance ) {
  14. if ( class_exists('WPCOM_RelatedPosts') && method_exists( 'WPCOM_RelatedPosts', 'init' ) ) {
  15. self::$instance = WPCOM_RelatedPosts::init();
  16. } else {
  17. self::$instance = new Jetpack_RelatedPosts(
  18. get_current_blog_id(),
  19. Jetpack_Options::get_option( 'id' )
  20. );
  21. }
  22. }
  23. return self::$instance;
  24. }
  25. /**
  26. * Creates and returns a static instance of Jetpack_RelatedPosts_Raw.
  27. *
  28. * @return Jetpack_RelatedPosts
  29. */
  30. public static function init_raw() {
  31. if ( ! self::$instance_raw ) {
  32. if ( class_exists('WPCOM_RelatedPosts') && method_exists( 'WPCOM_RelatedPosts', 'init_raw' ) ) {
  33. self::$instance_raw = WPCOM_RelatedPosts::init_raw();
  34. } else {
  35. self::$instance_raw = new Jetpack_RelatedPosts_Raw(
  36. get_current_blog_id(),
  37. Jetpack_Options::get_option( 'id' )
  38. );
  39. }
  40. }
  41. return self::$instance_raw;
  42. }
  43. protected $_blog_id_local;
  44. protected $_blog_id_wpcom;
  45. protected $_options;
  46. protected $_allow_feature_toggle;
  47. protected $_blog_charset;
  48. protected $_convert_charset;
  49. protected $_previous_post_id;
  50. protected $_found_shortcode = false;
  51. /**
  52. * Constructor for Jetpack_RelatedPosts.
  53. *
  54. * @param int $blog_id_local
  55. * @param int $blog_id_wpcom
  56. * @uses get_option, add_action, apply_filters
  57. * @return null
  58. */
  59. public function __construct( $blog_id_local, $blog_id_wpcom ) {
  60. $this->_blog_id_local = $blog_id_local;
  61. $this->_blog_id_wpcom = $blog_id_wpcom;
  62. $this->_blog_charset = get_option( 'blog_charset' );
  63. $this->_convert_charset = ( function_exists( 'iconv' ) && ! preg_match( '/^utf\-?8$/i', $this->_blog_charset ) );
  64. add_action( 'admin_init', array( $this, 'action_admin_init' ) );
  65. add_action( 'wp', array( $this, 'action_frontend_init' ) );
  66. if ( ! class_exists( 'Jetpack_Media_Summary' ) ) {
  67. jetpack_require_lib( 'class.media-summary' );
  68. }
  69. // Add Related Posts to the REST API Post response.
  70. if ( function_exists( 'register_rest_field' ) ) {
  71. add_action( 'rest_api_init', array( $this, 'rest_register_related_posts' ) );
  72. }
  73. }
  74. /**
  75. * =================
  76. * ACTIONS & FILTERS
  77. * =================
  78. */
  79. /**
  80. * Add a checkbox field to Settings > Reading for enabling related posts.
  81. *
  82. * @action admin_init
  83. * @uses add_settings_field, __, register_setting, add_action
  84. * @return null
  85. */
  86. public function action_admin_init() {
  87. // Add the setting field [jetpack_relatedposts] and place it in Settings > Reading
  88. add_settings_field( 'jetpack_relatedposts', '<span id="jetpack_relatedposts">' . __( 'Related posts', 'jetpack' ) . '</span>', array( $this, 'print_setting_html' ), 'reading' );
  89. register_setting( 'reading', 'jetpack_relatedposts', array( $this, 'parse_options' ) );
  90. add_action('admin_head', array( $this, 'print_setting_head' ) );
  91. if( 'options-reading.php' == $GLOBALS['pagenow'] ) {
  92. // Enqueue style for live preview on the reading settings page
  93. $this->_enqueue_assets( false, true );
  94. }
  95. }
  96. /**
  97. * Load related posts assets if it's a elegiable front end page or execute search and return JSON if it's an endpoint request.
  98. *
  99. * @global $_GET
  100. * @action wp
  101. * @uses add_shortcode, get_the_ID
  102. * @returns null
  103. */
  104. public function action_frontend_init() {
  105. // Add a shortcode handler that outputs nothing, this gets overridden later if we can display related content
  106. add_shortcode( self::SHORTCODE, array( $this, 'get_target_html_unsupported' ) );
  107. if ( ! $this->_enabled_for_request() )
  108. return;
  109. if ( isset( $_GET['relatedposts'] ) ) {
  110. $excludes = array();
  111. if ( isset( $_GET['relatedposts_exclude'] ) ) {
  112. if ( is_string( $_GET['relatedposts_exclude'] ) ) {
  113. $excludes = explode( ',', $_GET['relatedposts_exclude'] );
  114. } elseif ( is_array( $_GET['relatedposts_exclude'] ) ) {
  115. $excludes = array_values( $_GET['relatedposts_exclude'] );
  116. }
  117. $excludes = array_unique( array_filter( array_map( 'absint', $excludes ) ) );
  118. }
  119. $this->_action_frontend_init_ajax( $excludes );
  120. } else {
  121. if ( isset( $_GET['relatedposts_hit'], $_GET['relatedposts_origin'], $_GET['relatedposts_position'] ) ) {
  122. $this->_log_click( $_GET['relatedposts_origin'], get_the_ID(), $_GET['relatedposts_position'] );
  123. $this->_previous_post_id = (int) $_GET['relatedposts_origin'];
  124. }
  125. $this->_action_frontend_init_page();
  126. }
  127. }
  128. /**
  129. * Render insertion point.
  130. *
  131. * @since 4.2.0
  132. *
  133. * @return string
  134. */
  135. public function get_headline() {
  136. $options = $this->get_options();
  137. if ( $options['show_headline'] ) {
  138. $headline = sprintf(
  139. /** This filter is already documented in modules/sharedaddy/sharing-service.php */
  140. apply_filters( 'jetpack_sharing_headline_html', '<h3 class="jp-relatedposts-headline"><em>%s</em></h3>', esc_html( $options['headline'] ), 'related-posts' ),
  141. esc_html( $options['headline'] )
  142. );
  143. } else {
  144. $headline = '';
  145. }
  146. return $headline;
  147. }
  148. /**
  149. * Adds a target to the post content to load related posts into if a shortcode for it did not already exist.
  150. *
  151. * @filter the_content
  152. * @param string $content
  153. * @returns string
  154. */
  155. public function filter_add_target_to_dom( $content ) {
  156. if ( !$this->_found_shortcode ) {
  157. $content .= "\n" . $this->get_target_html();
  158. }
  159. return $content;
  160. }
  161. /**
  162. * Looks for our shortcode on the unfiltered content, this has to execute early.
  163. *
  164. * @filter the_content
  165. * @param string $content
  166. * @uses has_shortcode
  167. * @returns string
  168. */
  169. public function test_for_shortcode( $content ) {
  170. $this->_found_shortcode = has_shortcode( $content, self::SHORTCODE );
  171. return $content;
  172. }
  173. /**
  174. * Returns the HTML for the related posts section.
  175. *
  176. * @uses esc_html__, apply_filters
  177. * @returns string
  178. */
  179. public function get_target_html() {
  180. require_once JETPACK__PLUGIN_DIR . '/sync/class.jetpack-sync-settings.php';
  181. if ( Jetpack_Sync_Settings::is_syncing() ) {
  182. return '';
  183. }
  184. /**
  185. * Filter the Related Posts headline.
  186. *
  187. * @module related-posts
  188. *
  189. * @since 3.0.0
  190. *
  191. * @param string $headline Related Posts heading.
  192. */
  193. $headline = apply_filters( 'jetpack_relatedposts_filter_headline', $this->get_headline() );
  194. if ( $this->_previous_post_id ) {
  195. $exclude = "data-exclude='{$this->_previous_post_id}'";
  196. } else {
  197. $exclude = "";
  198. }
  199. return <<<EOT
  200. <div id='jp-relatedposts' class='jp-relatedposts' $exclude>
  201. $headline
  202. </div>
  203. EOT;
  204. }
  205. /**
  206. * Returns the HTML for the related posts section if it's running in the loop or other instances where we don't support related posts.
  207. *
  208. * @returns string
  209. */
  210. public function get_target_html_unsupported() {
  211. require_once JETPACK__PLUGIN_DIR . '/sync/class.jetpack-sync-settings.php';
  212. if ( Jetpack_Sync_Settings::is_syncing() ) {
  213. return '';
  214. }
  215. return "\n\n<!-- Jetpack Related Posts is not supported in this context. -->\n\n";
  216. }
  217. /**
  218. * ========================
  219. * PUBLIC UTILITY FUNCTIONS
  220. * ========================
  221. */
  222. /**
  223. * Gets options set for Jetpack_RelatedPosts and merge with defaults.
  224. *
  225. * @uses Jetpack_Options::get_option, apply_filters
  226. * @return array
  227. */
  228. public function get_options() {
  229. if ( null === $this->_options ) {
  230. $this->_options = Jetpack_Options::get_option( 'relatedposts', array() );
  231. if ( ! is_array( $this->_options ) )
  232. $this->_options = array();
  233. if ( ! isset( $this->_options['enabled'] ) )
  234. $this->_options['enabled'] = true;
  235. if ( ! isset( $this->_options['show_headline'] ) )
  236. $this->_options['show_headline'] = true;
  237. if ( ! isset( $this->_options['show_thumbnails'] ) )
  238. $this->_options['show_thumbnails'] = false;
  239. if ( ! isset( $this->_options['show_date'] ) ) {
  240. $this->_options['show_date'] = true;
  241. }
  242. if ( ! isset( $this->_options['show_context'] ) ) {
  243. $this->_options['show_context'] = true;
  244. }
  245. if ( ! isset( $this->_options['layout'] ) ) {
  246. $this->_options['layout'] = 'grid';
  247. }
  248. if ( ! isset( $this->_options['headline'] ) ) {
  249. $this->_options['headline'] = esc_html__( 'Related', 'jetpack' );
  250. }
  251. if ( empty( $this->_options['size'] ) || (int)$this->_options['size'] < 1 )
  252. $this->_options['size'] = 3;
  253. /**
  254. * Filter Related Posts basic options.
  255. *
  256. * @module related-posts
  257. *
  258. * @since 2.8.0
  259. *
  260. * @param array $this->_options Array of basic Related Posts options.
  261. */
  262. $this->_options = apply_filters( 'jetpack_relatedposts_filter_options', $this->_options );
  263. }
  264. return $this->_options;
  265. }
  266. public function get_option( $option_name ) {
  267. $options = $this->get_options();
  268. if ( isset( $options[ $option_name ] ) ) {
  269. return $options[ $option_name ];
  270. }
  271. return false;
  272. }
  273. /**
  274. * Parses input and returns normalized options array.
  275. *
  276. * @param array $input
  277. * @uses self::get_options
  278. * @return array
  279. */
  280. public function parse_options( $input ) {
  281. $current = $this->get_options();
  282. if ( !is_array( $input ) )
  283. $input = array();
  284. if (
  285. ! isset( $input['enabled'] )
  286. || isset( $input['show_date'] )
  287. || isset( $input['show_context'] )
  288. || isset( $input['layout'] )
  289. || isset( $input['headline'] )
  290. ) {
  291. $input['enabled'] = '1';
  292. }
  293. if ( '1' == $input['enabled'] ) {
  294. $current['enabled'] = true;
  295. $current['show_headline'] = ( isset( $input['show_headline'] ) && '1' == $input['show_headline'] );
  296. $current['show_thumbnails'] = ( isset( $input['show_thumbnails'] ) && '1' == $input['show_thumbnails'] );
  297. $current['show_date'] = ( isset( $input['show_date'] ) && '1' == $input['show_date'] );
  298. $current['show_context'] = ( isset( $input['show_context'] ) && '1' == $input['show_context'] );
  299. $current['layout'] = isset( $input['layout'] ) && in_array( $input['layout'], array( 'grid', 'list' ), true ) ? $input['layout'] : 'grid';
  300. $current['headline'] = isset( $input['headline'] ) ? $input['headline'] : esc_html__( 'Related', 'jetpack' );
  301. } else {
  302. $current['enabled'] = false;
  303. }
  304. if ( isset( $input['size'] ) && (int)$input['size'] > 0 )
  305. $current['size'] = (int)$input['size'];
  306. else
  307. $current['size'] = null;
  308. return $current;
  309. }
  310. /**
  311. * HTML for admin settings page.
  312. *
  313. * @uses self::get_options, checked, esc_html__
  314. * @returns null
  315. */
  316. public function print_setting_html() {
  317. $options = $this->get_options();
  318. $ui_settings_template = <<<EOT
  319. <ul id="settings-reading-relatedposts-customize">
  320. <li>
  321. <label><input name="jetpack_relatedposts[show_headline]" type="checkbox" value="1" %s /> %s</label>
  322. </li>
  323. <li>
  324. <label><input name="jetpack_relatedposts[show_thumbnails]" type="checkbox" value="1" %s /> %s</label>
  325. </li>
  326. <li>
  327. <label><input name="jetpack_relatedposts[show_date]" type="checkbox" value="1" %s /> %s</label>
  328. </li>
  329. <li>
  330. <label><input name="jetpack_relatedposts[show_context]" type="checkbox" value="1" %s /> %s</label>
  331. </li>
  332. </ul>
  333. <div id='settings-reading-relatedposts-preview'>
  334. %s
  335. <div id="jp-relatedposts" class="jp-relatedposts"></div>
  336. </div>
  337. EOT;
  338. $ui_settings = sprintf(
  339. $ui_settings_template,
  340. checked( $options['show_headline'], true, false ),
  341. esc_html__( 'Highlight related content with a heading', 'jetpack' ),
  342. checked( $options['show_thumbnails'], true, false ),
  343. esc_html__( 'Show a thumbnail image where available', 'jetpack' ),
  344. checked( $options['show_date'], true, false ),
  345. esc_html__( 'Show entry date', 'jetpack' ),
  346. checked( $options['show_context'], true, false ),
  347. esc_html__( 'Show context (category or tag)', 'jetpack' ),
  348. esc_html__( 'Preview:', 'jetpack' )
  349. );
  350. if ( !$this->_allow_feature_toggle() ) {
  351. $template = <<<EOT
  352. <input type="hidden" name="jetpack_relatedposts[enabled]" value="1" />
  353. %s
  354. EOT;
  355. printf(
  356. $template,
  357. $ui_settings
  358. );
  359. } else {
  360. $template = <<<EOT
  361. <ul id="settings-reading-relatedposts">
  362. <li>
  363. <label><input type="radio" name="jetpack_relatedposts[enabled]" value="0" class="tog" %s /> %s</label>
  364. </li>
  365. <li>
  366. <label><input type="radio" name="jetpack_relatedposts[enabled]" value="1" class="tog" %s /> %s</label>
  367. %s
  368. </li>
  369. </ul>
  370. EOT;
  371. printf(
  372. $template,
  373. checked( $options['enabled'], false, false ),
  374. esc_html__( 'Hide related content after posts', 'jetpack' ),
  375. checked( $options['enabled'], true, false ),
  376. esc_html__( 'Show related content after posts', 'jetpack' ),
  377. $ui_settings
  378. );
  379. }
  380. }
  381. /**
  382. * Head JS/CSS for admin settings page.
  383. *
  384. * @uses esc_html__
  385. * @returns null
  386. */
  387. public function print_setting_head() {
  388. // only dislay the Related Posts JavaScript on the Reading Settings Admin Page
  389. $current_screen = get_current_screen();
  390. if ( is_null( $current_screen ) ) {
  391. return;
  392. }
  393. if( 'options-reading' != $current_screen->id )
  394. return;
  395. $related_headline = sprintf(
  396. '<h3 class="jp-relatedposts-headline"><em>%s</em></h3>',
  397. esc_html__( 'Related', 'jetpack' )
  398. );
  399. $href_params = 'class="jp-relatedposts-post-a" href="#jetpack_relatedposts" rel="nofollow" data-origin="0" data-position="0"';
  400. $related_with_images = <<<EOT
  401. <div class="jp-relatedposts-items jp-relatedposts-items-visual">
  402. <div class="jp-relatedposts-post jp-relatedposts-post0 jp-relatedposts-post-thumbs" data-post-id="0" data-post-format="image">
  403. <a $href_params>
  404. <img class="jp-relatedposts-post-img" src="https://jetpackme.files.wordpress.com/2014/08/1-wpios-ipad-3-1-viewsite.png?w=350&amp;h=200&amp;crop=1" width="350" alt="Big iPhone/iPad Update Now Available" scale="0">
  405. </a>
  406. <h4 class="jp-relatedposts-post-title">
  407. <a $href_params>Big iPhone/iPad Update Now Available</a>
  408. </h4>
  409. <p class="jp-relatedposts-post-excerpt">Big iPhone/iPad Update Now Available</p>
  410. <p class="jp-relatedposts-post-context">In "Mobile"</p>
  411. </div>
  412. <div class="jp-relatedposts-post jp-relatedposts-post1 jp-relatedposts-post-thumbs" data-post-id="0" data-post-format="image">
  413. <a $href_params>
  414. <img class="jp-relatedposts-post-img" src="https://jetpackme.files.wordpress.com/2014/08/wordpress-com-news-wordpress-for-android-ui-update2.jpg?w=350&amp;h=200&amp;crop=1" width="350" alt="The WordPress for Android App Gets a Big Facelift" scale="0">
  415. </a>
  416. <h4 class="jp-relatedposts-post-title">
  417. <a $href_params>The WordPress for Android App Gets a Big Facelift</a>
  418. </h4>
  419. <p class="jp-relatedposts-post-excerpt">The WordPress for Android App Gets a Big Facelift</p>
  420. <p class="jp-relatedposts-post-context">In "Mobile"</p>
  421. </div>
  422. <div class="jp-relatedposts-post jp-relatedposts-post2 jp-relatedposts-post-thumbs" data-post-id="0" data-post-format="image">
  423. <a $href_params>
  424. <img class="jp-relatedposts-post-img" src="https://jetpackme.files.wordpress.com/2014/08/videopresswedding.jpg?w=350&amp;h=200&amp;crop=1" width="350" alt="Upgrade Focus: VideoPress For Weddings" scale="0">
  425. </a>
  426. <h4 class="jp-relatedposts-post-title">
  427. <a $href_params>Upgrade Focus: VideoPress For Weddings</a>
  428. </h4>
  429. <p class="jp-relatedposts-post-excerpt">Upgrade Focus: VideoPress For Weddings</p>
  430. <p class="jp-relatedposts-post-context">In "Upgrade"</p>
  431. </div>
  432. </div>
  433. EOT;
  434. $related_with_images = str_replace( "\n", '', $related_with_images );
  435. $related_without_images = <<<EOT
  436. <div class="jp-relatedposts-items jp-relatedposts-items-minimal">
  437. <p class="jp-relatedposts-post jp-relatedposts-post0" data-post-id="0" data-post-format="image">
  438. <span class="jp-relatedposts-post-title"><a $href_params>Big iPhone/iPad Update Now Available</a></span>
  439. <span class="jp-relatedposts-post-context">In "Mobile"</span>
  440. </p>
  441. <p class="jp-relatedposts-post jp-relatedposts-post1" data-post-id="0" data-post-format="image">
  442. <span class="jp-relatedposts-post-title"><a $href_params>The WordPress for Android App Gets a Big Facelift</a></span>
  443. <span class="jp-relatedposts-post-context">In "Mobile"</span>
  444. </p>
  445. <p class="jp-relatedposts-post jp-relatedposts-post2" data-post-id="0" data-post-format="image">
  446. <span class="jp-relatedposts-post-title"><a $href_params>Upgrade Focus: VideoPress For Weddings</a></span>
  447. <span class="jp-relatedposts-post-context">In "Upgrade"</span>
  448. </p>
  449. </div>
  450. EOT;
  451. $related_without_images = str_replace( "\n", '', $related_without_images );
  452. if ( $this->_allow_feature_toggle() ) {
  453. $extra_css = '#settings-reading-relatedposts-customize { padding-left:2em; margin-top:.5em; }';
  454. } else {
  455. $extra_css = '';
  456. }
  457. echo <<<EOT
  458. <style type="text/css">
  459. #settings-reading-relatedposts .disabled { opacity:.5; filter:Alpha(opacity=50); }
  460. #settings-reading-relatedposts-preview .jp-relatedposts { background:#fff; padding:.5em; width:75%; }
  461. $extra_css
  462. </style>
  463. <script type="text/javascript">
  464. jQuery( document ).ready( function($) {
  465. var update_ui = function() {
  466. var is_enabled = true;
  467. if ( 'radio' == $( 'input[name="jetpack_relatedposts[enabled]"]' ).attr('type') ) {
  468. if ( '0' == $( 'input[name="jetpack_relatedposts[enabled]"]:checked' ).val() ) {
  469. is_enabled = false;
  470. }
  471. }
  472. if ( is_enabled ) {
  473. $( '#settings-reading-relatedposts-customize' )
  474. .removeClass( 'disabled' )
  475. .find( 'input' )
  476. .attr( 'disabled', false );
  477. $( '#settings-reading-relatedposts-preview' )
  478. .removeClass( 'disabled' );
  479. } else {
  480. $( '#settings-reading-relatedposts-customize' )
  481. .addClass( 'disabled' )
  482. .find( 'input' )
  483. .attr( 'disabled', true );
  484. $( '#settings-reading-relatedposts-preview' )
  485. .addClass( 'disabled' );
  486. }
  487. };
  488. var update_preview = function() {
  489. var html = '';
  490. if ( $( 'input[name="jetpack_relatedposts[show_headline]"]:checked' ).length ) {
  491. html += '$related_headline';
  492. }
  493. if ( $( 'input[name="jetpack_relatedposts[show_thumbnails]"]:checked' ).length ) {
  494. html += '$related_with_images';
  495. } else {
  496. html += '$related_without_images';
  497. }
  498. $( '#settings-reading-relatedposts-preview .jp-relatedposts' ).html( html );
  499. if ( $( 'input[name="jetpack_relatedposts[show_date]"]:checked' ).length ) {
  500. $( '.jp-relatedposts-post-title' ).each( function() {
  501. $( this ).after( $( '<span>August 8, 2005</span>' ) );
  502. } );
  503. }
  504. if ( $( 'input[name="jetpack_relatedposts[show_context]"]:checked' ).length ) {
  505. $( '.jp-relatedposts-post-context' ).show();
  506. } else {
  507. $( '.jp-relatedposts-post-context' ).hide();
  508. }
  509. $( '#settings-reading-relatedposts-preview .jp-relatedposts' ).show();
  510. };
  511. // Update on load
  512. update_preview();
  513. update_ui();
  514. // Update on change
  515. $( '#settings-reading-relatedposts-customize input' )
  516. .change( update_preview );
  517. $( '#settings-reading-relatedposts' )
  518. .find( 'input.tog' )
  519. .change( update_ui );
  520. });
  521. </script>
  522. EOT;
  523. }
  524. /**
  525. * Gets an array of related posts that match the given post_id.
  526. *
  527. * @param int $post_id
  528. * @param array $args - params to use when building Elasticsearch filters to narrow down the search domain.
  529. * @uses self::get_options, get_post_type, wp_parse_args, apply_filters
  530. * @return array
  531. */
  532. public function get_for_post_id( $post_id, array $args ) {
  533. $options = $this->get_options();
  534. if ( ! empty( $args['size'] ) ) {
  535. $options['size'] = $args['size'];
  536. }
  537. if ( ! $options['enabled'] || 0 == (int)$post_id || empty( $options['size'] ) || get_post_status( $post_id) !== 'publish' ) {
  538. return array();
  539. }
  540. $defaults = array(
  541. 'size' => (int)$options['size'],
  542. 'post_type' => get_post_type( $post_id ),
  543. 'post_formats' => array(),
  544. 'has_terms' => array(),
  545. 'date_range' => array(),
  546. 'exclude_post_ids' => array(),
  547. );
  548. $args = wp_parse_args( $args, $defaults );
  549. /**
  550. * Filter the arguments used to retrieve a list of Related Posts.
  551. *
  552. * @module related-posts
  553. *
  554. * @since 2.8.0
  555. *
  556. * @param array $args Array of options to retrieve Related Posts.
  557. * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
  558. */
  559. $args = apply_filters( 'jetpack_relatedposts_filter_args', $args, $post_id );
  560. $filters = $this->_get_es_filters_from_args( $post_id, $args );
  561. /**
  562. * Filter Elasticsearch options used to calculate Related Posts.
  563. *
  564. * @module related-posts
  565. *
  566. * @since 2.8.0
  567. *
  568. * @param array $filters Array of Elasticsearch filters based on the post_id and args.
  569. * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
  570. */
  571. $filters = apply_filters( 'jetpack_relatedposts_filter_filters', $filters, $post_id );
  572. $results = $this->_get_related_posts( $post_id, $args['size'], $filters );
  573. /**
  574. * Filter the array of related posts matched by Elasticsearch.
  575. *
  576. * @module related-posts
  577. *
  578. * @since 2.8.0
  579. *
  580. * @param array $results Array of related posts matched by Elasticsearch.
  581. * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
  582. */
  583. return apply_filters( 'jetpack_relatedposts_returned_results', $results, $post_id );
  584. }
  585. /**
  586. * =========================
  587. * PRIVATE UTILITY FUNCTIONS
  588. * =========================
  589. */
  590. /**
  591. * Creates an array of Elasticsearch filters based on the post_id and args.
  592. *
  593. * @param int $post_id
  594. * @param array $args
  595. * @uses apply_filters, get_post_types, get_post_format_strings
  596. * @return array
  597. */
  598. protected function _get_es_filters_from_args( $post_id, array $args ) {
  599. $filters = array();
  600. /**
  601. * Filter the terms used to search for Related Posts.
  602. *
  603. * @module related-posts
  604. *
  605. * @since 2.8.0
  606. *
  607. * @param array $args['has_terms'] Array of terms associated to the Related Posts.
  608. * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
  609. */
  610. $args['has_terms'] = apply_filters( 'jetpack_relatedposts_filter_has_terms', $args['has_terms'], $post_id );
  611. if ( ! empty( $args['has_terms'] ) ) {
  612. foreach( (array)$args['has_terms'] as $term ) {
  613. if ( mb_strlen( $term->taxonomy ) ) {
  614. switch ( $term->taxonomy ) {
  615. case 'post_tag':
  616. $tax_fld = 'tag.slug';
  617. break;
  618. case 'category':
  619. $tax_fld = 'category.slug';
  620. break;
  621. default:
  622. $tax_fld = 'taxonomy.' . $term->taxonomy . '.slug';
  623. break;
  624. }
  625. $filters[] = array( 'term' => array( $tax_fld => $term->slug ) );
  626. }
  627. }
  628. }
  629. /**
  630. * Filter the Post Types where we search Related Posts.
  631. *
  632. * @module related-posts
  633. *
  634. * @since 2.8.0
  635. *
  636. * @param array $args['post_type'] Array of Post Types.
  637. * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
  638. */
  639. $args['post_type'] = apply_filters( 'jetpack_relatedposts_filter_post_type', $args['post_type'], $post_id );
  640. $valid_post_types = get_post_types();
  641. if ( is_array( $args['post_type'] ) ) {
  642. $sanitized_post_types = array();
  643. foreach ( $args['post_type'] as $pt ) {
  644. if ( in_array( $pt, $valid_post_types ) )
  645. $sanitized_post_types[] = $pt;
  646. }
  647. if ( ! empty( $sanitized_post_types ) )
  648. $filters[] = array( 'terms' => array( 'post_type' => $sanitized_post_types ) );
  649. } else if ( in_array( $args['post_type'], $valid_post_types ) && 'all' != $args['post_type'] ) {
  650. $filters[] = array( 'term' => array( 'post_type' => $args['post_type'] ) );
  651. }
  652. /**
  653. * Filter the Post Formats where we search Related Posts.
  654. *
  655. * @module related-posts
  656. *
  657. * @since 3.3.0
  658. *
  659. * @param array $args['post_formats'] Array of Post Formats.
  660. * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
  661. */
  662. $args['post_formats'] = apply_filters( 'jetpack_relatedposts_filter_post_formats', $args['post_formats'], $post_id );
  663. $valid_post_formats = get_post_format_strings();
  664. $sanitized_post_formats = array();
  665. foreach ( $args['post_formats'] as $pf ) {
  666. if ( array_key_exists( $pf, $valid_post_formats ) ) {
  667. $sanitized_post_formats[] = $pf;
  668. }
  669. }
  670. if ( ! empty( $sanitized_post_formats ) ) {
  671. $filters[] = array( 'terms' => array( 'post_format' => $sanitized_post_formats ) );
  672. }
  673. /**
  674. * Filter the date range used to search Related Posts.
  675. *
  676. * @module related-posts
  677. *
  678. * @since 2.8.0
  679. *
  680. * @param array $args['date_range'] Array of a month interval where we search Related Posts.
  681. * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
  682. */
  683. $args['date_range'] = apply_filters( 'jetpack_relatedposts_filter_date_range', $args['date_range'], $post_id );
  684. if ( is_array( $args['date_range'] ) && ! empty( $args['date_range'] ) ) {
  685. $args['date_range'] = array_map( 'intval', $args['date_range'] );
  686. if ( !empty( $args['date_range']['from'] ) && !empty( $args['date_range']['to'] ) ) {
  687. $filters[] = array(
  688. 'range' => array(
  689. 'date_gmt' => $this->_get_coalesced_range( $args['date_range'] ),
  690. )
  691. );
  692. }
  693. }
  694. /**
  695. * Filter the Post IDs excluded from appearing in Related Posts.
  696. *
  697. * @module related-posts
  698. *
  699. * @since 2.9.0
  700. *
  701. * @param array $args['exclude_post_ids'] Array of Post IDs.
  702. * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
  703. */
  704. $args['exclude_post_ids'] = apply_filters( 'jetpack_relatedposts_filter_exclude_post_ids', $args['exclude_post_ids'], $post_id );
  705. if ( !empty( $args['exclude_post_ids'] ) && is_array( $args['exclude_post_ids'] ) ) {
  706. $excluded_post_ids = array();
  707. foreach ( $args['exclude_post_ids'] as $exclude_post_id) {
  708. $exclude_post_id = (int)$exclude_post_id;
  709. if ( $exclude_post_id > 0 )
  710. $excluded_post_ids[] = $exclude_post_id;
  711. }
  712. $filters[] = array( 'not' => array( 'terms' => array( 'post_id' => $excluded_post_ids ) ) );
  713. }
  714. return $filters;
  715. }
  716. /**
  717. * Takes a range and coalesces it into a month interval bracketed by a time as determined by the blog_id to enhance caching.
  718. *
  719. * @param array $date_range
  720. * @return array
  721. */
  722. protected function _get_coalesced_range( array $date_range ) {
  723. $now = time();
  724. $coalesce_time = $this->_blog_id_wpcom % 86400;
  725. $current_time = $now - strtotime( 'today', $now );
  726. if ( $current_time < $coalesce_time && '01' == date( 'd', $now ) ) {
  727. // Move back 1 period
  728. return array(
  729. 'from' => date( 'Y-m-01', strtotime( '-1 month', $date_range['from'] ) ) . ' ' . date( 'H:i:s', $coalesce_time ),
  730. 'to' => date( 'Y-m-01', $date_range['to'] ) . ' ' . date( 'H:i:s', $coalesce_time ),
  731. );
  732. } else {
  733. // Use current period
  734. return array(
  735. 'from' => date( 'Y-m-01', $date_range['from'] ) . ' ' . date( 'H:i:s', $coalesce_time ),
  736. 'to' => date( 'Y-m-01', strtotime( '+1 month', $date_range['to'] ) ) . ' ' . date( 'H:i:s', $coalesce_time ),
  737. );
  738. }
  739. }
  740. /**
  741. * Generate and output ajax response for related posts API call.
  742. * NOTE: Calls exit() to end all further processing after payload has been outputed.
  743. *
  744. * @param array $excludes array of post_ids to exclude
  745. * @uses send_nosniff_header, self::get_for_post_id, get_the_ID
  746. * @return null
  747. */
  748. protected function _action_frontend_init_ajax( array $excludes ) {
  749. define( 'DOING_AJAX', true );
  750. header( 'Content-type: application/json; charset=utf-8' ); // JSON can only be UTF-8
  751. send_nosniff_header();
  752. $options = $this->get_options();
  753. if ( isset( $_GET['jetpackrpcustomize'] ) ) {
  754. // If we're in the customizer, add dummy content.
  755. $date_now = current_time( get_option( 'date_format' ) );
  756. $related_posts = array(
  757. array(
  758. 'id' => - 1,
  759. 'url' => 'https://jetpackme.files.wordpress.com/2014/08/1-wpios-ipad-3-1-viewsite.png?w=350&h=200&crop=1',
  760. 'url_meta' => array(
  761. 'origin' => 0,
  762. 'position' => 0
  763. ),
  764. 'title' => esc_html__( 'Big iPhone/iPad Update Now Available', 'jetpack' ),
  765. 'date' => $date_now,
  766. 'format' => false,
  767. 'excerpt' => esc_html__( 'It is that time of the year when devices are shiny again.', 'jetpack' ),
  768. 'rel' => 'nofollow',
  769. 'context' => esc_html__( 'In "Mobile"', 'jetpack' ),
  770. 'img' => array(
  771. 'src' => 'https://jetpackme.files.wordpress.com/2014/08/1-wpios-ipad-3-1-viewsite.png?w=350&h=200&crop=1',
  772. 'width' => 350,
  773. 'height' => 200
  774. ),
  775. 'classes' => array()
  776. ),
  777. array(
  778. 'id' => - 1,
  779. 'url' => 'https://jetpackme.files.wordpress.com/2014/08/wordpress-com-news-wordpress-for-android-ui-update2.jpg?w=350&h=200&crop=1',
  780. 'url_meta' => array(
  781. 'origin' => 0,
  782. 'position' => 0
  783. ),
  784. 'title' => esc_html__( 'The WordPress for Android App Gets a Big Facelift', 'jetpack' ),
  785. 'date' => $date_now,
  786. 'format' => false,
  787. 'excerpt' => esc_html__( 'Writing is new again in Android with the new WordPress app.', 'jetpack' ),
  788. 'rel' => 'nofollow',
  789. 'context' => esc_html__( 'In "Mobile"', 'jetpack' ),
  790. 'img' => array(
  791. 'src' => 'https://jetpackme.files.wordpress.com/2014/08/wordpress-com-news-wordpress-for-android-ui-update2.jpg?w=350&h=200&crop=1',
  792. 'width' => 350,
  793. 'height' => 200
  794. ),
  795. 'classes' => array()
  796. ),
  797. array(
  798. 'id' => - 1,
  799. 'url' => 'https://jetpackme.files.wordpress.com/2014/08/videopresswedding.jpg?w=350&h=200&crop=1',
  800. 'url_meta' => array(
  801. 'origin' => 0,
  802. 'position' => 0
  803. ),
  804. 'title' => esc_html__( 'Upgrade Focus, VideoPress for weddings', 'jetpack' ),
  805. 'date' => $date_now,
  806. 'format' => false,
  807. 'excerpt' => esc_html__( 'Weddings are in the spotlight now with VideoPress for weddings.', 'jetpack' ),
  808. 'rel' => 'nofollow',
  809. 'context' => esc_html__( 'In "Mobile"', 'jetpack' ),
  810. 'img' => array(
  811. 'src' => 'https://jetpackme.files.wordpress.com/2014/08/videopresswedding.jpg?w=350&h=200&crop=1',
  812. 'width' => 350,
  813. 'height' => 200
  814. ),
  815. 'classes' => array()
  816. ),
  817. );
  818. for ( $total = 0; $total < $options['size'] - 3; $total++ ) {
  819. $related_posts[] = $related_posts[ $total ];
  820. }
  821. $current_post = get_post();
  822. // Exclude current post after filtering to make sure it's excluded and not lost during filtering.
  823. $excluded_posts = array_merge(
  824. /** This filter is already documented in modules/related-posts/jetpack-related-posts.php */
  825. apply_filters( 'jetpack_relatedposts_filter_exclude_post_ids', array() ),
  826. array( $current_post->ID )
  827. );
  828. // Fetch posts with featured image.
  829. $with_post_thumbnails = get_posts( array(
  830. 'posts_per_page' => $options['size'],
  831. 'post__not_in' => $excluded_posts,
  832. 'post_type' => $current_post->post_type,
  833. 'meta_key' => '_thumbnail_id',
  834. 'suppress_filters' => false,
  835. ) );
  836. // If we don't have enough, fetch posts without featured image.
  837. if ( 0 < ( $more = $options['size'] - count( $with_post_thumbnails ) ) ) {
  838. $no_post_thumbnails = get_posts( array(
  839. 'posts_per_page' => $more,
  840. 'post__not_in' => $excluded_posts,
  841. 'post_type' => $current_post->post_type,
  842. 'meta_query' => array(
  843. array(
  844. 'key' => '_thumbnail_id',
  845. 'compare' => 'NOT EXISTS',
  846. ),
  847. ),
  848. 'suppress_filters' => false,
  849. ) );
  850. } else {
  851. $no_post_thumbnails = array();
  852. }
  853. foreach ( array_merge( $with_post_thumbnails, $no_post_thumbnails ) as $index => $real_post ) {
  854. $related_posts[ $index ]['id'] = $real_post->ID;
  855. $related_posts[ $index ]['url'] = esc_url( get_permalink( $real_post ) );
  856. $related_posts[ $index ]['title'] = $this->_to_utf8( $this->_get_title( $real_post->post_title, $real_post->post_content ) );
  857. $related_posts[ $index ]['date'] = get_the_date( '', $real_post );
  858. $related_posts[ $index ]['excerpt'] = html_entity_decode( $this->_to_utf8( $this->_get_excerpt( $real_post->post_excerpt, $real_post->post_content ) ), ENT_QUOTES, 'UTF-8' );
  859. $related_posts[ $index ]['img'] = $this->_generate_related_post_image_params( $real_post->ID );
  860. $related_posts[ $index ]['context'] = $this->_generate_related_post_context( $real_post->ID );
  861. }
  862. } else {
  863. $related_posts = $this->get_for_post_id(
  864. get_the_ID(),
  865. array(
  866. 'exclude_post_ids' => $excludes,
  867. )
  868. );
  869. }
  870. $response = array(
  871. 'version' => self::VERSION,
  872. 'show_thumbnails' => (bool) $options['show_thumbnails'],
  873. 'show_date' => (bool) $options['show_date'],
  874. 'show_context' => (bool) $options['show_context'],
  875. 'layout' => (string) $options['layout'],
  876. 'headline' => (string) $options['headline'],
  877. 'items' => array(),
  878. );
  879. if ( count( $related_posts ) == $options['size'] )
  880. $response['items'] = $related_posts;
  881. echo json_encode( $response );
  882. exit();
  883. }
  884. /**
  885. * Returns a UTF-8 encoded array of post information for the given post_id
  886. *
  887. * @param int $post_id
  888. * @param int $position
  889. * @param int $origin The post id that this is related to
  890. * @uses get_post, get_permalink, remove_query_arg, get_post_format, apply_filters
  891. * @return array
  892. */
  893. protected function _get_related_post_data_for_post( $post_id, $position, $origin ) {
  894. $post = get_post( $post_id );
  895. return array(
  896. 'id' => $post->ID,
  897. 'url' => get_permalink( $post->ID ),
  898. 'url_meta' => array( 'origin' => $origin, 'position' => $position ),
  899. 'title' => $this->_to_utf8( $this->_get_title( $post->post_title, $post->post_content ) ),
  900. 'date' => get_the_date( '', $post->ID ),
  901. 'format' => get_post_format( $post->ID ),
  902. 'excerpt' => html_entity_decode( $this->_to_utf8( $this->_get_excerpt( $post->post_excerpt, $post->post_content ) ), ENT_QUOTES, 'UTF-8' ),
  903. /**
  904. * Filters the rel attribute for the Related Posts' links.
  905. *
  906. * @module related-posts
  907. *
  908. * @since 3.7.0
  909. *
  910. * @param string nofollow Link rel attribute for Related Posts' link. Default is nofollow.
  911. * @param int $post->ID Post ID.
  912. */
  913. 'rel' => apply_filters( 'jetpack_relatedposts_filter_post_link_rel', 'nofollow', $post->ID ),
  914. /**
  915. * Filter the context displayed below each Related Post.
  916. *
  917. * @module related-posts
  918. *
  919. * @since 3.0.0
  920. *
  921. * @param string $this->_to_utf8( $this->_generate_related_post_context( $post->ID ) ) Context displayed below each related post.
  922. * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
  923. */
  924. 'context' => apply_filters(
  925. 'jetpack_relatedposts_filter_post_context',
  926. $this->_to_utf8( $this->_generate_related_post_context( $post->ID ) ),
  927. $post->ID
  928. ),
  929. 'img' => $this->_generate_related_post_image_params( $post->ID ),
  930. /**
  931. * Filter the post css classes added on HTML markup.
  932. *
  933. * @module related-posts
  934. *
  935. * @since 3.8.0
  936. *
  937. * @param array array() CSS classes added on post HTML markup.
  938. * @param string $post_id Post ID.
  939. */
  940. 'classes' => apply_filters(
  941. 'jetpack_relatedposts_filter_post_css_classes',
  942. array(),
  943. $post->ID
  944. ),
  945. );
  946. }
  947. /**
  948. * Returns either the title or a small excerpt to use as title for post.
  949. *
  950. * @param string $post_title
  951. * @param string $post_content
  952. * @uses strip_shortcodes, wp_trim_words, __
  953. * @return string
  954. */
  955. protected function _get_title( $post_title, $post_content ) {
  956. if ( ! empty( $post_title ) ) {
  957. return wp_strip_all_tags( $post_title );
  958. }
  959. $post_title = wp_trim_words( wp_strip_all_tags( strip_shortcodes( $post_content ) ), 5, '…' );
  960. if ( ! empty( $post_title ) ) {
  961. return $post_title;
  962. }
  963. return __( 'Untitled Post', 'jetpack' );
  964. }
  965. /**
  966. * Returns a plain text post excerpt for title attribute of links.
  967. *
  968. * @param string $post_excerpt
  969. * @param string $post_content
  970. * @uses strip_shortcodes, wp_strip_all_tags, wp_trim_words
  971. * @return string
  972. */
  973. protected function _get_excerpt( $post_excerpt, $post_content ) {
  974. if ( empty( $post_excerpt ) )
  975. $excerpt = $post_content;
  976. else
  977. $excerpt = $post_excerpt;
  978. return wp_trim_words( wp_strip_all_tags( strip_shortcodes( $excerpt ) ), 50, '…' );
  979. }
  980. /**
  981. * Generates the thumbnail image to be used for the post. Uses the
  982. * image as returned by Jetpack_PostImages::get_image()
  983. *
  984. * @param int $post_id
  985. * @uses self::get_options, apply_filters, Jetpack_PostImages::get_image, Jetpack_PostImages::fit_image_url
  986. * @return string
  987. */
  988. protected function _generate_related_post_image_params( $post_id ) {
  989. $options = $this->get_options();
  990. $image_params = array(
  991. 'src' => '',
  992. 'width' => 0,
  993. 'height' => 0,
  994. );
  995. if ( ! $options['show_thumbnails'] ) {
  996. return $image_params;
  997. }
  998. /**
  999. * Filter the size of the Related Posts images.
  1000. *
  1001. * @module related-posts
  1002. *
  1003. * @since 2.8.0
  1004. *
  1005. * @param array array( 'width' => 350, 'height' => 200 ) Size of the images displayed below each Related Post.
  1006. */
  1007. $thumbnail_size = apply_filters(
  1008. 'jetpack_relatedposts_filter_thumbnail_size',
  1009. array( 'width' => 350, 'height' => 200 )
  1010. );
  1011. if ( !is_array( $thumbnail_size ) ) {
  1012. $thumbnail_size = array(
  1013. 'width' => (int)$thumbnail_size,
  1014. 'height' => (int)$thumbnail_size
  1015. );
  1016. }
  1017. // Try to get post image
  1018. if ( class_exists( 'Jetpack_PostImages' ) ) {
  1019. $img_url = '';
  1020. $post_image = Jetpack_PostImages::get_image(
  1021. $post_id,
  1022. $thumbnail_size
  1023. );
  1024. if ( is_array($post_image) ) {
  1025. $img_url = $post_image['src'];
  1026. } elseif ( class_exists( 'Jetpack_Media_Summary' ) ) {
  1027. $media = Jetpack_Media_Summary::get( $post_id );
  1028. if ( is_array($media) && !empty( $media['image'] ) ) {
  1029. $img_url = $media['image'];
  1030. }
  1031. }
  1032. if ( !empty( $img_url ) ) {
  1033. $image_params['width'] = $thumbnail_size['width'];
  1034. $image_params['height'] = $thumbnail_size['height'];
  1035. $image_params['src'] = Jetpack_PostImages::fit_image_url(
  1036. $img_url,
  1037. $thumbnail_size['width'],
  1038. $thumbnail_size['height']
  1039. );
  1040. }
  1041. }
  1042. return $image_params;
  1043. }
  1044. /**
  1045. * Returns the string UTF-8 encoded
  1046. *
  1047. * @param string $text
  1048. * @return string
  1049. */
  1050. protected function _to_utf8( $text ) {
  1051. if ( $this->_convert_charset ) {
  1052. return iconv( $this->_blog_charset, 'UTF-8', $text );
  1053. } else {
  1054. return $text;
  1055. }
  1056. }
  1057. /**
  1058. * =============================================
  1059. * PROTECTED UTILITY FUNCTIONS EXTENDED BY WPCOM
  1060. * =============================================
  1061. */
  1062. /**
  1063. * Workhorse method to return array of related posts matched by Elasticsearch.
  1064. *
  1065. * @param int $post_id
  1066. * @param int $size
  1067. * @param array $filters
  1068. * @uses wp_remote_post, is_wp_error, get_option, wp_remote_retrieve_body, get_post, add_query_arg, remove_query_arg, get_permalink, get_post_format, apply_filters
  1069. * @return array
  1070. */
  1071. protected function _get_related_posts( $post_id, $size, array $filters ) {
  1072. $hits = $this->_filter_non_public_posts(
  1073. $this->_get_related_post_ids(
  1074. $post_id,
  1075. $size,
  1076. $filters
  1077. )
  1078. );
  1079. /**
  1080. * Filter the Related Posts matched by Elasticsearch.
  1081. *
  1082. * @module related-posts
  1083. *
  1084. * @since 2.9.0
  1085. *
  1086. * @param array $hits Array of Post IDs matched by Elasticsearch.
  1087. * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
  1088. */
  1089. $hits = apply_filters( 'jetpack_relatedposts_filter_hits', $hits, $post_id );
  1090. $related_posts = array();
  1091. foreach ( $hits as $i => $hit ) {
  1092. $related_posts[] = $this->_get_related_post_data_for_post( $hit['id'], $i, $post_id );
  1093. }
  1094. return $related_posts;
  1095. }
  1096. /**
  1097. * Get array of related posts matched by Elasticsearch.
  1098. *
  1099. * @param int $post_id
  1100. * @param int $size
  1101. * @param array $filters
  1102. * @uses wp_remote_post, is_wp_error, wp_remote_retrieve_body, get_post_meta, update_post_meta
  1103. * @return array
  1104. */
  1105. protected function _get_related_post_ids( $post_id, $size, array $filters ) {
  1106. $now_ts = time();
  1107. $cache_meta_key = '_jetpack_related_posts_cache';
  1108. $body = array(
  1109. 'size' => (int) $size,
  1110. );
  1111. if ( !empty( $filters ) )
  1112. $body['filter'] = array( 'and' => $filters );
  1113. // Build cache key
  1114. $cache_key = md5( serialize( $body ) );
  1115. // Load all cached values
  1116. if ( wp_using_ext_object_cache() ) {
  1117. $transient_name = "{$cache_meta_key}_{$cache_key}_{$post_id}";
  1118. $cache = get_transient( $transient_name );
  1119. if ( false !== $cache ) {
  1120. return $cache;
  1121. }
  1122. } else {
  1123. $cache = get_post_meta( $post_id, $cache_meta_key, true );
  1124. if ( empty( $cache ) )
  1125. $cache = array();
  1126. // Cache is valid! Return cached value.
  1127. if ( isset( $cache[ $cache_key ] ) && is_array( $cache[ $cache_key ] ) && $cache[ $cache_key ][ 'expires' ] > $now_ts ) {
  1128. return $cache[ $cache_key ][ 'payload' ];
  1129. }
  1130. }
  1131. $response = wp_remote_post(
  1132. "https://public-api.wordpress.com/rest/v1/sites/{$this->_blog_id_wpcom}/posts/$post_id/related/",
  1133. array(
  1134. 'timeout' => 10,
  1135. 'user-agent' => 'jetpack_related_posts',
  1136. 'sslverify' => true,
  1137. 'body' => $body,
  1138. )
  1139. );
  1140. // Oh no... return nothing don't cache errors.
  1141. if ( is_wp_error( $response ) ) {
  1142. if ( isset( $cache[ $cache_key ] ) && is_array( $cache[ $cache_key ] ) )
  1143. return $cache[ $cache_key ][ 'payload' ]; // return stale
  1144. else
  1145. return array();
  1146. }
  1147. $results = json_decode( wp_remote_retrieve_body( $response ), true );
  1148. $related_posts = array();
  1149. if ( is_array( $results ) && !empty( $results['hits'] ) ) {
  1150. foreach( $results['hits'] as $hit ) {
  1151. $related_posts[] = array(
  1152. 'id' => $hit['fields']['post_id'],
  1153. );
  1154. }
  1155. }
  1156. // An empty array might indicate no related posts or that posts
  1157. // are not yet synced to WordPress.com, so we cache for only 1
  1158. // minute in this case
  1159. if ( empty( $related_posts ) ) {
  1160. $cache_ttl = 60;
  1161. } else {
  1162. $cache_ttl = 12 * HOUR_IN_SECONDS;
  1163. }
  1164. // Update cache
  1165. if ( wp_using_ext_object_cache() ) {
  1166. set_transient( $transient_name, $related_posts, $cache_ttl );
  1167. } else {
  1168. // Copy all valid cache values
  1169. $new_cache = array();
  1170. foreach ( $cache as $k => $v ) {
  1171. if ( is_array( $v ) && $v[ 'expires' ] > $now_ts ) {
  1172. $new_cache[ $k ] = $v;
  1173. }
  1174. }
  1175. // Set new cache value
  1176. $cache_expires = $cache_ttl + $now_ts;
  1177. $new_cache[ $cache_key ] = array(
  1178. 'expires' => $cache_expires,
  1179. 'payload' => $related_posts,
  1180. );
  1181. update_post_meta( $post_id, $cache_meta_key, $new_cache );
  1182. }
  1183. return $related_posts;
  1184. }
  1185. /**
  1186. * Filter out any hits that are not public anymore.
  1187. *
  1188. * @param array $related_posts
  1189. * @uses get_post_stati, get_post_status
  1190. * @return array
  1191. */
  1192. protected function _filter_non_public_posts( array $related_posts ) {
  1193. $public_stati = get_post_stati( array( 'public' => true ) );
  1194. $filtered = array();
  1195. foreach ( $related_posts as $hit ) {
  1196. if ( in_array( get_post_status( $hit['id'] ), $public_stati ) ) {
  1197. $filtered[] = $hit;
  1198. }
  1199. }
  1200. return $filtered;
  1201. }
  1202. /**
  1203. * Generates a context for the related content (second line in related post output).
  1204. * Order of importance:
  1205. * - First category (Not 'Uncategorized')
  1206. * - First post tag
  1207. * - Number of comments
  1208. *
  1209. * @param int $post_id
  1210. * @uses get_the_category, get_the_terms, get_comments_number, number_format_i18n, __, _n
  1211. * @return string
  1212. */
  1213. protected function _generate_related_post_context( $post_id ) {
  1214. $categories = get_the_category( $post_id );
  1215. if ( is_array( $categories ) ) {
  1216. foreach ( $categories as $category ) {
  1217. if ( 'uncategorized' != $category->slug && '' != trim( $category->name ) ) {
  1218. $post_cat_context = sprintf(
  1219. _x( 'In "%s"', 'in {category/tag name}', 'jetpack' ),
  1220. $category->name
  1221. );
  1222. /**
  1223. * Filter the "In Category" line displayed in the post context below each Related Post.
  1224. *
  1225. * @module related-posts
  1226. *
  1227. * @since 3.2.0
  1228. *
  1229. * @param string $post_cat_context "In Category" line displayed in the post context below each Related Post.
  1230. * @param array $category Array containing information about the category.
  1231. */
  1232. return apply_filters( 'jetpack_relatedposts_post_category_context', $post_cat_context, $category );
  1233. }
  1234. }
  1235. }
  1236. $tags = get_the_terms( $post_id, 'post_tag' );
  1237. if ( is_array( $tags ) ) {
  1238. foreach ( $tags as $tag ) {
  1239. if ( '' != trim( $tag->name ) ) {
  1240. $post_tag_context = sprintf(
  1241. _x( 'In "%s"', 'in {category/tag name}', 'jetpack' ),
  1242. $tag->name
  1243. );
  1244. /**
  1245. * Filter the "In Tag" line displayed in the post context below each Related Post.
  1246. *
  1247. * @module related-posts
  1248. *
  1249. * @since 3.2.0
  1250. *
  1251. * @param string $post_tag_context "In Tag" line displayed in the post context below each Related Post.
  1252. * @param array $tag Array containing information about the tag.
  1253. */
  1254. return apply_filters( 'jetpack_relatedposts_post_tag_context', $post_tag_context, $tag );
  1255. }
  1256. }
  1257. }
  1258. $comment_count = get_comments_number( $post_id );
  1259. if ( $comment_count > 0 ) {
  1260. return sprintf(
  1261. _n( 'With 1 comment', 'With %s comments', $comment_count, 'jetpack' ),
  1262. number_format_i18n( $comment_count )
  1263. );
  1264. }
  1265. return __( 'Similar post', 'jetpack' );
  1266. }
  1267. /**
  1268. * Logs clicks for clickthrough analysis and related result tuning.
  1269. *
  1270. * @return null
  1271. */
  1272. protected function _log_click( $post_id, $to_post_id, $link_position ) {
  1273. }
  1274. /**
  1275. * Determines if the current post is able to use related posts.
  1276. *
  1277. * @uses self::get_options, is_admin, is_single, apply_filters
  1278. * @return bool
  1279. */
  1280. protected function _enabled_for_request() {
  1281. $enabled = is_single()
  1282. &&
  1283. ! is_admin()
  1284. &&
  1285. ( !$this->_allow_feature_toggle() || $this->get_option( 'enabled' ) )
  1286. &&
  1287. ! Jetpack_AMP_Support::is_amp_request();
  1288. /**
  1289. * Filter the Enabled value to allow related posts to be shown on pages as well.
  1290. *
  1291. * @module related-posts
  1292. *
  1293. * @since 3.3.0
  1294. *
  1295. * @param bool $enabled Should Related Posts be enabled on the current page.
  1296. */
  1297. return apply_filters( 'jetpack_relatedposts_filter_enabled_for_request', $enabled );
  1298. }
  1299. /**
  1300. * Adds filters and enqueues assets.
  1301. *
  1302. * @uses self::_enqueue_assets, self::_setup_shortcode, add_filter
  1303. * @return null
  1304. */
  1305. protected function _action_frontend_init_page() {
  1306. $this->_enqueue_assets( true, true );
  1307. $this->_setup_shortcode();
  1308. add_filter( 'the_content', array( $this, 'filter_add_target_to_dom' ), 40 );
  1309. }
  1310. /**
  1311. * Enqueues assets needed to do async loading of related posts.
  1312. *
  1313. * @uses wp_enqueue_script, wp_enqueue_style, plugins_url
  1314. * @return null
  1315. */
  1316. protected function _enqueue_assets( $script, $style ) {
  1317. $dependencies = is_customize_preview() ? array( 'customize-base' ) : array( 'jquery' );
  1318. if ( $script ) {
  1319. wp_enqueue_script(
  1320. 'jetpack_related-posts',
  1321. Jetpack::get_file_url_for_environment(
  1322. '_inc/build/related-posts/related-posts.min.js',
  1323. 'modules/related-posts/related-posts.js'
  1324. ),
  1325. $dependencies,
  1326. self::VERSION
  1327. );
  1328. $related_posts_js_options = array(
  1329. /**
  1330. * Filter each Related Post Heading structure.
  1331. *
  1332. * @since 4.0.0
  1333. *
  1334. * @param string $str Related Post Heading structure. Default to h4.
  1335. */
  1336. 'post_heading' => apply_filters( 'jetpack_relatedposts_filter_post_heading', esc_attr( 'h4' ) ),
  1337. );
  1338. wp_localize_script( 'jetpack_related-posts', 'related_posts_js_options', $related_posts_js_options );
  1339. }
  1340. if ( $style ){
  1341. wp_enqueue_style( 'jetpack_related-posts', plugins_url( 'related-posts.css', __FILE__ ), array(), self::VERSION );
  1342. wp_style_add_data( 'jetpack_related-posts', 'rtl', 'replace' );
  1343. }
  1344. }
  1345. /**
  1346. * Sets up the shortcode processing.
  1347. *
  1348. * @uses add_filter, add_shortcode
  1349. * @return null
  1350. */
  1351. protected function _setup_shortcode() {
  1352. add_filter( 'the_content', array( $this, 'test_for_shortcode' ), 0 );
  1353. add_shortcode( self::SHORTCODE, array( $this, 'get_target_html' ) );
  1354. }
  1355. protected function _allow_feature_toggle() {
  1356. if ( null === $this->_allow_feature_toggle ) {
  1357. /**
  1358. * Filter the display of the Related Posts toggle in Settings > Reading.
  1359. *
  1360. * @module related-posts
  1361. *
  1362. * @since 2.8.0
  1363. *
  1364. * @param bool false Display a feature toggle. Default to false.
  1365. */
  1366. $this->_allow_feature_toggle = apply_filters( 'jetpack_relatedposts_filter_allow_feature_toggle', false );
  1367. }
  1368. return $this->_allow_feature_toggle;
  1369. }
  1370. /**
  1371. * ===================================================
  1372. * FUNCTIONS EXPOSING RELATED POSTS IN THE WP REST API
  1373. * ===================================================
  1374. */
  1375. /**
  1376. * Add Related Posts to the REST API Post response.
  1377. *
  1378. * @since 4.4.0
  1379. *
  1380. * @action rest_api_init
  1381. * @uses register_rest_field, self::rest_get_related_posts
  1382. * @return null
  1383. */
  1384. public function rest_register_related_posts() {
  1385. register_rest_field( 'post',
  1386. 'jetpack-related-posts',
  1387. array(
  1388. 'get_callback' => array( $this, 'rest_get_related_posts' ),
  1389. 'update_callback' => null,
  1390. 'schema' => null,
  1391. )
  1392. );
  1393. }
  1394. /**
  1395. * Build an array of Related Posts.
  1396. *
  1397. * @since 4.4.0
  1398. *
  1399. * @param array $object Details of current post.
  1400. * @param string $field_name Name of field.
  1401. * @param WP_REST_Request $request Current request
  1402. *
  1403. * @uses self::get_for_post_id
  1404. *
  1405. * @return array
  1406. */
  1407. public function rest_get_related_posts( $object, $field_name, $request ) {
  1408. return $this->get_for_post_id( $object['id'], array() );
  1409. }
  1410. }
  1411. class Jetpack_RelatedPosts_Raw extends Jetpack_RelatedPosts {
  1412. protected $_query_name;
  1413. /**
  1414. * Allows callers of this class to tag each query with a unique name for tracking purposes.
  1415. *
  1416. * @param string $name
  1417. * @return Jetpack_RelatedPosts_Raw
  1418. */
  1419. public function set_query_name( $name ) {
  1420. $this->_query_name = (string) $name;
  1421. return $this;
  1422. }
  1423. /**
  1424. * The raw related posts class can be used by other plugins or themes
  1425. * to get related content. This class wraps the existing RelatedPosts
  1426. * logic thus we never want to add anything to the DOM or do anything
  1427. * for event hooks. We will also not present any settings for this
  1428. * class and keep it enabled as calls to this class is done
  1429. * programmatically.
  1430. */
  1431. public function action_admin_init() {}
  1432. public function action_frontend_init() {}
  1433. public function get_options() {
  1434. return array(
  1435. 'enabled' => true,
  1436. );
  1437. }
  1438. /**
  1439. * Workhorse method to return array of related posts ids matched by Elasticsearch.
  1440. *
  1441. * @param int $post_id
  1442. * @param int $size
  1443. * @param array $filters
  1444. * @uses wp_remote_post, is_wp_error, wp_remote_retrieve_body
  1445. * @return array
  1446. */
  1447. protected function _get_related_posts( $post_id, $size, array $filters ) {
  1448. $hits = $this->_filter_non_public_posts(
  1449. $this->_get_related_post_ids(
  1450. $post_id,
  1451. $size,
  1452. $filters
  1453. )
  1454. );
  1455. /** This filter is already documented in modules/related-posts/related-posts.php */
  1456. $hits = apply_filters( 'jetpack_relatedposts_filter_hits', $hits, $post_id );
  1457. return $hits;
  1458. }
  1459. }