Completed
Push — add/geo-location-support ( 007f25...6296b5 )
by Brad
29:34 queued 17:46
created

Jetpack_RelatedPosts::_get_related_posts()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 27
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 3
dl 0
loc 27
rs 8.8571
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
84
	/**
85
	 * =================
86
	 * ACTIONS & FILTERS
87
	 * =================
88
	 */
89
90
	/**
91
	 * Add a checkbox field to Settings > Reading for enabling related posts.
92
	 *
93
	 * @action admin_init
94
	 * @uses add_settings_field, __, register_setting, add_action
95
	 * @return null
96
	 */
97
	public function action_admin_init() {
98
99
		// Add the setting field [jetpack_relatedposts] and place it in Settings > Reading
100
		add_settings_field( 'jetpack_relatedposts', '<span id="jetpack_relatedposts">' . __( 'Related posts', 'jetpack' ) . '</span>', array( $this, 'print_setting_html' ), 'reading' );
101
		register_setting( 'reading', 'jetpack_relatedposts', array( $this, 'parse_options' ) );
102
		add_action('admin_head', array( $this, 'print_setting_head' ) );
103
104
		if( 'options-reading.php' == $GLOBALS['pagenow'] ) {
105
			// Enqueue style for live preview on the reading settings page
106
			$this->_enqueue_assets( false, true );
107
		}
108
	}
109
110
	/**
111
	 * Load related posts assets if it's a elegiable front end page or execute search and return JSON if it's an endpoint request.
112
	 *
113
	 * @global $_GET
114
	 * @action wp
115
	 * @uses add_shortcode, get_the_ID
116
	 * @returns null
117
	 */
118
	public function action_frontend_init() {
119
		// Add a shortcode handler that outputs nothing, this gets overridden later if we can display related content
120
		add_shortcode( self::SHORTCODE, array( $this, 'get_target_html_unsupported' ) );
121
122
		if ( ! $this->_enabled_for_request() )
123
			return;
124
125
		if ( isset( $_GET['relatedposts'] ) ) {
126
			$excludes = array();
127
			if ( isset( $_GET['relatedposts_exclude'] ) ) {
128
				if ( is_string( $_GET['relatedposts_exclude'] ) ) {
129
					$excludes = explode( ',', $_GET['relatedposts_exclude'] );
130
				} elseif ( is_array( $_GET['relatedposts_exclude'] ) ) {
131
					$excludes = array_values( $_GET['relatedposts_exclude'] );
132
				}
133
134
				$excludes = array_unique( array_filter( array_map( 'absint', $excludes ) ) );
135
			}
136
137
			$this->_action_frontend_init_ajax( $excludes );
138
		} else {
139
			if ( isset( $_GET['relatedposts_hit'], $_GET['relatedposts_origin'], $_GET['relatedposts_position'] ) ) {
140
				$this->_log_click( $_GET['relatedposts_origin'], get_the_ID(), $_GET['relatedposts_position'] );
141
				$this->_previous_post_id = (int) $_GET['relatedposts_origin'];
142
			}
143
144
			$this->_action_frontend_init_page();
145
		}
146
147
	}
148
149
	/**
150
	 * Render insertion point.
151
	 *
152
	 * @since 4.2.0
153
	 *
154
	 * @return string
155
	 */
156
	public function get_headline() {
157
		$options = $this->get_options();
158
159
		if ( $options['show_headline'] ) {
160
			$headline = sprintf(
161
				/** This filter is already documented in modules/sharedaddy/sharing-service.php */
162
				apply_filters( 'jetpack_sharing_headline_html', '<h3 class="jp-relatedposts-headline"><em>%s</em></h3>', esc_html( $options['headline'] ), 'related-posts' ),
163
				esc_html( $options['headline'] )
164
			);
165
		} else {
166
			$headline = '';
167
		}
168
		return $headline;
169
	}
170
171
	/**
172
	 * Adds a target to the post content to load related posts into if a shortcode for it did not already exist.
173
	 *
174
	 * @filter the_content
175
	 * @param string $content
176
	 * @returns string
177
	 */
178
	public function filter_add_target_to_dom( $content ) {
179
		if ( !$this->_found_shortcode ) {
180
			$content .= "\n" . $this->get_target_html();
181
		}
182
183
		return $content;
184
	}
185
186
	/**
187
	 * Looks for our shortcode on the unfiltered content, this has to execute early.
188
	 *
189
	 * @filter the_content
190
	 * @param string $content
191
	 * @uses has_shortcode
192
	 * @returns string
193
	 */
194
	public function test_for_shortcode( $content ) {
195
		$this->_found_shortcode = has_shortcode( $content, self::SHORTCODE );
196
197
		return $content;
198
	}
199
200
	/**
201
	 * Returns the HTML for the related posts section.
202
	 *
203
	 * @uses esc_html__, apply_filters
204
	 * @returns string
205
	 */
206
	public function get_target_html() {
207
		require_once JETPACK__PLUGIN_DIR . '/sync/class.jetpack-sync-settings.php';
208
		if ( Jetpack_Sync_Settings::is_syncing() ) {
209
			return '';
210
		}
211
212
		/**
213
		 * Filter the Related Posts headline.
214
		 *
215
		 * @module related-posts
216
		 *
217
		 * @since 3.0.0
218
		 *
219
		 * @param string $headline Related Posts heading.
220
		 */
221
		$headline = apply_filters( 'jetpack_relatedposts_filter_headline', $this->get_headline() );
222
223
		if ( $this->_previous_post_id ) {
224
			$exclude = "data-exclude='{$this->_previous_post_id}'";
225
		} else {
226
			$exclude = "";
227
		}
228
229
		return <<<EOT
230
<div id='jp-relatedposts' class='jp-relatedposts' $exclude>
231
	$headline
232
</div>
233
EOT;
234
	}
235
236
	/**
237
	 * 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.
238
	 *
239
	 * @returns string
240
	 */
241
	public function get_target_html_unsupported() {
242
		require_once JETPACK__PLUGIN_DIR . '/sync/class.jetpack-sync-settings.php';
243
		if ( Jetpack_Sync_Settings::is_syncing() ) {
244
			return '';
245
		}
246
		return "\n\n<!-- Jetpack Related Posts is not supported in this context. -->\n\n";
247
	}
248
249
	/**
250
	 * ========================
251
	 * PUBLIC UTILITY FUNCTIONS
252
	 * ========================
253
	 */
254
255
	/**
256
	 * Gets options set for Jetpack_RelatedPosts and merge with defaults.
257
	 *
258
	 * @uses Jetpack_Options::get_option, apply_filters
259
	 * @return array
260
	 */
261
	public function get_options() {
262
		if ( null === $this->_options ) {
263
			$this->_options = Jetpack_Options::get_option( 'relatedposts', array() );
264
			if ( ! is_array( $this->_options ) )
265
				$this->_options = array();
266
			if ( ! isset( $this->_options['enabled'] ) )
267
				$this->_options['enabled'] = true;
268
			if ( ! isset( $this->_options['show_headline'] ) )
269
				$this->_options['show_headline'] = true;
270
			if ( ! isset( $this->_options['show_thumbnails'] ) )
271
				$this->_options['show_thumbnails'] = false;
272
			if ( ! isset( $this->_options['show_date'] ) ) {
273
				$this->_options['show_date'] = true;
274
			}
275
			if ( ! isset( $this->_options['show_context'] ) ) {
276
				$this->_options['show_context'] = true;
277
			}
278
			if ( ! isset( $this->_options['layout'] ) ) {
279
				$this->_options['layout'] = 'grid';
280
			}
281
			if ( ! isset( $this->_options['headline'] ) ) {
282
				$this->_options['headline'] = esc_html__( 'Related', 'jetpack' );
283
			}
284
			if ( empty( $this->_options['size'] ) || (int)$this->_options['size'] < 1 )
285
				$this->_options['size'] = 3;
286
287
			/**
288
			 * Filter Related Posts basic options.
289
			 *
290
			 * @module related-posts
291
			 *
292
			 * @since 2.8.0
293
			 *
294
			 * @param array $this->_options Array of basic Related Posts options.
295
			 */
296
			$this->_options = apply_filters( 'jetpack_relatedposts_filter_options', $this->_options );
297
		}
298
299
		return $this->_options;
300
	}
301
302
	public function get_option( $option_name ) {
303
		$options = $this->get_options();
304
305
		if ( isset( $options[ $option_name ] ) ) {
306
			return $options[ $option_name ];
307
		}
308
309
		return false;
310
	}
311
312
	/**
313
	 * Parses input and returns normalized options array.
314
	 *
315
	 * @param array $input
316
	 * @uses self::get_options
317
	 * @return array
318
	 */
319
	public function parse_options( $input ) {
320
		$current = $this->get_options();
321
322
		if ( !is_array( $input ) )
323
			$input = array();
324
325
		if (
326
			! isset( $input['enabled'] )
327
			|| isset( $input['show_date'] )
328
			|| isset( $input['show_context'] )
329
			|| isset( $input['layout'] )
330
			|| isset( $input['headline'] )
331
			) {
332
			$input['enabled'] = '1';
333
		}
334
335
		if ( '1' == $input['enabled'] ) {
336
			$current['enabled'] = true;
337
			$current['show_headline'] = ( isset( $input['show_headline'] ) && '1' == $input['show_headline'] );
338
			$current['show_thumbnails'] = ( isset( $input['show_thumbnails'] ) && '1' == $input['show_thumbnails'] );
339
			$current['show_date'] = ( isset( $input['show_date'] ) && '1' == $input['show_date'] );
340
			$current['show_context'] = ( isset( $input['show_context'] ) && '1' == $input['show_context'] );
341
			$current['layout'] = isset( $input['layout'] ) && in_array( $input['layout'], array( 'grid', 'list' ), true ) ? $input['layout'] : 'grid';
342
			$current['headline'] = isset( $input['headline'] ) ? $input['headline'] : esc_html__( 'Related', 'jetpack' );
343
		} else {
344
			$current['enabled'] = false;
345
		}
346
347
		if ( isset( $input['size'] ) && (int)$input['size'] > 0 )
348
			$current['size'] = (int)$input['size'];
349
		else
350
			$current['size'] = null;
351
352
		return $current;
353
	}
354
355
	/**
356
	 * HTML for admin settings page.
357
	 *
358
	 * @uses self::get_options, checked, esc_html__
359
	 * @returns null
360
	 */
361
	public function print_setting_html() {
362
		$options = $this->get_options();
363
364
		$ui_settings_template = <<<EOT
365
<ul id="settings-reading-relatedposts-customize">
366
	<li>
367
		<label><input name="jetpack_relatedposts[show_headline]" type="checkbox" value="1" %s /> %s</label>
368
	</li>
369
	<li>
370
		<label><input name="jetpack_relatedposts[show_thumbnails]" type="checkbox" value="1" %s /> %s</label>
371
	</li>
372
	<li>
373
		<label><input name="jetpack_relatedposts[show_date]" type="checkbox" value="1" %s /> %s</label>
374
	</li>
375
	<li>
376
		<label><input name="jetpack_relatedposts[show_context]" type="checkbox" value="1" %s /> %s</label>
377
	</li>
378
</ul>
379
<div id='settings-reading-relatedposts-preview'>
380
	%s
381
	<div id="jp-relatedposts" class="jp-relatedposts"></div>
382
</div>
383
EOT;
384
		$ui_settings = sprintf(
385
			$ui_settings_template,
386
			checked( $options['show_headline'], true, false ),
387
			esc_html__( 'Show a "Related" header to more clearly separate the related section from posts', 'jetpack' ),
388
			checked( $options['show_thumbnails'], true, false ),
389
			esc_html__( 'Show a thumbnail image where available', 'jetpack' ),
390
			checked( $options['show_date'], true, false ),
391
			esc_html__( 'Show entry date', 'jetpack' ),
392
			checked( $options['show_context'], true, false ),
393
			esc_html__( 'Show context (category or tag)', 'jetpack' ),
394
			esc_html__( 'Preview:', 'jetpack' )
395
		);
396
397
		if ( !$this->_allow_feature_toggle() ) {
398
			$template = <<<EOT
399
<input type="hidden" name="jetpack_relatedposts[enabled]" value="1" />
400
%s
401
EOT;
402
			printf(
403
				$template,
404
				$ui_settings
405
			);
406
		} else {
407
			$template = <<<EOT
408
<ul id="settings-reading-relatedposts">
409
	<li>
410
		<label><input type="radio" name="jetpack_relatedposts[enabled]" value="0" class="tog" %s /> %s</label>
411
	</li>
412
	<li>
413
		<label><input type="radio" name="jetpack_relatedposts[enabled]" value="1" class="tog" %s /> %s</label>
414
		%s
415
	</li>
416
</ul>
417
EOT;
418
			printf(
419
				$template,
420
				checked( $options['enabled'], false, false ),
421
				esc_html__( 'Hide related content after posts', 'jetpack' ),
422
				checked( $options['enabled'], true, false ),
423
				esc_html__( 'Show related content after posts', 'jetpack' ),
424
				$ui_settings
425
			);
426
		}
427
	}
428
429
	/**
430
	 * Head JS/CSS for admin settings page.
431
	 *
432
	 * @uses esc_html__
433
	 * @returns null
434
	 */
435
	public function print_setting_head() {
436
437
		// only dislay the Related Posts JavaScript on the Reading Settings Admin Page
438
		$current_screen =  get_current_screen();
439
440
		if ( is_null( $current_screen ) ) {
441
			return;
442
		}
443
444
		if( 'options-reading' != $current_screen->id )
445
			return;
446
447
		$related_headline = sprintf(
448
			'<h3 class="jp-relatedposts-headline"><em>%s</em></h3>',
449
			esc_html__( 'Related', 'jetpack' )
450
		);
451
452
		$href_params = 'class="jp-relatedposts-post-a" href="#jetpack_relatedposts" rel="nofollow" data-origin="0" data-position="0"';
453
		$related_with_images = <<<EOT
454
<div class="jp-relatedposts-items jp-relatedposts-items-visual">
455
	<div class="jp-relatedposts-post jp-relatedposts-post0 jp-relatedposts-post-thumbs" data-post-id="0" data-post-format="image">
456
		<a $href_params>
457
			<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">
458
		</a>
459
		<h4 class="jp-relatedposts-post-title">
460
			<a $href_params>Big iPhone/iPad Update Now Available</a>
461
		</h4>
462
		<p class="jp-relatedposts-post-excerpt">Big iPhone/iPad Update Now Available</p>
463
		<p class="jp-relatedposts-post-context">In "Mobile"</p>
464
	</div>
465
	<div class="jp-relatedposts-post jp-relatedposts-post1 jp-relatedposts-post-thumbs" data-post-id="0" data-post-format="image">
466
		<a $href_params>
467
			<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">
468
		</a>
469
		<h4 class="jp-relatedposts-post-title">
470
			<a $href_params>The WordPress for Android App Gets a Big Facelift</a>
471
		</h4>
472
		<p class="jp-relatedposts-post-excerpt">The WordPress for Android App Gets a Big Facelift</p>
473
		<p class="jp-relatedposts-post-context">In "Mobile"</p>
474
	</div>
475
	<div class="jp-relatedposts-post jp-relatedposts-post2 jp-relatedposts-post-thumbs" data-post-id="0" data-post-format="image">
476
		<a $href_params>
477
			<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">
478
		</a>
479
		<h4 class="jp-relatedposts-post-title">
480
			<a $href_params>Upgrade Focus: VideoPress For Weddings</a>
481
		</h4>
482
		<p class="jp-relatedposts-post-excerpt">Upgrade Focus: VideoPress For Weddings</p>
483
		<p class="jp-relatedposts-post-context">In "Upgrade"</p>
484
	</div>
485
</div>
486
EOT;
487
		$related_with_images = str_replace( "\n", '', $related_with_images );
488
		$related_without_images = <<<EOT
489
<div class="jp-relatedposts-items jp-relatedposts-items-minimal">
490
	<p class="jp-relatedposts-post jp-relatedposts-post0" data-post-id="0" data-post-format="image">
491
		<span class="jp-relatedposts-post-title"><a $href_params>Big iPhone/iPad Update Now Available</a></span>
492
		<span class="jp-relatedposts-post-context">In "Mobile"</span>
493
	</p>
494
	<p class="jp-relatedposts-post jp-relatedposts-post1" data-post-id="0" data-post-format="image">
495
		<span class="jp-relatedposts-post-title"><a $href_params>The WordPress for Android App Gets a Big Facelift</a></span>
496
		<span class="jp-relatedposts-post-context">In "Mobile"</span>
497
	</p>
498
	<p class="jp-relatedposts-post jp-relatedposts-post2" data-post-id="0" data-post-format="image">
499
		<span class="jp-relatedposts-post-title"><a $href_params>Upgrade Focus: VideoPress For Weddings</a></span>
500
		<span class="jp-relatedposts-post-context">In "Upgrade"</span>
501
	</p>
502
</div>
503
EOT;
504
		$related_without_images = str_replace( "\n", '', $related_without_images );
505
506
		if ( $this->_allow_feature_toggle() ) {
507
			$extra_css = '#settings-reading-relatedposts-customize { padding-left:2em; margin-top:.5em; }';
508
		} else {
509
			$extra_css = '';
510
		}
511
512
		echo <<<EOT
513
<style type="text/css">
514
	#settings-reading-relatedposts .disabled { opacity:.5; filter:Alpha(opacity=50); }
515
	#settings-reading-relatedposts-preview .jp-relatedposts { background:#fff; padding:.5em; width:75%; }
516
	$extra_css
517
</style>
518
<script type="text/javascript">
519
	jQuery( document ).ready( function($) {
520
		var update_ui = function() {
521
			var is_enabled = true;
522
			if ( 'radio' == $( 'input[name="jetpack_relatedposts[enabled]"]' ).attr('type') ) {
523
				if ( '0' == $( 'input[name="jetpack_relatedposts[enabled]"]:checked' ).val() ) {
524
					is_enabled = false;
525
				}
526
			}
527
			if ( is_enabled ) {
528
				$( '#settings-reading-relatedposts-customize' )
529
					.removeClass( 'disabled' )
530
					.find( 'input' )
531
					.attr( 'disabled', false );
532
				$( '#settings-reading-relatedposts-preview' )
533
					.removeClass( 'disabled' );
534
			} else {
535
				$( '#settings-reading-relatedposts-customize' )
536
					.addClass( 'disabled' )
537
					.find( 'input' )
538
					.attr( 'disabled', true );
539
				$( '#settings-reading-relatedposts-preview' )
540
					.addClass( 'disabled' );
541
			}
542
		};
543
544
		var update_preview = function() {
545
			var html = '';
546
			if ( $( 'input[name="jetpack_relatedposts[show_headline]"]:checked' ).length ) {
547
				html += '$related_headline';
548
			}
549
			if ( $( 'input[name="jetpack_relatedposts[show_thumbnails]"]:checked' ).length ) {
550
				html += '$related_with_images';
551
			} else {
552
				html += '$related_without_images';
553
			}
554
			$( '#settings-reading-relatedposts-preview .jp-relatedposts' ).html( html );
555
			if ( $( 'input[name="jetpack_relatedposts[show_date]"]:checked' ).length ) {
556
				$( '.jp-relatedposts-post-title' ).each( function() {
557
					$( this ).after( $( '<span>August 8, 2005</span>' ) );
558
				} );
559
			}
560
			if ( $( 'input[name="jetpack_relatedposts[show_context]"]:checked' ).length ) {
561
				$( '.jp-relatedposts-post-context' ).show();
562
			} else {
563
				$( '.jp-relatedposts-post-context' ).hide();
564
			}
565
			$( '#settings-reading-relatedposts-preview .jp-relatedposts' ).show();
566
		};
567
568
		// Update on load
569
		update_preview();
570
		update_ui();
571
572
		// Update on change
573
		$( '#settings-reading-relatedposts-customize input' )
574
			.change( update_preview );
575
		$( '#settings-reading-relatedposts' )
576
			.find( 'input.tog' )
577
			.change( update_ui );
578
	});
579
</script>
580
EOT;
581
	}
582
583
	/**
584
	 * Gets an array of related posts that match the given post_id.
585
	 *
586
	 * @param int $post_id
587
	 * @param array $args - params to use when building Elasticsearch filters to narrow down the search domain.
588
	 * @uses self::get_options, get_post_type, wp_parse_args, apply_filters
589
	 * @return array
590
	 */
591
	public function get_for_post_id( $post_id, array $args ) {
592
		$options = $this->get_options();
593
594
		if ( ! empty( $args['size'] ) ) {
595
			$options['size'] = $args['size'];
596
		}
597
598
		if ( ! $options['enabled'] || 0 == (int)$post_id || empty( $options['size'] ) || get_post_status( $post_id) !== 'publish' ) {
599
			return array();
600
		}
601
602
		$defaults = array(
603
			'size' => (int)$options['size'],
604
			'post_type' => get_post_type( $post_id ),
605
			'post_formats' => array(),
606
			'has_terms' => array(),
607
			'date_range' => array(),
608
			'exclude_post_ids' => array(),
609
		);
610
		$args = wp_parse_args( $args, $defaults );
611
		/**
612
		 * Filter the arguments used to retrieve a list of Related Posts.
613
		 *
614
		 * @module related-posts
615
		 *
616
		 * @since 2.8.0
617
		 *
618
		 * @param array $args Array of options to retrieve Related Posts.
619
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
620
		 */
621
		$args = apply_filters( 'jetpack_relatedposts_filter_args', $args, $post_id );
622
623
		$filters = $this->_get_es_filters_from_args( $post_id, $args );
624
		/**
625
		 * Filter Elasticsearch options used to calculate Related Posts.
626
		 *
627
		 * @module related-posts
628
		 *
629
		 * @since 2.8.0
630
		 *
631
		 * @param array $filters Array of Elasticsearch filters based on the post_id and args.
632
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
633
		 */
634
		$filters = apply_filters( 'jetpack_relatedposts_filter_filters', $filters, $post_id );
635
636
		$results = $this->_get_related_posts( $post_id, $args['size'], $filters );
637
		/**
638
		 * Filter the array of related posts matched by Elasticsearch.
639
		 *
640
		 * @module related-posts
641
		 *
642
		 * @since 2.8.0
643
		 *
644
		 * @param array $results Array of related posts matched by Elasticsearch.
645
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
646
		 */
647
		return apply_filters( 'jetpack_relatedposts_returned_results', $results, $post_id );
648
	}
649
650
	/**
651
	 * =========================
652
	 * PRIVATE UTILITY FUNCTIONS
653
	 * =========================
654
	 */
655
656
	/**
657
	 * Creates an array of Elasticsearch filters based on the post_id and args.
658
	 *
659
	 * @param int $post_id
660
	 * @param array $args
661
	 * @uses apply_filters, get_post_types, get_post_format_strings
662
	 * @return array
663
	 */
664
	protected function _get_es_filters_from_args( $post_id, array $args ) {
665
		$filters = array();
666
667
		/**
668
		 * Filter the terms used to search for Related Posts.
669
		 *
670
		 * @module related-posts
671
		 *
672
		 * @since 2.8.0
673
		 *
674
		 * @param array $args['has_terms'] Array of terms associated to the Related Posts.
675
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
676
		 */
677
		$args['has_terms'] = apply_filters( 'jetpack_relatedposts_filter_has_terms', $args['has_terms'], $post_id );
678
		if ( ! empty( $args['has_terms'] ) ) {
679
			foreach( (array)$args['has_terms'] as $term ) {
680
				if ( mb_strlen( $term->taxonomy ) ) {
681 View Code Duplication
					switch ( $term->taxonomy ) {
682
						case 'post_tag':
683
							$tax_fld = 'tag.slug';
684
							break;
685
						case 'category':
686
							$tax_fld = 'category.slug';
687
							break;
688
						default:
689
							$tax_fld = 'taxonomy.' . $term->taxonomy . '.slug';
690
							break;
691
					}
692
					$filters[] = array( 'term' => array( $tax_fld => $term->slug ) );
693
				}
694
			}
695
		}
696
697
		/**
698
		 * Filter the Post Types where we search Related Posts.
699
		 *
700
		 * @module related-posts
701
		 *
702
		 * @since 2.8.0
703
		 *
704
		 * @param array $args['post_type'] Array of Post Types.
705
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
706
		 */
707
		$args['post_type'] = apply_filters( 'jetpack_relatedposts_filter_post_type', $args['post_type'], $post_id );
708
		$valid_post_types = get_post_types();
709
		if ( is_array( $args['post_type'] ) ) {
710
			$sanitized_post_types = array();
711
			foreach ( $args['post_type'] as $pt ) {
712
				if ( in_array( $pt, $valid_post_types ) )
713
					$sanitized_post_types[] = $pt;
714
			}
715
			if ( ! empty( $sanitized_post_types ) )
716
				$filters[] = array( 'terms' => array( 'post_type' => $sanitized_post_types ) );
717
		} else if ( in_array( $args['post_type'], $valid_post_types ) && 'all' != $args['post_type'] ) {
718
			$filters[] = array( 'term' => array( 'post_type' => $args['post_type'] ) );
719
		}
720
721
		/**
722
		 * Filter the Post Formats where we search Related Posts.
723
		 *
724
		 * @module related-posts
725
		 *
726
		 * @since 3.3.0
727
		 *
728
		 * @param array $args['post_formats'] Array of Post Formats.
729
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
730
		 */
731
		$args['post_formats'] = apply_filters( 'jetpack_relatedposts_filter_post_formats', $args['post_formats'], $post_id );
732
		$valid_post_formats = get_post_format_strings();
733
		$sanitized_post_formats = array();
734
		foreach ( $args['post_formats'] as $pf ) {
735
			if ( array_key_exists( $pf, $valid_post_formats ) ) {
736
				$sanitized_post_formats[] = $pf;
737
			}
738
		}
739
		if ( ! empty( $sanitized_post_formats ) ) {
740
			$filters[] = array( 'terms' => array( 'post_format' => $sanitized_post_formats ) );
741
		}
742
743
		/**
744
		 * Filter the date range used to search Related Posts.
745
		 *
746
		 * @module related-posts
747
		 *
748
		 * @since 2.8.0
749
		 *
750
		 * @param array $args['date_range'] Array of a month interval where we search Related Posts.
751
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
752
		 */
753
		$args['date_range'] = apply_filters( 'jetpack_relatedposts_filter_date_range', $args['date_range'], $post_id );
754
		if ( is_array( $args['date_range'] ) && ! empty( $args['date_range'] ) ) {
755
			$args['date_range'] = array_map( 'intval', $args['date_range'] );
756
			if ( !empty( $args['date_range']['from'] ) && !empty( $args['date_range']['to'] ) ) {
757
				$filters[] = array(
758
					'range' => array(
759
						'date_gmt' => $this->_get_coalesced_range( $args['date_range'] ),
760
					)
761
				);
762
			}
763
		}
764
765
		/**
766
		 * Filter the Post IDs excluded from appearing in Related Posts.
767
		 *
768
		 * @module related-posts
769
		 *
770
		 * @since 2.9.0
771
		 *
772
		 * @param array $args['exclude_post_ids'] Array of Post IDs.
773
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
774
		 */
775
		$args['exclude_post_ids'] = apply_filters( 'jetpack_relatedposts_filter_exclude_post_ids', $args['exclude_post_ids'], $post_id );
776
		if ( !empty( $args['exclude_post_ids'] ) && is_array( $args['exclude_post_ids'] ) ) {
777
			$excluded_post_ids = array();
778
			foreach ( $args['exclude_post_ids'] as $exclude_post_id) {
779
				$exclude_post_id = (int)$exclude_post_id;
780
				if ( $exclude_post_id > 0 )
781
					$excluded_post_ids[] = $exclude_post_id;
782
			}
783
			$filters[] = array( 'not' => array( 'terms' => array( 'post_id' => $excluded_post_ids ) ) );
784
		}
785
786
		return $filters;
787
	}
788
789
	/**
790
	 * Takes a range and coalesces it into a month interval bracketed by a time as determined by the blog_id to enhance caching.
791
	 *
792
	 * @param array $date_range
793
	 * @return array
794
	 */
795
	protected function _get_coalesced_range( array $date_range ) {
796
		$now = time();
797
		$coalesce_time = $this->_blog_id_wpcom % 86400;
798
		$current_time = $now - strtotime( 'today', $now );
799
800
		if ( $current_time < $coalesce_time && '01' == date( 'd', $now ) ) {
801
			// Move back 1 period
802
			return array(
803
				'from' => date( 'Y-m-01', strtotime( '-1 month', $date_range['from'] ) ) . ' ' . date( 'H:i:s', $coalesce_time ),
804
				'to'   => date( 'Y-m-01', $date_range['to'] ) . ' ' . date( 'H:i:s', $coalesce_time ),
805
			);
806
		} else {
807
			// Use current period
808
			return array(
809
				'from' => date( 'Y-m-01', $date_range['from'] ) . ' ' . date( 'H:i:s', $coalesce_time ),
810
				'to'   => date( 'Y-m-01', strtotime( '+1 month', $date_range['to'] ) ) . ' ' . date( 'H:i:s', $coalesce_time ),
811
			);
812
		}
813
	}
814
815
	/**
816
	 * Generate and output ajax response for related posts API call.
817
	 * NOTE: Calls exit() to end all further processing after payload has been outputed.
818
	 *
819
	 * @param array $excludes array of post_ids to exclude
820
	 * @uses send_nosniff_header, self::get_for_post_id, get_the_ID
821
	 * @return null
822
	 */
823
	protected function _action_frontend_init_ajax( array $excludes ) {
824
		define( 'DOING_AJAX', true );
825
826
		header( 'Content-type: application/json; charset=utf-8' ); // JSON can only be UTF-8
827
		send_nosniff_header();
828
829
		$options = $this->get_options();
830
831
		if ( isset( $_GET['jetpackrpcustomize'] ) ) {
832
833
			// If we're in the customizer, add dummy content.
834
			$date_now = current_time( get_option( 'date_format' ) );
835
			$related_posts = array(
836
				array(
837
					'id'       => - 1,
838
					'url'      => 'https://jetpackme.files.wordpress.com/2014/08/1-wpios-ipad-3-1-viewsite.png?w=350&h=200&crop=1',
839
					'url_meta' => array(
840
						'origin'   => 0,
841
						'position' => 0
842
					),
843
					'title'    => esc_html__( 'Big iPhone/iPad Update Now Available', 'jetpack' ),
844
					'date'     => $date_now,
845
					'format'   => false,
846
					'excerpt'  => esc_html__( 'It is that time of the year when devices are shiny again.', 'jetpack' ),
847
					'rel'      => 'nofollow',
848
					'context'  => esc_html__( 'In "Mobile"', 'jetpack' ),
849
					'img'      => array(
850
						'src'    => 'https://jetpackme.files.wordpress.com/2014/08/1-wpios-ipad-3-1-viewsite.png?w=350&h=200&crop=1',
851
						'width'  => 350,
852
						'height' => 200
853
					),
854
					'classes'  => array()
855
				),
856
				array(
857
					'id'       => - 1,
858
					'url'      => 'https://jetpackme.files.wordpress.com/2014/08/wordpress-com-news-wordpress-for-android-ui-update2.jpg?w=350&h=200&crop=1',
859
					'url_meta' => array(
860
						'origin'   => 0,
861
						'position' => 0
862
					),
863
					'title'    => esc_html__( 'The WordPress for Android App Gets a Big Facelift', 'jetpack' ),
864
					'date'     => $date_now,
865
					'format'   => false,
866
					'excerpt'  => esc_html__( 'Writing is new again in Android with the new WordPress app.', 'jetpack' ),
867
					'rel'      => 'nofollow',
868
					'context'  => esc_html__( 'In "Mobile"', 'jetpack' ),
869
					'img'      => array(
870
						'src'    => 'https://jetpackme.files.wordpress.com/2014/08/wordpress-com-news-wordpress-for-android-ui-update2.jpg?w=350&h=200&crop=1',
871
						'width'  => 350,
872
						'height' => 200
873
					),
874
					'classes'  => array()
875
				),
876
				array(
877
					'id'       => - 1,
878
					'url'      => 'https://jetpackme.files.wordpress.com/2014/08/videopresswedding.jpg?w=350&h=200&crop=1',
879
					'url_meta' => array(
880
						'origin'   => 0,
881
						'position' => 0
882
					),
883
					'title'    => esc_html__( 'Upgrade Focus, VideoPress for weddings', 'jetpack' ),
884
					'date'     => $date_now,
885
					'format'   => false,
886
					'excerpt'  => esc_html__( 'Weddings are in the spotlight now with VideoPress for weddings.', 'jetpack' ),
887
					'rel'      => 'nofollow',
888
					'context'  => esc_html__( 'In "Mobile"', 'jetpack' ),
889
					'img'      => array(
890
						'src'    => 'https://jetpackme.files.wordpress.com/2014/08/videopresswedding.jpg?w=350&h=200&crop=1',
891
						'width'  => 350,
892
						'height' => 200
893
					),
894
					'classes'  => array()
895
				),
896
			);
897
898
			for ( $total = 0; $total < $options['size'] - 3; $total++ ) {
899
				$related_posts[] = $related_posts[ $total ];
900
			}
901
902
			$current_post = get_post();
903
904
			// Exclude current post after filtering to make sure it's excluded and not lost during filtering.
905
			$excluded_posts = array_merge(
906
				/** This filter is already documented in modules/related-posts/jetpack-related-posts.php */
907
				apply_filters( 'jetpack_relatedposts_filter_exclude_post_ids', array() ),
908
				array( $current_post->ID )
909
			);
910
911
			// Fetch posts with featured image.
912
			$with_post_thumbnails = get_posts( array(
913
				'posts_per_page'   => $options['size'],
914
				'post__not_in'     => $excluded_posts,
915
				'post_type'        => $current_post->post_type,
916
				'meta_key'         => '_thumbnail_id',
917
				'suppress_filters' => false,
918
			) );
919
920
			// If we don't have enough, fetch posts without featured image.
921
			if ( 0 < ( $more = $options['size'] - count( $with_post_thumbnails ) ) ) {
922
				$no_post_thumbnails = get_posts( array(
923
					'posts_per_page'  => $more,
924
					'post__not_in'    => $excluded_posts,
925
					'post_type'       => $current_post->post_type,
926
					'meta_query' => array(
927
						array(
928
							'key'     => '_thumbnail_id',
929
							'compare' => 'NOT EXISTS',
930
						),
931
					),
932
					'suppress_filters' => false,
933
				) );
934
			} else {
935
				$no_post_thumbnails = array();
936
			}
937
938
			foreach ( array_merge( $with_post_thumbnails, $no_post_thumbnails ) as $index => $real_post ) {
939
				$related_posts[ $index ]['id']      = $real_post->ID;
940
				$related_posts[ $index ]['url']     = esc_url( get_permalink( $real_post ) );
941
				$related_posts[ $index ]['title']   = $this->_to_utf8( $this->_get_title( $real_post->post_title, $real_post->post_content ) );
942
				$related_posts[ $index ]['date']    = get_the_date( '', $real_post );
943
				$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' );
944
				$related_posts[ $index ]['img']     = $this->_generate_related_post_image_params( $real_post->ID );
945
				$related_posts[ $index ]['context'] = $this->_generate_related_post_context( $real_post->ID );
946
			}
947
		} else {
948
			$related_posts = $this->get_for_post_id(
949
				get_the_ID(),
950
				array(
951
					'exclude_post_ids' => $excludes,
952
				)
953
			);
954
		}
955
956
		$response = array(
957
			'version' => self::VERSION,
958
			'show_thumbnails' => (bool) $options['show_thumbnails'],
959
			'show_date' => (bool) $options['show_date'],
960
			'show_context' => (bool) $options['show_context'],
961
			'layout' => (string) $options['layout'],
962
			'headline' => (string) $options['headline'],
963
			'items' => array(),
964
		);
965
966
		if ( count( $related_posts ) == $options['size'] )
967
			$response['items'] = $related_posts;
968
969
		echo json_encode( $response );
970
971
		exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method _action_frontend_init_ajax() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
972
	}
973
974
	/**
975
	 * Returns a UTF-8 encoded array of post information for the given post_id
976
	 *
977
	 * @param int $post_id
978
	 * @param int $position
979
	 * @param int $origin The post id that this is related to
980
	 * @uses get_post, get_permalink, remove_query_arg, get_post_format, apply_filters
981
	 * @return array
982
	 */
983
	protected function _get_related_post_data_for_post( $post_id, $position, $origin ) {
984
		$post = get_post( $post_id );
985
986
		return array(
987
			'id' => $post->ID,
988
			'url' => get_permalink( $post->ID ),
989
			'url_meta' => array( 'origin' => $origin, 'position' => $position ),
990
			'title' => $this->_to_utf8( $this->_get_title( $post->post_title, $post->post_content ) ),
991
			'date' => get_the_date( '', $post->ID ),
992
			'format' => get_post_format( $post->ID ),
993
			'excerpt' => html_entity_decode( $this->_to_utf8( $this->_get_excerpt( $post->post_excerpt, $post->post_content ) ), ENT_QUOTES, 'UTF-8' ),
994
			/**
995
			 * Filters the rel attribute for the Related Posts' links.
996
			 *
997
			 * @module related-posts
998
			 *
999
			 * @since 3.7.0
1000
			 *
1001
			 * @param string nofollow Link rel attribute for Related Posts' link. Default is nofollow.
1002
			 * @param int $post->ID Post ID.
1003
			 */
1004
			'rel' => apply_filters( 'jetpack_relatedposts_filter_post_link_rel', 'nofollow', $post->ID ),
1005
			/**
1006
			 * Filter the context displayed below each Related Post.
1007
			 *
1008
			 * @module related-posts
1009
			 *
1010
			 * @since 3.0.0
1011
			 *
1012
			 * @param string $this->_to_utf8( $this->_generate_related_post_context( $post->ID ) ) Context displayed below each related post.
1013
			 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
1014
			 */
1015
			'context' => apply_filters(
1016
				'jetpack_relatedposts_filter_post_context',
1017
				$this->_to_utf8( $this->_generate_related_post_context( $post->ID ) ),
1018
				$post->ID
1019
			),
1020
			'img' => $this->_generate_related_post_image_params( $post->ID ),
1021
			/**
1022
			 * Filter the post css classes added on HTML markup.
1023
			 *
1024
			 * @module related-posts
1025
			 *
1026
			 * @since 3.8.0
1027
			 *
1028
			 * @param array array() CSS classes added on post HTML markup.
1029
			 * @param string $post_id Post ID.
1030
			 */
1031
			'classes' => apply_filters(
1032
				'jetpack_relatedposts_filter_post_css_classes',
1033
				array(),
1034
				$post->ID
1035
			),
1036
		);
1037
	}
1038
1039
	/**
1040
	 * Returns either the title or a small excerpt to use as title for post.
1041
	 *
1042
	 * @param string $post_title
1043
	 * @param string $post_content
1044
	 * @uses strip_shortcodes, wp_trim_words, __
1045
	 * @return string
1046
	 */
1047
	protected function _get_title( $post_title, $post_content ) {
1048
		if ( ! empty( $post_title ) ) {
1049
			return wp_strip_all_tags( $post_title );
1050
		}
1051
1052
		$post_title = wp_trim_words( wp_strip_all_tags( strip_shortcodes( $post_content ) ), 5, '…' );
1053
		if ( ! empty( $post_title ) ) {
1054
			return $post_title;
1055
		}
1056
1057
		return __( 'Untitled Post', 'jetpack' );
1058
	}
1059
1060
	/**
1061
	 * Returns a plain text post excerpt for title attribute of links.
1062
	 *
1063
	 * @param string $post_excerpt
1064
	 * @param string $post_content
1065
	 * @uses strip_shortcodes, wp_strip_all_tags, wp_trim_words
1066
	 * @return string
1067
	 */
1068
	protected function _get_excerpt( $post_excerpt, $post_content ) {
1069
		if ( empty( $post_excerpt ) )
1070
			$excerpt = $post_content;
1071
		else
1072
			$excerpt = $post_excerpt;
1073
1074
		return wp_trim_words( wp_strip_all_tags( strip_shortcodes( $excerpt ) ), 50, '…' );
1075
	}
1076
1077
	/**
1078
	 * Generates the thumbnail image to be used for the post. Uses the
1079
	 * image as returned by Jetpack_PostImages::get_image()
1080
	 *
1081
	 * @param int $post_id
1082
	 * @uses self::get_options, apply_filters, Jetpack_PostImages::get_image, Jetpack_PostImages::fit_image_url
1083
	 * @return string
1084
	 */
1085
	protected function _generate_related_post_image_params( $post_id ) {
1086
		$options = $this->get_options();
1087
		$image_params = array(
1088
			'src' => '',
1089
			'width' => 0,
1090
			'height' => 0,
1091
		);
1092
1093
		if ( ! $options['show_thumbnails'] ) {
1094
			return $image_params;
1095
		}
1096
1097
		/**
1098
		 * Filter the size of the Related Posts images.
1099
		 *
1100
		 * @module related-posts
1101
		 *
1102
		 * @since 2.8.0
1103
		 *
1104
		 * @param array array( 'width' => 350, 'height' => 200 ) Size of the images displayed below each Related Post.
1105
		 */
1106
		$thumbnail_size = apply_filters(
1107
			'jetpack_relatedposts_filter_thumbnail_size',
1108
			array( 'width' => 350, 'height' => 200 )
1109
		);
1110
		if ( !is_array( $thumbnail_size ) ) {
1111
			$thumbnail_size = array(
1112
				'width' => (int)$thumbnail_size,
1113
				'height' => (int)$thumbnail_size
1114
			);
1115
		}
1116
1117
		// Try to get post image
1118
		if ( class_exists( 'Jetpack_PostImages' ) ) {
1119
			$img_url = '';
1120
			$post_image = Jetpack_PostImages::get_image(
1121
				$post_id,
1122
				$thumbnail_size
1123
			);
1124
1125
			if ( is_array($post_image) ) {
1126
				$img_url = $post_image['src'];
1127
			} elseif ( class_exists( 'Jetpack_Media_Summary' ) ) {
1128
				$media = Jetpack_Media_Summary::get( $post_id );
1129
1130
				if ( is_array($media) && !empty( $media['image'] ) ) {
1131
					$img_url = $media['image'];
1132
				}
1133
			}
1134
1135 View Code Duplication
			if ( !empty( $img_url ) ) {
1136
				$image_params['width'] = $thumbnail_size['width'];
1137
				$image_params['height'] = $thumbnail_size['height'];
1138
				$image_params['src'] = Jetpack_PostImages::fit_image_url(
1139
					$img_url,
1140
					$thumbnail_size['width'],
1141
					$thumbnail_size['height']
1142
				);
1143
			}
1144
		}
1145
1146
		return $image_params;
1147
	}
1148
1149
	/**
1150
	 * Returns the string UTF-8 encoded
1151
	 *
1152
	 * @param string $text
1153
	 * @return string
1154
	 */
1155
	protected function _to_utf8( $text ) {
1156
		if ( $this->_convert_charset ) {
1157
			return iconv( $this->_blog_charset, 'UTF-8', $text );
1158
		} else {
1159
			return $text;
1160
		}
1161
	}
1162
1163
	/**
1164
	 * =============================================
1165
	 * PROTECTED UTILITY FUNCTIONS EXTENDED BY WPCOM
1166
	 * =============================================
1167
	 */
1168
1169
	/**
1170
	 * Workhorse method to return array of related posts matched by Elasticsearch.
1171
	 *
1172
	 * @param int $post_id
1173
	 * @param int $size
1174
	 * @param array $filters
1175
	 * @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
1176
	 * @return array
1177
	 */
1178
	protected function _get_related_posts( $post_id, $size, array $filters ) {
1179
		$hits = $this->_filter_non_public_posts(
1180
			$this->_get_related_post_ids(
1181
				$post_id,
1182
				$size,
1183
				$filters
1184
			)
1185
		);
1186
1187
		/**
1188
		 * Filter the Related Posts matched by Elasticsearch.
1189
		 *
1190
		 * @module related-posts
1191
		 *
1192
		 * @since 2.9.0
1193
		 *
1194
		 * @param array $hits Array of Post IDs matched by Elasticsearch.
1195
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
1196
		 */
1197
		$hits = apply_filters( 'jetpack_relatedposts_filter_hits', $hits, $post_id );
1198
1199
		$related_posts = array();
1200
		foreach ( $hits as $i => $hit ) {
1201
			$related_posts[] = $this->_get_related_post_data_for_post( $hit['id'], $i, $post_id );
1202
		}
1203
		return $related_posts;
1204
	}
1205
1206
	/**
1207
	 * Get array of related posts matched by Elasticsearch.
1208
	 *
1209
	 * @param int $post_id
1210
	 * @param int $size
1211
	 * @param array $filters
1212
	 * @uses wp_remote_post, is_wp_error, wp_remote_retrieve_body, get_post_meta, update_post_meta
1213
	 * @return array
1214
	 */
1215
	protected function _get_related_post_ids( $post_id, $size, array $filters ) {
1216
		$now_ts = time();
1217
		$cache_meta_key = '_jetpack_related_posts_cache';
1218
1219
		$body = array(
1220
			'size' => (int) $size,
1221
		);
1222
1223
		if ( !empty( $filters ) )
1224
			$body['filter'] = array( 'and' => $filters );
1225
1226
		// Build cache key
1227
		$cache_key = md5( serialize( $body ) );
1228
1229
		// Load all cached values
1230
		if ( wp_using_ext_object_cache() ) {
1231
			$transient_name = "{$cache_meta_key}_{$cache_key}_{$post_id}";
1232
			$cache = get_transient( $transient_name );
1233
			if ( false !== $cache ) {
1234
				return $cache;
1235
			}
1236
		} else {
1237
			$cache = get_post_meta( $post_id, $cache_meta_key, true );
1238
1239
			if ( empty( $cache ) )
1240
				$cache = array();
1241
1242
1243
			// Cache is valid! Return cached value.
1244
			if ( isset( $cache[ $cache_key ] ) && is_array( $cache[ $cache_key ] ) && $cache[ $cache_key ][ 'expires' ] > $now_ts ) {
1245
				return $cache[ $cache_key ][ 'payload' ];
1246
			}
1247
		}
1248
1249
		$response = wp_remote_post(
1250
			"https://public-api.wordpress.com/rest/v1/sites/{$this->_blog_id_wpcom}/posts/$post_id/related/",
1251
			array(
1252
				'timeout' => 10,
1253
				'user-agent' => 'jetpack_related_posts',
1254
				'sslverify' => true,
1255
				'body' => $body,
1256
			)
1257
		);
1258
1259
		// Oh no... return nothing don't cache errors.
1260
		if ( is_wp_error( $response ) ) {
1261
			if ( isset( $cache[ $cache_key ] ) && is_array( $cache[ $cache_key ] ) )
1262
				return $cache[ $cache_key ][ 'payload' ]; // return stale
1263
			else
1264
				return array();
1265
		}
1266
1267
		$results = json_decode( wp_remote_retrieve_body( $response ), true );
1268
		$related_posts = array();
1269
		if ( is_array( $results ) && !empty( $results['hits'] ) ) {
1270
			foreach( $results['hits'] as $hit ) {
1271
				$related_posts[] = array(
1272
					'id' => $hit['fields']['post_id'],
1273
				);
1274
			}
1275
		}
1276
1277
		// An empty array might indicate no related posts or that posts
1278
		// are not yet synced to WordPress.com, so we cache for only 1
1279
		// minute in this case
1280
		if ( empty( $related_posts ) ) {
1281
			$cache_ttl = 60;
1282
		} else {
1283
			$cache_ttl = 12 * HOUR_IN_SECONDS;
1284
		}
1285
1286
		// Update cache
1287
		if ( wp_using_ext_object_cache() ) {
1288
			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...
1289
		} else {
1290
			// Copy all valid cache values
1291
			$new_cache = array();
1292
			foreach ( $cache as $k => $v ) {
1293
				if ( is_array( $v ) && $v[ 'expires' ] > $now_ts ) {
1294
					$new_cache[ $k ] = $v;
1295
				}
1296
			}
1297
1298
			// Set new cache value
1299
			$cache_expires = $cache_ttl + $now_ts;
1300
			$new_cache[ $cache_key ] = array(
1301
				'expires' => $cache_expires,
1302
				'payload' => $related_posts,
1303
			);
1304
			update_post_meta( $post_id, $cache_meta_key, $new_cache );
1305
		}
1306
1307
		return $related_posts;
1308
	}
1309
1310
	/**
1311
	 * Filter out any hits that are not public anymore.
1312
	 *
1313
	 * @param array $related_posts
1314
	 * @uses get_post_stati, get_post_status
1315
	 * @return array
1316
	 */
1317
	protected function _filter_non_public_posts( array $related_posts ) {
1318
		$public_stati = get_post_stati( array( 'public' => true ) );
1319
1320
		$filtered = array();
1321
		foreach ( $related_posts as $hit ) {
1322
			if ( in_array( get_post_status( $hit['id'] ), $public_stati ) ) {
1323
				$filtered[] = $hit;
1324
			}
1325
		}
1326
		return $filtered;
1327
	}
1328
1329
	/**
1330
	 * Generates a context for the related content (second line in related post output).
1331
	 * Order of importance:
1332
	 *   - First category (Not 'Uncategorized')
1333
	 *   - First post tag
1334
	 *   - Number of comments
1335
	 *
1336
	 * @param int $post_id
1337
	 * @uses get_the_category, get_the_terms, get_comments_number, number_format_i18n, __, _n
1338
	 * @return string
1339
	 */
1340
	protected function _generate_related_post_context( $post_id ) {
1341
		$categories = get_the_category( $post_id );
1342 View Code Duplication
		if ( is_array( $categories ) ) {
1343
			foreach ( $categories as $category ) {
1344
				if ( 'uncategorized' != $category->slug && '' != trim( $category->name ) ) {
1345
					$post_cat_context = sprintf(
1346
						_x( 'In "%s"', 'in {category/tag name}', 'jetpack' ),
1347
						$category->name
1348
					);
1349
					/**
1350
					 * Filter the "In Category" line displayed in the post context below each Related Post.
1351
					 *
1352
					 * @module related-posts
1353
					 *
1354
					 * @since 3.2.0
1355
					 *
1356
					 * @param string $post_cat_context "In Category" line displayed in the post context below each Related Post.
1357
					 * @param array $category Array containing information about the category.
1358
					 */
1359
					return apply_filters( 'jetpack_relatedposts_post_category_context', $post_cat_context, $category );
1360
				}
1361
			}
1362
		}
1363
1364
		$tags = get_the_terms( $post_id, 'post_tag' );
1365 View Code Duplication
		if ( is_array( $tags ) ) {
1366
			foreach ( $tags as $tag ) {
1367
				if ( '' != trim( $tag->name ) ) {
1368
					$post_tag_context = sprintf(
1369
						_x( 'In "%s"', 'in {category/tag name}', 'jetpack' ),
1370
						$tag->name
1371
					);
1372
					/**
1373
					 * Filter the "In Tag" line displayed in the post context below each Related Post.
1374
					 *
1375
					 * @module related-posts
1376
					 *
1377
					 * @since 3.2.0
1378
					 *
1379
					 * @param string $post_tag_context "In Tag" line displayed in the post context below each Related Post.
1380
					 * @param array $tag Array containing information about the tag.
1381
					 */
1382
					return apply_filters( 'jetpack_relatedposts_post_tag_context', $post_tag_context, $tag );
1383
				}
1384
			}
1385
		}
1386
1387
		$comment_count = get_comments_number( $post_id );
1388
		if ( $comment_count > 0 ) {
1389
			return sprintf(
1390
				_n( 'With 1 comment', 'With %s comments', $comment_count, 'jetpack' ),
1391
				number_format_i18n( $comment_count )
1392
			);
1393
		}
1394
1395
		return __( 'Similar post', 'jetpack' );
1396
	}
1397
1398
	/**
1399
	 * Logs clicks for clickthrough analysis and related result tuning.
1400
	 *
1401
	 * @return null
1402
	 */
1403
	protected function _log_click( $post_id, $to_post_id, $link_position ) {
1404
1405
	}
1406
1407
	/**
1408
	 * Determines if the current post is able to use related posts.
1409
	 *
1410
	 * @uses self::get_options, is_admin, is_single, apply_filters
1411
	 * @return bool
1412
	 */
1413
	protected function _enabled_for_request() {
1414
		$enabled = is_single()
1415
			&&
1416
				! is_admin()
1417
			&&
1418
				( !$this->_allow_feature_toggle() || $this->get_option( 'enabled' ) )
1419
			&&
1420
				! Jetpack_AMP_Support::is_amp_request();
1421
1422
		/**
1423
		 * Filter the Enabled value to allow related posts to be shown on pages as well.
1424
		 *
1425
		 * @module related-posts
1426
		 *
1427
		 * @since 3.3.0
1428
		 *
1429
		 * @param bool $enabled Should Related Posts be enabled on the current page.
1430
		 */
1431
		return apply_filters( 'jetpack_relatedposts_filter_enabled_for_request', $enabled );
1432
	}
1433
1434
	/**
1435
	 * Adds filters and enqueues assets.
1436
	 *
1437
	 * @uses self::_enqueue_assets, self::_setup_shortcode, add_filter
1438
	 * @return null
1439
	 */
1440
	protected function _action_frontend_init_page() {
1441
		$this->_enqueue_assets( true, true );
1442
		$this->_setup_shortcode();
1443
1444
		add_filter( 'the_content', array( $this, 'filter_add_target_to_dom' ), 40 );
1445
	}
1446
1447
	/**
1448
	 * Enqueues assets needed to do async loading of related posts.
1449
	 *
1450
	 * @uses wp_enqueue_script, wp_enqueue_style, plugins_url
1451
	 * @return null
1452
	 */
1453
	protected function _enqueue_assets( $script, $style ) {
1454
		$dependencies = is_customize_preview() ? array( 'customize-base' ) : array( 'jquery' );
1455
		if ( $script ) {
1456
			wp_enqueue_script(
1457
				'jetpack_related-posts',
1458
				Jetpack::get_file_url_for_environment(
1459
					'_inc/build/related-posts/related-posts.min.js',
1460
					'modules/related-posts/related-posts.js'
1461
				),
1462
				$dependencies,
1463
				self::VERSION
1464
			);
1465
			$related_posts_js_options = array(
1466
				/**
1467
				 * Filter each Related Post Heading structure.
1468
				 *
1469
				 * @since 4.0.0
1470
				 *
1471
				 * @param string $str Related Post Heading structure. Default to h4.
1472
				 */
1473
				'post_heading' => apply_filters( 'jetpack_relatedposts_filter_post_heading', esc_attr( 'h4' ) ),
1474
			);
1475
			wp_localize_script( 'jetpack_related-posts', 'related_posts_js_options', $related_posts_js_options );
1476
		}
1477
		if ( $style ){
1478
			wp_enqueue_style( 'jetpack_related-posts', plugins_url( 'related-posts.css', __FILE__ ), array(), self::VERSION );
1479
			wp_style_add_data( 'jetpack_related-posts', 'rtl', 'replace' );
1480
		}
1481
	}
1482
1483
	/**
1484
	 * Sets up the shortcode processing.
1485
	 *
1486
	 * @uses add_filter, add_shortcode
1487
	 * @return null
1488
	 */
1489
	protected function _setup_shortcode() {
1490
		add_filter( 'the_content', array( $this, 'test_for_shortcode' ), 0 );
1491
1492
		add_shortcode( self::SHORTCODE, array( $this, 'get_target_html' ) );
1493
	}
1494
1495
	protected function _allow_feature_toggle() {
1496
		if ( null === $this->_allow_feature_toggle ) {
1497
			/**
1498
			 * Filter the display of the Related Posts toggle in Settings > Reading.
1499
			 *
1500
			 * @module related-posts
1501
			 *
1502
			 * @since 2.8.0
1503
			 *
1504
			 * @param bool false Display a feature toggle. Default to false.
1505
			 */
1506
			$this->_allow_feature_toggle = apply_filters( 'jetpack_relatedposts_filter_allow_feature_toggle', false );
1507
		}
1508
		return $this->_allow_feature_toggle;
1509
	}
1510
1511
	/**
1512
	 * ===================================================
1513
	 * FUNCTIONS EXPOSING RELATED POSTS IN THE WP REST API
1514
	 * ===================================================
1515
	 */
1516
1517
	/**
1518
	 * Add Related Posts to the REST API Post response.
1519
	 *
1520
	 * @since 4.4.0
1521
	 *
1522
	 * @action rest_api_init
1523
	 * @uses register_rest_field, self::rest_get_related_posts
1524
	 * @return null
1525
	 */
1526
	public function rest_register_related_posts() {
1527
		register_rest_field( 'post',
1528
			'jetpack-related-posts',
1529
			array(
1530
				'get_callback' => array( $this, 'rest_get_related_posts' ),
1531
				'update_callback' => null,
1532
				'schema'          => null,
1533
			)
1534
		);
1535
	}
1536
1537
	/**
1538
	 * Build an array of Related Posts.
1539
	 *
1540
	 * @since 4.4.0
1541
	 *
1542
	 * @param array $object Details of current post.
1543
	 * @param string $field_name Name of field.
1544
	 * @param WP_REST_Request $request Current request
1545
	 *
1546
	 * @uses self::get_for_post_id
1547
	 *
1548
	 * @return array
1549
	 */
1550
	public function rest_get_related_posts( $object, $field_name, $request ) {
1551
		return $this->get_for_post_id( $object['id'], array() );
1552
	}
1553
}
1554
1555
class Jetpack_RelatedPosts_Raw extends Jetpack_RelatedPosts {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
1556
	protected $_query_name;
1557
1558
	/**
1559
	 * Allows callers of this class to tag each query with a unique name for tracking purposes.
1560
	 *
1561
	 * @param string $name
1562
	 * @return Jetpack_RelatedPosts_Raw
1563
	 */
1564
	public function set_query_name( $name ) {
1565
		$this->_query_name = (string) $name;
1566
		return $this;
1567
	}
1568
1569
	/**
1570
	 * The raw related posts class can be used by other plugins or themes
1571
	 * to get related content. This class wraps the existing RelatedPosts
1572
	 * logic thus we never want to add anything to the DOM or do anything
1573
	 * for event hooks. We will also not present any settings for this
1574
	 * class and keep it enabled as calls to this class is done
1575
	 * programmatically.
1576
	 */
1577
	public function action_admin_init() {}
1578
	public function action_frontend_init() {}
1579
	public function get_options() {
1580
		return array(
1581
			'enabled' => true,
1582
		);
1583
	}
1584
1585
	/**
1586
	 * Workhorse method to return array of related posts ids matched by Elasticsearch.
1587
	 *
1588
	 * @param int $post_id
1589
	 * @param int $size
1590
	 * @param array $filters
1591
	 * @uses wp_remote_post, is_wp_error, wp_remote_retrieve_body
1592
	 * @return array
1593
	 */
1594
	protected function _get_related_posts( $post_id, $size, array $filters ) {
1595
		$hits = $this->_filter_non_public_posts(
1596
			$this->_get_related_post_ids(
1597
				$post_id,
1598
				$size,
1599
				$filters
1600
			)
1601
		);
1602
1603
		/** This filter is already documented in modules/related-posts/related-posts.php */
1604
		$hits = apply_filters( 'jetpack_relatedposts_filter_hits', $hits, $post_id );
1605
1606
		return $hits;
1607
	}
1608
}
1609