Completed
Push — add/site-importer-ui ( 829ce4...ff4189 )
by
unknown
07:07
created

Jetpack_RelatedPosts::render_block()   F

Complexity

Conditions 17
Paths 1152

Size

Total Lines 96

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
nc 1152
nop 1
dl 0
loc 96
rs 0.9272
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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