Completed
Push — renovate/webpack-cli-3.x ( 961c1b...02322b )
by
unknown
06:55
created

Jetpack_RelatedPosts::render_block_row()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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