Completed
Push — renovate/major-react-monorepo ( 5a9765...516ec4 )
by Jeremy
20:32 queued 13:15
created

Jetpack_RelatedPosts::action_frontend_init()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 0
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
1
<?php
2
class Jetpack_RelatedPosts {
3
	const VERSION = '20181213';
4
	const SHORTCODE = 'jetpack-related-posts';
5
	private static $instance = null;
6
	private static $instance_raw = null;
7
8
	/**
9
	 * Creates and returns a static instance of Jetpack_RelatedPosts.
10
	 *
11
	 * @return Jetpack_RelatedPosts
12
	 */
13 View Code Duplication
	public static function init() {
14
		if ( ! self::$instance ) {
15
			if ( class_exists('WPCOM_RelatedPosts') && method_exists( 'WPCOM_RelatedPosts', 'init' ) ) {
16
				self::$instance = WPCOM_RelatedPosts::init();
17
			} else {
18
				self::$instance = new Jetpack_RelatedPosts(
19
					get_current_blog_id(),
20
					Jetpack_Options::get_option( 'id' )
21
				);
22
			}
23
		}
24
25
		return self::$instance;
26
	}
27
28
	/**
29
	 * Creates and returns a static instance of Jetpack_RelatedPosts_Raw.
30
	 *
31
	 * @return Jetpack_RelatedPosts
32
	 */
33 View Code Duplication
	public static function init_raw() {
34
		if ( ! self::$instance_raw ) {
35
			if ( class_exists('WPCOM_RelatedPosts') && method_exists( 'WPCOM_RelatedPosts', 'init_raw' ) ) {
36
				self::$instance_raw = WPCOM_RelatedPosts::init_raw();
37
			} else {
38
				self::$instance_raw = new Jetpack_RelatedPosts_Raw(
39
					get_current_blog_id(),
40
					Jetpack_Options::get_option( 'id' )
41
				);
42
			}
43
		}
44
45
		return self::$instance_raw;
46
	}
47
48
	protected $_blog_id_local;
49
	protected $_blog_id_wpcom;
50
	protected $_options;
51
	protected $_allow_feature_toggle;
52
	protected $_blog_charset;
53
	protected $_convert_charset;
54
	protected $_previous_post_id;
55
	protected $_found_shortcode = false;
56
57
	/**
58
	 * Constructor for Jetpack_RelatedPosts.
59
	 *
60
	 * @param int $blog_id_local
61
	 * @param int $blog_id_wpcom
62
	 * @uses get_option, add_action, apply_filters
63
	 * @return null
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
64
	 */
65
	public function __construct( $blog_id_local, $blog_id_wpcom ) {
66
		$this->_blog_id_local = $blog_id_local;
67
		$this->_blog_id_wpcom = $blog_id_wpcom;
68
		$this->_blog_charset = get_option( 'blog_charset' );
69
		$this->_convert_charset = ( function_exists( 'iconv' ) && ! preg_match( '/^utf\-?8$/i', $this->_blog_charset ) );
70
71
		add_action( 'admin_init', array( $this, 'action_admin_init' ) );
72
		add_action( 'wp', array( $this, 'action_frontend_init' ) );
73
74
		if ( ! class_exists( 'Jetpack_Media_Summary' ) ) {
75
			jetpack_require_lib( 'class.media-summary' );
76
		}
77
78
		// Add Related Posts to the REST API Post response.
79
		if ( function_exists( 'register_rest_field' ) ) {
80
			add_action( 'rest_api_init', array( $this, 'rest_register_related_posts' ) );
81
		}
82
83
		jetpack_register_block(
84
			'related-posts',
85
			array(
86
				'render_callback' => array( $this, 'render_block' ),
87
			)
88
		);
89
	}
90
91
	/**
92
	 * =================
93
	 * ACTIONS & FILTERS
94
	 * =================
95
	 */
96
97
	/**
98
	 * Add a checkbox field to Settings > Reading for enabling related posts.
99
	 *
100
	 * @action admin_init
101
	 * @uses add_settings_field, __, register_setting, add_action
102
	 * @return null
103
	 */
104
	public function action_admin_init() {
105
106
		// Add the setting field [jetpack_relatedposts] and place it in Settings > Reading
107
		add_settings_field( 'jetpack_relatedposts', '<span id="jetpack_relatedposts">' . __( 'Related posts', 'jetpack' ) . '</span>', array( $this, 'print_setting_html' ), 'reading' );
108
		register_setting( 'reading', 'jetpack_relatedposts', array( $this, 'parse_options' ) );
109
		add_action('admin_head', array( $this, 'print_setting_head' ) );
110
111
		if( 'options-reading.php' == $GLOBALS['pagenow'] ) {
112
			// Enqueue style for live preview on the reading settings page
113
			$this->_enqueue_assets( false, true );
114
		}
115
	}
116
117
	/**
118
	 * Load related posts assets if it's a elegiable front end page or execute search and return JSON if it's an endpoint request.
119
	 *
120
	 * @global $_GET
121
	 * @action wp
122
	 * @uses add_shortcode, get_the_ID
123
	 * @returns null
124
	 */
125
	public function action_frontend_init() {
126
		// Add a shortcode handler that outputs nothing, this gets overridden later if we can display related content
127
		add_shortcode( self::SHORTCODE, array( $this, 'get_target_html_unsupported' ) );
128
129
		if ( ! $this->_enabled_for_request() )
130
			return;
131
132
		if ( isset( $_GET['relatedposts'] ) ) {
133
			$excludes = $this->parse_numeric_get_arg( 'relatedposts_exclude' );
134
			$this->_action_frontend_init_ajax( $excludes );
135
		} else {
136
			if ( isset( $_GET['relatedposts_hit'], $_GET['relatedposts_origin'], $_GET['relatedposts_position'] ) ) {
137
				$this->_log_click( $_GET['relatedposts_origin'], get_the_ID(), $_GET['relatedposts_position'] );
138
				$this->_previous_post_id = (int) $_GET['relatedposts_origin'];
139
			}
140
141
			$this->_action_frontend_init_page();
142
		}
143
144
	}
145
146
	/**
147
	 * Render insertion point.
148
	 *
149
	 * @since 4.2.0
150
	 *
151
	 * @return string
152
	 */
153
	public function get_headline() {
154
		$options = $this->get_options();
155
156
		if ( $options['show_headline'] ) {
157
			$headline = sprintf(
158
				/** This filter is already documented in modules/sharedaddy/sharing-service.php */
159
				apply_filters( 'jetpack_sharing_headline_html', '<h3 class="jp-relatedposts-headline"><em>%s</em></h3>', esc_html( $options['headline'] ), 'related-posts' ),
160
				esc_html( $options['headline'] )
161
			);
162
		} else {
163
			$headline = '';
164
		}
165
		return $headline;
166
	}
167
168
	/**
169
	 * Adds a target to the post content to load related posts into if a shortcode for it did not already exist.
170
	 * Will skip adding the target if the post content contains a Related Posts block.
171
	 *
172
	 * @filter the_content
173
	 * @param string $content
174
	 * @returns string
175
	 */
176
	public function filter_add_target_to_dom( $content ) {
177
		if ( function_exists( 'has_block' ) && has_block( 'jetpack/related-posts', $content ) ) {
178
			return $content;
179
		}
180
181
		if ( ! $this->_found_shortcode ) {
182
			$content .= "\n" . $this->get_target_html();
183
		}
184
185
		return $content;
186
	}
187
188
	/**
189
	 * Looks for our shortcode on the unfiltered content, this has to execute early.
190
	 *
191
	 * @filter the_content
192
	 * @param string $content
193
	 * @uses has_shortcode
194
	 * @returns string
195
	 */
196
	public function test_for_shortcode( $content ) {
197
		$this->_found_shortcode = has_shortcode( $content, self::SHORTCODE );
198
199
		return $content;
200
	}
201
202
	/**
203
	 * Returns the HTML for the related posts section.
204
	 *
205
	 * @uses esc_html__, apply_filters
206
	 * @returns string
207
	 */
208
	public function get_target_html() {
209
		require_once JETPACK__PLUGIN_DIR . '/sync/class.jetpack-sync-settings.php';
210
		if ( Jetpack_Sync_Settings::is_syncing() ) {
211
			return '';
212
		}
213
214
		/**
215
		 * Filter the Related Posts headline.
216
		 *
217
		 * @module related-posts
218
		 *
219
		 * @since 3.0.0
220
		 *
221
		 * @param string $headline Related Posts heading.
222
		 */
223
		$headline = apply_filters( 'jetpack_relatedposts_filter_headline', $this->get_headline() );
224
225
		if ( $this->_previous_post_id ) {
226
			$exclude = "data-exclude='{$this->_previous_post_id}'";
227
		} else {
228
			$exclude = "";
229
		}
230
231
		return <<<EOT
232
<div id='jp-relatedposts' class='jp-relatedposts' $exclude>
233
	$headline
234
</div>
235
EOT;
236
	}
237
238
	/**
239
	 * Returns the HTML for the related posts section if it's running in the loop or other instances where we don't support related posts.
240
	 *
241
	 * @returns string
242
	 */
243
	public function get_target_html_unsupported() {
244
		require_once JETPACK__PLUGIN_DIR . '/sync/class.jetpack-sync-settings.php';
245
		if ( Jetpack_Sync_Settings::is_syncing() ) {
246
			return '';
247
		}
248
		return "\n\n<!-- Jetpack Related Posts is not supported in this context. -->\n\n";
249
	}
250
251
	/**
252
	 * ===============
253
	 * GUTENBERG BLOCK
254
	 * ===============
255
	 */
256
257
	/**
258
	 * Render the related posts markup.
259
	 *
260
	 * @param array $attributes Block attributes.
261
	 * @return string
262
	 */
263
	public function render_block( $attributes ) {
264
		$block_attributes = array(
265
			'show_thumbnails' => isset( $attributes['displayThumbnails'] ) && $attributes['displayThumbnails'],
266
			'show_date'       => isset( $attributes['displayDate'] ) ? (bool) $attributes['displayDate'] : true,
267
			'show_context'    => isset( $attributes['displayContext'] ) && $attributes['displayContext'],
268
			'layout'          => isset( $attributes['postLayout'] ) && 'list' === $attributes['postLayout'] ? $attributes['postLayout'] : 'grid',
269
			'size'            => ! empty( $attributes['postsToShow'] ) ? absint( $attributes['postsToShow'] ) : 3,
270
		);
271
272
		$excludes = $this->parse_numeric_get_arg( 'relatedposts_origin' );
273
		$related_posts = $this->get_for_post_id(
274
			get_the_ID(),
275
			array(
276
				'size'             => $block_attributes['size'],
277
				'exclude_post_ids' => $excludes,
278
			)
279
		);
280
281
		if ( ! $related_posts ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $related_posts of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

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