Completed
Push — try/amp-related-posts ( c1b455...293a75 )
by
unknown
08:09
created

Jetpack_RelatedPosts::get_client_rendered_html()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 0
dl 0
loc 28
rs 9.472
c 0
b 0
f 0
1
<?php
2
3
use Automattic\Jetpack\Assets;
4
use Automattic\Jetpack\Sync\Settings;
5
6
class Jetpack_RelatedPosts {
7
	const VERSION   = '20190204';
8
	const SHORTCODE = 'jetpack-related-posts';
9
10
	private static $instance     = null;
11
	private static $instance_raw = null;
12
13
	/**
14
	 * Creates and returns a static instance of Jetpack_RelatedPosts.
15
	 *
16
	 * @return Jetpack_RelatedPosts
17
	 */
18
	public static function init() {
19
		if ( ! self::$instance ) {
20
			if ( class_exists('WPCOM_RelatedPosts') && method_exists( 'WPCOM_RelatedPosts', 'init' ) ) {
21
				self::$instance = WPCOM_RelatedPosts::init();
22
			} else {
23
				self::$instance = new Jetpack_RelatedPosts();
24
			}
25
		}
26
27
		return self::$instance;
28
	}
29
30
	/**
31
	 * Creates and returns a static instance of Jetpack_RelatedPosts_Raw.
32
	 *
33
	 * @return Jetpack_RelatedPosts
34
	 */
35
	public static function init_raw() {
36
		if ( ! self::$instance_raw ) {
37
			if ( class_exists('WPCOM_RelatedPosts') && method_exists( 'WPCOM_RelatedPosts', 'init_raw' ) ) {
38
				self::$instance_raw = WPCOM_RelatedPosts::init_raw();
39
			} else {
40
				self::$instance_raw = new Jetpack_RelatedPosts_Raw();
41
			}
42
		}
43
44
		return self::$instance_raw;
45
	}
46
47
	protected $_options;
48
	protected $_allow_feature_toggle;
49
	protected $_blog_charset;
50
	protected $_convert_charset;
51
	protected $_previous_post_id;
52
	protected $_found_shortcode = false;
53
54
	/**
55
	 * Constructor for Jetpack_RelatedPosts.
56
	 *
57
	 * @uses get_option, add_action, apply_filters
58
	 *
59
	 * @return null
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
60
	 */
61
	public function __construct() {
62
		$this->_blog_charset = get_option( 'blog_charset' );
63
		$this->_convert_charset = ( function_exists( 'iconv' ) && ! preg_match( '/^utf\-?8$/i', $this->_blog_charset ) );
64
65
		add_action( 'admin_init', array( $this, 'action_admin_init' ) );
66
		add_action( 'wp', array( $this, 'action_frontend_init' ) );
67
68
		if ( ! class_exists( 'Jetpack_Media_Summary' ) ) {
69
			jetpack_require_lib( 'class.media-summary' );
70
		}
71
72
		// Add Related Posts to the REST API Post response.
73
		add_action( 'rest_api_init', array( $this, 'rest_register_related_posts' ) );
74
75
		jetpack_register_block(
76
			'jetpack/related-posts',
77
			array(
78
				'render_callback' => array( $this, 'render_block' ),
79
			)
80
		);
81
	}
82
83
	protected function get_blog_id() {
84
		return Jetpack_Options::get_option( 'id' );
85
	}
86
87
	/**
88
	 * =================
89
	 * ACTIONS & FILTERS
90
	 * =================
91
	 */
92
93
	/**
94
	 * Add a checkbox field to Settings > Reading for enabling related posts.
95
	 *
96
	 * @action admin_init
97
	 * @uses add_settings_field, __, register_setting, add_action
98
	 * @return null
99
	 */
100
	public function action_admin_init() {
101
102
		// Add the setting field [jetpack_relatedposts] and place it in Settings > Reading
103
		add_settings_field( 'jetpack_relatedposts', '<span id="jetpack_relatedposts">' . __( 'Related posts', 'jetpack' ) . '</span>', array( $this, 'print_setting_html' ), 'reading' );
104
		register_setting( 'reading', 'jetpack_relatedposts', array( $this, 'parse_options' ) );
105
		add_action('admin_head', array( $this, 'print_setting_head' ) );
106
107
		if( 'options-reading.php' == $GLOBALS['pagenow'] ) {
108
			// Enqueue style for live preview on the reading settings page
109
			$this->_enqueue_assets( false, true );
110
		}
111
	}
112
113
	/**
114
	 * Load related posts assets if it's a elegiable front end page or execute search and return JSON if it's an endpoint request.
115
	 *
116
	 * @global $_GET
117
	 * @action wp
118
	 * @uses add_shortcode, get_the_ID
119
	 * @returns null
120
	 */
121
	public function action_frontend_init() {
122
		// Add a shortcode handler that outputs nothing, this gets overridden later if we can display related content
123
		add_shortcode( self::SHORTCODE, array( $this, 'get_client_rendered_html_unsupported' ) );
124
125
		if ( ! $this->_enabled_for_request() )
126
			return;
127
128
		if ( isset( $_GET['relatedposts'] ) ) {
129
			$excludes = $this->parse_numeric_get_arg( 'relatedposts_exclude' );
130
			$this->_action_frontend_init_ajax( $excludes );
131
		} else {
132
			if ( isset( $_GET['relatedposts_hit'], $_GET['relatedposts_origin'], $_GET['relatedposts_position'] ) ) {
133
				$this->_log_click( $_GET['relatedposts_origin'], get_the_ID(), $_GET['relatedposts_position'] );
134
				$this->_previous_post_id = (int) $_GET['relatedposts_origin'];
135
			}
136
137
			$this->_action_frontend_init_page();
138
		}
139
140
	}
141
142
	/**
143
	 * Render insertion point.
144
	 *
145
	 * @since 4.2.0
146
	 *
147
	 * @return string
148
	 */
149
	public function get_headline() {
150
		$options = $this->get_options();
151
152
		if ( $options['show_headline'] ) {
153
			$headline = sprintf(
154
				/** This filter is already documented in modules/sharedaddy/sharing-service.php */
155
				apply_filters( 'jetpack_sharing_headline_html', '<h3 class="jp-relatedposts-headline"><em>%s</em></h3>', esc_html( $options['headline'] ), 'related-posts' ),
156
				esc_html( $options['headline'] )
157
			);
158
		} else {
159
			$headline = '';
160
		}
161
		return $headline;
162
	}
163
164
	/**
165
	 * Adds a target to the post content to load related posts into if a shortcode for it did not already exist.
166
	 * Will skip adding the target if the post content contains a Related Posts block.
167
	 *
168
	 * @filter the_content
169
	 * @param string $content
170
	 * @returns string
171
	 */
172
	public function filter_add_target_to_dom( $content ) {
173
		if ( has_block( 'jetpack/related-posts', $content ) ) {
174
			return $content;
175
		}
176
177
		if ( ! $this->_found_shortcode ) {
178
			if ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() ) {
179
				$content .= "\n" . $this->get_server_rendered_html();
180
			} else {
181
				$content .= "\n" . $this->get_client_rendered_html();
182
			}
183
		}
184
185
		return $content;
186
	}
187
188
	/**
189
	 * Render static markup based on the Gutenberg block code
190
	 *
191
	 * @return string Rendered related posts HTML.
192
	 */
193
	function get_server_rendered_html() {
194
		$rp_settings = Jetpack_Options::get_option( 'relatedposts', array() );
195
		$block_rp_settings = array(
196
			'displayThumbnails' => $rp_settings['show_thumbnails'],
197
			'showHeadline' => $rp_settings['show_headline'],
198
			'displayDate' => isset( $rp_settings['show_date'] ) ? (bool) $rp_settings['show_date'] : true,
199
			'displayContext' => isset( $rp_settings['show_context'] ) && $rp_settings['show_context'],
200
			'postLayout' => isset( $rp_settings['layout'] ) ? $rp_settings['layout'] : 'grid',
201
			'postsToShow' => isset( $rp_settings['size'] ) ? $rp_settings['size'] : 3,
202
			'headline' => apply_filters( 'jetpack_relatedposts_filter_headline', $this->get_headline() )
203
		);
204
		return $this->render_block( $block_rp_settings );
205
	}
206
207
	/**
208
	 * Looks for our shortcode on the unfiltered content, this has to execute early.
209
	 *
210
	 * @filter the_content
211
	 * @param string $content
212
	 * @uses has_shortcode
213
	 * @returns string
214
	 */
215
	public function test_for_shortcode( $content ) {
216
		$this->_found_shortcode = has_shortcode( $content, self::SHORTCODE );
217
218
		return $content;
219
	}
220
221
	/**
222
	 * Returns the HTML for the related posts section.
223
	 *
224
	 * @uses esc_html__, apply_filters
225
	 * @returns string
226
	 */
227
	public function get_client_rendered_html() {
228
		if ( Settings::is_syncing() ) {
229
			return '';
230
		}
231
232
		/**
233
		 * Filter the Related Posts headline.
234
		 *
235
		 * @module related-posts
236
		 *
237
		 * @since 3.0.0
238
		 *
239
		 * @param string $headline Related Posts heading.
240
		 */
241
		$headline = apply_filters( 'jetpack_relatedposts_filter_headline', $this->get_headline() );
242
243
		if ( $this->_previous_post_id ) {
244
			$exclude = "data-exclude='{$this->_previous_post_id}'";
245
		} else {
246
			$exclude = "";
247
		}
248
249
		return <<<EOT
250
<div id='jp-relatedposts' class='jp-relatedposts' $exclude>
251
	$headline
252
</div>
253
EOT;
254
	}
255
256
	/**
257
	 * 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.
258
	 *
259
	 * @returns string
260
	 */
261
	public function get_client_rendered_html_unsupported() {
262
		if ( Settings::is_syncing() ) {
263
			return '';
264
		}
265
		return "\n\n<!-- Jetpack Related Posts is not supported in this context. -->\n\n";
266
	}
267
268
	/**
269
	 * ===============
270
	 * GUTENBERG BLOCK
271
	 * ===============
272
	 */
273
274
	/**
275
	 * Echoes out items for the Gutenberg block
276
	 *
277
	 * @param array $related_post The post oject.
278
	 * @param array $block_attributes The block attributes.
279
	 */
280
	public function render_block_item( $related_post, $block_attributes ) {
281
		$instance_id = 'related-posts-item-' . uniqid();
282
		$label_id    = $instance_id . '-label';
283
284
		$item_markup = sprintf(
285
			'<ul id="%1$s" aria-labelledby="%2$s" class="jp-related-posts-i2__post" role="menuitem">',
286
			esc_attr( $instance_id ),
287
			esc_attr( $label_id )
288
		);
289
290
		$item_markup .= sprintf(
291
			'<li class="jp-related-posts-i2__post-link"><a id="%1$s" href="%2$s" rel="%4$s">%3$s</a></li>',
292
			esc_attr( $label_id ),
293
			esc_url( $related_post['url'] ),
294
			esc_attr( $related_post['title'] ),
295
			esc_attr( $related_post['rel'] )
296
		);
297
298
		if ( ! empty( $block_attributes['show_thumbnails'] ) && ! empty( $related_post['img']['src'] ) ) {
299
			$img_link = sprintf(
300
				'<li class="jp-related-posts-i2__post-img-link"><a href="%1$s" rel="%2$s"><img src="%3$s" width="%4$s" alt="%5$s" /></a></li>',
301
				esc_url( $related_post['url'] ),
302
				esc_attr( $related_post['rel'] ),
303
				esc_url( $related_post['img']['src'] ),
304
				esc_attr( $related_post['img']['width'] ),
305
				esc_attr( $related_post['img']['alt_text'] )
306
			);
307
308
			$item_markup .= $img_link;
309
		}
310
311
		if ( $block_attributes['show_date'] ) {
312
			$date_tag = sprintf(
313
				'<li class="jp-related-posts-i2__post-date">%1$s</li>',
314
				esc_html( $related_post['date'] )
315
			);
316
317
			$item_markup .= $date_tag;
318
		}
319
320
		if ( ( $block_attributes['show_context'] ) && ! empty( $related_post['context'] ) ) {
321
			$context_tag = sprintf(
322
				'<li class="jp-related-posts-i2__post-context">%1$s</li>',
323
				esc_html( $related_post['context'] )
324
			);
325
326
			$item_markup .= $context_tag;
327
		}
328
329
		$item_markup .= '</ul>';
330
331
		return $item_markup;
332
	}
333
334
	/**
335
	 * Render a related posts row.
336
	 *
337
	 * @param array $posts The posts to render into the row.
338
	 * @param array $block_attributes Block attributes.
339
	 */
340
	public function render_block_row( $posts, $block_attributes ) {
341
		$rows_markup = '';
342
		foreach ( $posts as $post ) {
343
			$rows_markup .= $this->render_block_item( $post, $block_attributes );
344
		}
345
		return sprintf(
346
			'<div class="jp-related-posts-i2__row" data-post-count="%1$s">%2$s</div>',
347
			count( $posts ),
348
			$rows_markup
349
		);
350
	}
351
352
	/**
353
	 * Render the related posts markup.
354
	 *
355
	 * @param array $attributes Block attributes.
356
	 * @return string
357
	 */
358
	public function render_block( $attributes ) {
359
		$block_attributes = array(
360
			'headline'        => isset( $attributes['headline'] ) ? $attributes['headline'] : null,
361
			'show_thumbnails' => isset( $attributes['displayThumbnails'] ) && $attributes['displayThumbnails'],
362
			'show_date'       => isset( $attributes['displayDate'] ) ? (bool) $attributes['displayDate'] : true,
363
			'show_context'    => isset( $attributes['displayContext'] ) && $attributes['displayContext'],
364
			'layout'          => isset( $attributes['postLayout'] ) && 'list' === $attributes['postLayout'] ? $attributes['postLayout'] : 'grid',
365
			'size'            => ! empty( $attributes['postsToShow'] ) ? absint( $attributes['postsToShow'] ) : 3,
366
		);
367
368
		$excludes      = $this->parse_numeric_get_arg( 'relatedposts_origin' );
369
370
		$target_to_dom_priority = has_filter(
371
			'the_content',
372
			array( $this, 'filter_add_target_to_dom' )
373
		);
374
		remove_filter(
375
			'the_content',
376
			array( $this, 'filter_add_target_to_dom' ),
377
			$target_to_dom_priority
378
		);
379
380
		$related_posts = $this->get_for_post_id(
381
			get_the_ID(),
382
			array(
383
				'size'             => $block_attributes['size'],
384
				'exclude_post_ids' => $excludes,
385
			)
386
		);
387
388
		$display_lower_row = $block_attributes['size'] > 3;
389
390
		if ( empty( $related_posts ) ) {
391
			return '';
392
		}
393
394
		switch ( count( $related_posts ) ) {
395
			case 2:
396
			case 4:
397
			case 5:
398
				$top_row_end = 2;
399
				break;
400
401
			default:
402
				$top_row_end = 3;
403
				break;
404
		}
405
406
		$upper_row_posts = array_slice( $related_posts, 0, $top_row_end );
407
		$lower_row_posts = array_slice( $related_posts, $top_row_end );
408
409
		$rows_markup = $this->render_block_row( $upper_row_posts, $block_attributes );
410
		if ( $display_lower_row ) {
411
			$rows_markup .= $this->render_block_row( $lower_row_posts, $block_attributes );
412
		}
413
414
		/*
415
		 * Below is a hack to get the block content to render correctly.
416
		 *
417
		 * This functionality should be covered in /inc/blocks.php but due to an error,
418
		 * this has not been fixed as of this writing.
419
		 *
420
		 * Alda has submitted a patch to Core in order to have this issue fixed at
421
		 * https://core.trac.wordpress.org/ticket/45495 and
422
		 * made it into WordPress 5.2.
423
		 *
424
		 * @todo update when WP 5.2 is the minimum support version.
425
		 */
426
		$priority = has_filter( 'the_content', 'wpautop' );
427
		remove_filter( 'the_content', 'wpautop', $priority );
428
		add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 );
429
430
		return sprintf(
431
			'<nav class="jp-relatedposts-i2" data-layout="%1$s">%2$s%3$s</nav>',
432
			esc_attr( $block_attributes['layout'] ),
433
			$block_attributes['headline'],
434
			$rows_markup
435
		);
436
	}
437
438
	/**
439
	 * ========================
440
	 * PUBLIC UTILITY FUNCTIONS
441
	 * ========================
442
	 */
443
444
	/**
445
	 * Parse a numeric GET variable to an array of values.
446
	 *
447
	 * @since 6.9.0
448
	 *
449
	 * @uses absint
450
	 *
451
	 * @param string $arg Name of the GET variable
452
	 * @return array $result Parsed value(s)
453
	 */
454
	public function parse_numeric_get_arg( $arg ) {
455
		$result = array();
456
457
		if ( isset( $_GET[ $arg ] ) ) {
458
			if ( is_string( $_GET[ $arg ] ) ) {
459
				$result = explode( ',', $_GET[ $arg ] );
460
			} elseif ( is_array( $_GET[ $arg ] ) ) {
461
				$result = array_values( $_GET[ $arg ] );
462
			}
463
464
			$result = array_unique( array_filter( array_map( 'absint', $result ) ) );
465
		}
466
467
		return $result;
468
	}
469
470
	/**
471
	 * Gets options set for Jetpack_RelatedPosts and merge with defaults.
472
	 *
473
	 * @uses Jetpack_Options::get_option, apply_filters
474
	 * @return array
475
	 */
476
	public function get_options() {
477
		if ( null === $this->_options ) {
478
			$this->_options = Jetpack_Options::get_option( 'relatedposts', array() );
479
			if ( ! is_array( $this->_options ) )
480
				$this->_options = array();
481
			if ( ! isset( $this->_options['enabled'] ) )
482
				$this->_options['enabled'] = true;
483
			if ( ! isset( $this->_options['show_headline'] ) )
484
				$this->_options['show_headline'] = true;
485
			if ( ! isset( $this->_options['show_thumbnails'] ) )
486
				$this->_options['show_thumbnails'] = false;
487
			if ( ! isset( $this->_options['show_date'] ) ) {
488
				$this->_options['show_date'] = true;
489
			}
490
			if ( ! isset( $this->_options['show_context'] ) ) {
491
				$this->_options['show_context'] = true;
492
			}
493
			if ( ! isset( $this->_options['layout'] ) ) {
494
				$this->_options['layout'] = 'grid';
495
			}
496
			if ( ! isset( $this->_options['headline'] ) ) {
497
				$this->_options['headline'] = esc_html__( 'Related', 'jetpack' );
498
			}
499
			if ( empty( $this->_options['size'] ) || (int)$this->_options['size'] < 1 )
500
				$this->_options['size'] = 3;
501
502
			/**
503
			 * Filter Related Posts basic options.
504
			 *
505
			 * @module related-posts
506
			 *
507
			 * @since 2.8.0
508
			 *
509
			 * @param array $this->_options Array of basic Related Posts options.
510
			 */
511
			$this->_options = apply_filters( 'jetpack_relatedposts_filter_options', $this->_options );
512
		}
513
514
		return $this->_options;
515
	}
516
517
	public function get_option( $option_name ) {
518
		$options = $this->get_options();
519
520
		if ( isset( $options[ $option_name ] ) ) {
521
			return $options[ $option_name ];
522
		}
523
524
		return false;
525
	}
526
527
	/**
528
	 * Parses input and returns normalized options array.
529
	 *
530
	 * @param array $input
531
	 * @uses self::get_options
532
	 * @return array
533
	 */
534
	public function parse_options( $input ) {
535
		$current = $this->get_options();
536
537
		if ( !is_array( $input ) )
538
			$input = array();
539
540
		if (
541
			! isset( $input['enabled'] )
542
			|| isset( $input['show_date'] )
543
			|| isset( $input['show_context'] )
544
			|| isset( $input['layout'] )
545
			|| isset( $input['headline'] )
546
			) {
547
			$input['enabled'] = '1';
548
		}
549
550
		if ( '1' == $input['enabled'] ) {
551
			$current['enabled'] = true;
552
			$current['show_headline'] = ( isset( $input['show_headline'] ) && '1' == $input['show_headline'] );
553
			$current['show_thumbnails'] = ( isset( $input['show_thumbnails'] ) && '1' == $input['show_thumbnails'] );
554
			$current['show_date'] = ( isset( $input['show_date'] ) && '1' == $input['show_date'] );
555
			$current['show_context'] = ( isset( $input['show_context'] ) && '1' == $input['show_context'] );
556
			$current['layout'] = isset( $input['layout'] ) && in_array( $input['layout'], array( 'grid', 'list' ), true ) ? $input['layout'] : 'grid';
557
			$current['headline'] = isset( $input['headline'] ) ? $input['headline'] : esc_html__( 'Related', 'jetpack' );
558
		} else {
559
			$current['enabled'] = false;
560
		}
561
562
		if ( isset( $input['size'] ) && (int)$input['size'] > 0 )
563
			$current['size'] = (int)$input['size'];
564
		else
565
			$current['size'] = null;
566
567
		return $current;
568
	}
569
570
	/**
571
	 * HTML for admin settings page.
572
	 *
573
	 * @uses self::get_options, checked, esc_html__
574
	 * @returns null
575
	 */
576
	public function print_setting_html() {
577
		$options = $this->get_options();
578
579
		$ui_settings_template = <<<EOT
580
<p class="description">%s</p>
581
<ul id="settings-reading-relatedposts-customize">
582
	<li>
583
		<label><input name="jetpack_relatedposts[show_headline]" type="checkbox" value="1" %s /> %s</label>
584
	</li>
585
	<li>
586
		<label><input name="jetpack_relatedposts[show_thumbnails]" type="checkbox" value="1" %s /> %s</label>
587
	</li>
588
	<li>
589
		<label><input name="jetpack_relatedposts[show_date]" type="checkbox" value="1" %s /> %s</label>
590
	</li>
591
	<li>
592
		<label><input name="jetpack_relatedposts[show_context]" type="checkbox" value="1" %s /> %s</label>
593
	</li>
594
</ul>
595
<div id='settings-reading-relatedposts-preview'>
596
	%s
597
	<div id="jp-relatedposts" class="jp-relatedposts"></div>
598
</div>
599
EOT;
600
		$ui_settings = sprintf(
601
			$ui_settings_template,
602
			esc_html__( 'The following settings will impact all related posts on your site, except for those you created via the block editor:', 'jetpack' ),
603
			checked( $options['show_headline'], true, false ),
604
			esc_html__( 'Highlight related content with a heading', 'jetpack' ),
605
			checked( $options['show_thumbnails'], true, false ),
606
			esc_html__( 'Show a thumbnail image where available', 'jetpack' ),
607
			checked( $options['show_date'], true, false ),
608
			esc_html__( 'Show entry date', 'jetpack' ),
609
			checked( $options['show_context'], true, false ),
610
			esc_html__( 'Show context (category or tag)', 'jetpack' ),
611
			esc_html__( 'Preview:', 'jetpack' )
612
		);
613
614
		if ( !$this->_allow_feature_toggle() ) {
615
			$template = <<<EOT
616
<input type="hidden" name="jetpack_relatedposts[enabled]" value="1" />
617
%s
618
EOT;
619
			printf(
620
				$template,
621
				$ui_settings
622
			);
623
		} else {
624
			$template = <<<EOT
625
<ul id="settings-reading-relatedposts">
626
	<li>
627
		<label><input type="radio" name="jetpack_relatedposts[enabled]" value="0" class="tog" %s /> %s</label>
628
	</li>
629
	<li>
630
		<label><input type="radio" name="jetpack_relatedposts[enabled]" value="1" class="tog" %s /> %s</label>
631
		%s
632
	</li>
633
</ul>
634
EOT;
635
			printf(
636
				$template,
637
				checked( $options['enabled'], false, false ),
638
				esc_html__( 'Hide related content after posts', 'jetpack' ),
639
				checked( $options['enabled'], true, false ),
640
				esc_html__( 'Show related content after posts', 'jetpack' ),
641
				$ui_settings
642
			);
643
		}
644
	}
645
646
	/**
647
	 * Head JS/CSS for admin settings page.
648
	 *
649
	 * @uses esc_html__
650
	 * @returns null
651
	 */
652
	public function print_setting_head() {
653
654
		// only dislay the Related Posts JavaScript on the Reading Settings Admin Page
655
		$current_screen =  get_current_screen();
656
657
		if ( is_null( $current_screen ) ) {
658
			return;
659
		}
660
661
		if( 'options-reading' != $current_screen->id )
662
			return;
663
664
		$related_headline = sprintf(
665
			'<h3 class="jp-relatedposts-headline"><em>%s</em></h3>',
666
			esc_html__( 'Related', 'jetpack' )
667
		);
668
669
		$href_params = 'class="jp-relatedposts-post-a" href="#jetpack_relatedposts" rel="nofollow" data-origin="0" data-position="0"';
670
		$related_with_images = <<<EOT
671
<div class="jp-relatedposts-items jp-relatedposts-items-visual">
672
	<div class="jp-relatedposts-post jp-relatedposts-post0 jp-relatedposts-post-thumbs" data-post-id="0" data-post-format="image">
673
		<a $href_params>
674
			<img class="jp-relatedposts-post-img" src="https://jetpackme.files.wordpress.com/2019/03/cat-blog.png" width="350" alt="Big iPhone/iPad Update Now Available" scale="0">
675
		</a>
676
		<h4 class="jp-relatedposts-post-title">
677
			<a $href_params>Big iPhone/iPad Update Now Available</a>
678
		</h4>
679
		<p class="jp-relatedposts-post-excerpt">Big iPhone/iPad Update Now Available</p>
680
		<p class="jp-relatedposts-post-context">In "Mobile"</p>
681
	</div>
682
	<div class="jp-relatedposts-post jp-relatedposts-post1 jp-relatedposts-post-thumbs" data-post-id="0" data-post-format="image">
683
		<a $href_params>
684
			<img class="jp-relatedposts-post-img" src="https://jetpackme.files.wordpress.com/2019/03/devices.jpg" width="350" alt="The WordPress for Android App Gets a Big Facelift" scale="0">
685
		</a>
686
		<h4 class="jp-relatedposts-post-title">
687
			<a $href_params>The WordPress for Android App Gets a Big Facelift</a>
688
		</h4>
689
		<p class="jp-relatedposts-post-excerpt">The WordPress for Android App Gets a Big Facelift</p>
690
		<p class="jp-relatedposts-post-context">In "Mobile"</p>
691
	</div>
692
	<div class="jp-relatedposts-post jp-relatedposts-post2 jp-relatedposts-post-thumbs" data-post-id="0" data-post-format="image">
693
		<a $href_params>
694
			<img class="jp-relatedposts-post-img" src="https://jetpackme.files.wordpress.com/2019/03/mobile-wedding.jpg" width="350" alt="Upgrade Focus: VideoPress For Weddings" scale="0">
695
		</a>
696
		<h4 class="jp-relatedposts-post-title">
697
			<a $href_params>Upgrade Focus: VideoPress For Weddings</a>
698
		</h4>
699
		<p class="jp-relatedposts-post-excerpt">Upgrade Focus: VideoPress For Weddings</p>
700
		<p class="jp-relatedposts-post-context">In "Upgrade"</p>
701
	</div>
702
</div>
703
EOT;
704
		$related_with_images = str_replace( "\n", '', $related_with_images );
705
		$related_without_images = <<<EOT
706
<div class="jp-relatedposts-items jp-relatedposts-items-minimal">
707
	<p class="jp-relatedposts-post jp-relatedposts-post0" data-post-id="0" data-post-format="image">
708
		<span class="jp-relatedposts-post-title"><a $href_params>Big iPhone/iPad Update Now Available</a></span>
709
		<span class="jp-relatedposts-post-context">In "Mobile"</span>
710
	</p>
711
	<p class="jp-relatedposts-post jp-relatedposts-post1" data-post-id="0" data-post-format="image">
712
		<span class="jp-relatedposts-post-title"><a $href_params>The WordPress for Android App Gets a Big Facelift</a></span>
713
		<span class="jp-relatedposts-post-context">In "Mobile"</span>
714
	</p>
715
	<p class="jp-relatedposts-post jp-relatedposts-post2" data-post-id="0" data-post-format="image">
716
		<span class="jp-relatedposts-post-title"><a $href_params>Upgrade Focus: VideoPress For Weddings</a></span>
717
		<span class="jp-relatedposts-post-context">In "Upgrade"</span>
718
	</p>
719
</div>
720
EOT;
721
		$related_without_images = str_replace( "\n", '', $related_without_images );
722
723
		if ( $this->_allow_feature_toggle() ) {
724
			$extra_css = '#settings-reading-relatedposts-customize { padding-left:2em; margin-top:.5em; }';
725
		} else {
726
			$extra_css = '';
727
		}
728
729
		echo <<<EOT
730
<style type="text/css">
731
	#settings-reading-relatedposts .disabled { opacity:.5; filter:Alpha(opacity=50); }
732
	#settings-reading-relatedposts-preview .jp-relatedposts { background:#fff; padding:.5em; width:75%; }
733
	$extra_css
734
</style>
735
<script type="text/javascript">
736
	jQuery( document ).ready( function($) {
737
		var update_ui = function() {
738
			var is_enabled = true;
739
			if ( 'radio' == $( 'input[name="jetpack_relatedposts[enabled]"]' ).attr('type') ) {
740
				if ( '0' == $( 'input[name="jetpack_relatedposts[enabled]"]:checked' ).val() ) {
741
					is_enabled = false;
742
				}
743
			}
744
			if ( is_enabled ) {
745
				$( '#settings-reading-relatedposts-customize' )
746
					.removeClass( 'disabled' )
747
					.find( 'input' )
748
					.attr( 'disabled', false );
749
				$( '#settings-reading-relatedposts-preview' )
750
					.removeClass( 'disabled' );
751
			} else {
752
				$( '#settings-reading-relatedposts-customize' )
753
					.addClass( 'disabled' )
754
					.find( 'input' )
755
					.attr( 'disabled', true );
756
				$( '#settings-reading-relatedposts-preview' )
757
					.addClass( 'disabled' );
758
			}
759
		};
760
761
		var update_preview = function() {
762
			var html = '';
763
			if ( $( 'input[name="jetpack_relatedposts[show_headline]"]:checked' ).length ) {
764
				html += '$related_headline';
765
			}
766
			if ( $( 'input[name="jetpack_relatedposts[show_thumbnails]"]:checked' ).length ) {
767
				html += '$related_with_images';
768
			} else {
769
				html += '$related_without_images';
770
			}
771
			$( '#settings-reading-relatedposts-preview .jp-relatedposts' ).html( html );
772
			if ( $( 'input[name="jetpack_relatedposts[show_date]"]:checked' ).length ) {
773
				$( '.jp-relatedposts-post-title' ).each( function() {
774
					$( this ).after( $( '<span>August 8, 2005</span>' ) );
775
				} );
776
			}
777
			if ( $( 'input[name="jetpack_relatedposts[show_context]"]:checked' ).length ) {
778
				$( '.jp-relatedposts-post-context' ).show();
779
			} else {
780
				$( '.jp-relatedposts-post-context' ).hide();
781
			}
782
			$( '#settings-reading-relatedposts-preview .jp-relatedposts' ).show();
783
		};
784
785
		// Update on load
786
		update_preview();
787
		update_ui();
788
789
		// Update on change
790
		$( '#settings-reading-relatedposts-customize input' )
791
			.change( update_preview );
792
		$( '#settings-reading-relatedposts' )
793
			.find( 'input.tog' )
794
			.change( update_ui );
795
	});
796
</script>
797
EOT;
798
	}
799
800
	/**
801
	 * Gets an array of related posts that match the given post_id.
802
	 *
803
	 * @param int   $post_id Post which we want to find related posts for.
804
	 * @param array $args - params to use when building Elasticsearch filters to narrow down the search domain.
805
	 * @uses self::get_options, get_post_type, wp_parse_args, apply_filters
806
	 * @return array
807
	 */
808
	public function get_for_post_id( $post_id, array $args ) {
809
		$options = $this->get_options();
810
811
		if ( ! empty( $args['size'] ) ) {
812
			$options['size'] = $args['size'];
813
		}
814
815
		if (
816
			! $options['enabled']
817
			|| 0 === (int) $post_id
818
			|| empty( $options['size'] )
819
		) {
820
			return array();
821
		}
822
823
		$defaults = array(
824
			'size'             => (int) $options['size'],
825
			'post_type'        => get_post_type( $post_id ),
826
			'post_formats'     => array(),
827
			'has_terms'        => array(),
828
			'date_range'       => array(),
829
			'exclude_post_ids' => array(),
830
		);
831
		$args     = wp_parse_args( $args, $defaults );
832
		/**
833
		 * Filter the arguments used to retrieve a list of Related Posts.
834
		 *
835
		 * @module related-posts
836
		 *
837
		 * @since 2.8.0
838
		 *
839
		 * @param array $args Array of options to retrieve Related Posts.
840
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
841
		 */
842
		$args = apply_filters( 'jetpack_relatedposts_filter_args', $args, $post_id );
843
844
		$filters = $this->_get_es_filters_from_args( $post_id, $args );
845
		/**
846
		 * Filter Elasticsearch options used to calculate Related Posts.
847
		 *
848
		 * @module related-posts
849
		 *
850
		 * @since 2.8.0
851
		 *
852
		 * @param array $filters Array of Elasticsearch filters based on the post_id and args.
853
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
854
		 */
855
		$filters = apply_filters( 'jetpack_relatedposts_filter_filters', $filters, $post_id );
856
857
		$results = $this->_get_related_posts( $post_id, $args['size'], $filters );
858
		/**
859
		 * Filter the array of related posts matched by Elasticsearch.
860
		 *
861
		 * @module related-posts
862
		 *
863
		 * @since 2.8.0
864
		 *
865
		 * @param array $results Array of related posts matched by Elasticsearch.
866
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
867
		 */
868
		return apply_filters( 'jetpack_relatedposts_returned_results', $results, $post_id );
869
	}
870
871
	/**
872
	 * =========================
873
	 * PRIVATE UTILITY FUNCTIONS
874
	 * =========================
875
	 */
876
877
	/**
878
	 * Creates an array of Elasticsearch filters based on the post_id and args.
879
	 *
880
	 * @param int $post_id
881
	 * @param array $args
882
	 * @uses apply_filters, get_post_types, get_post_format_strings
883
	 * @return array
884
	 */
885
	protected function _get_es_filters_from_args( $post_id, array $args ) {
886
		$filters = array();
887
888
		/**
889
		 * Filter the terms used to search for Related Posts.
890
		 *
891
		 * @module related-posts
892
		 *
893
		 * @since 2.8.0
894
		 *
895
		 * @param array $args['has_terms'] Array of terms associated to the Related Posts.
896
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
897
		 */
898
		$args['has_terms'] = apply_filters( 'jetpack_relatedposts_filter_has_terms', $args['has_terms'], $post_id );
899
		if ( ! empty( $args['has_terms'] ) ) {
900
			foreach( (array)$args['has_terms'] as $term ) {
901
				if ( mb_strlen( $term->taxonomy ) ) {
902 View Code Duplication
					switch ( $term->taxonomy ) {
903
						case 'post_tag':
904
							$tax_fld = 'tag.slug';
905
							break;
906
						case 'category':
907
							$tax_fld = 'category.slug';
908
							break;
909
						default:
910
							$tax_fld = 'taxonomy.' . $term->taxonomy . '.slug';
911
							break;
912
					}
913
					$filters[] = array( 'term' => array( $tax_fld => $term->slug ) );
914
				}
915
			}
916
		}
917
918
		/**
919
		 * Filter the Post Types where we search Related Posts.
920
		 *
921
		 * @module related-posts
922
		 *
923
		 * @since 2.8.0
924
		 *
925
		 * @param array $args['post_type'] Array of Post Types.
926
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
927
		 */
928
		$args['post_type'] = apply_filters( 'jetpack_relatedposts_filter_post_type', $args['post_type'], $post_id );
929
		$valid_post_types = get_post_types();
930
		if ( is_array( $args['post_type'] ) ) {
931
			$sanitized_post_types = array();
932
			foreach ( $args['post_type'] as $pt ) {
933
				if ( in_array( $pt, $valid_post_types ) )
934
					$sanitized_post_types[] = $pt;
935
			}
936
			if ( ! empty( $sanitized_post_types ) )
937
				$filters[] = array( 'terms' => array( 'post_type' => $sanitized_post_types ) );
938
		} else if ( in_array( $args['post_type'], $valid_post_types ) && 'all' != $args['post_type'] ) {
939
			$filters[] = array( 'term' => array( 'post_type' => $args['post_type'] ) );
940
		}
941
942
		/**
943
		 * Filter the Post Formats where we search Related Posts.
944
		 *
945
		 * @module related-posts
946
		 *
947
		 * @since 3.3.0
948
		 *
949
		 * @param array $args['post_formats'] Array of Post Formats.
950
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
951
		 */
952
		$args['post_formats'] = apply_filters( 'jetpack_relatedposts_filter_post_formats', $args['post_formats'], $post_id );
953
		$valid_post_formats = get_post_format_strings();
954
		$sanitized_post_formats = array();
955
		foreach ( $args['post_formats'] as $pf ) {
956
			if ( array_key_exists( $pf, $valid_post_formats ) ) {
957
				$sanitized_post_formats[] = $pf;
958
			}
959
		}
960
		if ( ! empty( $sanitized_post_formats ) ) {
961
			$filters[] = array( 'terms' => array( 'post_format' => $sanitized_post_formats ) );
962
		}
963
964
		/**
965
		 * Filter the date range used to search Related Posts.
966
		 *
967
		 * @module related-posts
968
		 *
969
		 * @since 2.8.0
970
		 *
971
		 * @param array $args['date_range'] Array of a month interval where we search Related Posts.
972
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
973
		 */
974
		$args['date_range'] = apply_filters( 'jetpack_relatedposts_filter_date_range', $args['date_range'], $post_id );
975
		if ( is_array( $args['date_range'] ) && ! empty( $args['date_range'] ) ) {
976
			$args['date_range'] = array_map( 'intval', $args['date_range'] );
977
			if ( !empty( $args['date_range']['from'] ) && !empty( $args['date_range']['to'] ) ) {
978
				$filters[] = array(
979
					'range' => array(
980
						'date_gmt' => $this->_get_coalesced_range( $args['date_range'] ),
981
					)
982
				);
983
			}
984
		}
985
986
		/**
987
		 * Filter the Post IDs excluded from appearing in Related Posts.
988
		 *
989
		 * @module related-posts
990
		 *
991
		 * @since 2.9.0
992
		 *
993
		 * @param array $args['exclude_post_ids'] Array of Post IDs.
994
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
995
		 */
996
		$args['exclude_post_ids'] = apply_filters( 'jetpack_relatedposts_filter_exclude_post_ids', $args['exclude_post_ids'], $post_id );
997
		if ( !empty( $args['exclude_post_ids'] ) && is_array( $args['exclude_post_ids'] ) ) {
998
			$excluded_post_ids = array();
999
			foreach ( $args['exclude_post_ids'] as $exclude_post_id) {
1000
				$exclude_post_id = (int)$exclude_post_id;
1001
				if ( $exclude_post_id > 0 )
1002
					$excluded_post_ids[] = $exclude_post_id;
1003
			}
1004
			$filters[] = array( 'not' => array( 'terms' => array( 'post_id' => $excluded_post_ids ) ) );
1005
		}
1006
1007
		return $filters;
1008
	}
1009
1010
	/**
1011
	 * Takes a range and coalesces it into a month interval bracketed by a time as determined by the blog_id to enhance caching.
1012
	 *
1013
	 * @param array $date_range
1014
	 * @return array
1015
	 */
1016
	protected function _get_coalesced_range( array $date_range ) {
1017
		$now = time();
1018
		$coalesce_time = $this->get_blog_id() % 86400;
1019
		$current_time = $now - strtotime( 'today', $now );
1020
1021
		if ( $current_time < $coalesce_time && '01' == date( 'd', $now ) ) {
1022
			// Move back 1 period
1023
			return array(
1024
				'from' => date( 'Y-m-01', strtotime( '-1 month', $date_range['from'] ) ) . ' ' . date( 'H:i:s', $coalesce_time ),
1025
				'to'   => date( 'Y-m-01', $date_range['to'] ) . ' ' . date( 'H:i:s', $coalesce_time ),
1026
			);
1027
		} else {
1028
			// Use current period
1029
			return array(
1030
				'from' => date( 'Y-m-01', $date_range['from'] ) . ' ' . date( 'H:i:s', $coalesce_time ),
1031
				'to'   => date( 'Y-m-01', strtotime( '+1 month', $date_range['to'] ) ) . ' ' . date( 'H:i:s', $coalesce_time ),
1032
			);
1033
		}
1034
	}
1035
1036
	/**
1037
	 * Generate and output ajax response for related posts API call.
1038
	 * NOTE: Calls exit() to end all further processing after payload has been outputed.
1039
	 *
1040
	 * @param array $excludes array of post_ids to exclude
1041
	 * @uses send_nosniff_header, self::get_for_post_id, get_the_ID
1042
	 * @return null
1043
	 */
1044
	protected function _action_frontend_init_ajax( array $excludes ) {
1045
		define( 'DOING_AJAX', true );
1046
1047
		header( 'Content-type: application/json; charset=utf-8' ); // JSON can only be UTF-8
1048
		send_nosniff_header();
1049
1050
		$options = $this->get_options();
1051
1052
		if ( isset( $_GET['jetpackrpcustomize'] ) ) {
1053
1054
			// If we're in the customizer, add dummy content.
1055
			$date_now = current_time( get_option( 'date_format' ) );
1056
			$related_posts = array(
1057
				array(
1058
					'id'       => - 1,
1059
					'url'      => 'https://jetpackme.files.wordpress.com/2019/03/cat-blog.png',
1060
					'url_meta' => array(
1061
						'origin'   => 0,
1062
						'position' => 0
1063
					),
1064
					'title'    => esc_html__( 'Big iPhone/iPad Update Now Available', 'jetpack' ),
1065
					'date'     => $date_now,
1066
					'format'   => false,
1067
					'excerpt'  => esc_html__( 'It is that time of the year when devices are shiny again.', 'jetpack' ),
1068
					'rel'      => 'nofollow',
1069
					'context'  => esc_html__( 'In "Mobile"', 'jetpack' ),
1070
					'img'      => array(
1071
						'src'    => 'https://jetpackme.files.wordpress.com/2019/03/cat-blog.png',
1072
						'width'  => 350,
1073
						'height' => 200
1074
					),
1075
					'classes'  => array()
1076
				),
1077
				array(
1078
					'id'       => - 1,
1079
					'url'      => 'https://jetpackme.files.wordpress.com/2019/03/devices.jpg',
1080
					'url_meta' => array(
1081
						'origin'   => 0,
1082
						'position' => 0
1083
					),
1084
					'title'    => esc_html__( 'The WordPress for Android App Gets a Big Facelift', 'jetpack' ),
1085
					'date'     => $date_now,
1086
					'format'   => false,
1087
					'excerpt'  => esc_html__( 'Writing is new again in Android with the new WordPress app.', 'jetpack' ),
1088
					'rel'      => 'nofollow',
1089
					'context'  => esc_html__( 'In "Mobile"', 'jetpack' ),
1090
					'img'      => array(
1091
						'src'    => 'https://jetpackme.files.wordpress.com/2019/03/devices.jpg',
1092
						'width'  => 350,
1093
						'height' => 200
1094
					),
1095
					'classes'  => array()
1096
				),
1097
				array(
1098
					'id'       => - 1,
1099
					'url'      => 'https://jetpackme.files.wordpress.com/2019/03/mobile-wedding.jpg',
1100
					'url_meta' => array(
1101
						'origin'   => 0,
1102
						'position' => 0
1103
					),
1104
					'title'    => esc_html__( 'Upgrade Focus, VideoPress for weddings', 'jetpack' ),
1105
					'date'     => $date_now,
1106
					'format'   => false,
1107
					'excerpt'  => esc_html__( 'Weddings are in the spotlight now with VideoPress for weddings.', 'jetpack' ),
1108
					'rel'      => 'nofollow',
1109
					'context'  => esc_html__( 'In "Mobile"', 'jetpack' ),
1110
					'img'      => array(
1111
						'src'    => 'https://jetpackme.files.wordpress.com/2019/03/mobile-wedding.jpg',
1112
						'width'  => 350,
1113
						'height' => 200
1114
					),
1115
					'classes'  => array()
1116
				),
1117
			);
1118
1119
			for ( $total = 0; $total < $options['size'] - 3; $total++ ) {
1120
				$related_posts[] = $related_posts[ $total ];
1121
			}
1122
1123
			$current_post = get_post();
1124
1125
			// Exclude current post after filtering to make sure it's excluded and not lost during filtering.
1126
			$excluded_posts = array_merge(
1127
				/** This filter is already documented in modules/related-posts/jetpack-related-posts.php */
1128
				apply_filters( 'jetpack_relatedposts_filter_exclude_post_ids', array() ),
1129
				array( $current_post->ID )
1130
			);
1131
1132
			// Fetch posts with featured image.
1133
			$with_post_thumbnails = get_posts( array(
1134
				'posts_per_page'   => $options['size'],
1135
				'post__not_in'     => $excluded_posts,
1136
				'post_type'        => $current_post->post_type,
1137
				'meta_key'         => '_thumbnail_id',
1138
				'suppress_filters' => false,
1139
			) );
1140
1141
			// If we don't have enough, fetch posts without featured image.
1142
			if ( 0 < ( $more = $options['size'] - count( $with_post_thumbnails ) ) ) {
1143
				$no_post_thumbnails = get_posts( array(
1144
					'posts_per_page'  => $more,
1145
					'post__not_in'    => $excluded_posts,
1146
					'post_type'       => $current_post->post_type,
1147
					'meta_query' => array(
1148
						array(
1149
							'key'     => '_thumbnail_id',
1150
							'compare' => 'NOT EXISTS',
1151
						),
1152
					),
1153
					'suppress_filters' => false,
1154
				) );
1155
			} else {
1156
				$no_post_thumbnails = array();
1157
			}
1158
1159
			foreach ( array_merge( $with_post_thumbnails, $no_post_thumbnails ) as $index => $real_post ) {
1160
				$related_posts[ $index ]['id']      = $real_post->ID;
1161
				$related_posts[ $index ]['url']     = esc_url( get_permalink( $real_post ) );
1162
				$related_posts[ $index ]['title']   = $this->_to_utf8( $this->_get_title( $real_post->post_title, $real_post->post_content ) );
1163
				$related_posts[ $index ]['date']    = get_the_date( '', $real_post );
1164
				$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' );
1165
				$related_posts[ $index ]['img']     = $this->_generate_related_post_image_params( $real_post->ID );
1166
				$related_posts[ $index ]['context'] = $this->_generate_related_post_context( $real_post->ID );
1167
			}
1168
		} else {
1169
			$related_posts = $this->get_for_post_id(
1170
				get_the_ID(),
1171
				array(
1172
					'exclude_post_ids' => $excludes,
1173
				)
1174
			);
1175
		}
1176
1177
		$response = array(
1178
			'version' => self::VERSION,
1179
			'show_thumbnails' => (bool) $options['show_thumbnails'],
1180
			'show_date' => (bool) $options['show_date'],
1181
			'show_context' => (bool) $options['show_context'],
1182
			'layout' => (string) $options['layout'],
1183
			'headline' => (string) $options['headline'],
1184
			'items' => array(),
1185
		);
1186
1187
		if ( count( $related_posts ) == $options['size'] )
1188
			$response['items'] = $related_posts;
1189
1190
		echo json_encode( $response );
1191
1192
		exit();
1193
	}
1194
1195
	/**
1196
	 * Returns a UTF-8 encoded array of post information for the given post_id
1197
	 *
1198
	 * @param int $post_id
1199
	 * @param int $position
1200
	 * @param int $origin The post id that this is related to
1201
	 * @uses get_post, get_permalink, remove_query_arg, get_post_format, apply_filters
1202
	 * @return array
1203
	 */
1204
	public function get_related_post_data_for_post( $post_id, $position, $origin ) {
1205
		$post = get_post( $post_id );
1206
1207
		return array(
1208
			'id' => $post->ID,
1209
			'url' => get_permalink( $post->ID ),
1210
			'url_meta' => array( 'origin' => $origin, 'position' => $position ),
1211
			'title' => $this->_to_utf8( $this->_get_title( $post->post_title, $post->post_content ) ),
1212
			'date' => get_the_date( '', $post->ID ),
1213
			'format' => get_post_format( $post->ID ),
1214
			'excerpt' => html_entity_decode( $this->_to_utf8( $this->_get_excerpt( $post->post_excerpt, $post->post_content ) ), ENT_QUOTES, 'UTF-8' ),
1215
			/**
1216
			 * Filters the rel attribute for the Related Posts' links.
1217
			 *
1218
			 * @module related-posts
1219
			 *
1220
			 * @since 3.7.0
1221
			 *
1222
			 * @param string nofollow Link rel attribute for Related Posts' link. Default is nofollow.
1223
			 * @param int $post->ID Post ID.
1224
			 */
1225
			'rel' => apply_filters( 'jetpack_relatedposts_filter_post_link_rel', 'nofollow', $post->ID ),
1226
			/**
1227
			 * Filter the context displayed below each Related Post.
1228
			 *
1229
			 * @module related-posts
1230
			 *
1231
			 * @since 3.0.0
1232
			 *
1233
			 * @param string $this->_to_utf8( $this->_generate_related_post_context( $post->ID ) ) Context displayed below each related post.
1234
			 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
1235
			 */
1236
			'context' => apply_filters(
1237
				'jetpack_relatedposts_filter_post_context',
1238
				$this->_to_utf8( $this->_generate_related_post_context( $post->ID ) ),
1239
				$post->ID
1240
			),
1241
			'img' => $this->_generate_related_post_image_params( $post->ID ),
1242
			/**
1243
			 * Filter the post css classes added on HTML markup.
1244
			 *
1245
			 * @module related-posts
1246
			 *
1247
			 * @since 3.8.0
1248
			 *
1249
			 * @param array array() CSS classes added on post HTML markup.
1250
			 * @param string $post_id Post ID.
1251
			 */
1252
			'classes' => apply_filters(
1253
				'jetpack_relatedposts_filter_post_css_classes',
1254
				array(),
1255
				$post->ID
1256
			),
1257
		);
1258
	}
1259
1260
	/**
1261
	 * Returns either the title or a small excerpt to use as title for post.
1262
	 *
1263
	 * @param string $post_title
1264
	 * @param string $post_content
1265
	 * @uses strip_shortcodes, wp_trim_words, __
1266
	 * @return string
1267
	 */
1268
	protected function _get_title( $post_title, $post_content ) {
1269
		if ( ! empty( $post_title ) ) {
1270
			return wp_strip_all_tags( $post_title );
1271
		}
1272
1273
		$post_title = wp_trim_words( wp_strip_all_tags( strip_shortcodes( $post_content ) ), 5, '…' );
1274
		if ( ! empty( $post_title ) ) {
1275
			return $post_title;
1276
		}
1277
1278
		return __( 'Untitled Post', 'jetpack' );
1279
	}
1280
1281
	/**
1282
	 * Returns a plain text post excerpt for title attribute of links.
1283
	 *
1284
	 * @param string $post_excerpt
1285
	 * @param string $post_content
1286
	 * @uses strip_shortcodes, wp_strip_all_tags, wp_trim_words
1287
	 * @return string
1288
	 */
1289
	protected function _get_excerpt( $post_excerpt, $post_content ) {
1290
		if ( empty( $post_excerpt ) )
1291
			$excerpt = $post_content;
1292
		else
1293
			$excerpt = $post_excerpt;
1294
1295
		return wp_trim_words( wp_strip_all_tags( strip_shortcodes( $excerpt ) ), 50, '…' );
1296
	}
1297
1298
	/**
1299
	 * Generates the thumbnail image to be used for the post. Uses the
1300
	 * image as returned by Jetpack_PostImages::get_image()
1301
	 *
1302
	 * @param int $post_id
1303
	 * @uses self::get_options, apply_filters, Jetpack_PostImages::get_image, Jetpack_PostImages::fit_image_url
1304
	 * @return string
1305
	 */
1306
	protected function _generate_related_post_image_params( $post_id ) {
1307
		$options = $this->get_options();
0 ignored issues
show
Unused Code introduced by
$options is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1308
		$image_params = array(
1309
			'alt_text' => '',
1310
			'src'      => '',
1311
			'width'    => 0,
1312
			'height'   => 0,
1313
		);
1314
1315
		/**
1316
		 * Filter the size of the Related Posts images.
1317
		 *
1318
		 * @module related-posts
1319
		 *
1320
		 * @since 2.8.0
1321
		 *
1322
		 * @param array array( 'width' => 350, 'height' => 200 ) Size of the images displayed below each Related Post.
1323
		 */
1324
		$thumbnail_size = apply_filters(
1325
			'jetpack_relatedposts_filter_thumbnail_size',
1326
			array( 'width' => 350, 'height' => 200 )
1327
		);
1328
		if ( !is_array( $thumbnail_size ) ) {
1329
			$thumbnail_size = array(
1330
				'width' => (int)$thumbnail_size,
1331
				'height' => (int)$thumbnail_size
1332
			);
1333
		}
1334
1335
		// Try to get post image
1336
		if ( class_exists( 'Jetpack_PostImages' ) ) {
1337
			$img_url    = '';
1338
			$post_image = Jetpack_PostImages::get_image(
1339
				$post_id,
1340
				$thumbnail_size
1341
			);
1342
1343
			if ( is_array($post_image) ) {
1344
				$img_url = $post_image['src'];
1345
			} elseif ( class_exists( 'Jetpack_Media_Summary' ) ) {
1346
				$media = Jetpack_Media_Summary::get( $post_id );
1347
1348
				if ( is_array($media) && !empty( $media['image'] ) ) {
1349
					$img_url = $media['image'];
1350
				}
1351
			}
1352
1353
			if ( ! empty( $img_url ) ) {
1354
				if ( ! empty( $post_image['alt_text'] ) ) {
1355
					$image_params['alt_text'] = $post_image['alt_text'];
1356
				} else {
1357
					$image_params['alt_text'] = '';
1358
				}
1359
				$image_params['width']  = $thumbnail_size['width'];
1360
				$image_params['height'] = $thumbnail_size['height'];
1361
				$image_params['src']    = Jetpack_PostImages::fit_image_url(
1362
					$img_url,
1363
					$thumbnail_size['width'],
1364
					$thumbnail_size['height']
1365
				);
1366
			}
1367
		}
1368
1369
		return $image_params;
1370
	}
1371
1372
	/**
1373
	 * Returns the string UTF-8 encoded
1374
	 *
1375
	 * @param string $text
1376
	 * @return string
1377
	 */
1378
	protected function _to_utf8( $text ) {
1379
		if ( $this->_convert_charset ) {
1380
			return iconv( $this->_blog_charset, 'UTF-8', $text );
1381
		} else {
1382
			return $text;
1383
		}
1384
	}
1385
1386
	/**
1387
	 * =============================================
1388
	 * PROTECTED UTILITY FUNCTIONS EXTENDED BY WPCOM
1389
	 * =============================================
1390
	 */
1391
1392
	/**
1393
	 * Workhorse method to return array of related posts matched by Elasticsearch.
1394
	 *
1395
	 * @param int $post_id
1396
	 * @param int $size
1397
	 * @param array $filters
1398
	 * @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
1399
	 * @return array
1400
	 */
1401
	protected function _get_related_posts( $post_id, $size, array $filters ) {
1402
		$hits = $this->_filter_non_public_posts(
1403
			$this->_get_related_post_ids(
1404
				$post_id,
1405
				$size,
1406
				$filters
1407
			)
1408
		);
1409
1410
		/**
1411
		 * Filter the Related Posts matched by Elasticsearch.
1412
		 *
1413
		 * @module related-posts
1414
		 *
1415
		 * @since 2.9.0
1416
		 *
1417
		 * @param array $hits Array of Post IDs matched by Elasticsearch.
1418
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
1419
		 */
1420
		$hits = apply_filters( 'jetpack_relatedposts_filter_hits', $hits, $post_id );
1421
1422
		$related_posts = array();
1423
		foreach ( $hits as $i => $hit ) {
1424
			$related_posts[] = $this->get_related_post_data_for_post( $hit['id'], $i, $post_id );
1425
		}
1426
		return $related_posts;
1427
	}
1428
1429
	/**
1430
	 * Get array of related posts matched by Elasticsearch.
1431
	 *
1432
	 * @param int $post_id
1433
	 * @param int $size
1434
	 * @param array $filters
1435
	 * @uses wp_remote_post, is_wp_error, wp_remote_retrieve_body, get_post_meta, update_post_meta
1436
	 * @return array
1437
	 */
1438
	protected function _get_related_post_ids( $post_id, $size, array $filters ) {
1439
		$now_ts = time();
1440
		$cache_meta_key = '_jetpack_related_posts_cache';
1441
1442
		$body = array(
1443
			'size' => (int) $size,
1444
		);
1445
1446
		if ( !empty( $filters ) )
1447
			$body['filter'] = array( 'and' => $filters );
1448
1449
		// Build cache key
1450
		$cache_key = md5( serialize( $body ) );
1451
1452
		// Load all cached values
1453
		if ( wp_using_ext_object_cache() ) {
1454
			$transient_name = "{$cache_meta_key}_{$cache_key}_{$post_id}";
1455
			$cache = get_transient( $transient_name );
1456
			if ( false !== $cache ) {
1457
				return $cache;
1458
			}
1459
		} else {
1460
			$cache = get_post_meta( $post_id, $cache_meta_key, true );
1461
1462
			if ( empty( $cache ) )
1463
				$cache = array();
1464
1465
1466
			// Cache is valid! Return cached value.
1467
			if ( isset( $cache[ $cache_key ] ) && is_array( $cache[ $cache_key ] ) && $cache[ $cache_key ][ 'expires' ] > $now_ts ) {
1468
				return $cache[ $cache_key ][ 'payload' ];
1469
			}
1470
		}
1471
1472
		$response = wp_remote_post(
1473
			"https://public-api.wordpress.com/rest/v1/sites/{$this->get_blog_id()}/posts/$post_id/related/",
1474
			array(
1475
				'timeout' => 10,
1476
				'user-agent' => 'jetpack_related_posts',
1477
				'sslverify' => true,
1478
				'body' => $body,
1479
			)
1480
		);
1481
1482
		// Oh no... return nothing don't cache errors.
1483
		if ( is_wp_error( $response ) ) {
1484
			if ( isset( $cache[ $cache_key ] ) && is_array( $cache[ $cache_key ] ) )
1485
				return $cache[ $cache_key ][ 'payload' ]; // return stale
1486
			else
1487
				return array();
1488
		}
1489
1490
		$results = json_decode( wp_remote_retrieve_body( $response ), true );
1491
		$related_posts = array();
1492
		if ( is_array( $results ) && !empty( $results['hits'] ) ) {
1493
			foreach( $results['hits'] as $hit ) {
1494
				$related_posts[] = array(
1495
					'id' => $hit['fields']['post_id'],
1496
				);
1497
			}
1498
		}
1499
1500
		// An empty array might indicate no related posts or that posts
1501
		// are not yet synced to WordPress.com, so we cache for only 1
1502
		// minute in this case
1503
		if ( empty( $related_posts ) ) {
1504
			$cache_ttl = 60;
1505
		} else {
1506
			$cache_ttl = 12 * HOUR_IN_SECONDS;
1507
		}
1508
1509
		// Update cache
1510
		if ( wp_using_ext_object_cache() ) {
1511
			set_transient( $transient_name, $related_posts, $cache_ttl );
0 ignored issues
show
Bug introduced by
The variable $transient_name does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1512
		} else {
1513
			// Copy all valid cache values
1514
			$new_cache = array();
1515
			foreach ( $cache as $k => $v ) {
1516
				if ( is_array( $v ) && $v[ 'expires' ] > $now_ts ) {
1517
					$new_cache[ $k ] = $v;
1518
				}
1519
			}
1520
1521
			// Set new cache value
1522
			$cache_expires = $cache_ttl + $now_ts;
1523
			$new_cache[ $cache_key ] = array(
1524
				'expires' => $cache_expires,
1525
				'payload' => $related_posts,
1526
			);
1527
			update_post_meta( $post_id, $cache_meta_key, $new_cache );
1528
		}
1529
1530
		return $related_posts;
1531
	}
1532
1533
	/**
1534
	 * Filter out any hits that are not public anymore.
1535
	 *
1536
	 * @param array $related_posts
1537
	 * @uses get_post_stati, get_post_status
1538
	 * @return array
1539
	 */
1540
	protected function _filter_non_public_posts( array $related_posts ) {
1541
		$public_stati = get_post_stati( array( 'public' => true ) );
1542
1543
		$filtered = array();
1544
		foreach ( $related_posts as $hit ) {
1545
			if ( in_array( get_post_status( $hit['id'] ), $public_stati ) ) {
1546
				$filtered[] = $hit;
1547
			}
1548
		}
1549
		return $filtered;
1550
	}
1551
1552
	/**
1553
	 * Generates a context for the related content (second line in related post output).
1554
	 * Order of importance:
1555
	 *   - First category (Not 'Uncategorized')
1556
	 *   - First post tag
1557
	 *   - Number of comments
1558
	 *
1559
	 * @param int $post_id
1560
	 * @uses get_the_category, get_the_terms, get_comments_number, number_format_i18n, __, _n
1561
	 * @return string
1562
	 */
1563
	protected function _generate_related_post_context( $post_id ) {
1564
		$categories = get_the_category( $post_id );
1565 View Code Duplication
		if ( is_array( $categories ) ) {
1566
			foreach ( $categories as $category ) {
1567
				if ( 'uncategorized' != $category->slug && '' != trim( $category->name ) ) {
1568
					$post_cat_context = sprintf(
1569
						esc_html_x( 'In "%s"', 'in {category/tag name}', 'jetpack' ),
1570
						$category->name
1571
					);
1572
					/**
1573
					 * Filter the "In Category" line displayed in the post context below each Related Post.
1574
					 *
1575
					 * @module related-posts
1576
					 *
1577
					 * @since 3.2.0
1578
					 *
1579
					 * @param string $post_cat_context "In Category" line displayed in the post context below each Related Post.
1580
					 * @param array $category Array containing information about the category.
1581
					 */
1582
					return apply_filters( 'jetpack_relatedposts_post_category_context', $post_cat_context, $category );
1583
				}
1584
			}
1585
		}
1586
1587
		$tags = get_the_terms( $post_id, 'post_tag' );
1588 View Code Duplication
		if ( is_array( $tags ) ) {
1589
			foreach ( $tags as $tag ) {
1590
				if ( '' != trim( $tag->name ) ) {
1591
					$post_tag_context = sprintf(
1592
						_x( 'In "%s"', 'in {category/tag name}', 'jetpack' ),
1593
						$tag->name
1594
					);
1595
					/**
1596
					 * Filter the "In Tag" line displayed in the post context below each Related Post.
1597
					 *
1598
					 * @module related-posts
1599
					 *
1600
					 * @since 3.2.0
1601
					 *
1602
					 * @param string $post_tag_context "In Tag" line displayed in the post context below each Related Post.
1603
					 * @param array $tag Array containing information about the tag.
1604
					 */
1605
					return apply_filters( 'jetpack_relatedposts_post_tag_context', $post_tag_context, $tag );
1606
				}
1607
			}
1608
		}
1609
1610
		$comment_count = get_comments_number( $post_id );
1611
		if ( $comment_count > 0 ) {
1612
			return sprintf(
1613
				_n( 'With 1 comment', 'With %s comments', $comment_count, 'jetpack' ),
1614
				number_format_i18n( $comment_count )
1615
			);
1616
		}
1617
1618
		return __( 'Similar post', 'jetpack' );
1619
	}
1620
1621
	/**
1622
	 * Logs clicks for clickthrough analysis and related result tuning.
1623
	 *
1624
	 * @return null
1625
	 */
1626
	protected function _log_click( $post_id, $to_post_id, $link_position ) {
1627
1628
	}
1629
1630
	/**
1631
	 * Determines if the current post is able to use related posts.
1632
	 *
1633
	 * @uses self::get_options, is_admin, is_single, apply_filters
1634
	 * @return bool
1635
	 */
1636
	protected function _enabled_for_request() {
1637
		$enabled = is_single()
1638
			&& ! is_attachment()
1639
			&& ! is_admin()
1640
			&& ( ! $this->_allow_feature_toggle() || $this->get_option( 'enabled' ) );
1641
1642
		/**
1643
		 * Filter the Enabled value to allow related posts to be shown on pages as well.
1644
		 *
1645
		 * @module related-posts
1646
		 *
1647
		 * @since 3.3.0
1648
		 *
1649
		 * @param bool $enabled Should Related Posts be enabled on the current page.
1650
		 */
1651
		return apply_filters( 'jetpack_relatedposts_filter_enabled_for_request', $enabled );
1652
	}
1653
1654
	/**
1655
	 * Adds filters and enqueues assets.
1656
	 *
1657
	 * @uses self::_enqueue_assets, self::_setup_shortcode, add_filter
1658
	 * @return null
1659
	 */
1660
	protected function _action_frontend_init_page() {
1661
1662
		$enqueue_script = ! ( class_exists( 'Jetpack_AMP_Support' ) || Jetpack_AMP_Support::is_amp_request() );
1663
		$this->_enqueue_assets( $enqueue_script, true );
1664
		$this->_setup_shortcode();
1665
1666
		add_filter( 'the_content', array( $this, 'filter_add_target_to_dom' ), 40 );
1667
	}
1668
1669
	/**
1670
	 * Enqueues assets needed to do async loading of related posts.
1671
	 *
1672
	 * @uses wp_enqueue_script, wp_enqueue_style, plugins_url
1673
	 * @return null
1674
	 */
1675
	protected function _enqueue_assets( $script, $style ) {
1676
		$dependencies = is_customize_preview() ? array( 'customize-base' ) : array( 'jquery' );
1677
		if ( $script ) {
1678
			wp_enqueue_script(
1679
				'jetpack_related-posts',
1680
				Assets::get_file_url_for_environment(
1681
					'_inc/build/related-posts/related-posts.min.js',
1682
					'modules/related-posts/related-posts.js'
1683
				),
1684
				$dependencies,
1685
				self::VERSION
1686
			);
1687
			$related_posts_js_options = array(
1688
				/**
1689
				 * Filter each Related Post Heading structure.
1690
				 *
1691
				 * @since 4.0.0
1692
				 *
1693
				 * @param string $str Related Post Heading structure. Default to h4.
1694
				 */
1695
				'post_heading' => apply_filters( 'jetpack_relatedposts_filter_post_heading', esc_attr( 'h4' ) ),
1696
			);
1697
			wp_localize_script( 'jetpack_related-posts', 'related_posts_js_options', $related_posts_js_options );
1698
		}
1699
		if ( $style ){
1700
			wp_enqueue_style( 'jetpack_related-posts', plugins_url( 'related-posts.css', __FILE__ ), array(), self::VERSION );
1701
			wp_style_add_data( 'jetpack_related-posts', 'rtl', 'replace' );
1702
		}
1703
	}
1704
1705
	/**
1706
	 * Sets up the shortcode processing.
1707
	 *
1708
	 * @uses add_filter, add_shortcode
1709
	 * @return null
1710
	 */
1711
	protected function _setup_shortcode() {
1712
		add_filter( 'the_content', array( $this, 'test_for_shortcode' ), 0 );
1713
1714
		add_shortcode( self::SHORTCODE, array( $this, 'get_client_rendered_html' ) );
1715
	}
1716
1717
	protected function _allow_feature_toggle() {
1718
		if ( null === $this->_allow_feature_toggle ) {
1719
			/**
1720
			 * Filter the display of the Related Posts toggle in Settings > Reading.
1721
			 *
1722
			 * @module related-posts
1723
			 *
1724
			 * @since 2.8.0
1725
			 *
1726
			 * @param bool false Display a feature toggle. Default to false.
1727
			 */
1728
			$this->_allow_feature_toggle = apply_filters( 'jetpack_relatedposts_filter_allow_feature_toggle', false );
1729
		}
1730
		return $this->_allow_feature_toggle;
1731
	}
1732
1733
	/**
1734
	 * ===================================================
1735
	 * FUNCTIONS EXPOSING RELATED POSTS IN THE WP REST API
1736
	 * ===================================================
1737
	 */
1738
1739
	/**
1740
	 * Add Related Posts to the REST API Post response.
1741
	 *
1742
	 * @since 4.4.0
1743
	 *
1744
	 * @action rest_api_init
1745
	 * @uses register_rest_field, self::rest_get_related_posts
1746
	 * @return null
1747
	 */
1748
	public function rest_register_related_posts() {
1749
		register_rest_field( 'post',
1750
			'jetpack-related-posts',
1751
			array(
1752
				'get_callback' => array( $this, 'rest_get_related_posts' ),
1753
				'update_callback' => null,
1754
				'schema'          => null,
1755
			)
1756
		);
1757
	}
1758
1759
	/**
1760
	 * Build an array of Related Posts.
1761
	 * By default returns cached results that are stored for up to 12 hours.
1762
	 *
1763
	 * @since 4.4.0
1764
	 *
1765
	 * @param array $object Details of current post.
1766
	 * @param string $field_name Name of field.
1767
	 * @param WP_REST_Request $request Current request
1768
	 *
1769
	 * @uses self::get_for_post_id
1770
	 *
1771
	 * @return array
1772
	 */
1773
	public function rest_get_related_posts( $object, $field_name, $request ) {
1774
		return $this->get_for_post_id( $object['id'], array( 'size' => 6 ) );
1775
	}
1776
}
1777
1778
class Jetpack_RelatedPosts_Raw extends Jetpack_RelatedPosts {
1779
	protected $_query_name;
1780
1781
	/**
1782
	 * Allows callers of this class to tag each query with a unique name for tracking purposes.
1783
	 *
1784
	 * @param string $name
1785
	 * @return Jetpack_RelatedPosts_Raw
1786
	 */
1787
	public function set_query_name( $name ) {
1788
		$this->_query_name = (string) $name;
1789
		return $this;
1790
	}
1791
1792
	/**
1793
	 * The raw related posts class can be used by other plugins or themes
1794
	 * to get related content. This class wraps the existing RelatedPosts
1795
	 * logic thus we never want to add anything to the DOM or do anything
1796
	 * for event hooks. We will also not present any settings for this
1797
	 * class and keep it enabled as calls to this class is done
1798
	 * programmatically.
1799
	 */
1800
	public function action_admin_init() {}
1801
	public function action_frontend_init() {}
1802
	public function get_options() {
1803
		return array(
1804
			'enabled' => true,
1805
		);
1806
	}
1807
1808
	/**
1809
	 * Workhorse method to return array of related posts ids matched by Elasticsearch.
1810
	 *
1811
	 * @param int $post_id
1812
	 * @param int $size
1813
	 * @param array $filters
1814
	 * @uses wp_remote_post, is_wp_error, wp_remote_retrieve_body
1815
	 * @return array
1816
	 */
1817
	protected function _get_related_posts( $post_id, $size, array $filters ) {
1818
		$hits = $this->_filter_non_public_posts(
1819
			$this->_get_related_post_ids(
1820
				$post_id,
1821
				$size,
1822
				$filters
1823
			)
1824
		);
1825
1826
		/** This filter is already documented in modules/related-posts/related-posts.php */
1827
		$hits = apply_filters( 'jetpack_relatedposts_filter_hits', $hits, $post_id );
1828
1829
		return $hits;
1830
	}
1831
}
1832