Completed
Push — try/sync-package ( 228b13 )
by Marin
07:37
created

Jetpack_RelatedPosts::get_options()   F

Complexity

Conditions 12
Paths 513

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
nc 513
nop 0
dl 0
loc 40
rs 3.4763
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
use Automattic\Jetpack\Sync\Settings;
4
5
class Jetpack_RelatedPosts {
6
	const VERSION   = '20190204';
7
	const SHORTCODE = 'jetpack-related-posts';
8
9
	private static $instance     = null;
10
	private static $instance_raw = null;
11
12
	/**
13
	 * Creates and returns a static instance of Jetpack_RelatedPosts.
14
	 *
15
	 * @return Jetpack_RelatedPosts
16
	 */
17
	public static function init() {
18
		if ( ! self::$instance ) {
19
			if ( class_exists('WPCOM_RelatedPosts') && method_exists( 'WPCOM_RelatedPosts', 'init' ) ) {
20
				self::$instance = WPCOM_RelatedPosts::init();
21
			} else {
22
				self::$instance = new Jetpack_RelatedPosts();
23
			}
24
		}
25
26
		return self::$instance;
27
	}
28
29
	/**
30
	 * Creates and returns a static instance of Jetpack_RelatedPosts_Raw.
31
	 *
32
	 * @return Jetpack_RelatedPosts
33
	 */
34
	public static function init_raw() {
35
		if ( ! self::$instance_raw ) {
36
			if ( class_exists('WPCOM_RelatedPosts') && method_exists( 'WPCOM_RelatedPosts', 'init_raw' ) ) {
37
				self::$instance_raw = WPCOM_RelatedPosts::init_raw();
38
			} else {
39
				self::$instance_raw = new Jetpack_RelatedPosts_Raw();
40
			}
41
		}
42
43
		return self::$instance_raw;
44
	}
45
46
	protected $_options;
47
	protected $_allow_feature_toggle;
48
	protected $_blog_charset;
49
	protected $_convert_charset;
50
	protected $_previous_post_id;
51
	protected $_found_shortcode = false;
52
53
	/**
54
	 * Constructor for Jetpack_RelatedPosts.
55
	 *
56
	 * @uses get_option, add_action, apply_filters
57
	 * @return null
58
	 */
59
	public function __construct() {
60
		$this->_blog_charset = get_option( 'blog_charset' );
61
		$this->_convert_charset = ( function_exists( 'iconv' ) && ! preg_match( '/^utf\-?8$/i', $this->_blog_charset ) );
62
63
		add_action( 'admin_init', array( $this, 'action_admin_init' ) );
64
		add_action( 'wp', array( $this, 'action_frontend_init' ) );
65
66
		if ( ! class_exists( 'Jetpack_Media_Summary' ) ) {
67
			jetpack_require_lib( 'class.media-summary' );
68
		}
69
70
		// Add Related Posts to the REST API Post response.
71
		add_action( 'rest_api_init', array( $this, 'rest_register_related_posts' ) );
72
73
		jetpack_register_block(
74
			'jetpack/related-posts',
75
			array(
76
				'render_callback' => array( $this, 'render_block' ),
77
			)
78
		);
79
	}
80
81
	protected function get_blog_id() {
82
		return Jetpack_Options::get_option( 'id' );
83
	}
84
85
	/**
86
	 * =================
87
	 * ACTIONS & FILTERS
88
	 * =================
89
	 */
90
91
	/**
92
	 * Add a checkbox field to Settings > Reading for enabling related posts.
93
	 *
94
	 * @action admin_init
95
	 * @uses add_settings_field, __, register_setting, add_action
96
	 * @return null
97
	 */
98
	public function action_admin_init() {
99
100
		// Add the setting field [jetpack_relatedposts] and place it in Settings > Reading
101
		add_settings_field( 'jetpack_relatedposts', '<span id="jetpack_relatedposts">' . __( 'Related posts', 'jetpack' ) . '</span>', array( $this, 'print_setting_html' ), 'reading' );
102
		register_setting( 'reading', 'jetpack_relatedposts', array( $this, 'parse_options' ) );
103
		add_action('admin_head', array( $this, 'print_setting_head' ) );
104
105
		if( 'options-reading.php' == $GLOBALS['pagenow'] ) {
106
			// Enqueue style for live preview on the reading settings page
107
			$this->_enqueue_assets( false, true );
108
		}
109
	}
110
111
	/**
112
	 * Load related posts assets if it's a elegiable front end page or execute search and return JSON if it's an endpoint request.
113
	 *
114
	 * @global $_GET
115
	 * @action wp
116
	 * @uses add_shortcode, get_the_ID
117
	 * @returns null
118
	 */
119
	public function action_frontend_init() {
120
		// Add a shortcode handler that outputs nothing, this gets overridden later if we can display related content
121
		add_shortcode( self::SHORTCODE, array( $this, 'get_target_html_unsupported' ) );
122
123
		if ( ! $this->_enabled_for_request() )
124
			return;
125
126
		if ( isset( $_GET['relatedposts'] ) ) {
127
			$excludes = $this->parse_numeric_get_arg( 'relatedposts_exclude' );
128
			$this->_action_frontend_init_ajax( $excludes );
129
		} else {
130
			if ( isset( $_GET['relatedposts_hit'], $_GET['relatedposts_origin'], $_GET['relatedposts_position'] ) ) {
131
				$this->_log_click( $_GET['relatedposts_origin'], get_the_ID(), $_GET['relatedposts_position'] );
132
				$this->_previous_post_id = (int) $_GET['relatedposts_origin'];
133
			}
134
135
			$this->_action_frontend_init_page();
136
		}
137
138
	}
139
140
	/**
141
	 * Render insertion point.
142
	 *
143
	 * @since 4.2.0
144
	 *
145
	 * @return string
146
	 */
147
	public function get_headline() {
148
		$options = $this->get_options();
149
150
		if ( $options['show_headline'] ) {
151
			$headline = sprintf(
152
				/** This filter is already documented in modules/sharedaddy/sharing-service.php */
153
				apply_filters( 'jetpack_sharing_headline_html', '<h3 class="jp-relatedposts-headline"><em>%s</em></h3>', esc_html( $options['headline'] ), 'related-posts' ),
154
				esc_html( $options['headline'] )
155
			);
156
		} else {
157
			$headline = '';
158
		}
159
		return $headline;
160
	}
161
162
	/**
163
	 * Adds a target to the post content to load related posts into if a shortcode for it did not already exist.
164
	 * Will skip adding the target if the post content contains a Related Posts block.
165
	 *
166
	 * @filter the_content
167
	 * @param string $content
168
	 * @returns string
169
	 */
170
	public function filter_add_target_to_dom( $content ) {
171
		if ( has_block( 'jetpack/related-posts', $content ) ) {
172
			return $content;
173
		}
174
175
		if ( ! $this->_found_shortcode ) {
176
			$content .= "\n" . $this->get_target_html();
177
		}
178
179
		return $content;
180
	}
181
182
	/**
183
	 * Looks for our shortcode on the unfiltered content, this has to execute early.
184
	 *
185
	 * @filter the_content
186
	 * @param string $content
187
	 * @uses has_shortcode
188
	 * @returns string
189
	 */
190
	public function test_for_shortcode( $content ) {
191
		$this->_found_shortcode = has_shortcode( $content, self::SHORTCODE );
192
193
		return $content;
194
	}
195
196
	/**
197
	 * Returns the HTML for the related posts section.
198
	 *
199
	 * @uses esc_html__, apply_filters
200
	 * @returns string
201
	 */
202
		if ( Settings::is_syncing() ) {
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

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