Completed
Push — update/akismet-dashitem ( 001fc7...3a6c16 )
by
unknown
08:51 queued 01:45
created

Jetpack_RelatedPosts::get_blog_id()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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