Completed
Push — renovate/jest-monorepo ( bd2eaf...d289c3 )
by
unknown
44:07 queued 37:28
created

Jetpack_RelatedPosts::_enabled_for_request()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

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