Completed
Push — add/image-block-detection ( 198131...be1940 )
by
unknown
06:25
created

Jetpack_RelatedPosts::__construct()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

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