Completed
Push — related-posts-allow-more-posts... ( 06ee6d )
by
unknown
11:59 queued 02:20
created

Jetpack_RelatedPosts   F

Complexity

Total Complexity 194

Size/Duplication

Total Lines 1742
Duplicated Lines 0.63 %

Coupling/Cohesion

Components 2
Dependencies 7

Importance

Changes 0
Metric Value
wmc 194
lcom 2
cbo 7
dl 11
loc 1742
rs 0.8
c 0
b 0
f 0

41 Methods

Rating   Name   Duplication   Size   Complexity  
A action_admin_init() 0 12 2
A render_block_row() 0 14 2
A init() 0 11 4
A init_raw() 0 11 4
A __construct() 0 23 4
A get_blog_id() 0 3 1
A action_frontend_init() 0 20 4
A get_headline() 0 14 2
A filter_add_target_to_dom() 0 11 4
A test_for_shortcode() 0 5 1
A get_target_html() 0 29 3
A get_target_html_unsupported() 0 7 2
B render_block_item() 0 58 7
F render_block() 0 71 12
A parse_numeric_get_arg() 0 15 4
F get_options() 0 40 12
A get_option() 0 9 2
F parse_options() 0 35 17
B print_setting_html() 0 69 2
B print_setting_head() 0 147 4
B get_for_post_id() 0 58 4
F _get_es_filters_from_args() 11 124 23
A _get_coalesced_range() 0 19 3
B _action_frontend_init_ajax() 0 150 6
B get_related_post_data_for_post() 0 55 1
A _get_title() 0 12 3
A _get_excerpt() 0 8 2
B _generate_related_post_image_params() 0 59 8
A _to_utf8() 0 7 2
A _get_related_posts() 0 27 2
D _get_related_post_ids() 0 94 19
A _filter_non_public_posts() 0 11 3
B _generate_related_post_context() 0 57 9
A _log_click() 0 3 1
A _enabled_for_request() 0 20 5
A _action_frontend_init_page() 0 6 1
A _enqueue_assets() 0 29 4
A _setup_shortcode() 0 5 1
A _allow_feature_toggle() 0 15 2
A rest_register_related_posts() 0 10 1
A rest_get_related_posts() 0 3 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Jetpack_RelatedPosts often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Jetpack_RelatedPosts, and based on these observations, apply Extract Interface, too.

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