Completed
Push — try/amp-related-posts ( 08c27d )
by
unknown
06:48
created

Jetpack_RelatedPosts::init()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 3
nop 0
dl 0
loc 11
rs 9.9
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_target_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 ( Jetpack_AMP_Support::is_amp_request() ) {
179
				$content .= "\n" . $this->get_amp_html();
180
			} else {
181
				$content .= "\n" . $this->get_target_html();
182
			}
183
		}
184
185
		return $content;
186
	}
187
188
	/**
189
	 * Render static markup based on the Gutenberg block code
190
	 */
191
	function get_amp_html() {
192
		$rp_settings = Jetpack_Options::get_option( 'relatedposts', array() );
193
		$block_rp_settings = array(
194
			'displayThumbnails' => $rp_settings['show_thumbnails'],
195
			'showHeadline' => $rp_settings['show_headline'],
196
			'displayDate' => isset( $rp_settings['show_date'] ) ? (bool) $rp_settings['show_date'] : true,
197
			'displayContext' => isset( $rp_settings['show_context'] ) && $rp_settings['show_context'],
198
			'postLayout' => isset( $rp_settings['layout'] ) ? $rp_settings['layout'] : 'grid',
199
			'postsToShow' => isset( $rp_settings['size'] ) ? $rp_settings['size'] : 3,
200
			'headline' => apply_filters( 'jetpack_relatedposts_filter_headline', $this->get_headline() )
201
		);
202
		return $this->render_block( $block_rp_settings );
203
	}
204
205
	/**
206
	 * Looks for our shortcode on the unfiltered content, this has to execute early.
207
	 *
208
	 * @filter the_content
209
	 * @param string $content
210
	 * @uses has_shortcode
211
	 * @returns string
212
	 */
213
	public function test_for_shortcode( $content ) {
214
		$this->_found_shortcode = has_shortcode( $content, self::SHORTCODE );
215
216
		return $content;
217
	}
218
219
	/**
220
	 * Returns the HTML for the related posts section.
221
	 *
222
	 * @uses esc_html__, apply_filters
223
	 * @returns string
224
	 */
225
	public function get_target_html() {
226
		if ( Settings::is_syncing() ) {
227
			return '';
228
		}
229
230
		/**
231
		 * Filter the Related Posts headline.
232
		 *
233
		 * @module related-posts
234
		 *
235
		 * @since 3.0.0
236
		 *
237
		 * @param string $headline Related Posts heading.
238
		 */
239
		$headline = apply_filters( 'jetpack_relatedposts_filter_headline', $this->get_headline() );
240
241
		if ( $this->_previous_post_id ) {
242
			$exclude = "data-exclude='{$this->_previous_post_id}'";
243
		} else {
244
			$exclude = "";
245
		}
246
247
		return <<<EOT
248
<div id='jp-relatedposts' class='jp-relatedposts' $exclude>
249
	$headline
250
</div>
251
EOT;
252
	}
253
254
	/**
255
	 * 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.
256
	 *
257
	 * @returns string
258
	 */
259
	public function get_target_html_unsupported() {
260
		if ( Settings::is_syncing() ) {
261
			return '';
262
		}
263
		return "\n\n<!-- Jetpack Related Posts is not supported in this context. -->\n\n";
264
	}
265
266
	/**
267
	 * ===============
268
	 * GUTENBERG BLOCK
269
	 * ===============
270
	 */
271
272
	/**
273
	 * Echoes out items for the Gutenberg block
274
	 *
275
	 * @param array $related_post The post oject.
276
	 * @param array $block_attributes The block attributes.
277
	 */
278
	public function render_block_item( $related_post, $block_attributes ) {
279
		$instance_id = 'related-posts-item-' . uniqid();
280
		$label_id    = $instance_id . '-label';
281
282
		$item_markup = sprintf(
283
			'<ul id="%1$s" aria-labelledby="%2$s" class="jp-related-posts-i2__post" role="menuitem">',
284
			esc_attr( $instance_id ),
285
			esc_attr( $label_id )
286
		);
287
288
		$item_markup .= sprintf(
289
			'<li class="jp-related-posts-i2__post-link"><a id="%1$s" href="%2$s" rel="%4$s">%3$s</a></li>',
290
			esc_attr( $label_id ),
291
			esc_url( $related_post['url'] ),
292
			esc_attr( $related_post['title'] ),
293
			esc_attr( $related_post['rel'] )
294
		);
295
296
		if ( ! empty( $block_attributes['show_thumbnails'] ) && ! empty( $related_post['img']['src'] ) ) {
297
			$img_link = sprintf(
298
				'<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>',
299
				esc_url( $related_post['url'] ),
300
				esc_attr( $related_post['rel'] ),
301
				esc_url( $related_post['img']['src'] ),
302
				esc_attr( $related_post['img']['width'] ),
303
				esc_attr( $related_post['img']['alt_text'] )
304
			);
305
306
			$item_markup .= $img_link;
307
		}
308
309
		if ( $block_attributes['show_date'] ) {
310
			$date_tag = sprintf(
311
				'<li class="jp-related-posts-i2__post-date">%1$s</li>',
312
				esc_html( $related_post['date'] )
313
			);
314
315
			$item_markup .= $date_tag;
316
		}
317
318
		if ( ( $block_attributes['show_context'] ) && ! empty( $related_post['context'] ) ) {
319
			$context_tag = sprintf(
320
				'<li class="jp-related-posts-i2__post-context">%1$s</li>',
321
				esc_html( $related_post['context'] )
322
			);
323
324
			$item_markup .= $context_tag;
325
		}
326
327
		$item_markup .= '</ul>';
328
329
		return $item_markup;
330
	}
331
332
	/**
333
	 * Render a related posts row.
334
	 *
335
	 * @param array $posts The posts to render into the row.
336
	 * @param array $block_attributes Block attributes.
337
	 */
338
	public function render_block_row( $posts, $block_attributes ) {
339
		$rows_markup = '';
340
		foreach ( $posts as $post ) {
341
			$rows_markup .= $this->render_block_item( $post, $block_attributes );
342
		}
343
		return sprintf(
344
			'<div class="jp-related-posts-i2__row" data-post-count="%1$s">%2$s</div>',
345
			count( $posts ),
346
			$rows_markup
347
		);
348
	}
349
350
	/**
351
	 * Render the related posts markup.
352
	 *
353
	 * @param array $attributes Block attributes.
354
	 * @return string
355
	 */
356
	public function render_block( $attributes ) {
357
		$block_attributes = array(
358
			'headline'        => isset( $attributes['headline'] ) ? $attributes['headline'] : null,
359
			'show_thumbnails' => isset( $attributes['displayThumbnails'] ) && $attributes['displayThumbnails'],
360
			'show_date'       => isset( $attributes['displayDate'] ) ? (bool) $attributes['displayDate'] : true,
361
			'show_context'    => isset( $attributes['displayContext'] ) && $attributes['displayContext'],
362
			'layout'          => isset( $attributes['postLayout'] ) && 'list' === $attributes['postLayout'] ? $attributes['postLayout'] : 'grid',
363
			'size'            => ! empty( $attributes['postsToShow'] ) ? absint( $attributes['postsToShow'] ) : 3,
364
		);
365
366
		$excludes      = $this->parse_numeric_get_arg( 'relatedposts_origin' );
367
368
		$target_to_dom_priority = has_filter(
369
			'the_content',
370
			array( $this, 'filter_add_target_to_dom' )
371
		);
372
		remove_filter(
373
			'the_content',
374
			array( $this, 'filter_add_target_to_dom' ),
375
			$target_to_dom_priority
376
		);
377
378
		$related_posts = $this->get_for_post_id(
379
			get_the_ID(),
380
			array(
381
				'size'             => $block_attributes['size'],
382
				'exclude_post_ids' => $excludes,
383
			)
384
		);
385
386
		$display_lower_row = $block_attributes['size'] > 3;
387
388
		if ( empty( $related_posts ) ) {
389
			return '';
390
		}
391
392
		switch ( count( $related_posts ) ) {
393
			case 2:
394
			case 4:
395
			case 5:
396
				$top_row_end = 2;
397
				break;
398
399
			default:
400
				$top_row_end = 3;
401
				break;
402
		}
403
404
		$upper_row_posts = array_slice( $related_posts, 0, $top_row_end );
405
		$lower_row_posts = array_slice( $related_posts, $top_row_end );
406
407
		$rows_markup = $this->render_block_row( $upper_row_posts, $block_attributes );
408
		if ( $display_lower_row ) {
409
			$rows_markup .= $this->render_block_row( $lower_row_posts, $block_attributes );
410
		}
411
412
		/*
413
		 * Below is a hack to get the block content to render correctly.
414
		 *
415
		 * This functionality should be covered in /inc/blocks.php but due to an error,
416
		 * this has not been fixed as of this writing.
417
		 *
418
		 * Alda has submitted a patch to Core in order to have this issue fixed at
419
		 * https://core.trac.wordpress.org/ticket/45495 and
420
		 * made it into WordPress 5.2.
421
		 *
422
		 * @todo update when WP 5.2 is the minimum support version.
423
		 */
424
		$priority = has_filter( 'the_content', 'wpautop' );
425
		remove_filter( 'the_content', 'wpautop', $priority );
426
		add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 );
427
428
		return sprintf(
429
			'<nav class="jp-relatedposts-i2" data-layout="%1$s">%2$s%3$s</nav>',
430
			esc_attr( $block_attributes['layout'] ),
431
			$block_attributes['headline'],
432
			$rows_markup
433
		);
434
	}
435
436
	/**
437
	 * ========================
438
	 * PUBLIC UTILITY FUNCTIONS
439
	 * ========================
440
	 */
441
442
	/**
443
	 * Parse a numeric GET variable to an array of values.
444
	 *
445
	 * @since 6.9.0
446
	 *
447
	 * @uses absint
448
	 *
449
	 * @param string $arg Name of the GET variable
450
	 * @return array $result Parsed value(s)
451
	 */
452
	public function parse_numeric_get_arg( $arg ) {
453
		$result = array();
454
455
		if ( isset( $_GET[ $arg ] ) ) {
456
			if ( is_string( $_GET[ $arg ] ) ) {
457
				$result = explode( ',', $_GET[ $arg ] );
458
			} elseif ( is_array( $_GET[ $arg ] ) ) {
459
				$result = array_values( $_GET[ $arg ] );
460
			}
461
462
			$result = array_unique( array_filter( array_map( 'absint', $result ) ) );
463
		}
464
465
		return $result;
466
	}
467
468
	/**
469
	 * Gets options set for Jetpack_RelatedPosts and merge with defaults.
470
	 *
471
	 * @uses Jetpack_Options::get_option, apply_filters
472
	 * @return array
473
	 */
474
	public function get_options() {
475
		if ( null === $this->_options ) {
476
			$this->_options = Jetpack_Options::get_option( 'relatedposts', array() );
477
			if ( ! is_array( $this->_options ) )
478
				$this->_options = array();
479
			if ( ! isset( $this->_options['enabled'] ) )
480
				$this->_options['enabled'] = true;
481
			if ( ! isset( $this->_options['show_headline'] ) )
482
				$this->_options['show_headline'] = true;
483
			if ( ! isset( $this->_options['show_thumbnails'] ) )
484
				$this->_options['show_thumbnails'] = false;
485
			if ( ! isset( $this->_options['show_date'] ) ) {
486
				$this->_options['show_date'] = true;
487
			}
488
			if ( ! isset( $this->_options['show_context'] ) ) {
489
				$this->_options['show_context'] = true;
490
			}
491
			if ( ! isset( $this->_options['layout'] ) ) {
492
				$this->_options['layout'] = 'grid';
493
			}
494
			if ( ! isset( $this->_options['headline'] ) ) {
495
				$this->_options['headline'] = esc_html__( 'Related', 'jetpack' );
496
			}
497
			if ( empty( $this->_options['size'] ) || (int)$this->_options['size'] < 1 )
498
				$this->_options['size'] = 3;
499
500
			/**
501
			 * Filter Related Posts basic options.
502
			 *
503
			 * @module related-posts
504
			 *
505
			 * @since 2.8.0
506
			 *
507
			 * @param array $this->_options Array of basic Related Posts options.
508
			 */
509
			$this->_options = apply_filters( 'jetpack_relatedposts_filter_options', $this->_options );
510
		}
511
512
		return $this->_options;
513
	}
514
515
	public function get_option( $option_name ) {
516
		$options = $this->get_options();
517
518
		if ( isset( $options[ $option_name ] ) ) {
519
			return $options[ $option_name ];
520
		}
521
522
		return false;
523
	}
524
525
	/**
526
	 * Parses input and returns normalized options array.
527
	 *
528
	 * @param array $input
529
	 * @uses self::get_options
530
	 * @return array
531
	 */
532
	public function parse_options( $input ) {
533
		$current = $this->get_options();
534
535
		if ( !is_array( $input ) )
536
			$input = array();
537
538
		if (
539
			! isset( $input['enabled'] )
540
			|| isset( $input['show_date'] )
541
			|| isset( $input['show_context'] )
542
			|| isset( $input['layout'] )
543
			|| isset( $input['headline'] )
544
			) {
545
			$input['enabled'] = '1';
546
		}
547
548
		if ( '1' == $input['enabled'] ) {
549
			$current['enabled'] = true;
550
			$current['show_headline'] = ( isset( $input['show_headline'] ) && '1' == $input['show_headline'] );
551
			$current['show_thumbnails'] = ( isset( $input['show_thumbnails'] ) && '1' == $input['show_thumbnails'] );
552
			$current['show_date'] = ( isset( $input['show_date'] ) && '1' == $input['show_date'] );
553
			$current['show_context'] = ( isset( $input['show_context'] ) && '1' == $input['show_context'] );
554
			$current['layout'] = isset( $input['layout'] ) && in_array( $input['layout'], array( 'grid', 'list' ), true ) ? $input['layout'] : 'grid';
555
			$current['headline'] = isset( $input['headline'] ) ? $input['headline'] : esc_html__( 'Related', 'jetpack' );
556
		} else {
557
			$current['enabled'] = false;
558
		}
559
560
		if ( isset( $input['size'] ) && (int)$input['size'] > 0 )
561
			$current['size'] = (int)$input['size'];
562
		else
563
			$current['size'] = null;
564
565
		return $current;
566
	}
567
568
	/**
569
	 * HTML for admin settings page.
570
	 *
571
	 * @uses self::get_options, checked, esc_html__
572
	 * @returns null
573
	 */
574
	public function print_setting_html() {
575
		$options = $this->get_options();
576
577
		$ui_settings_template = <<<EOT
578
<p class="description">%s</p>
579
<ul id="settings-reading-relatedposts-customize">
580
	<li>
581
		<label><input name="jetpack_relatedposts[show_headline]" type="checkbox" value="1" %s /> %s</label>
582
	</li>
583
	<li>
584
		<label><input name="jetpack_relatedposts[show_thumbnails]" type="checkbox" value="1" %s /> %s</label>
585
	</li>
586
	<li>
587
		<label><input name="jetpack_relatedposts[show_date]" type="checkbox" value="1" %s /> %s</label>
588
	</li>
589
	<li>
590
		<label><input name="jetpack_relatedposts[show_context]" type="checkbox" value="1" %s /> %s</label>
591
	</li>
592
</ul>
593
<div id='settings-reading-relatedposts-preview'>
594
	%s
595
	<div id="jp-relatedposts" class="jp-relatedposts"></div>
596
</div>
597
EOT;
598
		$ui_settings = sprintf(
599
			$ui_settings_template,
600
			esc_html__( 'The following settings will impact all related posts on your site, except for those you created via the block editor:', 'jetpack' ),
601
			checked( $options['show_headline'], true, false ),
602
			esc_html__( 'Highlight related content with a heading', 'jetpack' ),
603
			checked( $options['show_thumbnails'], true, false ),
604
			esc_html__( 'Show a thumbnail image where available', 'jetpack' ),
605
			checked( $options['show_date'], true, false ),
606
			esc_html__( 'Show entry date', 'jetpack' ),
607
			checked( $options['show_context'], true, false ),
608
			esc_html__( 'Show context (category or tag)', 'jetpack' ),
609
			esc_html__( 'Preview:', 'jetpack' )
610
		);
611
612
		if ( !$this->_allow_feature_toggle() ) {
613
			$template = <<<EOT
614
<input type="hidden" name="jetpack_relatedposts[enabled]" value="1" />
615
%s
616
EOT;
617
			printf(
618
				$template,
619
				$ui_settings
620
			);
621
		} else {
622
			$template = <<<EOT
623
<ul id="settings-reading-relatedposts">
624
	<li>
625
		<label><input type="radio" name="jetpack_relatedposts[enabled]" value="0" class="tog" %s /> %s</label>
626
	</li>
627
	<li>
628
		<label><input type="radio" name="jetpack_relatedposts[enabled]" value="1" class="tog" %s /> %s</label>
629
		%s
630
	</li>
631
</ul>
632
EOT;
633
			printf(
634
				$template,
635
				checked( $options['enabled'], false, false ),
636
				esc_html__( 'Hide related content after posts', 'jetpack' ),
637
				checked( $options['enabled'], true, false ),
638
				esc_html__( 'Show related content after posts', 'jetpack' ),
639
				$ui_settings
640
			);
641
		}
642
	}
643
644
	/**
645
	 * Head JS/CSS for admin settings page.
646
	 *
647
	 * @uses esc_html__
648
	 * @returns null
649
	 */
650
	public function print_setting_head() {
651
652
		// only dislay the Related Posts JavaScript on the Reading Settings Admin Page
653
		$current_screen =  get_current_screen();
654
655
		if ( is_null( $current_screen ) ) {
656
			return;
657
		}
658
659
		if( 'options-reading' != $current_screen->id )
660
			return;
661
662
		$related_headline = sprintf(
663
			'<h3 class="jp-relatedposts-headline"><em>%s</em></h3>',
664
			esc_html__( 'Related', 'jetpack' )
665
		);
666
667
		$href_params = 'class="jp-relatedposts-post-a" href="#jetpack_relatedposts" rel="nofollow" data-origin="0" data-position="0"';
668
		$related_with_images = <<<EOT
669
<div class="jp-relatedposts-items jp-relatedposts-items-visual">
670
	<div class="jp-relatedposts-post jp-relatedposts-post0 jp-relatedposts-post-thumbs" data-post-id="0" data-post-format="image">
671
		<a $href_params>
672
			<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">
673
		</a>
674
		<h4 class="jp-relatedposts-post-title">
675
			<a $href_params>Big iPhone/iPad Update Now Available</a>
676
		</h4>
677
		<p class="jp-relatedposts-post-excerpt">Big iPhone/iPad Update Now Available</p>
678
		<p class="jp-relatedposts-post-context">In "Mobile"</p>
679
	</div>
680
	<div class="jp-relatedposts-post jp-relatedposts-post1 jp-relatedposts-post-thumbs" data-post-id="0" data-post-format="image">
681
		<a $href_params>
682
			<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">
683
		</a>
684
		<h4 class="jp-relatedposts-post-title">
685
			<a $href_params>The WordPress for Android App Gets a Big Facelift</a>
686
		</h4>
687
		<p class="jp-relatedposts-post-excerpt">The WordPress for Android App Gets a Big Facelift</p>
688
		<p class="jp-relatedposts-post-context">In "Mobile"</p>
689
	</div>
690
	<div class="jp-relatedposts-post jp-relatedposts-post2 jp-relatedposts-post-thumbs" data-post-id="0" data-post-format="image">
691
		<a $href_params>
692
			<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">
693
		</a>
694
		<h4 class="jp-relatedposts-post-title">
695
			<a $href_params>Upgrade Focus: VideoPress For Weddings</a>
696
		</h4>
697
		<p class="jp-relatedposts-post-excerpt">Upgrade Focus: VideoPress For Weddings</p>
698
		<p class="jp-relatedposts-post-context">In "Upgrade"</p>
699
	</div>
700
</div>
701
EOT;
702
		$related_with_images = str_replace( "\n", '', $related_with_images );
703
		$related_without_images = <<<EOT
704
<div class="jp-relatedposts-items jp-relatedposts-items-minimal">
705
	<p class="jp-relatedposts-post jp-relatedposts-post0" data-post-id="0" data-post-format="image">
706
		<span class="jp-relatedposts-post-title"><a $href_params>Big iPhone/iPad Update Now Available</a></span>
707
		<span class="jp-relatedposts-post-context">In "Mobile"</span>
708
	</p>
709
	<p class="jp-relatedposts-post jp-relatedposts-post1" data-post-id="0" data-post-format="image">
710
		<span class="jp-relatedposts-post-title"><a $href_params>The WordPress for Android App Gets a Big Facelift</a></span>
711
		<span class="jp-relatedposts-post-context">In "Mobile"</span>
712
	</p>
713
	<p class="jp-relatedposts-post jp-relatedposts-post2" data-post-id="0" data-post-format="image">
714
		<span class="jp-relatedposts-post-title"><a $href_params>Upgrade Focus: VideoPress For Weddings</a></span>
715
		<span class="jp-relatedposts-post-context">In "Upgrade"</span>
716
	</p>
717
</div>
718
EOT;
719
		$related_without_images = str_replace( "\n", '', $related_without_images );
720
721
		if ( $this->_allow_feature_toggle() ) {
722
			$extra_css = '#settings-reading-relatedposts-customize { padding-left:2em; margin-top:.5em; }';
723
		} else {
724
			$extra_css = '';
725
		}
726
727
		echo <<<EOT
728
<style type="text/css">
729
	#settings-reading-relatedposts .disabled { opacity:.5; filter:Alpha(opacity=50); }
730
	#settings-reading-relatedposts-preview .jp-relatedposts { background:#fff; padding:.5em; width:75%; }
731
	$extra_css
732
</style>
733
<script type="text/javascript">
734
	jQuery( document ).ready( function($) {
735
		var update_ui = function() {
736
			var is_enabled = true;
737
			if ( 'radio' == $( 'input[name="jetpack_relatedposts[enabled]"]' ).attr('type') ) {
738
				if ( '0' == $( 'input[name="jetpack_relatedposts[enabled]"]:checked' ).val() ) {
739
					is_enabled = false;
740
				}
741
			}
742
			if ( is_enabled ) {
743
				$( '#settings-reading-relatedposts-customize' )
744
					.removeClass( 'disabled' )
745
					.find( 'input' )
746
					.attr( 'disabled', false );
747
				$( '#settings-reading-relatedposts-preview' )
748
					.removeClass( 'disabled' );
749
			} else {
750
				$( '#settings-reading-relatedposts-customize' )
751
					.addClass( 'disabled' )
752
					.find( 'input' )
753
					.attr( 'disabled', true );
754
				$( '#settings-reading-relatedposts-preview' )
755
					.addClass( 'disabled' );
756
			}
757
		};
758
759
		var update_preview = function() {
760
			var html = '';
761
			if ( $( 'input[name="jetpack_relatedposts[show_headline]"]:checked' ).length ) {
762
				html += '$related_headline';
763
			}
764
			if ( $( 'input[name="jetpack_relatedposts[show_thumbnails]"]:checked' ).length ) {
765
				html += '$related_with_images';
766
			} else {
767
				html += '$related_without_images';
768
			}
769
			$( '#settings-reading-relatedposts-preview .jp-relatedposts' ).html( html );
770
			if ( $( 'input[name="jetpack_relatedposts[show_date]"]:checked' ).length ) {
771
				$( '.jp-relatedposts-post-title' ).each( function() {
772
					$( this ).after( $( '<span>August 8, 2005</span>' ) );
773
				} );
774
			}
775
			if ( $( 'input[name="jetpack_relatedposts[show_context]"]:checked' ).length ) {
776
				$( '.jp-relatedposts-post-context' ).show();
777
			} else {
778
				$( '.jp-relatedposts-post-context' ).hide();
779
			}
780
			$( '#settings-reading-relatedposts-preview .jp-relatedposts' ).show();
781
		};
782
783
		// Update on load
784
		update_preview();
785
		update_ui();
786
787
		// Update on change
788
		$( '#settings-reading-relatedposts-customize input' )
789
			.change( update_preview );
790
		$( '#settings-reading-relatedposts' )
791
			.find( 'input.tog' )
792
			.change( update_ui );
793
	});
794
</script>
795
EOT;
796
	}
797
798
	/**
799
	 * Gets an array of related posts that match the given post_id.
800
	 *
801
	 * @param int   $post_id Post which we want to find related posts for.
802
	 * @param array $args - params to use when building Elasticsearch filters to narrow down the search domain.
803
	 * @uses self::get_options, get_post_type, wp_parse_args, apply_filters
804
	 * @return array
805
	 */
806
	public function get_for_post_id( $post_id, array $args ) {
807
		$options = $this->get_options();
808
809
		if ( ! empty( $args['size'] ) ) {
810
			$options['size'] = $args['size'];
811
		}
812
813
		if (
814
			! $options['enabled']
815
			|| 0 === (int) $post_id
816
			|| empty( $options['size'] )
817
		) {
818
			return array();
819
		}
820
821
		$defaults = array(
822
			'size'             => (int) $options['size'],
823
			'post_type'        => get_post_type( $post_id ),
824
			'post_formats'     => array(),
825
			'has_terms'        => array(),
826
			'date_range'       => array(),
827
			'exclude_post_ids' => array(),
828
		);
829
		$args     = wp_parse_args( $args, $defaults );
830
		/**
831
		 * Filter the arguments used to retrieve a list of Related Posts.
832
		 *
833
		 * @module related-posts
834
		 *
835
		 * @since 2.8.0
836
		 *
837
		 * @param array $args Array of options to retrieve Related Posts.
838
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
839
		 */
840
		$args = apply_filters( 'jetpack_relatedposts_filter_args', $args, $post_id );
841
842
		$filters = $this->_get_es_filters_from_args( $post_id, $args );
843
		/**
844
		 * Filter Elasticsearch options used to calculate Related Posts.
845
		 *
846
		 * @module related-posts
847
		 *
848
		 * @since 2.8.0
849
		 *
850
		 * @param array $filters Array of Elasticsearch filters based on the post_id and args.
851
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
852
		 */
853
		$filters = apply_filters( 'jetpack_relatedposts_filter_filters', $filters, $post_id );
854
855
		$results = $this->_get_related_posts( $post_id, $args['size'], $filters );
856
		/**
857
		 * Filter the array of related posts matched by Elasticsearch.
858
		 *
859
		 * @module related-posts
860
		 *
861
		 * @since 2.8.0
862
		 *
863
		 * @param array $results Array of related posts matched by Elasticsearch.
864
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
865
		 */
866
		return apply_filters( 'jetpack_relatedposts_returned_results', $results, $post_id );
867
	}
868
869
	/**
870
	 * =========================
871
	 * PRIVATE UTILITY FUNCTIONS
872
	 * =========================
873
	 */
874
875
	/**
876
	 * Creates an array of Elasticsearch filters based on the post_id and args.
877
	 *
878
	 * @param int $post_id
879
	 * @param array $args
880
	 * @uses apply_filters, get_post_types, get_post_format_strings
881
	 * @return array
882
	 */
883
	protected function _get_es_filters_from_args( $post_id, array $args ) {
884
		$filters = array();
885
886
		/**
887
		 * Filter the terms used to search for Related Posts.
888
		 *
889
		 * @module related-posts
890
		 *
891
		 * @since 2.8.0
892
		 *
893
		 * @param array $args['has_terms'] Array of terms associated to the Related Posts.
894
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
895
		 */
896
		$args['has_terms'] = apply_filters( 'jetpack_relatedposts_filter_has_terms', $args['has_terms'], $post_id );
897
		if ( ! empty( $args['has_terms'] ) ) {
898
			foreach( (array)$args['has_terms'] as $term ) {
899
				if ( mb_strlen( $term->taxonomy ) ) {
900 View Code Duplication
					switch ( $term->taxonomy ) {
901
						case 'post_tag':
902
							$tax_fld = 'tag.slug';
903
							break;
904
						case 'category':
905
							$tax_fld = 'category.slug';
906
							break;
907
						default:
908
							$tax_fld = 'taxonomy.' . $term->taxonomy . '.slug';
909
							break;
910
					}
911
					$filters[] = array( 'term' => array( $tax_fld => $term->slug ) );
912
				}
913
			}
914
		}
915
916
		/**
917
		 * Filter the Post Types where we search Related Posts.
918
		 *
919
		 * @module related-posts
920
		 *
921
		 * @since 2.8.0
922
		 *
923
		 * @param array $args['post_type'] Array of Post Types.
924
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
925
		 */
926
		$args['post_type'] = apply_filters( 'jetpack_relatedposts_filter_post_type', $args['post_type'], $post_id );
927
		$valid_post_types = get_post_types();
928
		if ( is_array( $args['post_type'] ) ) {
929
			$sanitized_post_types = array();
930
			foreach ( $args['post_type'] as $pt ) {
931
				if ( in_array( $pt, $valid_post_types ) )
932
					$sanitized_post_types[] = $pt;
933
			}
934
			if ( ! empty( $sanitized_post_types ) )
935
				$filters[] = array( 'terms' => array( 'post_type' => $sanitized_post_types ) );
936
		} else if ( in_array( $args['post_type'], $valid_post_types ) && 'all' != $args['post_type'] ) {
937
			$filters[] = array( 'term' => array( 'post_type' => $args['post_type'] ) );
938
		}
939
940
		/**
941
		 * Filter the Post Formats where we search Related Posts.
942
		 *
943
		 * @module related-posts
944
		 *
945
		 * @since 3.3.0
946
		 *
947
		 * @param array $args['post_formats'] Array of Post Formats.
948
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
949
		 */
950
		$args['post_formats'] = apply_filters( 'jetpack_relatedposts_filter_post_formats', $args['post_formats'], $post_id );
951
		$valid_post_formats = get_post_format_strings();
952
		$sanitized_post_formats = array();
953
		foreach ( $args['post_formats'] as $pf ) {
954
			if ( array_key_exists( $pf, $valid_post_formats ) ) {
955
				$sanitized_post_formats[] = $pf;
956
			}
957
		}
958
		if ( ! empty( $sanitized_post_formats ) ) {
959
			$filters[] = array( 'terms' => array( 'post_format' => $sanitized_post_formats ) );
960
		}
961
962
		/**
963
		 * Filter the date range used to search Related Posts.
964
		 *
965
		 * @module related-posts
966
		 *
967
		 * @since 2.8.0
968
		 *
969
		 * @param array $args['date_range'] Array of a month interval where we search Related Posts.
970
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
971
		 */
972
		$args['date_range'] = apply_filters( 'jetpack_relatedposts_filter_date_range', $args['date_range'], $post_id );
973
		if ( is_array( $args['date_range'] ) && ! empty( $args['date_range'] ) ) {
974
			$args['date_range'] = array_map( 'intval', $args['date_range'] );
975
			if ( !empty( $args['date_range']['from'] ) && !empty( $args['date_range']['to'] ) ) {
976
				$filters[] = array(
977
					'range' => array(
978
						'date_gmt' => $this->_get_coalesced_range( $args['date_range'] ),
979
					)
980
				);
981
			}
982
		}
983
984
		/**
985
		 * Filter the Post IDs excluded from appearing in Related Posts.
986
		 *
987
		 * @module related-posts
988
		 *
989
		 * @since 2.9.0
990
		 *
991
		 * @param array $args['exclude_post_ids'] Array of Post IDs.
992
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
993
		 */
994
		$args['exclude_post_ids'] = apply_filters( 'jetpack_relatedposts_filter_exclude_post_ids', $args['exclude_post_ids'], $post_id );
995
		if ( !empty( $args['exclude_post_ids'] ) && is_array( $args['exclude_post_ids'] ) ) {
996
			$excluded_post_ids = array();
997
			foreach ( $args['exclude_post_ids'] as $exclude_post_id) {
998
				$exclude_post_id = (int)$exclude_post_id;
999
				if ( $exclude_post_id > 0 )
1000
					$excluded_post_ids[] = $exclude_post_id;
1001
			}
1002
			$filters[] = array( 'not' => array( 'terms' => array( 'post_id' => $excluded_post_ids ) ) );
1003
		}
1004
1005
		return $filters;
1006
	}
1007
1008
	/**
1009
	 * Takes a range and coalesces it into a month interval bracketed by a time as determined by the blog_id to enhance caching.
1010
	 *
1011
	 * @param array $date_range
1012
	 * @return array
1013
	 */
1014
	protected function _get_coalesced_range( array $date_range ) {
1015
		$now = time();
1016
		$coalesce_time = $this->get_blog_id() % 86400;
1017
		$current_time = $now - strtotime( 'today', $now );
1018
1019
		if ( $current_time < $coalesce_time && '01' == date( 'd', $now ) ) {
1020
			// Move back 1 period
1021
			return array(
1022
				'from' => date( 'Y-m-01', strtotime( '-1 month', $date_range['from'] ) ) . ' ' . date( 'H:i:s', $coalesce_time ),
1023
				'to'   => date( 'Y-m-01', $date_range['to'] ) . ' ' . date( 'H:i:s', $coalesce_time ),
1024
			);
1025
		} else {
1026
			// Use current period
1027
			return array(
1028
				'from' => date( 'Y-m-01', $date_range['from'] ) . ' ' . date( 'H:i:s', $coalesce_time ),
1029
				'to'   => date( 'Y-m-01', strtotime( '+1 month', $date_range['to'] ) ) . ' ' . date( 'H:i:s', $coalesce_time ),
1030
			);
1031
		}
1032
	}
1033
1034
	/**
1035
	 * Generate and output ajax response for related posts API call.
1036
	 * NOTE: Calls exit() to end all further processing after payload has been outputed.
1037
	 *
1038
	 * @param array $excludes array of post_ids to exclude
1039
	 * @uses send_nosniff_header, self::get_for_post_id, get_the_ID
1040
	 * @return null
1041
	 */
1042
	protected function _action_frontend_init_ajax( array $excludes ) {
1043
		define( 'DOING_AJAX', true );
1044
1045
		header( 'Content-type: application/json; charset=utf-8' ); // JSON can only be UTF-8
1046
		send_nosniff_header();
1047
1048
		$options = $this->get_options();
1049
1050
		if ( isset( $_GET['jetpackrpcustomize'] ) ) {
1051
1052
			// If we're in the customizer, add dummy content.
1053
			$date_now = current_time( get_option( 'date_format' ) );
1054
			$related_posts = array(
1055
				array(
1056
					'id'       => - 1,
1057
					'url'      => 'https://jetpackme.files.wordpress.com/2019/03/cat-blog.png',
1058
					'url_meta' => array(
1059
						'origin'   => 0,
1060
						'position' => 0
1061
					),
1062
					'title'    => esc_html__( 'Big iPhone/iPad Update Now Available', 'jetpack' ),
1063
					'date'     => $date_now,
1064
					'format'   => false,
1065
					'excerpt'  => esc_html__( 'It is that time of the year when devices are shiny again.', 'jetpack' ),
1066
					'rel'      => 'nofollow',
1067
					'context'  => esc_html__( 'In "Mobile"', 'jetpack' ),
1068
					'img'      => array(
1069
						'src'    => 'https://jetpackme.files.wordpress.com/2019/03/cat-blog.png',
1070
						'width'  => 350,
1071
						'height' => 200
1072
					),
1073
					'classes'  => array()
1074
				),
1075
				array(
1076
					'id'       => - 1,
1077
					'url'      => 'https://jetpackme.files.wordpress.com/2019/03/devices.jpg',
1078
					'url_meta' => array(
1079
						'origin'   => 0,
1080
						'position' => 0
1081
					),
1082
					'title'    => esc_html__( 'The WordPress for Android App Gets a Big Facelift', 'jetpack' ),
1083
					'date'     => $date_now,
1084
					'format'   => false,
1085
					'excerpt'  => esc_html__( 'Writing is new again in Android with the new WordPress app.', 'jetpack' ),
1086
					'rel'      => 'nofollow',
1087
					'context'  => esc_html__( 'In "Mobile"', 'jetpack' ),
1088
					'img'      => array(
1089
						'src'    => 'https://jetpackme.files.wordpress.com/2019/03/devices.jpg',
1090
						'width'  => 350,
1091
						'height' => 200
1092
					),
1093
					'classes'  => array()
1094
				),
1095
				array(
1096
					'id'       => - 1,
1097
					'url'      => 'https://jetpackme.files.wordpress.com/2019/03/mobile-wedding.jpg',
1098
					'url_meta' => array(
1099
						'origin'   => 0,
1100
						'position' => 0
1101
					),
1102
					'title'    => esc_html__( 'Upgrade Focus, VideoPress for weddings', 'jetpack' ),
1103
					'date'     => $date_now,
1104
					'format'   => false,
1105
					'excerpt'  => esc_html__( 'Weddings are in the spotlight now with VideoPress for weddings.', 'jetpack' ),
1106
					'rel'      => 'nofollow',
1107
					'context'  => esc_html__( 'In "Mobile"', 'jetpack' ),
1108
					'img'      => array(
1109
						'src'    => 'https://jetpackme.files.wordpress.com/2019/03/mobile-wedding.jpg',
1110
						'width'  => 350,
1111
						'height' => 200
1112
					),
1113
					'classes'  => array()
1114
				),
1115
			);
1116
1117
			for ( $total = 0; $total < $options['size'] - 3; $total++ ) {
1118
				$related_posts[] = $related_posts[ $total ];
1119
			}
1120
1121
			$current_post = get_post();
1122
1123
			// Exclude current post after filtering to make sure it's excluded and not lost during filtering.
1124
			$excluded_posts = array_merge(
1125
				/** This filter is already documented in modules/related-posts/jetpack-related-posts.php */
1126
				apply_filters( 'jetpack_relatedposts_filter_exclude_post_ids', array() ),
1127
				array( $current_post->ID )
1128
			);
1129
1130
			// Fetch posts with featured image.
1131
			$with_post_thumbnails = get_posts( array(
1132
				'posts_per_page'   => $options['size'],
1133
				'post__not_in'     => $excluded_posts,
1134
				'post_type'        => $current_post->post_type,
1135
				'meta_key'         => '_thumbnail_id',
1136
				'suppress_filters' => false,
1137
			) );
1138
1139
			// If we don't have enough, fetch posts without featured image.
1140
			if ( 0 < ( $more = $options['size'] - count( $with_post_thumbnails ) ) ) {
1141
				$no_post_thumbnails = get_posts( array(
1142
					'posts_per_page'  => $more,
1143
					'post__not_in'    => $excluded_posts,
1144
					'post_type'       => $current_post->post_type,
1145
					'meta_query' => array(
1146
						array(
1147
							'key'     => '_thumbnail_id',
1148
							'compare' => 'NOT EXISTS',
1149
						),
1150
					),
1151
					'suppress_filters' => false,
1152
				) );
1153
			} else {
1154
				$no_post_thumbnails = array();
1155
			}
1156
1157
			foreach ( array_merge( $with_post_thumbnails, $no_post_thumbnails ) as $index => $real_post ) {
1158
				$related_posts[ $index ]['id']      = $real_post->ID;
1159
				$related_posts[ $index ]['url']     = esc_url( get_permalink( $real_post ) );
1160
				$related_posts[ $index ]['title']   = $this->_to_utf8( $this->_get_title( $real_post->post_title, $real_post->post_content ) );
1161
				$related_posts[ $index ]['date']    = get_the_date( '', $real_post );
1162
				$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' );
1163
				$related_posts[ $index ]['img']     = $this->_generate_related_post_image_params( $real_post->ID );
1164
				$related_posts[ $index ]['context'] = $this->_generate_related_post_context( $real_post->ID );
1165
			}
1166
		} else {
1167
			$related_posts = $this->get_for_post_id(
1168
				get_the_ID(),
1169
				array(
1170
					'exclude_post_ids' => $excludes,
1171
				)
1172
			);
1173
		}
1174
1175
		$response = array(
1176
			'version' => self::VERSION,
1177
			'show_thumbnails' => (bool) $options['show_thumbnails'],
1178
			'show_date' => (bool) $options['show_date'],
1179
			'show_context' => (bool) $options['show_context'],
1180
			'layout' => (string) $options['layout'],
1181
			'headline' => (string) $options['headline'],
1182
			'items' => array(),
1183
		);
1184
1185
		if ( count( $related_posts ) == $options['size'] )
1186
			$response['items'] = $related_posts;
1187
1188
		echo json_encode( $response );
1189
1190
		exit();
1191
	}
1192
1193
	/**
1194
	 * Returns a UTF-8 encoded array of post information for the given post_id
1195
	 *
1196
	 * @param int $post_id
1197
	 * @param int $position
1198
	 * @param int $origin The post id that this is related to
1199
	 * @uses get_post, get_permalink, remove_query_arg, get_post_format, apply_filters
1200
	 * @return array
1201
	 */
1202
	public function get_related_post_data_for_post( $post_id, $position, $origin ) {
1203
		$post = get_post( $post_id );
1204
1205
		return array(
1206
			'id' => $post->ID,
1207
			'url' => get_permalink( $post->ID ),
1208
			'url_meta' => array( 'origin' => $origin, 'position' => $position ),
1209
			'title' => $this->_to_utf8( $this->_get_title( $post->post_title, $post->post_content ) ),
1210
			'date' => get_the_date( '', $post->ID ),
1211
			'format' => get_post_format( $post->ID ),
1212
			'excerpt' => html_entity_decode( $this->_to_utf8( $this->_get_excerpt( $post->post_excerpt, $post->post_content ) ), ENT_QUOTES, 'UTF-8' ),
1213
			/**
1214
			 * Filters the rel attribute for the Related Posts' links.
1215
			 *
1216
			 * @module related-posts
1217
			 *
1218
			 * @since 3.7.0
1219
			 *
1220
			 * @param string nofollow Link rel attribute for Related Posts' link. Default is nofollow.
1221
			 * @param int $post->ID Post ID.
1222
			 */
1223
			'rel' => apply_filters( 'jetpack_relatedposts_filter_post_link_rel', 'nofollow', $post->ID ),
1224
			/**
1225
			 * Filter the context displayed below each Related Post.
1226
			 *
1227
			 * @module related-posts
1228
			 *
1229
			 * @since 3.0.0
1230
			 *
1231
			 * @param string $this->_to_utf8( $this->_generate_related_post_context( $post->ID ) ) Context displayed below each related post.
1232
			 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
1233
			 */
1234
			'context' => apply_filters(
1235
				'jetpack_relatedposts_filter_post_context',
1236
				$this->_to_utf8( $this->_generate_related_post_context( $post->ID ) ),
1237
				$post->ID
1238
			),
1239
			'img' => $this->_generate_related_post_image_params( $post->ID ),
1240
			/**
1241
			 * Filter the post css classes added on HTML markup.
1242
			 *
1243
			 * @module related-posts
1244
			 *
1245
			 * @since 3.8.0
1246
			 *
1247
			 * @param array array() CSS classes added on post HTML markup.
1248
			 * @param string $post_id Post ID.
1249
			 */
1250
			'classes' => apply_filters(
1251
				'jetpack_relatedposts_filter_post_css_classes',
1252
				array(),
1253
				$post->ID
1254
			),
1255
		);
1256
	}
1257
1258
	/**
1259
	 * Returns either the title or a small excerpt to use as title for post.
1260
	 *
1261
	 * @param string $post_title
1262
	 * @param string $post_content
1263
	 * @uses strip_shortcodes, wp_trim_words, __
1264
	 * @return string
1265
	 */
1266
	protected function _get_title( $post_title, $post_content ) {
1267
		if ( ! empty( $post_title ) ) {
1268
			return wp_strip_all_tags( $post_title );
1269
		}
1270
1271
		$post_title = wp_trim_words( wp_strip_all_tags( strip_shortcodes( $post_content ) ), 5, '…' );
1272
		if ( ! empty( $post_title ) ) {
1273
			return $post_title;
1274
		}
1275
1276
		return __( 'Untitled Post', 'jetpack' );
1277
	}
1278
1279
	/**
1280
	 * Returns a plain text post excerpt for title attribute of links.
1281
	 *
1282
	 * @param string $post_excerpt
1283
	 * @param string $post_content
1284
	 * @uses strip_shortcodes, wp_strip_all_tags, wp_trim_words
1285
	 * @return string
1286
	 */
1287
	protected function _get_excerpt( $post_excerpt, $post_content ) {
1288
		if ( empty( $post_excerpt ) )
1289
			$excerpt = $post_content;
1290
		else
1291
			$excerpt = $post_excerpt;
1292
1293
		return wp_trim_words( wp_strip_all_tags( strip_shortcodes( $excerpt ) ), 50, '…' );
1294
	}
1295
1296
	/**
1297
	 * Generates the thumbnail image to be used for the post. Uses the
1298
	 * image as returned by Jetpack_PostImages::get_image()
1299
	 *
1300
	 * @param int $post_id
1301
	 * @uses self::get_options, apply_filters, Jetpack_PostImages::get_image, Jetpack_PostImages::fit_image_url
1302
	 * @return string
1303
	 */
1304
	protected function _generate_related_post_image_params( $post_id ) {
1305
		$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...
1306
		$image_params = array(
1307
			'alt_text' => '',
1308
			'src'      => '',
1309
			'width'    => 0,
1310
			'height'   => 0,
1311
		);
1312
1313
		/**
1314
		 * Filter the size of the Related Posts images.
1315
		 *
1316
		 * @module related-posts
1317
		 *
1318
		 * @since 2.8.0
1319
		 *
1320
		 * @param array array( 'width' => 350, 'height' => 200 ) Size of the images displayed below each Related Post.
1321
		 */
1322
		$thumbnail_size = apply_filters(
1323
			'jetpack_relatedposts_filter_thumbnail_size',
1324
			array( 'width' => 350, 'height' => 200 )
1325
		);
1326
		if ( !is_array( $thumbnail_size ) ) {
1327
			$thumbnail_size = array(
1328
				'width' => (int)$thumbnail_size,
1329
				'height' => (int)$thumbnail_size
1330
			);
1331
		}
1332
1333
		// Try to get post image
1334
		if ( class_exists( 'Jetpack_PostImages' ) ) {
1335
			$img_url    = '';
1336
			$post_image = Jetpack_PostImages::get_image(
1337
				$post_id,
1338
				$thumbnail_size
1339
			);
1340
1341
			if ( is_array($post_image) ) {
1342
				$img_url = $post_image['src'];
1343
			} elseif ( class_exists( 'Jetpack_Media_Summary' ) ) {
1344
				$media = Jetpack_Media_Summary::get( $post_id );
1345
1346
				if ( is_array($media) && !empty( $media['image'] ) ) {
1347
					$img_url = $media['image'];
1348
				}
1349
			}
1350
1351
			if ( ! empty( $img_url ) ) {
1352
				if ( ! empty( $post_image['alt_text'] ) ) {
1353
					$image_params['alt_text'] = $post_image['alt_text'];
1354
				} else {
1355
					$image_params['alt_text'] = '';
1356
				}
1357
				$image_params['width']  = $thumbnail_size['width'];
1358
				$image_params['height'] = $thumbnail_size['height'];
1359
				$image_params['src']    = Jetpack_PostImages::fit_image_url(
1360
					$img_url,
1361
					$thumbnail_size['width'],
1362
					$thumbnail_size['height']
1363
				);
1364
			}
1365
		}
1366
1367
		return $image_params;
1368
	}
1369
1370
	/**
1371
	 * Returns the string UTF-8 encoded
1372
	 *
1373
	 * @param string $text
1374
	 * @return string
1375
	 */
1376
	protected function _to_utf8( $text ) {
1377
		if ( $this->_convert_charset ) {
1378
			return iconv( $this->_blog_charset, 'UTF-8', $text );
1379
		} else {
1380
			return $text;
1381
		}
1382
	}
1383
1384
	/**
1385
	 * =============================================
1386
	 * PROTECTED UTILITY FUNCTIONS EXTENDED BY WPCOM
1387
	 * =============================================
1388
	 */
1389
1390
	/**
1391
	 * Workhorse method to return array of related posts matched by Elasticsearch.
1392
	 *
1393
	 * @param int $post_id
1394
	 * @param int $size
1395
	 * @param array $filters
1396
	 * @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
1397
	 * @return array
1398
	 */
1399
	protected function _get_related_posts( $post_id, $size, array $filters ) {
1400
		$hits = $this->_filter_non_public_posts(
1401
			$this->_get_related_post_ids(
1402
				$post_id,
1403
				$size,
1404
				$filters
1405
			)
1406
		);
1407
1408
		/**
1409
		 * Filter the Related Posts matched by Elasticsearch.
1410
		 *
1411
		 * @module related-posts
1412
		 *
1413
		 * @since 2.9.0
1414
		 *
1415
		 * @param array $hits Array of Post IDs matched by Elasticsearch.
1416
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
1417
		 */
1418
		$hits = apply_filters( 'jetpack_relatedposts_filter_hits', $hits, $post_id );
1419
1420
		$related_posts = array();
1421
		foreach ( $hits as $i => $hit ) {
1422
			$related_posts[] = $this->get_related_post_data_for_post( $hit['id'], $i, $post_id );
1423
		}
1424
		return $related_posts;
1425
	}
1426
1427
	/**
1428
	 * Get array of related posts matched by Elasticsearch.
1429
	 *
1430
	 * @param int $post_id
1431
	 * @param int $size
1432
	 * @param array $filters
1433
	 * @uses wp_remote_post, is_wp_error, wp_remote_retrieve_body, get_post_meta, update_post_meta
1434
	 * @return array
1435
	 */
1436
	protected function _get_related_post_ids( $post_id, $size, array $filters ) {
1437
		$now_ts = time();
1438
		$cache_meta_key = '_jetpack_related_posts_cache';
1439
1440
		$body = array(
1441
			'size' => (int) $size,
1442
		);
1443
1444
		if ( !empty( $filters ) )
1445
			$body['filter'] = array( 'and' => $filters );
1446
1447
		// Build cache key
1448
		$cache_key = md5( serialize( $body ) );
1449
1450
		// Load all cached values
1451
		if ( wp_using_ext_object_cache() ) {
1452
			$transient_name = "{$cache_meta_key}_{$cache_key}_{$post_id}";
1453
			$cache = get_transient( $transient_name );
1454
			if ( false !== $cache ) {
1455
				return $cache;
1456
			}
1457
		} else {
1458
			$cache = get_post_meta( $post_id, $cache_meta_key, true );
1459
1460
			if ( empty( $cache ) )
1461
				$cache = array();
1462
1463
1464
			// Cache is valid! Return cached value.
1465
			if ( isset( $cache[ $cache_key ] ) && is_array( $cache[ $cache_key ] ) && $cache[ $cache_key ][ 'expires' ] > $now_ts ) {
1466
				return $cache[ $cache_key ][ 'payload' ];
1467
			}
1468
		}
1469
1470
		$response = wp_remote_post(
1471
			"https://public-api.wordpress.com/rest/v1/sites/{$this->get_blog_id()}/posts/$post_id/related/",
1472
			array(
1473
				'timeout' => 10,
1474
				'user-agent' => 'jetpack_related_posts',
1475
				'sslverify' => true,
1476
				'body' => $body,
1477
			)
1478
		);
1479
1480
		// Oh no... return nothing don't cache errors.
1481
		if ( is_wp_error( $response ) ) {
1482
			if ( isset( $cache[ $cache_key ] ) && is_array( $cache[ $cache_key ] ) )
1483
				return $cache[ $cache_key ][ 'payload' ]; // return stale
1484
			else
1485
				return array();
1486
		}
1487
1488
		$results = json_decode( wp_remote_retrieve_body( $response ), true );
1489
		$related_posts = array();
1490
		if ( is_array( $results ) && !empty( $results['hits'] ) ) {
1491
			foreach( $results['hits'] as $hit ) {
1492
				$related_posts[] = array(
1493
					'id' => $hit['fields']['post_id'],
1494
				);
1495
			}
1496
		}
1497
1498
		// An empty array might indicate no related posts or that posts
1499
		// are not yet synced to WordPress.com, so we cache for only 1
1500
		// minute in this case
1501
		if ( empty( $related_posts ) ) {
1502
			$cache_ttl = 60;
1503
		} else {
1504
			$cache_ttl = 12 * HOUR_IN_SECONDS;
1505
		}
1506
1507
		// Update cache
1508
		if ( wp_using_ext_object_cache() ) {
1509
			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...
1510
		} else {
1511
			// Copy all valid cache values
1512
			$new_cache = array();
1513
			foreach ( $cache as $k => $v ) {
1514
				if ( is_array( $v ) && $v[ 'expires' ] > $now_ts ) {
1515
					$new_cache[ $k ] = $v;
1516
				}
1517
			}
1518
1519
			// Set new cache value
1520
			$cache_expires = $cache_ttl + $now_ts;
1521
			$new_cache[ $cache_key ] = array(
1522
				'expires' => $cache_expires,
1523
				'payload' => $related_posts,
1524
			);
1525
			update_post_meta( $post_id, $cache_meta_key, $new_cache );
1526
		}
1527
1528
		return $related_posts;
1529
	}
1530
1531
	/**
1532
	 * Filter out any hits that are not public anymore.
1533
	 *
1534
	 * @param array $related_posts
1535
	 * @uses get_post_stati, get_post_status
1536
	 * @return array
1537
	 */
1538
	protected function _filter_non_public_posts( array $related_posts ) {
1539
		$public_stati = get_post_stati( array( 'public' => true ) );
1540
1541
		$filtered = array();
1542
		foreach ( $related_posts as $hit ) {
1543
			if ( in_array( get_post_status( $hit['id'] ), $public_stati ) ) {
1544
				$filtered[] = $hit;
1545
			}
1546
		}
1547
		return $filtered;
1548
	}
1549
1550
	/**
1551
	 * Generates a context for the related content (second line in related post output).
1552
	 * Order of importance:
1553
	 *   - First category (Not 'Uncategorized')
1554
	 *   - First post tag
1555
	 *   - Number of comments
1556
	 *
1557
	 * @param int $post_id
1558
	 * @uses get_the_category, get_the_terms, get_comments_number, number_format_i18n, __, _n
1559
	 * @return string
1560
	 */
1561
	protected function _generate_related_post_context( $post_id ) {
1562
		$categories = get_the_category( $post_id );
1563 View Code Duplication
		if ( is_array( $categories ) ) {
1564
			foreach ( $categories as $category ) {
1565
				if ( 'uncategorized' != $category->slug && '' != trim( $category->name ) ) {
1566
					$post_cat_context = sprintf(
1567
						esc_html_x( 'In "%s"', 'in {category/tag name}', 'jetpack' ),
1568
						$category->name
1569
					);
1570
					/**
1571
					 * Filter the "In Category" line displayed in the post context below each Related Post.
1572
					 *
1573
					 * @module related-posts
1574
					 *
1575
					 * @since 3.2.0
1576
					 *
1577
					 * @param string $post_cat_context "In Category" line displayed in the post context below each Related Post.
1578
					 * @param array $category Array containing information about the category.
1579
					 */
1580
					return apply_filters( 'jetpack_relatedposts_post_category_context', $post_cat_context, $category );
1581
				}
1582
			}
1583
		}
1584
1585
		$tags = get_the_terms( $post_id, 'post_tag' );
1586 View Code Duplication
		if ( is_array( $tags ) ) {
1587
			foreach ( $tags as $tag ) {
1588
				if ( '' != trim( $tag->name ) ) {
1589
					$post_tag_context = sprintf(
1590
						_x( 'In "%s"', 'in {category/tag name}', 'jetpack' ),
1591
						$tag->name
1592
					);
1593
					/**
1594
					 * Filter the "In Tag" line displayed in the post context below each Related Post.
1595
					 *
1596
					 * @module related-posts
1597
					 *
1598
					 * @since 3.2.0
1599
					 *
1600
					 * @param string $post_tag_context "In Tag" line displayed in the post context below each Related Post.
1601
					 * @param array $tag Array containing information about the tag.
1602
					 */
1603
					return apply_filters( 'jetpack_relatedposts_post_tag_context', $post_tag_context, $tag );
1604
				}
1605
			}
1606
		}
1607
1608
		$comment_count = get_comments_number( $post_id );
1609
		if ( $comment_count > 0 ) {
1610
			return sprintf(
1611
				_n( 'With 1 comment', 'With %s comments', $comment_count, 'jetpack' ),
1612
				number_format_i18n( $comment_count )
1613
			);
1614
		}
1615
1616
		return __( 'Similar post', 'jetpack' );
1617
	}
1618
1619
	/**
1620
	 * Logs clicks for clickthrough analysis and related result tuning.
1621
	 *
1622
	 * @return null
1623
	 */
1624
	protected function _log_click( $post_id, $to_post_id, $link_position ) {
1625
1626
	}
1627
1628
	/**
1629
	 * Determines if the current post is able to use related posts.
1630
	 *
1631
	 * @uses self::get_options, is_admin, is_single, apply_filters
1632
	 * @return bool
1633
	 */
1634
	protected function _enabled_for_request() {
1635
		$enabled = is_single()
1636
			&& ! is_attachment()
1637
			&& ! is_admin()
1638
			&& ( ! $this->_allow_feature_toggle() || $this->get_option( 'enabled' ) );
1639
1640
		/**
1641
		 * Filter the Enabled value to allow related posts to be shown on pages as well.
1642
		 *
1643
		 * @module related-posts
1644
		 *
1645
		 * @since 3.3.0
1646
		 *
1647
		 * @param bool $enabled Should Related Posts be enabled on the current page.
1648
		 */
1649
		return apply_filters( 'jetpack_relatedposts_filter_enabled_for_request', $enabled );
1650
	}
1651
1652
	/**
1653
	 * Adds filters and enqueues assets.
1654
	 *
1655
	 * @uses self::_enqueue_assets, self::_setup_shortcode, add_filter
1656
	 * @return null
1657
	 */
1658
	protected function _action_frontend_init_page() {
1659
		$this->_enqueue_assets( true, true );
1660
		$this->_setup_shortcode();
1661
1662
		add_filter( 'the_content', array( $this, 'filter_add_target_to_dom' ), 40 );
1663
	}
1664
1665
	/**
1666
	 * Enqueues assets needed to do async loading of related posts.
1667
	 *
1668
	 * @uses wp_enqueue_script, wp_enqueue_style, plugins_url
1669
	 * @return null
1670
	 */
1671
	protected function _enqueue_assets( $script, $style ) {
1672
		$dependencies = is_customize_preview() ? array( 'customize-base' ) : array( 'jquery' );
1673
		if ( $script ) {
1674
			wp_enqueue_script(
1675
				'jetpack_related-posts',
1676
				Assets::get_file_url_for_environment(
1677
					'_inc/build/related-posts/related-posts.min.js',
1678
					'modules/related-posts/related-posts.js'
1679
				),
1680
				$dependencies,
1681
				self::VERSION
1682
			);
1683
			$related_posts_js_options = array(
1684
				/**
1685
				 * Filter each Related Post Heading structure.
1686
				 *
1687
				 * @since 4.0.0
1688
				 *
1689
				 * @param string $str Related Post Heading structure. Default to h4.
1690
				 */
1691
				'post_heading' => apply_filters( 'jetpack_relatedposts_filter_post_heading', esc_attr( 'h4' ) ),
1692
			);
1693
			wp_localize_script( 'jetpack_related-posts', 'related_posts_js_options', $related_posts_js_options );
1694
		}
1695
		if ( $style ){
1696
			wp_enqueue_style( 'jetpack_related-posts', plugins_url( 'related-posts.css', __FILE__ ), array(), self::VERSION );
1697
			wp_style_add_data( 'jetpack_related-posts', 'rtl', 'replace' );
1698
		}
1699
	}
1700
1701
	/**
1702
	 * Sets up the shortcode processing.
1703
	 *
1704
	 * @uses add_filter, add_shortcode
1705
	 * @return null
1706
	 */
1707
	protected function _setup_shortcode() {
1708
		add_filter( 'the_content', array( $this, 'test_for_shortcode' ), 0 );
1709
1710
		add_shortcode( self::SHORTCODE, array( $this, 'get_target_html' ) );
1711
	}
1712
1713
	protected function _allow_feature_toggle() {
1714
		if ( null === $this->_allow_feature_toggle ) {
1715
			/**
1716
			 * Filter the display of the Related Posts toggle in Settings > Reading.
1717
			 *
1718
			 * @module related-posts
1719
			 *
1720
			 * @since 2.8.0
1721
			 *
1722
			 * @param bool false Display a feature toggle. Default to false.
1723
			 */
1724
			$this->_allow_feature_toggle = apply_filters( 'jetpack_relatedposts_filter_allow_feature_toggle', false );
1725
		}
1726
		return $this->_allow_feature_toggle;
1727
	}
1728
1729
	/**
1730
	 * ===================================================
1731
	 * FUNCTIONS EXPOSING RELATED POSTS IN THE WP REST API
1732
	 * ===================================================
1733
	 */
1734
1735
	/**
1736
	 * Add Related Posts to the REST API Post response.
1737
	 *
1738
	 * @since 4.4.0
1739
	 *
1740
	 * @action rest_api_init
1741
	 * @uses register_rest_field, self::rest_get_related_posts
1742
	 * @return null
1743
	 */
1744
	public function rest_register_related_posts() {
1745
		register_rest_field( 'post',
1746
			'jetpack-related-posts',
1747
			array(
1748
				'get_callback' => array( $this, 'rest_get_related_posts' ),
1749
				'update_callback' => null,
1750
				'schema'          => null,
1751
			)
1752
		);
1753
	}
1754
1755
	/**
1756
	 * Build an array of Related Posts.
1757
	 * By default returns cached results that are stored for up to 12 hours.
1758
	 *
1759
	 * @since 4.4.0
1760
	 *
1761
	 * @param array $object Details of current post.
1762
	 * @param string $field_name Name of field.
1763
	 * @param WP_REST_Request $request Current request
1764
	 *
1765
	 * @uses self::get_for_post_id
1766
	 *
1767
	 * @return array
1768
	 */
1769
	public function rest_get_related_posts( $object, $field_name, $request ) {
1770
		return $this->get_for_post_id( $object['id'], array( 'size' => 6 ) );
1771
	}
1772
}
1773
1774
class Jetpack_RelatedPosts_Raw extends Jetpack_RelatedPosts {
1775
	protected $_query_name;
1776
1777
	/**
1778
	 * Allows callers of this class to tag each query with a unique name for tracking purposes.
1779
	 *
1780
	 * @param string $name
1781
	 * @return Jetpack_RelatedPosts_Raw
1782
	 */
1783
	public function set_query_name( $name ) {
1784
		$this->_query_name = (string) $name;
1785
		return $this;
1786
	}
1787
1788
	/**
1789
	 * The raw related posts class can be used by other plugins or themes
1790
	 * to get related content. This class wraps the existing RelatedPosts
1791
	 * logic thus we never want to add anything to the DOM or do anything
1792
	 * for event hooks. We will also not present any settings for this
1793
	 * class and keep it enabled as calls to this class is done
1794
	 * programmatically.
1795
	 */
1796
	public function action_admin_init() {}
1797
	public function action_frontend_init() {}
1798
	public function get_options() {
1799
		return array(
1800
			'enabled' => true,
1801
		);
1802
	}
1803
1804
	/**
1805
	 * Workhorse method to return array of related posts ids matched by Elasticsearch.
1806
	 *
1807
	 * @param int $post_id
1808
	 * @param int $size
1809
	 * @param array $filters
1810
	 * @uses wp_remote_post, is_wp_error, wp_remote_retrieve_body
1811
	 * @return array
1812
	 */
1813
	protected function _get_related_posts( $post_id, $size, array $filters ) {
1814
		$hits = $this->_filter_non_public_posts(
1815
			$this->_get_related_post_ids(
1816
				$post_id,
1817
				$size,
1818
				$filters
1819
			)
1820
		);
1821
1822
		/** This filter is already documented in modules/related-posts/related-posts.php */
1823
		$hits = apply_filters( 'jetpack_relatedposts_filter_hits', $hits, $post_id );
1824
1825
		return $hits;
1826
	}
1827
}
1828