Completed
Push — try/sync-package ( 228b13...691df5 )
by Marin
06:41
created

Jetpack_RelatedPosts::init()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 3
nop 0
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
use Automattic\Jetpack\Sync\Settings;
4
5
class Jetpack_RelatedPosts {
6
	const VERSION   = '20190204';
7
	const SHORTCODE = 'jetpack-related-posts';
8
9
	private static $instance     = null;
10
	private static $instance_raw = null;
11
12
	/**
13
	 * Creates and returns a static instance of Jetpack_RelatedPosts.
14
	 *
15
	 * @return Jetpack_RelatedPosts
16
	 */
17
	public static function init() {
18
		if ( ! self::$instance ) {
19
			if ( class_exists('WPCOM_RelatedPosts') && method_exists( 'WPCOM_RelatedPosts', 'init' ) ) {
20
				self::$instance = WPCOM_RelatedPosts::init();
21
			} else {
22
				self::$instance = new Jetpack_RelatedPosts();
23
			}
24
		}
25
26
		return self::$instance;
27
	}
28
29
	/**
30
	 * Creates and returns a static instance of Jetpack_RelatedPosts_Raw.
31
	 *
32
	 * @return Jetpack_RelatedPosts
33
	 */
34
	public static function init_raw() {
35
		if ( ! self::$instance_raw ) {
36
			if ( class_exists('WPCOM_RelatedPosts') && method_exists( 'WPCOM_RelatedPosts', 'init_raw' ) ) {
37
				self::$instance_raw = WPCOM_RelatedPosts::init_raw();
38
			} else {
39
				self::$instance_raw = new Jetpack_RelatedPosts_Raw();
40
			}
41
		}
42
43
		return self::$instance_raw;
44
	}
45
46
	protected $_options;
47
	protected $_allow_feature_toggle;
48
	protected $_blog_charset;
49
	protected $_convert_charset;
50
	protected $_previous_post_id;
51
	protected $_found_shortcode = false;
52
53
	/**
54
	 * Constructor for Jetpack_RelatedPosts.
55
	 *
56
	 * @uses get_option, add_action, apply_filters
57
	 * @return null
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...
58
	 */
59
	public function __construct() {
60
		$this->_blog_charset = get_option( 'blog_charset' );
61
		$this->_convert_charset = ( function_exists( 'iconv' ) && ! preg_match( '/^utf\-?8$/i', $this->_blog_charset ) );
62
63
		add_action( 'admin_init', array( $this, 'action_admin_init' ) );
64
		add_action( 'wp', array( $this, 'action_frontend_init' ) );
65
66
		if ( ! class_exists( 'Jetpack_Media_Summary' ) ) {
67
			jetpack_require_lib( 'class.media-summary' );
68
		}
69
70
		// Add Related Posts to the REST API Post response.
71
		add_action( 'rest_api_init', array( $this, 'rest_register_related_posts' ) );
72
73
		jetpack_register_block(
74
			'jetpack/related-posts',
75
			array(
76
				'render_callback' => array( $this, 'render_block' ),
77
			)
78
		);
79
	}
80
81
	protected function get_blog_id() {
82
		return Jetpack_Options::get_option( 'id' );
83
	}
84
85
	/**
86
	 * =================
87
	 * ACTIONS & FILTERS
88
	 * =================
89
	 */
90
91
	/**
92
	 * Add a checkbox field to Settings > Reading for enabling related posts.
93
	 *
94
	 * @action admin_init
95
	 * @uses add_settings_field, __, register_setting, add_action
96
	 * @return null
97
	 */
98
	public function action_admin_init() {
99
100
		// Add the setting field [jetpack_relatedposts] and place it in Settings > Reading
101
		add_settings_field( 'jetpack_relatedposts', '<span id="jetpack_relatedposts">' . __( 'Related posts', 'jetpack' ) . '</span>', array( $this, 'print_setting_html' ), 'reading' );
102
		register_setting( 'reading', 'jetpack_relatedposts', array( $this, 'parse_options' ) );
103
		add_action('admin_head', array( $this, 'print_setting_head' ) );
104
105
		if( 'options-reading.php' == $GLOBALS['pagenow'] ) {
106
			// Enqueue style for live preview on the reading settings page
107
			$this->_enqueue_assets( false, true );
108
		}
109
	}
110
111
	/**
112
	 * Load related posts assets if it's a elegiable front end page or execute search and return JSON if it's an endpoint request.
113
	 *
114
	 * @global $_GET
115
	 * @action wp
116
	 * @uses add_shortcode, get_the_ID
117
	 * @returns null
118
	 */
119
	public function action_frontend_init() {
120
		// Add a shortcode handler that outputs nothing, this gets overridden later if we can display related content
121
		add_shortcode( self::SHORTCODE, array( $this, 'get_target_html_unsupported' ) );
122
123
		if ( ! $this->_enabled_for_request() )
124
			return;
125
126
		if ( isset( $_GET['relatedposts'] ) ) {
127
			$excludes = $this->parse_numeric_get_arg( 'relatedposts_exclude' );
128
			$this->_action_frontend_init_ajax( $excludes );
129
		} else {
130
			if ( isset( $_GET['relatedposts_hit'], $_GET['relatedposts_origin'], $_GET['relatedposts_position'] ) ) {
131
				$this->_log_click( $_GET['relatedposts_origin'], get_the_ID(), $_GET['relatedposts_position'] );
132
				$this->_previous_post_id = (int) $_GET['relatedposts_origin'];
133
			}
134
135
			$this->_action_frontend_init_page();
136
		}
137
138
	}
139
140
	/**
141
	 * Render insertion point.
142
	 *
143
	 * @since 4.2.0
144
	 *
145
	 * @return string
146
	 */
147
	public function get_headline() {
148
		$options = $this->get_options();
149
150
		if ( $options['show_headline'] ) {
151
			$headline = sprintf(
152
				/** This filter is already documented in modules/sharedaddy/sharing-service.php */
153
				apply_filters( 'jetpack_sharing_headline_html', '<h3 class="jp-relatedposts-headline"><em>%s</em></h3>', esc_html( $options['headline'] ), 'related-posts' ),
154
				esc_html( $options['headline'] )
155
			);
156
		} else {
157
			$headline = '';
158
		}
159
		return $headline;
160
	}
161
162
	/**
163
	 * Adds a target to the post content to load related posts into if a shortcode for it did not already exist.
164
	 * Will skip adding the target if the post content contains a Related Posts block.
165
	 *
166
	 * @filter the_content
167
	 * @param string $content
168
	 * @returns string
169
	 */
170
	public function filter_add_target_to_dom( $content ) {
171
		if ( has_block( 'jetpack/related-posts', $content ) ) {
172
			return $content;
173
		}
174
175
		if ( ! $this->_found_shortcode ) {
176
			$content .= "\n" . $this->get_target_html();
177
		}
178
179
		return $content;
180
	}
181
182
	/**
183
	 * Looks for our shortcode on the unfiltered content, this has to execute early.
184
	 *
185
	 * @filter the_content
186
	 * @param string $content
187
	 * @uses has_shortcode
188
	 * @returns string
189
	 */
190
	public function test_for_shortcode( $content ) {
191
		$this->_found_shortcode = has_shortcode( $content, self::SHORTCODE );
192
193
		return $content;
194
	}
195
196
	/**
197
	 * Returns the HTML for the related posts section.
198
	 *
199
	 * @uses esc_html__, apply_filters
200
	 * @returns string
201
	 */
202
	public function get_target_html() {
203
		if ( Settings::is_syncing() ) {
204
			return '';
205
		}
206
207
		/**
208
		 * Filter the Related Posts headline.
209
		 *
210
		 * @module related-posts
211
		 *
212
		 * @since 3.0.0
213
		 *
214
		 * @param string $headline Related Posts heading.
215
		 */
216
		$headline = apply_filters( 'jetpack_relatedposts_filter_headline', $this->get_headline() );
217
218
		if ( $this->_previous_post_id ) {
219
			$exclude = "data-exclude='{$this->_previous_post_id}'";
220
		} else {
221
			$exclude = "";
222
		}
223
224
		return <<<EOT
225
<div id='jp-relatedposts' class='jp-relatedposts' $exclude>
226
	$headline
227
</div>
228
EOT;
229
	}
230
231
	/**
232
	 * Returns the HTML for the related posts section if it's running in the loop or other instances where we don't support related posts.
233
	 *
234
	 * @returns string
235
	 */
236
	public function get_target_html_unsupported() {
237
		if ( Settings::is_syncing() ) {
238
			return '';
239
		}
240
		return "\n\n<!-- Jetpack Related Posts is not supported in this context. -->\n\n";
241
	}
242
243
	/**
244
	 * ===============
245
	 * GUTENBERG BLOCK
246
	 * ===============
247
	 */
248
249
	/**
250
	 * Echoes out items for the Gutenberg block
251
	 *
252
	 * @param array $related_post The post oject.
253
	 * @param array $block_attributes The block attributes.
254
	 */
255
	public function render_block_item( $related_post, $block_attributes ) {
256
		$instance_id = 'related-posts-item-' . uniqid();
257
		$label_id    = $instance_id . '-label';
258
259
		$item_markup = sprintf(
260
			'<ul id="%1$s" aria-labelledby="%2$s" class="jp-related-posts-i2__post" role="menuitem">',
261
			esc_attr( $instance_id ),
262
			esc_attr( $label_id )
263
		);
264
265
		$item_markup .= sprintf(
266
			'<li class="jp-related-posts-i2__post-link"><a id="%1$s" href="%2$s" rel="%4$s">%3$s</a></li>',
267
			esc_attr( $label_id ),
268
			esc_url( $related_post['url'] ),
269
			esc_attr( $related_post['title'] ),
270
			esc_attr( $related_post['rel'] )
271
		);
272
273
		if ( ! empty( $block_attributes['show_thumbnails'] ) && ! empty( $related_post['img']['src'] ) ) {
274
			$img_link = sprintf(
275
				'<li class="jp-related-posts-i2__post-img-link"><a href="%1$s" rel="%2$s"><img src="%3$s" width="%4$s" alt="%5$s" /></a></li>',
276
				esc_url( $related_post['url'] ),
277
				esc_attr( $related_post['rel'] ),
278
				esc_url( $related_post['img']['src'] ),
279
				esc_attr( $related_post['img']['width'] ),
280
				esc_attr( $related_post['img']['alt_text'] )
281
			);
282
283
			$item_markup .= $img_link;
284
		}
285
286
		if ( $block_attributes['show_date'] ) {
287
			$date_tag = sprintf(
288
				'<li class="jp-related-posts-i2__post-date">%1$s</li>',
289
				esc_html( $related_post['date'] )
290
			);
291
292
			$item_markup .= $date_tag;
293
		}
294
295
		if ( ( $block_attributes['show_context'] ) && ! empty( $related_post['context'] ) ) {
296
			$context_tag = sprintf(
297
				'<li class="jp-related-posts-i2__post-context">%1$s</li>',
298
				esc_html( $related_post['context'] )
299
			);
300
301
			$item_markup .= $context_tag;
302
		}
303
304
		$item_markup .= '</ul>';
305
306
		return $item_markup;
307
	}
308
309
	/**
310
	 * Render a related posts row.
311
	 *
312
	 * @param array $posts The posts to render into the row.
313
	 * @param array $block_attributes Block attributes.
314
	 */
315
	public function render_block_row( $posts, $block_attributes ) {
316
		$rows_markup = '';
317
		foreach ( $posts as $post ) {
318
			$rows_markup .= $this->render_block_item( $post, $block_attributes );
319
		}
320
		return sprintf(
321
			'<div class="jp-related-posts-i2__row" data-post-count="%1$s">%2$s</div>',
322
			count( $posts ),
323
			$rows_markup
324
		);
325
	}
326
327
	/**
328
	 * Render the related posts markup.
329
	 *
330
	 * @param array $attributes Block attributes.
331
	 * @return string
332
	 */
333
	public function render_block( $attributes ) {
334
		$block_attributes = array(
335
			'show_thumbnails' => isset( $attributes['displayThumbnails'] ) && $attributes['displayThumbnails'],
336
			'show_date'       => isset( $attributes['displayDate'] ) ? (bool) $attributes['displayDate'] : true,
337
			'show_context'    => isset( $attributes['displayContext'] ) && $attributes['displayContext'],
338
			'layout'          => isset( $attributes['postLayout'] ) && 'list' === $attributes['postLayout'] ? $attributes['postLayout'] : 'grid',
339
			'size'            => ! empty( $attributes['postsToShow'] ) ? absint( $attributes['postsToShow'] ) : 3,
340
		);
341
342
		$excludes      = $this->parse_numeric_get_arg( 'relatedposts_origin' );
343
		$related_posts = $this->get_for_post_id(
344
			get_the_ID(),
345
			array(
346
				'size'             => $block_attributes['size'],
347
				'exclude_post_ids' => $excludes,
348
			)
349
		);
350
351
		$display_lower_row = $block_attributes['size'] > 3;
352
353
		if ( empty( $related_posts ) ) {
354
			return '';
355
		}
356
357
		switch ( count( $related_posts ) ) {
358
			case 2:
359
			case 4:
360
			case 5:
361
				$top_row_end = 2;
362
				break;
363
364
			default:
365
				$top_row_end = 3;
366
				break;
367
		}
368
369
		$upper_row_posts = array_slice( $related_posts, 0, $top_row_end );
370
		$lower_row_posts = array_slice( $related_posts, $top_row_end );
371
372
		$rows_markup = $this->render_block_row( $upper_row_posts, $block_attributes );
373
		if ( $display_lower_row ) {
374
			$rows_markup .= $this->render_block_row( $lower_row_posts, $block_attributes );
375
		}
376
377
		$target_to_dom_priority = has_filter(
378
			'the_content',
379
			array( $this, 'filter_add_target_to_dom' )
380
		);
381
		remove_filter(
382
			'the_content',
383
			array( $this, 'filter_add_target_to_dom' ),
384
			$target_to_dom_priority
385
		);
386
387
		/*
388
		 * Below is a hack to get the block content to render correctly.
389
		 *
390
		 * This functionality should be covered in /inc/blocks.php but due to an error,
391
		 * this has not been fixed as of this writing.
392
		 *
393
		 * Alda has submitted a patch to Core in order to have this issue fixed at
394
		 * https://core.trac.wordpress.org/ticket/45495 and
395
		 * made it into WordPress 5.2.
396
		 *
397
		 * @todo update when WP 5.2 is the minimum support version.
398
		 */
399
		$priority = has_filter( 'the_content', 'wpautop' );
400
		remove_filter( 'the_content', 'wpautop', $priority );
401
		add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 );
402
403
		return sprintf(
404
			'<nav class="jp-relatedposts-i2" data-layout="%1$s">%2$s</nav>',
405
			esc_attr( $block_attributes['layout'] ),
406
			$rows_markup
407
		);
408
	}
409
410
	/**
411
	 * ========================
412
	 * PUBLIC UTILITY FUNCTIONS
413
	 * ========================
414
	 */
415
416
	/**
417
	 * Parse a numeric GET variable to an array of values.
418
	 *
419
	 * @since 6.9.0
420
	 *
421
	 * @uses absint
422
	 *
423
	 * @param string $arg Name of the GET variable
424
	 * @return array $result Parsed value(s)
425
	 */
426
	public function parse_numeric_get_arg( $arg ) {
427
		$result = array();
428
429
		if ( isset( $_GET[ $arg ] ) ) {
430
			if ( is_string( $_GET[ $arg ] ) ) {
431
				$result = explode( ',', $_GET[ $arg ] );
432
			} elseif ( is_array( $_GET[ $arg ] ) ) {
433
				$result = array_values( $_GET[ $arg ] );
434
			}
435
436
			$result = array_unique( array_filter( array_map( 'absint', $result ) ) );
437
		}
438
439
		return $result;
440
	}
441
442
	/**
443
	 * Gets options set for Jetpack_RelatedPosts and merge with defaults.
444
	 *
445
	 * @uses Jetpack_Options::get_option, apply_filters
446
	 * @return array
447
	 */
448
	public function get_options() {
449
		if ( null === $this->_options ) {
450
			$this->_options = Jetpack_Options::get_option( 'relatedposts', array() );
451
			if ( ! is_array( $this->_options ) )
452
				$this->_options = array();
453
			if ( ! isset( $this->_options['enabled'] ) )
454
				$this->_options['enabled'] = true;
455
			if ( ! isset( $this->_options['show_headline'] ) )
456
				$this->_options['show_headline'] = true;
457
			if ( ! isset( $this->_options['show_thumbnails'] ) )
458
				$this->_options['show_thumbnails'] = false;
459
			if ( ! isset( $this->_options['show_date'] ) ) {
460
				$this->_options['show_date'] = true;
461
			}
462
			if ( ! isset( $this->_options['show_context'] ) ) {
463
				$this->_options['show_context'] = true;
464
			}
465
			if ( ! isset( $this->_options['layout'] ) ) {
466
				$this->_options['layout'] = 'grid';
467
			}
468
			if ( ! isset( $this->_options['headline'] ) ) {
469
				$this->_options['headline'] = esc_html__( 'Related', 'jetpack' );
470
			}
471
			if ( empty( $this->_options['size'] ) || (int)$this->_options['size'] < 1 )
472
				$this->_options['size'] = 3;
473
474
			/**
475
			 * Filter Related Posts basic options.
476
			 *
477
			 * @module related-posts
478
			 *
479
			 * @since 2.8.0
480
			 *
481
			 * @param array $this->_options Array of basic Related Posts options.
482
			 */
483
			$this->_options = apply_filters( 'jetpack_relatedposts_filter_options', $this->_options );
484
		}
485
486
		return $this->_options;
487
	}
488
489
	public function get_option( $option_name ) {
490
		$options = $this->get_options();
491
492
		if ( isset( $options[ $option_name ] ) ) {
493
			return $options[ $option_name ];
494
		}
495
496
		return false;
497
	}
498
499
	/**
500
	 * Parses input and returns normalized options array.
501
	 *
502
	 * @param array $input
503
	 * @uses self::get_options
504
	 * @return array
505
	 */
506
	public function parse_options( $input ) {
507
		$current = $this->get_options();
508
509
		if ( !is_array( $input ) )
510
			$input = array();
511
512
		if (
513
			! isset( $input['enabled'] )
514
			|| isset( $input['show_date'] )
515
			|| isset( $input['show_context'] )
516
			|| isset( $input['layout'] )
517
			|| isset( $input['headline'] )
518
			) {
519
			$input['enabled'] = '1';
520
		}
521
522
		if ( '1' == $input['enabled'] ) {
523
			$current['enabled'] = true;
524
			$current['show_headline'] = ( isset( $input['show_headline'] ) && '1' == $input['show_headline'] );
525
			$current['show_thumbnails'] = ( isset( $input['show_thumbnails'] ) && '1' == $input['show_thumbnails'] );
526
			$current['show_date'] = ( isset( $input['show_date'] ) && '1' == $input['show_date'] );
527
			$current['show_context'] = ( isset( $input['show_context'] ) && '1' == $input['show_context'] );
528
			$current['layout'] = isset( $input['layout'] ) && in_array( $input['layout'], array( 'grid', 'list' ), true ) ? $input['layout'] : 'grid';
529
			$current['headline'] = isset( $input['headline'] ) ? $input['headline'] : esc_html__( 'Related', 'jetpack' );
530
		} else {
531
			$current['enabled'] = false;
532
		}
533
534
		if ( isset( $input['size'] ) && (int)$input['size'] > 0 )
535
			$current['size'] = (int)$input['size'];
536
		else
537
			$current['size'] = null;
538
539
		return $current;
540
	}
541
542
	/**
543
	 * HTML for admin settings page.
544
	 *
545
	 * @uses self::get_options, checked, esc_html__
546
	 * @returns null
547
	 */
548
	public function print_setting_html() {
549
		$options = $this->get_options();
550
551
		$ui_settings_template = <<<EOT
552
<p class="description">%s</p>
553
<ul id="settings-reading-relatedposts-customize">
554
	<li>
555
		<label><input name="jetpack_relatedposts[show_headline]" type="checkbox" value="1" %s /> %s</label>
556
	</li>
557
	<li>
558
		<label><input name="jetpack_relatedposts[show_thumbnails]" type="checkbox" value="1" %s /> %s</label>
559
	</li>
560
	<li>
561
		<label><input name="jetpack_relatedposts[show_date]" type="checkbox" value="1" %s /> %s</label>
562
	</li>
563
	<li>
564
		<label><input name="jetpack_relatedposts[show_context]" type="checkbox" value="1" %s /> %s</label>
565
	</li>
566
</ul>
567
<div id='settings-reading-relatedposts-preview'>
568
	%s
569
	<div id="jp-relatedposts" class="jp-relatedposts"></div>
570
</div>
571
EOT;
572
		$ui_settings = sprintf(
573
			$ui_settings_template,
574
			esc_html__( 'The following settings will impact all related posts on your site, except for those you created via the block editor:', 'jetpack' ),
575
			checked( $options['show_headline'], true, false ),
576
			esc_html__( 'Highlight related content with a heading', 'jetpack' ),
577
			checked( $options['show_thumbnails'], true, false ),
578
			esc_html__( 'Show a thumbnail image where available', 'jetpack' ),
579
			checked( $options['show_date'], true, false ),
580
			esc_html__( 'Show entry date', 'jetpack' ),
581
			checked( $options['show_context'], true, false ),
582
			esc_html__( 'Show context (category or tag)', 'jetpack' ),
583
			esc_html__( 'Preview:', 'jetpack' )
584
		);
585
586
		if ( !$this->_allow_feature_toggle() ) {
587
			$template = <<<EOT
588
<input type="hidden" name="jetpack_relatedposts[enabled]" value="1" />
589
%s
590
EOT;
591
			printf(
592
				$template,
593
				$ui_settings
594
			);
595
		} else {
596
			$template = <<<EOT
597
<ul id="settings-reading-relatedposts">
598
	<li>
599
		<label><input type="radio" name="jetpack_relatedposts[enabled]" value="0" class="tog" %s /> %s</label>
600
	</li>
601
	<li>
602
		<label><input type="radio" name="jetpack_relatedposts[enabled]" value="1" class="tog" %s /> %s</label>
603
		%s
604
	</li>
605
</ul>
606
EOT;
607
			printf(
608
				$template,
609
				checked( $options['enabled'], false, false ),
610
				esc_html__( 'Hide related content after posts', 'jetpack' ),
611
				checked( $options['enabled'], true, false ),
612
				esc_html__( 'Show related content after posts', 'jetpack' ),
613
				$ui_settings
614
			);
615
		}
616
	}
617
618
	/**
619
	 * Head JS/CSS for admin settings page.
620
	 *
621
	 * @uses esc_html__
622
	 * @returns null
623
	 */
624
	public function print_setting_head() {
625
626
		// only dislay the Related Posts JavaScript on the Reading Settings Admin Page
627
		$current_screen =  get_current_screen();
628
629
		if ( is_null( $current_screen ) ) {
630
			return;
631
		}
632
633
		if( 'options-reading' != $current_screen->id )
634
			return;
635
636
		$related_headline = sprintf(
637
			'<h3 class="jp-relatedposts-headline"><em>%s</em></h3>',
638
			esc_html__( 'Related', 'jetpack' )
639
		);
640
641
		$href_params = 'class="jp-relatedposts-post-a" href="#jetpack_relatedposts" rel="nofollow" data-origin="0" data-position="0"';
642
		$related_with_images = <<<EOT
643
<div class="jp-relatedposts-items jp-relatedposts-items-visual">
644
	<div class="jp-relatedposts-post jp-relatedposts-post0 jp-relatedposts-post-thumbs" data-post-id="0" data-post-format="image">
645
		<a $href_params>
646
			<img class="jp-relatedposts-post-img" src="https://jetpackme.files.wordpress.com/2019/03/cat-blog.png" width="350" alt="Big iPhone/iPad Update Now Available" scale="0">
647
		</a>
648
		<h4 class="jp-relatedposts-post-title">
649
			<a $href_params>Big iPhone/iPad Update Now Available</a>
650
		</h4>
651
		<p class="jp-relatedposts-post-excerpt">Big iPhone/iPad Update Now Available</p>
652
		<p class="jp-relatedposts-post-context">In "Mobile"</p>
653
	</div>
654
	<div class="jp-relatedposts-post jp-relatedposts-post1 jp-relatedposts-post-thumbs" data-post-id="0" data-post-format="image">
655
		<a $href_params>
656
			<img class="jp-relatedposts-post-img" src="https://jetpackme.files.wordpress.com/2019/03/devices.jpg" width="350" alt="The WordPress for Android App Gets a Big Facelift" scale="0">
657
		</a>
658
		<h4 class="jp-relatedposts-post-title">
659
			<a $href_params>The WordPress for Android App Gets a Big Facelift</a>
660
		</h4>
661
		<p class="jp-relatedposts-post-excerpt">The WordPress for Android App Gets a Big Facelift</p>
662
		<p class="jp-relatedposts-post-context">In "Mobile"</p>
663
	</div>
664
	<div class="jp-relatedposts-post jp-relatedposts-post2 jp-relatedposts-post-thumbs" data-post-id="0" data-post-format="image">
665
		<a $href_params>
666
			<img class="jp-relatedposts-post-img" src="https://jetpackme.files.wordpress.com/2019/03/mobile-wedding.jpg" width="350" alt="Upgrade Focus: VideoPress For Weddings" scale="0">
667
		</a>
668
		<h4 class="jp-relatedposts-post-title">
669
			<a $href_params>Upgrade Focus: VideoPress For Weddings</a>
670
		</h4>
671
		<p class="jp-relatedposts-post-excerpt">Upgrade Focus: VideoPress For Weddings</p>
672
		<p class="jp-relatedposts-post-context">In "Upgrade"</p>
673
	</div>
674
</div>
675
EOT;
676
		$related_with_images = str_replace( "\n", '', $related_with_images );
677
		$related_without_images = <<<EOT
678
<div class="jp-relatedposts-items jp-relatedposts-items-minimal">
679
	<p class="jp-relatedposts-post jp-relatedposts-post0" data-post-id="0" data-post-format="image">
680
		<span class="jp-relatedposts-post-title"><a $href_params>Big iPhone/iPad Update Now Available</a></span>
681
		<span class="jp-relatedposts-post-context">In "Mobile"</span>
682
	</p>
683
	<p class="jp-relatedposts-post jp-relatedposts-post1" data-post-id="0" data-post-format="image">
684
		<span class="jp-relatedposts-post-title"><a $href_params>The WordPress for Android App Gets a Big Facelift</a></span>
685
		<span class="jp-relatedposts-post-context">In "Mobile"</span>
686
	</p>
687
	<p class="jp-relatedposts-post jp-relatedposts-post2" data-post-id="0" data-post-format="image">
688
		<span class="jp-relatedposts-post-title"><a $href_params>Upgrade Focus: VideoPress For Weddings</a></span>
689
		<span class="jp-relatedposts-post-context">In "Upgrade"</span>
690
	</p>
691
</div>
692
EOT;
693
		$related_without_images = str_replace( "\n", '', $related_without_images );
694
695
		if ( $this->_allow_feature_toggle() ) {
696
			$extra_css = '#settings-reading-relatedposts-customize { padding-left:2em; margin-top:.5em; }';
697
		} else {
698
			$extra_css = '';
699
		}
700
701
		echo <<<EOT
702
<style type="text/css">
703
	#settings-reading-relatedposts .disabled { opacity:.5; filter:Alpha(opacity=50); }
704
	#settings-reading-relatedposts-preview .jp-relatedposts { background:#fff; padding:.5em; width:75%; }
705
	$extra_css
706
</style>
707
<script type="text/javascript">
708
	jQuery( document ).ready( function($) {
709
		var update_ui = function() {
710
			var is_enabled = true;
711
			if ( 'radio' == $( 'input[name="jetpack_relatedposts[enabled]"]' ).attr('type') ) {
712
				if ( '0' == $( 'input[name="jetpack_relatedposts[enabled]"]:checked' ).val() ) {
713
					is_enabled = false;
714
				}
715
			}
716
			if ( is_enabled ) {
717
				$( '#settings-reading-relatedposts-customize' )
718
					.removeClass( 'disabled' )
719
					.find( 'input' )
720
					.attr( 'disabled', false );
721
				$( '#settings-reading-relatedposts-preview' )
722
					.removeClass( 'disabled' );
723
			} else {
724
				$( '#settings-reading-relatedposts-customize' )
725
					.addClass( 'disabled' )
726
					.find( 'input' )
727
					.attr( 'disabled', true );
728
				$( '#settings-reading-relatedposts-preview' )
729
					.addClass( 'disabled' );
730
			}
731
		};
732
733
		var update_preview = function() {
734
			var html = '';
735
			if ( $( 'input[name="jetpack_relatedposts[show_headline]"]:checked' ).length ) {
736
				html += '$related_headline';
737
			}
738
			if ( $( 'input[name="jetpack_relatedposts[show_thumbnails]"]:checked' ).length ) {
739
				html += '$related_with_images';
740
			} else {
741
				html += '$related_without_images';
742
			}
743
			$( '#settings-reading-relatedposts-preview .jp-relatedposts' ).html( html );
744
			if ( $( 'input[name="jetpack_relatedposts[show_date]"]:checked' ).length ) {
745
				$( '.jp-relatedposts-post-title' ).each( function() {
746
					$( this ).after( $( '<span>August 8, 2005</span>' ) );
747
				} );
748
			}
749
			if ( $( 'input[name="jetpack_relatedposts[show_context]"]:checked' ).length ) {
750
				$( '.jp-relatedposts-post-context' ).show();
751
			} else {
752
				$( '.jp-relatedposts-post-context' ).hide();
753
			}
754
			$( '#settings-reading-relatedposts-preview .jp-relatedposts' ).show();
755
		};
756
757
		// Update on load
758
		update_preview();
759
		update_ui();
760
761
		// Update on change
762
		$( '#settings-reading-relatedposts-customize input' )
763
			.change( update_preview );
764
		$( '#settings-reading-relatedposts' )
765
			.find( 'input.tog' )
766
			.change( update_ui );
767
	});
768
</script>
769
EOT;
770
	}
771
772
	/**
773
	 * Gets an array of related posts that match the given post_id.
774
	 *
775
	 * @param int   $post_id Post which we want to find related posts for.
776
	 * @param array $args - params to use when building Elasticsearch filters to narrow down the search domain.
777
	 * @uses self::get_options, get_post_type, wp_parse_args, apply_filters
778
	 * @return array
779
	 */
780
	public function get_for_post_id( $post_id, array $args ) {
781
		$options = $this->get_options();
782
783
		if ( ! empty( $args['size'] ) ) {
784
			$options['size'] = $args['size'];
785
		}
786
787
		if (
788
			! $options['enabled']
789
			|| 0 === (int) $post_id
790
			|| empty( $options['size'] )
791
		) {
792
			return array();
793
		}
794
795
		$defaults = array(
796
			'size'             => (int) $options['size'],
797
			'post_type'        => get_post_type( $post_id ),
798
			'post_formats'     => array(),
799
			'has_terms'        => array(),
800
			'date_range'       => array(),
801
			'exclude_post_ids' => array(),
802
		);
803
		$args     = wp_parse_args( $args, $defaults );
804
		/**
805
		 * Filter the arguments used to retrieve a list of Related Posts.
806
		 *
807
		 * @module related-posts
808
		 *
809
		 * @since 2.8.0
810
		 *
811
		 * @param array $args Array of options to retrieve Related Posts.
812
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
813
		 */
814
		$args = apply_filters( 'jetpack_relatedposts_filter_args', $args, $post_id );
815
816
		$filters = $this->_get_es_filters_from_args( $post_id, $args );
817
		/**
818
		 * Filter Elasticsearch options used to calculate Related Posts.
819
		 *
820
		 * @module related-posts
821
		 *
822
		 * @since 2.8.0
823
		 *
824
		 * @param array $filters Array of Elasticsearch filters based on the post_id and args.
825
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
826
		 */
827
		$filters = apply_filters( 'jetpack_relatedposts_filter_filters', $filters, $post_id );
828
829
		$results = $this->_get_related_posts( $post_id, $args['size'], $filters );
830
		/**
831
		 * Filter the array of related posts matched by Elasticsearch.
832
		 *
833
		 * @module related-posts
834
		 *
835
		 * @since 2.8.0
836
		 *
837
		 * @param array $results Array of related posts matched by Elasticsearch.
838
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
839
		 */
840
		return apply_filters( 'jetpack_relatedposts_returned_results', $results, $post_id );
841
	}
842
843
	/**
844
	 * =========================
845
	 * PRIVATE UTILITY FUNCTIONS
846
	 * =========================
847
	 */
848
849
	/**
850
	 * Creates an array of Elasticsearch filters based on the post_id and args.
851
	 *
852
	 * @param int $post_id
853
	 * @param array $args
854
	 * @uses apply_filters, get_post_types, get_post_format_strings
855
	 * @return array
856
	 */
857
	protected function _get_es_filters_from_args( $post_id, array $args ) {
858
		$filters = array();
859
860
		/**
861
		 * Filter the terms used to search for Related Posts.
862
		 *
863
		 * @module related-posts
864
		 *
865
		 * @since 2.8.0
866
		 *
867
		 * @param array $args['has_terms'] Array of terms associated to the Related Posts.
868
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
869
		 */
870
		$args['has_terms'] = apply_filters( 'jetpack_relatedposts_filter_has_terms', $args['has_terms'], $post_id );
871
		if ( ! empty( $args['has_terms'] ) ) {
872
			foreach( (array)$args['has_terms'] as $term ) {
873
				if ( mb_strlen( $term->taxonomy ) ) {
874 View Code Duplication
					switch ( $term->taxonomy ) {
875
						case 'post_tag':
876
							$tax_fld = 'tag.slug';
877
							break;
878
						case 'category':
879
							$tax_fld = 'category.slug';
880
							break;
881
						default:
882
							$tax_fld = 'taxonomy.' . $term->taxonomy . '.slug';
883
							break;
884
					}
885
					$filters[] = array( 'term' => array( $tax_fld => $term->slug ) );
886
				}
887
			}
888
		}
889
890
		/**
891
		 * Filter the Post Types where we search Related Posts.
892
		 *
893
		 * @module related-posts
894
		 *
895
		 * @since 2.8.0
896
		 *
897
		 * @param array $args['post_type'] Array of Post Types.
898
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
899
		 */
900
		$args['post_type'] = apply_filters( 'jetpack_relatedposts_filter_post_type', $args['post_type'], $post_id );
901
		$valid_post_types = get_post_types();
902
		if ( is_array( $args['post_type'] ) ) {
903
			$sanitized_post_types = array();
904
			foreach ( $args['post_type'] as $pt ) {
905
				if ( in_array( $pt, $valid_post_types ) )
906
					$sanitized_post_types[] = $pt;
907
			}
908
			if ( ! empty( $sanitized_post_types ) )
909
				$filters[] = array( 'terms' => array( 'post_type' => $sanitized_post_types ) );
910
		} else if ( in_array( $args['post_type'], $valid_post_types ) && 'all' != $args['post_type'] ) {
911
			$filters[] = array( 'term' => array( 'post_type' => $args['post_type'] ) );
912
		}
913
914
		/**
915
		 * Filter the Post Formats where we search Related Posts.
916
		 *
917
		 * @module related-posts
918
		 *
919
		 * @since 3.3.0
920
		 *
921
		 * @param array $args['post_formats'] Array of Post Formats.
922
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
923
		 */
924
		$args['post_formats'] = apply_filters( 'jetpack_relatedposts_filter_post_formats', $args['post_formats'], $post_id );
925
		$valid_post_formats = get_post_format_strings();
926
		$sanitized_post_formats = array();
927
		foreach ( $args['post_formats'] as $pf ) {
928
			if ( array_key_exists( $pf, $valid_post_formats ) ) {
929
				$sanitized_post_formats[] = $pf;
930
			}
931
		}
932
		if ( ! empty( $sanitized_post_formats ) ) {
933
			$filters[] = array( 'terms' => array( 'post_format' => $sanitized_post_formats ) );
934
		}
935
936
		/**
937
		 * Filter the date range used to search Related Posts.
938
		 *
939
		 * @module related-posts
940
		 *
941
		 * @since 2.8.0
942
		 *
943
		 * @param array $args['date_range'] Array of a month interval where we search Related Posts.
944
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
945
		 */
946
		$args['date_range'] = apply_filters( 'jetpack_relatedposts_filter_date_range', $args['date_range'], $post_id );
947
		if ( is_array( $args['date_range'] ) && ! empty( $args['date_range'] ) ) {
948
			$args['date_range'] = array_map( 'intval', $args['date_range'] );
949
			if ( !empty( $args['date_range']['from'] ) && !empty( $args['date_range']['to'] ) ) {
950
				$filters[] = array(
951
					'range' => array(
952
						'date_gmt' => $this->_get_coalesced_range( $args['date_range'] ),
953
					)
954
				);
955
			}
956
		}
957
958
		/**
959
		 * Filter the Post IDs excluded from appearing in Related Posts.
960
		 *
961
		 * @module related-posts
962
		 *
963
		 * @since 2.9.0
964
		 *
965
		 * @param array $args['exclude_post_ids'] Array of Post IDs.
966
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
967
		 */
968
		$args['exclude_post_ids'] = apply_filters( 'jetpack_relatedposts_filter_exclude_post_ids', $args['exclude_post_ids'], $post_id );
969
		if ( !empty( $args['exclude_post_ids'] ) && is_array( $args['exclude_post_ids'] ) ) {
970
			$excluded_post_ids = array();
971
			foreach ( $args['exclude_post_ids'] as $exclude_post_id) {
972
				$exclude_post_id = (int)$exclude_post_id;
973
				if ( $exclude_post_id > 0 )
974
					$excluded_post_ids[] = $exclude_post_id;
975
			}
976
			$filters[] = array( 'not' => array( 'terms' => array( 'post_id' => $excluded_post_ids ) ) );
977
		}
978
979
		return $filters;
980
	}
981
982
	/**
983
	 * Takes a range and coalesces it into a month interval bracketed by a time as determined by the blog_id to enhance caching.
984
	 *
985
	 * @param array $date_range
986
	 * @return array
987
	 */
988
	protected function _get_coalesced_range( array $date_range ) {
989
		$now = time();
990
		$coalesce_time = $this->get_blog_id() % 86400;
991
		$current_time = $now - strtotime( 'today', $now );
992
993
		if ( $current_time < $coalesce_time && '01' == date( 'd', $now ) ) {
994
			// Move back 1 period
995
			return array(
996
				'from' => date( 'Y-m-01', strtotime( '-1 month', $date_range['from'] ) ) . ' ' . date( 'H:i:s', $coalesce_time ),
997
				'to'   => date( 'Y-m-01', $date_range['to'] ) . ' ' . date( 'H:i:s', $coalesce_time ),
998
			);
999
		} else {
1000
			// Use current period
1001
			return array(
1002
				'from' => date( 'Y-m-01', $date_range['from'] ) . ' ' . date( 'H:i:s', $coalesce_time ),
1003
				'to'   => date( 'Y-m-01', strtotime( '+1 month', $date_range['to'] ) ) . ' ' . date( 'H:i:s', $coalesce_time ),
1004
			);
1005
		}
1006
	}
1007
1008
	/**
1009
	 * Generate and output ajax response for related posts API call.
1010
	 * NOTE: Calls exit() to end all further processing after payload has been outputed.
1011
	 *
1012
	 * @param array $excludes array of post_ids to exclude
1013
	 * @uses send_nosniff_header, self::get_for_post_id, get_the_ID
1014
	 * @return null
1015
	 */
1016
	protected function _action_frontend_init_ajax( array $excludes ) {
1017
		define( 'DOING_AJAX', true );
1018
1019
		header( 'Content-type: application/json; charset=utf-8' ); // JSON can only be UTF-8
1020
		send_nosniff_header();
1021
1022
		$options = $this->get_options();
1023
1024
		if ( isset( $_GET['jetpackrpcustomize'] ) ) {
1025
1026
			// If we're in the customizer, add dummy content.
1027
			$date_now = current_time( get_option( 'date_format' ) );
1028
			$related_posts = array(
1029
				array(
1030
					'id'       => - 1,
1031
					'url'      => 'https://jetpackme.files.wordpress.com/2019/03/cat-blog.png',
1032
					'url_meta' => array(
1033
						'origin'   => 0,
1034
						'position' => 0
1035
					),
1036
					'title'    => esc_html__( 'Big iPhone/iPad Update Now Available', 'jetpack' ),
1037
					'date'     => $date_now,
1038
					'format'   => false,
1039
					'excerpt'  => esc_html__( 'It is that time of the year when devices are shiny again.', 'jetpack' ),
1040
					'rel'      => 'nofollow',
1041
					'context'  => esc_html__( 'In "Mobile"', 'jetpack' ),
1042
					'img'      => array(
1043
						'src'    => 'https://jetpackme.files.wordpress.com/2019/03/cat-blog.png',
1044
						'width'  => 350,
1045
						'height' => 200
1046
					),
1047
					'classes'  => array()
1048
				),
1049
				array(
1050
					'id'       => - 1,
1051
					'url'      => 'https://jetpackme.files.wordpress.com/2019/03/devices.jpg',
1052
					'url_meta' => array(
1053
						'origin'   => 0,
1054
						'position' => 0
1055
					),
1056
					'title'    => esc_html__( 'The WordPress for Android App Gets a Big Facelift', 'jetpack' ),
1057
					'date'     => $date_now,
1058
					'format'   => false,
1059
					'excerpt'  => esc_html__( 'Writing is new again in Android with the new WordPress app.', 'jetpack' ),
1060
					'rel'      => 'nofollow',
1061
					'context'  => esc_html__( 'In "Mobile"', 'jetpack' ),
1062
					'img'      => array(
1063
						'src'    => 'https://jetpackme.files.wordpress.com/2019/03/devices.jpg',
1064
						'width'  => 350,
1065
						'height' => 200
1066
					),
1067
					'classes'  => array()
1068
				),
1069
				array(
1070
					'id'       => - 1,
1071
					'url'      => 'https://jetpackme.files.wordpress.com/2019/03/mobile-wedding.jpg',
1072
					'url_meta' => array(
1073
						'origin'   => 0,
1074
						'position' => 0
1075
					),
1076
					'title'    => esc_html__( 'Upgrade Focus, VideoPress for weddings', 'jetpack' ),
1077
					'date'     => $date_now,
1078
					'format'   => false,
1079
					'excerpt'  => esc_html__( 'Weddings are in the spotlight now with VideoPress for weddings.', 'jetpack' ),
1080
					'rel'      => 'nofollow',
1081
					'context'  => esc_html__( 'In "Mobile"', 'jetpack' ),
1082
					'img'      => array(
1083
						'src'    => 'https://jetpackme.files.wordpress.com/2019/03/mobile-wedding.jpg',
1084
						'width'  => 350,
1085
						'height' => 200
1086
					),
1087
					'classes'  => array()
1088
				),
1089
			);
1090
1091
			for ( $total = 0; $total < $options['size'] - 3; $total++ ) {
1092
				$related_posts[] = $related_posts[ $total ];
1093
			}
1094
1095
			$current_post = get_post();
1096
1097
			// Exclude current post after filtering to make sure it's excluded and not lost during filtering.
1098
			$excluded_posts = array_merge(
1099
				/** This filter is already documented in modules/related-posts/jetpack-related-posts.php */
1100
				apply_filters( 'jetpack_relatedposts_filter_exclude_post_ids', array() ),
1101
				array( $current_post->ID )
1102
			);
1103
1104
			// Fetch posts with featured image.
1105
			$with_post_thumbnails = get_posts( array(
1106
				'posts_per_page'   => $options['size'],
1107
				'post__not_in'     => $excluded_posts,
1108
				'post_type'        => $current_post->post_type,
1109
				'meta_key'         => '_thumbnail_id',
1110
				'suppress_filters' => false,
1111
			) );
1112
1113
			// If we don't have enough, fetch posts without featured image.
1114
			if ( 0 < ( $more = $options['size'] - count( $with_post_thumbnails ) ) ) {
1115
				$no_post_thumbnails = get_posts( array(
1116
					'posts_per_page'  => $more,
1117
					'post__not_in'    => $excluded_posts,
1118
					'post_type'       => $current_post->post_type,
1119
					'meta_query' => array(
1120
						array(
1121
							'key'     => '_thumbnail_id',
1122
							'compare' => 'NOT EXISTS',
1123
						),
1124
					),
1125
					'suppress_filters' => false,
1126
				) );
1127
			} else {
1128
				$no_post_thumbnails = array();
1129
			}
1130
1131
			foreach ( array_merge( $with_post_thumbnails, $no_post_thumbnails ) as $index => $real_post ) {
1132
				$related_posts[ $index ]['id']      = $real_post->ID;
1133
				$related_posts[ $index ]['url']     = esc_url( get_permalink( $real_post ) );
1134
				$related_posts[ $index ]['title']   = $this->_to_utf8( $this->_get_title( $real_post->post_title, $real_post->post_content ) );
1135
				$related_posts[ $index ]['date']    = get_the_date( '', $real_post );
1136
				$related_posts[ $index ]['excerpt'] = html_entity_decode( $this->_to_utf8( $this->_get_excerpt( $real_post->post_excerpt, $real_post->post_content ) ), ENT_QUOTES, 'UTF-8' );
1137
				$related_posts[ $index ]['img']     = $this->_generate_related_post_image_params( $real_post->ID );
1138
				$related_posts[ $index ]['context'] = $this->_generate_related_post_context( $real_post->ID );
1139
			}
1140
		} else {
1141
			$related_posts = $this->get_for_post_id(
1142
				get_the_ID(),
1143
				array(
1144
					'exclude_post_ids' => $excludes,
1145
				)
1146
			);
1147
		}
1148
1149
		$response = array(
1150
			'version' => self::VERSION,
1151
			'show_thumbnails' => (bool) $options['show_thumbnails'],
1152
			'show_date' => (bool) $options['show_date'],
1153
			'show_context' => (bool) $options['show_context'],
1154
			'layout' => (string) $options['layout'],
1155
			'headline' => (string) $options['headline'],
1156
			'items' => array(),
1157
		);
1158
1159
		if ( count( $related_posts ) == $options['size'] )
1160
			$response['items'] = $related_posts;
1161
1162
		echo json_encode( $response );
1163
1164
		exit();
1165
	}
1166
1167
	/**
1168
	 * Returns a UTF-8 encoded array of post information for the given post_id
1169
	 *
1170
	 * @param int $post_id
1171
	 * @param int $position
1172
	 * @param int $origin The post id that this is related to
1173
	 * @uses get_post, get_permalink, remove_query_arg, get_post_format, apply_filters
1174
	 * @return array
1175
	 */
1176
	public function get_related_post_data_for_post( $post_id, $position, $origin ) {
1177
		$post = get_post( $post_id );
1178
1179
		return array(
1180
			'id' => $post->ID,
1181
			'url' => get_permalink( $post->ID ),
1182
			'url_meta' => array( 'origin' => $origin, 'position' => $position ),
1183
			'title' => $this->_to_utf8( $this->_get_title( $post->post_title, $post->post_content ) ),
1184
			'date' => get_the_date( '', $post->ID ),
1185
			'format' => get_post_format( $post->ID ),
1186
			'excerpt' => html_entity_decode( $this->_to_utf8( $this->_get_excerpt( $post->post_excerpt, $post->post_content ) ), ENT_QUOTES, 'UTF-8' ),
1187
			/**
1188
			 * Filters the rel attribute for the Related Posts' links.
1189
			 *
1190
			 * @module related-posts
1191
			 *
1192
			 * @since 3.7.0
1193
			 *
1194
			 * @param string nofollow Link rel attribute for Related Posts' link. Default is nofollow.
1195
			 * @param int $post->ID Post ID.
1196
			 */
1197
			'rel' => apply_filters( 'jetpack_relatedposts_filter_post_link_rel', 'nofollow', $post->ID ),
1198
			/**
1199
			 * Filter the context displayed below each Related Post.
1200
			 *
1201
			 * @module related-posts
1202
			 *
1203
			 * @since 3.0.0
1204
			 *
1205
			 * @param string $this->_to_utf8( $this->_generate_related_post_context( $post->ID ) ) Context displayed below each related post.
1206
			 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
1207
			 */
1208
			'context' => apply_filters(
1209
				'jetpack_relatedposts_filter_post_context',
1210
				$this->_to_utf8( $this->_generate_related_post_context( $post->ID ) ),
1211
				$post->ID
1212
			),
1213
			'img' => $this->_generate_related_post_image_params( $post->ID ),
1214
			/**
1215
			 * Filter the post css classes added on HTML markup.
1216
			 *
1217
			 * @module related-posts
1218
			 *
1219
			 * @since 3.8.0
1220
			 *
1221
			 * @param array array() CSS classes added on post HTML markup.
1222
			 * @param string $post_id Post ID.
1223
			 */
1224
			'classes' => apply_filters(
1225
				'jetpack_relatedposts_filter_post_css_classes',
1226
				array(),
1227
				$post->ID
1228
			),
1229
		);
1230
	}
1231
1232
	/**
1233
	 * Returns either the title or a small excerpt to use as title for post.
1234
	 *
1235
	 * @param string $post_title
1236
	 * @param string $post_content
1237
	 * @uses strip_shortcodes, wp_trim_words, __
1238
	 * @return string
1239
	 */
1240
	protected function _get_title( $post_title, $post_content ) {
1241
		if ( ! empty( $post_title ) ) {
1242
			return wp_strip_all_tags( $post_title );
1243
		}
1244
1245
		$post_title = wp_trim_words( wp_strip_all_tags( strip_shortcodes( $post_content ) ), 5, '…' );
1246
		if ( ! empty( $post_title ) ) {
1247
			return $post_title;
1248
		}
1249
1250
		return __( 'Untitled Post', 'jetpack' );
1251
	}
1252
1253
	/**
1254
	 * Returns a plain text post excerpt for title attribute of links.
1255
	 *
1256
	 * @param string $post_excerpt
1257
	 * @param string $post_content
1258
	 * @uses strip_shortcodes, wp_strip_all_tags, wp_trim_words
1259
	 * @return string
1260
	 */
1261
	protected function _get_excerpt( $post_excerpt, $post_content ) {
1262
		if ( empty( $post_excerpt ) )
1263
			$excerpt = $post_content;
1264
		else
1265
			$excerpt = $post_excerpt;
1266
1267
		return wp_trim_words( wp_strip_all_tags( strip_shortcodes( $excerpt ) ), 50, '…' );
1268
	}
1269
1270
	/**
1271
	 * Generates the thumbnail image to be used for the post. Uses the
1272
	 * image as returned by Jetpack_PostImages::get_image()
1273
	 *
1274
	 * @param int $post_id
1275
	 * @uses self::get_options, apply_filters, Jetpack_PostImages::get_image, Jetpack_PostImages::fit_image_url
1276
	 * @return string
1277
	 */
1278
	protected function _generate_related_post_image_params( $post_id ) {
1279
		$options = $this->get_options();
0 ignored issues
show
Unused Code introduced by
$options is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1280
		$image_params = array(
1281
			'alt_text' => '',
1282
			'src'      => '',
1283
			'width'    => 0,
1284
			'height'   => 0,
1285
		);
1286
1287
		/**
1288
		 * Filter the size of the Related Posts images.
1289
		 *
1290
		 * @module related-posts
1291
		 *
1292
		 * @since 2.8.0
1293
		 *
1294
		 * @param array array( 'width' => 350, 'height' => 200 ) Size of the images displayed below each Related Post.
1295
		 */
1296
		$thumbnail_size = apply_filters(
1297
			'jetpack_relatedposts_filter_thumbnail_size',
1298
			array( 'width' => 350, 'height' => 200 )
1299
		);
1300
		if ( !is_array( $thumbnail_size ) ) {
1301
			$thumbnail_size = array(
1302
				'width' => (int)$thumbnail_size,
1303
				'height' => (int)$thumbnail_size
1304
			);
1305
		}
1306
1307
		// Try to get post image
1308
		if ( class_exists( 'Jetpack_PostImages' ) ) {
1309
			$img_url    = '';
1310
			$post_image = Jetpack_PostImages::get_image(
1311
				$post_id,
1312
				$thumbnail_size
1313
			);
1314
1315
			if ( is_array($post_image) ) {
1316
				$img_url = $post_image['src'];
1317
			} elseif ( class_exists( 'Jetpack_Media_Summary' ) ) {
1318
				$media = Jetpack_Media_Summary::get( $post_id );
1319
1320
				if ( is_array($media) && !empty( $media['image'] ) ) {
1321
					$img_url = $media['image'];
1322
				}
1323
			}
1324
1325
			if ( ! empty( $img_url ) ) {
1326
				if ( ! empty( $post_image['alt_text'] ) ) {
1327
					$image_params['alt_text'] = $post_image['alt_text'];
1328
				} else {
1329
					$image_params['alt_text'] = '';
1330
				}
1331
				$image_params['width']  = $thumbnail_size['width'];
1332
				$image_params['height'] = $thumbnail_size['height'];
1333
				$image_params['src']    = Jetpack_PostImages::fit_image_url(
1334
					$img_url,
1335
					$thumbnail_size['width'],
1336
					$thumbnail_size['height']
1337
				);
1338
			}
1339
		}
1340
1341
		return $image_params;
1342
	}
1343
1344
	/**
1345
	 * Returns the string UTF-8 encoded
1346
	 *
1347
	 * @param string $text
1348
	 * @return string
1349
	 */
1350
	protected function _to_utf8( $text ) {
1351
		if ( $this->_convert_charset ) {
1352
			return iconv( $this->_blog_charset, 'UTF-8', $text );
1353
		} else {
1354
			return $text;
1355
		}
1356
	}
1357
1358
	/**
1359
	 * =============================================
1360
	 * PROTECTED UTILITY FUNCTIONS EXTENDED BY WPCOM
1361
	 * =============================================
1362
	 */
1363
1364
	/**
1365
	 * Workhorse method to return array of related posts matched by Elasticsearch.
1366
	 *
1367
	 * @param int $post_id
1368
	 * @param int $size
1369
	 * @param array $filters
1370
	 * @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
1371
	 * @return array
1372
	 */
1373
	protected function _get_related_posts( $post_id, $size, array $filters ) {
1374
		$hits = $this->_filter_non_public_posts(
1375
			$this->_get_related_post_ids(
1376
				$post_id,
1377
				$size,
1378
				$filters
1379
			)
1380
		);
1381
1382
		/**
1383
		 * Filter the Related Posts matched by Elasticsearch.
1384
		 *
1385
		 * @module related-posts
1386
		 *
1387
		 * @since 2.9.0
1388
		 *
1389
		 * @param array $hits Array of Post IDs matched by Elasticsearch.
1390
		 * @param string $post_id Post ID of the post for which we are retrieving Related Posts.
1391
		 */
1392
		$hits = apply_filters( 'jetpack_relatedposts_filter_hits', $hits, $post_id );
1393
1394
		$related_posts = array();
1395
		foreach ( $hits as $i => $hit ) {
1396
			$related_posts[] = $this->get_related_post_data_for_post( $hit['id'], $i, $post_id );
1397
		}
1398
		return $related_posts;
1399
	}
1400
1401
	/**
1402
	 * Get array of related posts matched by Elasticsearch.
1403
	 *
1404
	 * @param int $post_id
1405
	 * @param int $size
1406
	 * @param array $filters
1407
	 * @uses wp_remote_post, is_wp_error, wp_remote_retrieve_body, get_post_meta, update_post_meta
1408
	 * @return array
1409
	 */
1410
	protected function _get_related_post_ids( $post_id, $size, array $filters ) {
1411
		$now_ts = time();
1412
		$cache_meta_key = '_jetpack_related_posts_cache';
1413
1414
		$body = array(
1415
			'size' => (int) $size,
1416
		);
1417
1418
		if ( !empty( $filters ) )
1419
			$body['filter'] = array( 'and' => $filters );
1420
1421
		// Build cache key
1422
		$cache_key = md5( serialize( $body ) );
1423
1424
		// Load all cached values
1425
		if ( wp_using_ext_object_cache() ) {
1426
			$transient_name = "{$cache_meta_key}_{$cache_key}_{$post_id}";
1427
			$cache = get_transient( $transient_name );
1428
			if ( false !== $cache ) {
1429
				return $cache;
1430
			}
1431
		} else {
1432
			$cache = get_post_meta( $post_id, $cache_meta_key, true );
1433
1434
			if ( empty( $cache ) )
1435
				$cache = array();
1436
1437
1438
			// Cache is valid! Return cached value.
1439
			if ( isset( $cache[ $cache_key ] ) && is_array( $cache[ $cache_key ] ) && $cache[ $cache_key ][ 'expires' ] > $now_ts ) {
1440
				return $cache[ $cache_key ][ 'payload' ];
1441
			}
1442
		}
1443
1444
		$response = wp_remote_post(
1445
			"https://public-api.wordpress.com/rest/v1/sites/{$this->get_blog_id()}/posts/$post_id/related/",
1446
			array(
1447
				'timeout' => 10,
1448
				'user-agent' => 'jetpack_related_posts',
1449
				'sslverify' => true,
1450
				'body' => $body,
1451
			)
1452
		);
1453
1454
		// Oh no... return nothing don't cache errors.
1455
		if ( is_wp_error( $response ) ) {
1456
			if ( isset( $cache[ $cache_key ] ) && is_array( $cache[ $cache_key ] ) )
1457
				return $cache[ $cache_key ][ 'payload' ]; // return stale
1458
			else
1459
				return array();
1460
		}
1461
1462
		$results = json_decode( wp_remote_retrieve_body( $response ), true );
1463
		$related_posts = array();
1464
		if ( is_array( $results ) && !empty( $results['hits'] ) ) {
1465
			foreach( $results['hits'] as $hit ) {
1466
				$related_posts[] = array(
1467
					'id' => $hit['fields']['post_id'],
1468
				);
1469
			}
1470
		}
1471
1472
		// An empty array might indicate no related posts or that posts
1473
		// are not yet synced to WordPress.com, so we cache for only 1
1474
		// minute in this case
1475
		if ( empty( $related_posts ) ) {
1476
			$cache_ttl = 60;
1477
		} else {
1478
			$cache_ttl = 12 * HOUR_IN_SECONDS;
1479
		}
1480
1481
		// Update cache
1482
		if ( wp_using_ext_object_cache() ) {
1483
			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...
1484
		} else {
1485
			// Copy all valid cache values
1486
			$new_cache = array();
1487
			foreach ( $cache as $k => $v ) {
1488
				if ( is_array( $v ) && $v[ 'expires' ] > $now_ts ) {
1489
					$new_cache[ $k ] = $v;
1490
				}
1491
			}
1492
1493
			// Set new cache value
1494
			$cache_expires = $cache_ttl + $now_ts;
1495
			$new_cache[ $cache_key ] = array(
1496
				'expires' => $cache_expires,
1497
				'payload' => $related_posts,
1498
			);
1499
			update_post_meta( $post_id, $cache_meta_key, $new_cache );
1500
		}
1501
1502
		return $related_posts;
1503
	}
1504
1505
	/**
1506
	 * Filter out any hits that are not public anymore.
1507
	 *
1508
	 * @param array $related_posts
1509
	 * @uses get_post_stati, get_post_status
1510
	 * @return array
1511
	 */
1512
	protected function _filter_non_public_posts( array $related_posts ) {
1513
		$public_stati = get_post_stati( array( 'public' => true ) );
1514
1515
		$filtered = array();
1516
		foreach ( $related_posts as $hit ) {
1517
			if ( in_array( get_post_status( $hit['id'] ), $public_stati ) ) {
1518
				$filtered[] = $hit;
1519
			}
1520
		}
1521
		return $filtered;
1522
	}
1523
1524
	/**
1525
	 * Generates a context for the related content (second line in related post output).
1526
	 * Order of importance:
1527
	 *   - First category (Not 'Uncategorized')
1528
	 *   - First post tag
1529
	 *   - Number of comments
1530
	 *
1531
	 * @param int $post_id
1532
	 * @uses get_the_category, get_the_terms, get_comments_number, number_format_i18n, __, _n
1533
	 * @return string
1534
	 */
1535
	protected function _generate_related_post_context( $post_id ) {
1536
		$categories = get_the_category( $post_id );
1537 View Code Duplication
		if ( is_array( $categories ) ) {
1538
			foreach ( $categories as $category ) {
1539
				if ( 'uncategorized' != $category->slug && '' != trim( $category->name ) ) {
1540
					$post_cat_context = sprintf(
1541
						esc_html_x( 'In "%s"', 'in {category/tag name}', 'jetpack' ),
1542
						$category->name
1543
					);
1544
					/**
1545
					 * Filter the "In Category" line displayed in the post context below each Related Post.
1546
					 *
1547
					 * @module related-posts
1548
					 *
1549
					 * @since 3.2.0
1550
					 *
1551
					 * @param string $post_cat_context "In Category" line displayed in the post context below each Related Post.
1552
					 * @param array $category Array containing information about the category.
1553
					 */
1554
					return apply_filters( 'jetpack_relatedposts_post_category_context', $post_cat_context, $category );
1555
				}
1556
			}
1557
		}
1558
1559
		$tags = get_the_terms( $post_id, 'post_tag' );
1560 View Code Duplication
		if ( is_array( $tags ) ) {
1561
			foreach ( $tags as $tag ) {
1562
				if ( '' != trim( $tag->name ) ) {
1563
					$post_tag_context = sprintf(
1564
						_x( 'In "%s"', 'in {category/tag name}', 'jetpack' ),
1565
						$tag->name
1566
					);
1567
					/**
1568
					 * Filter the "In Tag" line displayed in the post context below each Related Post.
1569
					 *
1570
					 * @module related-posts
1571
					 *
1572
					 * @since 3.2.0
1573
					 *
1574
					 * @param string $post_tag_context "In Tag" line displayed in the post context below each Related Post.
1575
					 * @param array $tag Array containing information about the tag.
1576
					 */
1577
					return apply_filters( 'jetpack_relatedposts_post_tag_context', $post_tag_context, $tag );
1578
				}
1579
			}
1580
		}
1581
1582
		$comment_count = get_comments_number( $post_id );
1583
		if ( $comment_count > 0 ) {
1584
			return sprintf(
1585
				_n( 'With 1 comment', 'With %s comments', $comment_count, 'jetpack' ),
1586
				number_format_i18n( $comment_count )
1587
			);
1588
		}
1589
1590
		return __( 'Similar post', 'jetpack' );
1591
	}
1592
1593
	/**
1594
	 * Logs clicks for clickthrough analysis and related result tuning.
1595
	 *
1596
	 * @return null
1597
	 */
1598
	protected function _log_click( $post_id, $to_post_id, $link_position ) {
1599
1600
	}
1601
1602
	/**
1603
	 * Determines if the current post is able to use related posts.
1604
	 *
1605
	 * @uses self::get_options, is_admin, is_single, apply_filters
1606
	 * @return bool
1607
	 */
1608
	protected function _enabled_for_request() {
1609
		$enabled = is_single()
1610
			&& ! is_attachment()
1611
			&& ! is_admin()
1612
			&& ( ! $this->_allow_feature_toggle() || $this->get_option( 'enabled' ) );
1613
1614
		if (
1615
			class_exists( 'Jetpack_AMP_Support' )
1616
			&& Jetpack_AMP_Support::is_amp_request()
1617
		) {
1618
			$enabled = false;
1619
		}
1620
1621
		/**
1622
		 * Filter the Enabled value to allow related posts to be shown on pages as well.
1623
		 *
1624
		 * @module related-posts
1625
		 *
1626
		 * @since 3.3.0
1627
		 *
1628
		 * @param bool $enabled Should Related Posts be enabled on the current page.
1629
		 */
1630
		return apply_filters( 'jetpack_relatedposts_filter_enabled_for_request', $enabled );
1631
	}
1632
1633
	/**
1634
	 * Adds filters and enqueues assets.
1635
	 *
1636
	 * @uses self::_enqueue_assets, self::_setup_shortcode, add_filter
1637
	 * @return null
1638
	 */
1639
	protected function _action_frontend_init_page() {
1640
		$this->_enqueue_assets( true, true );
1641
		$this->_setup_shortcode();
1642
1643
		add_filter( 'the_content', array( $this, 'filter_add_target_to_dom' ), 40 );
1644
	}
1645
1646
	/**
1647
	 * Enqueues assets needed to do async loading of related posts.
1648
	 *
1649
	 * @uses wp_enqueue_script, wp_enqueue_style, plugins_url
1650
	 * @return null
1651
	 */
1652
	protected function _enqueue_assets( $script, $style ) {
1653
		$dependencies = is_customize_preview() ? array( 'customize-base' ) : array( 'jquery' );
1654
		if ( $script ) {
1655
			wp_enqueue_script(
1656
				'jetpack_related-posts',
1657
				Jetpack::get_file_url_for_environment(
1658
					'_inc/build/related-posts/related-posts.min.js',
1659
					'modules/related-posts/related-posts.js'
1660
				),
1661
				$dependencies,
1662
				self::VERSION
1663
			);
1664
			$related_posts_js_options = array(
1665
				/**
1666
				 * Filter each Related Post Heading structure.
1667
				 *
1668
				 * @since 4.0.0
1669
				 *
1670
				 * @param string $str Related Post Heading structure. Default to h4.
1671
				 */
1672
				'post_heading' => apply_filters( 'jetpack_relatedposts_filter_post_heading', esc_attr( 'h4' ) ),
1673
			);
1674
			wp_localize_script( 'jetpack_related-posts', 'related_posts_js_options', $related_posts_js_options );
1675
		}
1676
		if ( $style ){
1677
			wp_enqueue_style( 'jetpack_related-posts', plugins_url( 'related-posts.css', __FILE__ ), array(), self::VERSION );
1678
			wp_style_add_data( 'jetpack_related-posts', 'rtl', 'replace' );
1679
		}
1680
	}
1681
1682
	/**
1683
	 * Sets up the shortcode processing.
1684
	 *
1685
	 * @uses add_filter, add_shortcode
1686
	 * @return null
1687
	 */
1688
	protected function _setup_shortcode() {
1689
		add_filter( 'the_content', array( $this, 'test_for_shortcode' ), 0 );
1690
1691
		add_shortcode( self::SHORTCODE, array( $this, 'get_target_html' ) );
1692
	}
1693
1694
	protected function _allow_feature_toggle() {
1695
		if ( null === $this->_allow_feature_toggle ) {
1696
			/**
1697
			 * Filter the display of the Related Posts toggle in Settings > Reading.
1698
			 *
1699
			 * @module related-posts
1700
			 *
1701
			 * @since 2.8.0
1702
			 *
1703
			 * @param bool false Display a feature toggle. Default to false.
1704
			 */
1705
			$this->_allow_feature_toggle = apply_filters( 'jetpack_relatedposts_filter_allow_feature_toggle', false );
1706
		}
1707
		return $this->_allow_feature_toggle;
1708
	}
1709
1710
	/**
1711
	 * ===================================================
1712
	 * FUNCTIONS EXPOSING RELATED POSTS IN THE WP REST API
1713
	 * ===================================================
1714
	 */
1715
1716
	/**
1717
	 * Add Related Posts to the REST API Post response.
1718
	 *
1719
	 * @since 4.4.0
1720
	 *
1721
	 * @action rest_api_init
1722
	 * @uses register_rest_field, self::rest_get_related_posts
1723
	 * @return null
1724
	 */
1725
	public function rest_register_related_posts() {
1726
		register_rest_field( 'post',
1727
			'jetpack-related-posts',
1728
			array(
1729
				'get_callback' => array( $this, 'rest_get_related_posts' ),
1730
				'update_callback' => null,
1731
				'schema'          => null,
1732
			)
1733
		);
1734
	}
1735
1736
	/**
1737
	 * Build an array of Related Posts.
1738
	 * By default returns cached results that are stored for up to 12 hours.
1739
	 *
1740
	 * @since 4.4.0
1741
	 *
1742
	 * @param array $object Details of current post.
1743
	 * @param string $field_name Name of field.
1744
	 * @param WP_REST_Request $request Current request
1745
	 *
1746
	 * @uses self::get_for_post_id
1747
	 *
1748
	 * @return array
1749
	 */
1750
	public function rest_get_related_posts( $object, $field_name, $request ) {
1751
		return $this->get_for_post_id( $object['id'], array( 'size' => 6 ) );
1752
	}
1753
}
1754
1755
class Jetpack_RelatedPosts_Raw extends Jetpack_RelatedPosts {
1756
	protected $_query_name;
1757
1758
	/**
1759
	 * Allows callers of this class to tag each query with a unique name for tracking purposes.
1760
	 *
1761
	 * @param string $name
1762
	 * @return Jetpack_RelatedPosts_Raw
1763
	 */
1764
	public function set_query_name( $name ) {
1765
		$this->_query_name = (string) $name;
1766
		return $this;
1767
	}
1768
1769
	/**
1770
	 * The raw related posts class can be used by other plugins or themes
1771
	 * to get related content. This class wraps the existing RelatedPosts
1772
	 * logic thus we never want to add anything to the DOM or do anything
1773
	 * for event hooks. We will also not present any settings for this
1774
	 * class and keep it enabled as calls to this class is done
1775
	 * programmatically.
1776
	 */
1777
	public function action_admin_init() {}
1778
	public function action_frontend_init() {}
1779
	public function get_options() {
1780
		return array(
1781
			'enabled' => true,
1782
		);
1783
	}
1784
1785
	/**
1786
	 * Workhorse method to return array of related posts ids matched by Elasticsearch.
1787
	 *
1788
	 * @param int $post_id
1789
	 * @param int $size
1790
	 * @param array $filters
1791
	 * @uses wp_remote_post, is_wp_error, wp_remote_retrieve_body
1792
	 * @return array
1793
	 */
1794
	protected function _get_related_posts( $post_id, $size, array $filters ) {
1795
		$hits = $this->_filter_non_public_posts(
1796
			$this->_get_related_post_ids(
1797
				$post_id,
1798
				$size,
1799
				$filters
1800
			)
1801
		);
1802
1803
		/** This filter is already documented in modules/related-posts/related-posts.php */
1804
		$hits = apply_filters( 'jetpack_relatedposts_filter_hits', $hits, $post_id );
1805
1806
		return $hits;
1807
	}
1808
}
1809