Completed
Push — fix/podcast-player-link-error-... ( b24311...d8cf64 )
by
unknown
88:09 queued 81:00
created

Jetpack_Top_Posts_Widget::get_posts()   C

Complexity

Conditions 12
Paths 28

Size

Total Lines 68

Duplication

Lines 3
Ratio 4.41 %

Importance

Changes 0
Metric Value
cc 12
nc 28
nop 3
dl 3
loc 68
rs 6.2714
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
3
/*
4
 * Currently, this widget depends on the Stats Module. To not load this file
5
 * when the Stats Module is not active would potentially bypass Jetpack's
6
 * fatal error detection on module activation, so we always load this file.
7
 * Instead, we don't register the widget if the Stats Module isn't active.
8
 */
9
10
/**
11
 * Register the widget for use in Appearance -> Widgets
12
 */
13
add_action( 'widgets_init', 'jetpack_top_posts_widget_init' );
14
15
function jetpack_top_posts_widget_init() {
16
	// Currently, this widget depends on the Stats Module
17
	if (
18
		( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM )
19
	&&
20
		! function_exists( 'stats_get_from_restapi' )
21
	) {
22
		return;
23
	}
24
25
	register_widget( 'Jetpack_Top_Posts_Widget' );
26
}
27
28
class Jetpack_Top_Posts_Widget extends WP_Widget {
29
	public $alt_option_name = 'widget_stats_topposts';
30
	public $default_title   = '';
31
32
	function __construct() {
33
		parent::__construct(
34
			'top-posts',
35
			/** This filter is documented in modules/widgets/facebook-likebox.php */
36
			apply_filters( 'jetpack_widget_name', __( 'Top Posts &amp; Pages', 'jetpack' ) ),
37
			array(
38
				'description'                 => __( 'Shows your most viewed posts and pages.', 'jetpack' ),
39
				'customize_selective_refresh' => true,
40
			)
41
		);
42
43
		$this->default_title = __( 'Top Posts &amp; Pages', 'jetpack' );
44
45
		if ( is_active_widget( false, false, $this->id_base ) || is_customize_preview() ) {
46
			add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_style' ) );
47
		}
48
49
		/**
50
		 * Add explanation about how the statistics are calculated.
51
		 *
52
		 * @module widgets
53
		 *
54
		 * @since 3.9.3
55
		 */
56
		add_action( 'jetpack_widget_top_posts_after_fields', array( $this, 'stats_explanation' ) );
57
	}
58
59
	function enqueue_style() {
60
		wp_register_style( 'jetpack-top-posts-widget', plugins_url( 'top-posts/style.css', __FILE__ ), array(), '20141013' );
61
		wp_enqueue_style( 'jetpack-top-posts-widget' );
62
	}
63
64
	function form( $instance ) {
65
		$instance = wp_parse_args( (array) $instance, $this->defaults() );
66
67
		if ( false === $instance['title'] ) {
68
			$instance['title'] = $this->default_title;
69
		}
70
		$title = stripslashes( $instance['title'] );
71
72
		$count = isset( $instance['count'] ) ? (int) $instance['count'] : 10;
73
		if ( $count < 1 || 10 < $count ) {
74
			$count = 10;
75
		}
76
77
		$allowed_post_types = array_values( get_post_types( array( 'public' => true ) ) );
78
		$types              = isset( $instance['types'] ) ? (array) $instance['types'] : array( 'post', 'page' );
79
80
		// 'likes' are not available in Jetpack
81
		$ordering = isset( $instance['ordering'] ) && 'likes' === $instance['ordering'] ? 'likes' : 'views';
82
83 View Code Duplication
		if ( isset( $instance['display'] ) && in_array( $instance['display'], array( 'grid', 'list', 'text' ) ) ) {
84
			$display = $instance['display'];
85
		} else {
86
			$display = 'text';
87
		}
88
89
		?>
90
91
		<p>
92
			<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php esc_html_e( 'Title:', 'jetpack' ); ?></label>
93
			<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
94
		</p>
95
96
		<p>
97
			<label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php esc_html_e( 'Maximum number of posts to show (no more than 10):', 'jetpack' ); ?></label>
98
			<input id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>" type="number" value="<?php echo (int) $count; ?>" min="1" max="10" />
99
		</p>
100
101
		<?php if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) : ?>
102
		<p>
103
			<label><?php esc_html_e( 'Order Top Posts &amp; Pages By:', 'jetpack' ); ?></label>
104
			<ul>
105
				<li><label><input id="<?php echo $this->get_field_id( 'ordering' ); ?>-likes" name="<?php echo $this->get_field_name( 'ordering' ); ?>" type="radio" value="likes" <?php checked( 'likes', $ordering ); ?> /> <?php esc_html_e( 'Likes', 'jetpack' ); ?></label></li>
106
				<li><label><input id="<?php echo $this->get_field_id( 'ordering' ); ?>-views" name="<?php echo $this->get_field_name( 'ordering' ); ?>" type="radio" value="views" <?php checked( 'views', $ordering ); ?> /> <?php esc_html_e( 'Views', 'jetpack' ); ?></label></li>
107
			</ul>
108
		</p>
109
		<?php endif; ?>
110
111
		<p>
112
			<label for="<?php echo $this->get_field_id( 'types' ); ?>"><?php esc_html_e( 'Types of pages to display:', 'jetpack' ); ?></label>
113
			<ul>
114
				<?php
115
				foreach ( $allowed_post_types as $type ) {
116
					// Get the Post Type name to display next to the checkbox
117
					$post_type_object = get_post_type_object( $type );
118
					$label            = $post_type_object->labels->name;
119
120
					$checked = '';
121
					if ( in_array( $type, $types ) ) {
122
						$checked = 'checked="checked" ';
123
					}
124
					?>
125
126
					<li><label>
127
						<input value="<?php echo esc_attr( $type ); ?>" name="<?php echo $this->get_field_name( 'types' ); ?>[]" id="<?php echo $this->get_field_id( 'types' ); ?>-<?php echo $type; ?>" type="checkbox" <?php echo $checked; ?>>
128
						<?php echo esc_html( $label ); ?>
129
					</label></li>
130
131
				<?php } // End foreach ?>
132
			</ul>
133
		</p>
134
135
		<p>
136
			<label><?php esc_html_e( 'Display as:', 'jetpack' ); ?></label>
137
			<ul>
138
				<li><label><input id="<?php echo $this->get_field_id( 'display' ); ?>-text" name="<?php echo $this->get_field_name( 'display' ); ?>" type="radio" value="text" <?php checked( 'text', $display ); ?> /> <?php esc_html_e( 'Text List', 'jetpack' ); ?></label></li>
139
				<li><label><input id="<?php echo $this->get_field_id( 'display' ); ?>-list" name="<?php echo $this->get_field_name( 'display' ); ?>" type="radio" value="list" <?php checked( 'list', $display ); ?> /> <?php esc_html_e( 'Image List', 'jetpack' ); ?></label></li>
140
				<li><label><input id="<?php echo $this->get_field_id( 'display' ); ?>-grid" name="<?php echo $this->get_field_name( 'display' ); ?>" type="radio" value="grid" <?php checked( 'grid', $display ); ?> /> <?php esc_html_e( 'Image Grid', 'jetpack' ); ?></label></li>
141
			</ul>
142
		</p>
143
		<?php
144
145
		/**
146
		 * Fires after the fields are displayed in the Top Posts Widget settings in wp-admin.
147
		 *
148
		 * Allow adding extra content after the fields are displayed.
149
		 *
150
		 * @module widgets
151
		 *
152
		 * @since 3.9.3
153
		 *
154
		 * @param array $args {
155
		 *     @param array $instance The widget instance.
156
		 *     @param object $this The class object.
157
		 * }
158
		 */
159
		do_action( 'jetpack_widget_top_posts_after_fields', array( $instance, $this ) );
160
	}
161
162
	/**
163
	 * Explains how the statics are calculated.
164
	 */
165
	function stats_explanation() {
166
		?>
167
168
		<p><?php esc_html_e( 'Top Posts &amp; Pages by views are calculated from 24-48 hours of stats. They take a while to change.', 'jetpack' ); ?></p>
169
								<?php
170
	}
171
172
	function update( $new_instance, $old_instance ) {
173
		$instance          = array();
174
		$instance['title'] = wp_kses( $new_instance['title'], array() );
175
		if ( $instance['title'] === $this->default_title ) {
176
			$instance['title'] = false; // Store as false in case of language change
177
		}
178
179
		$instance['count'] = (int) $new_instance['count'];
180
		if ( $instance['count'] < 1 || 10 < $instance['count'] ) {
181
			$instance['count'] = 10;
182
		}
183
184
		// 'likes' are not available in Jetpack
185
		$instance['ordering'] = isset( $new_instance['ordering'] ) && 'likes' == $new_instance['ordering'] ? 'likes' : 'views';
186
187
		$allowed_post_types = array_values( get_post_types( array( 'public' => true ) ) );
188
		$instance['types']  = $new_instance['types'];
189
		foreach ( $new_instance['types'] as $key => $type ) {
190
			if ( ! in_array( $type, $allowed_post_types ) ) {
191
				unset( $new_instance['types'][ $key ] );
192
			}
193
		}
194
195 View Code Duplication
		if ( isset( $new_instance['display'] ) && in_array( $new_instance['display'], array( 'grid', 'list', 'text' ) ) ) {
196
			$instance['display'] = $new_instance['display'];
197
		} else {
198
			$instance['display'] = 'text';
199
		}
200
201
		/**
202
		 * Filters Top Posts Widget settings before they're saved.
203
		 *
204
		 * @module widgets
205
		 *
206
		 * @since 3.9.3
207
		 *
208
		 * @param array $instance The santized widget instance. Only contains data processed by the current widget.
209
		 * @param array $new_instance The new widget instance before sanitization.
210
		 */
211
		$instance = apply_filters( 'jetpack_top_posts_saving', $instance, $new_instance );
212
213
		return $instance;
214
	}
215
216
	function widget( $args, $instance ) {
217
		/** This action is documented in modules/widgets/gravatar-profile.php */
218
		do_action( 'jetpack_stats_extra', 'widget_view', 'top_posts' );
219
220
		$instance = wp_parse_args( (array) $instance, $this->defaults() );
221
222
		$title = isset( $instance['title'] ) ? $instance['title'] : false;
223
		if ( false === $title ) {
224
			$title = $this->default_title;
225
		}
226
		/** This filter is documented in core/src/wp-includes/default-widgets.php */
227
		$title = apply_filters( 'widget_title', $title );
228
229
		$count = isset( $instance['count'] ) ? (int) $instance['count'] : false;
230
		if ( $count < 1 || 10 < $count ) {
231
			$count = 10;
232
		}
233
		/**
234
		 * Control the number of displayed posts.
235
		 *
236
		 * @module widgets
237
		 *
238
		 * @since 3.3.0
239
		 *
240
		 * @param string $count Number of Posts displayed in the Top Posts widget. Default is 10.
241
		 */
242
		$count = apply_filters( 'jetpack_top_posts_widget_count', $count );
243
244
		$types = isset( $instance['types'] ) ? (array) $instance['types'] : array( 'post', 'page' );
245
246
		// 'likes' are not available in Jetpack
247
		$ordering = isset( $instance['ordering'] ) && 'likes' == $instance['ordering'] ? 'likes' : 'views';
248
249 View Code Duplication
		if ( isset( $instance['display'] ) && in_array( $instance['display'], array( 'grid', 'list', 'text' ) ) ) {
250
			$display = $instance['display'];
251
		} else {
252
			$display = 'text';
253
		}
254
255
		if ( 'text' != $display ) {
256
			$get_image_options = array(
257
				'fallback_to_avatars' => true,
258
				/** This filter is documented in modules/stats.php */
259
				'gravatar_default'    => apply_filters( 'jetpack_static_url', set_url_scheme( 'https://en.wordpress.com/i/logo/white-gray-80.png' ) ),
260
				'avatar_size'         => 40,
261
				'width'               => null,
262
				'height'              => null,
263
			);
264
			if ( 'grid' == $display ) {
265
				$get_image_options['avatar_size'] = 200;
266
			}
267
			/**
268
			 * Top Posts Widget Image options.
269
			 *
270
			 * @module widgets
271
			 *
272
			 * @since 1.8.0
273
			 *
274
			 * @param array $get_image_options {
275
			 * Array of Image options.
276
			 * @type bool true Should we default to Gravatars when no image is found? Default is true.
277
			 * @type string $gravatar_default Default Image URL if no Gravatar is found.
278
			 * @type int $avatar_size Default Image size.
279
			 * @type mixed $width Image width, not set by default and $avatar_size is used instead.
280
			 * @type mixed $height Image height, not set by default and $avatar_size is used instead.
281
			 * }
282
			 */
283
			$get_image_options = apply_filters( 'jetpack_top_posts_widget_image_options', $get_image_options );
284
		}
285
286
		if ( function_exists( 'wpl_get_blogs_most_liked_posts' ) && 'likes' == $ordering ) {
287
			$posts = $this->get_by_likes( $count, $types );
288
		} else {
289
			$posts = $this->get_by_views( $count, $args, $types );
290
		}
291
292
		if ( ! $posts ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $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...
293
			$posts = $this->get_fallback_posts( $count, $types );
294
		}
295
296
		echo $args['before_widget'];
297
		if ( ! empty( $title ) ) {
298
			echo $args['before_title'] . $title . $args['after_title'];
299
		}
300
301
		if ( ! $posts ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $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...
302
			$link = 'https://jetpack.com/support/getting-more-views-and-traffic/';
303
			if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
304
				$link = 'https://en.support.wordpress.com/getting-more-site-traffic/';
305
			}
306
307
			if ( current_user_can( 'edit_theme_options' ) ) {
308
				echo '<p>' . sprintf(
309
					__( 'There are no posts to display. <a href="%s" target="_blank">Want more traffic?</a>', 'jetpack' ),
310
					esc_url( $link )
311
				) . '</p>';
312
			}
313
314
			echo $args['after_widget'];
315
			return;
316
		}
317
318
		/**
319
		 * Filter the layout of the Top Posts Widget
320
		 *
321
		 * @module widgets
322
		 *
323
		 * @since 6.4.0
324
		 *
325
		 * @param string $layout layout of the Top Posts Widget (empty string)
326
		 * @param array $posts IDs of the posts to be displayed
327
		 * @param array $display Display option from widget form
328
		 */
329
		$layout = apply_filters( 'jetpack_top_posts_widget_layout', '', $posts, $display );
330
		if ( ! empty( $layout ) ) {
331
			echo $layout;
332
			echo $args['after_widget'];
333
			return;
334
		}
335
336
		switch ( $display ) {
337
			case 'list':
338
			case 'grid':
339
				// Keep the avatar_size as default dimensions for backward compatibility.
340
				$width  = (int) $get_image_options['avatar_size'];
0 ignored issues
show
Bug introduced by
The variable $get_image_options 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...
341
				$height = (int) $get_image_options['avatar_size'];
342
343
				// Check if the user has changed the width.
344
				if ( ! empty( $get_image_options['width'] ) ) {
345
					$width = (int) $get_image_options['width'];
346
				}
347
348
				// Check if the user has changed the height.
349
				if ( ! empty( $get_image_options['height'] ) ) {
350
					$height = (int) $get_image_options['height'];
351
				}
352
353
				foreach ( $posts as &$post ) {
354
					$image         = Jetpack_PostImages::get_image(
355
						$post['post_id'],
356
						array(
357
							'fallback_to_avatars' => (bool) $get_image_options['fallback_to_avatars'],
358
							'width'               => (int) $width,
359
							'height'              => (int) $height,
360
							'avatar_size'         => (int) $get_image_options['avatar_size'],
361
						)
362
					);
363
					$post['image'] = $image['src'];
364
					if ( 'blavatar' != $image['from'] && 'gravatar' != $image['from'] ) {
365
						$post['image'] = jetpack_photon_url( $post['image'], array( 'resize' => "$width,$height" ) );
366
					}
367
				}
368
369
				unset( $post );
370
371
				if ( 'grid' == $display ) {
372
					echo "<div class='widgets-grid-layout no-grav'>\n";
373
					foreach ( $posts as $post ) :
374
					?>
375
					<div class="widget-grid-view-image">
376
						<?php
377
						/**
378
						 * Fires before each Top Post result, inside <li>.
379
						 *
380
						 * @module widgets
381
						 *
382
						 * @since 3.2.0
383
						 *
384
						 * @param string $post['post_id'] Post ID.
385
						 */
386
						do_action( 'jetpack_widget_top_posts_before_post', $post['post_id'] );
387
388
						/**
389
						 * Filter the permalink of items in the Top Posts widget.
390
						 *
391
						 * @module widgets
392
						 *
393
						 * @since 4.4.0
394
						 *
395
						 * @param string $post['permalink'] Post permalink.
396
						 * @param array  $post              Post array.
397
						 */
398
						$filtered_permalink = apply_filters( 'jetpack_top_posts_widget_permalink', $post['permalink'], $post );
399
400
						printf(
401
							'<a href="%1$s" title="%2$s" class="bump-view" data-bump-view="tp"%3$s><img width="%4$d" height="%5$d" src="%6$s" alt="%2$s" data-pin-nopin="true"/></a>',
402
							esc_url( $filtered_permalink ),
403
							esc_attr( wp_kses( $post['title'], array() ) ),
404
							( get_queried_object_id() === $post['post_id'] ? ' aria-current="page"' : '' ),
405
							absint( $width ),
406
							absint( $height ),
407
							esc_url( $post['image'] )
408
						);
409
410
						/**
411
						 * Fires after each Top Post result, inside <li>.
412
						 *
413
						 * @module widgets
414
						 *
415
						 * @since 3.2.0
416
						 *
417
						 * @param string $post['post_id'] Post ID.
418
						 */
419
						do_action( 'jetpack_widget_top_posts_after_post', $post['post_id'] );
420
						?>
421
						</div>
422
					<?php
423
					endforeach;
424
					echo "</div>\n";
425
				} else {
426
					echo "<ul class='widgets-list-layout no-grav'>\n";
427
					foreach ( $posts as $post ) :
428
					?>
429
					<li>
430
						<?php
431
						/** This action is documented in modules/widgets/top-posts.php */
432
						do_action( 'jetpack_widget_top_posts_before_post', $post['post_id'] );
433
434
						/** This filter is documented in modules/widgets/top-posts.php */
435
						$filtered_permalink = apply_filters( 'jetpack_top_posts_widget_permalink', $post['permalink'], $post );
436
437
						printf(
438
							'<a href="%1$s" title="%2$s" class="bump-view" data-bump-view="tp"%3$s>
439
								<img width="%4$d" height="%5$d" src="%6$s" alt="%2$s" data-pin-nopin="true" class="widgets-list-layout-blavatar"/>
440
							</a>
441
							<div class="widgets-list-layout-links">
442
								<a href="%1$s" title="%2$s" class="bump-view" data-bump-view="tp"%3$s>%7$s</a>
443
							</div>
444
							',
445
							esc_url( $filtered_permalink ),
446
							esc_attr( wp_kses( $post['title'], array() ) ),
447
							( get_queried_object_id() === $post['post_id'] ? ' aria-current="page"' : '' ),
448
							absint( $width ),
449
							absint( $height ),
450
							esc_url( $post['image'] ),
451
							esc_html( wp_kses( $post['title'], array() ) )
452
						);
453
454
						/** This action is documented in modules/widgets/top-posts.php */
455
						do_action( 'jetpack_widget_top_posts_after_post', $post['post_id'] );
456
						?>
457
						</li>
458
					<?php
459
					endforeach;
460
					echo "</ul>\n";
461
				}
462
				break;
463
			default:
464
				echo '<ul>';
465
				foreach ( $posts as $post ) :
466
				?>
467
				<li>
468
					<?php
469
					/** This action is documented in modules/widgets/top-posts.php */
470
					do_action( 'jetpack_widget_top_posts_before_post', $post['post_id'] );
471
472
					/** This filter is documented in modules/widgets/top-posts.php */
473
					$filtered_permalink = apply_filters( 'jetpack_top_posts_widget_permalink', $post['permalink'], $post );
474
475
					printf(
476
						'<a href="%1$s" class="bump-view" data-bump-view="tp"%2$s>%3$s</a>',
477
						esc_url( $filtered_permalink ),
478
						( get_queried_object_id() === $post['post_id'] ? ' aria-current="page"' : '' ),
479
						esc_html( wp_kses( $post['title'], array() ) )
480
					);
481
482
					/** This action is documented in modules/widgets/top-posts.php */
483
					do_action( 'jetpack_widget_top_posts_after_post', $post['post_id'] );
484
					?>
485
					</li>
486
				<?php
487
				endforeach;
488
				echo '</ul>';
489
		}
490
491
		echo $args['after_widget'];
492
	}
493
494
	public static function defaults() {
495
		return array(
496
			'title'    => esc_html__( 'Top Posts &amp; Pages', 'jetpack' ),
497
			'count'    => absint( 10 ),
498
			'types'    => array( 'post', 'page' ),
499
			'ordering' => 'views',
500
			'display'  => 'text',
501
		);
502
	}
503
504
	/**
505
	 * Get most liked posts
506
	 *
507
	 * ONLY TO BE USED IN WPCOM
508
	 *
509
	 * @since 8.4.0 Added $types param
510
	 *
511
	 * @param int   $count The maximum number of posts to be returned.
512
	 * @param array $types The post types that should be returned. Optional. Defaults to 'post' and 'page'.
513
	 *
514
	 * @return array array of posts.
515
	 */
516
	public function get_by_likes( $count, $types = array( 'post', 'page' ) ) {
517
		$post_likes = wpl_get_blogs_most_liked_posts();
518
		if ( ! $post_likes ) {
519
			return array();
520
		}
521
522
		return $this->get_posts( array_keys( $post_likes ), $count, $types );
523
	}
524
525
	/**
526
	 * Get the top posts based on views
527
	 *
528
	 * @param int   $count The maximum number of posts to be returned.
529
	 * @param array $args The widget arguments.
530
	 * @param array $types The post types that should be returned.
531
	 * @return array array of posts.
532
	 */
533
	public function get_by_views( $count, $args, $types ) {
534
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
535
			global $wpdb;
536
537
			$post_views = wp_cache_get( "get_top_posts_$count", 'stats' );
538
			if ( false === $post_views ) {
539
				$post_views = array_shift( stats_get_daily_history( false, get_current_blog_id(), 'postviews', 'post_id', false, 2, '', $count * 2 + 10, true ) );
0 ignored issues
show
Bug introduced by
stats_get_daily_history(... $count * 2 + 10, true) cannot be passed to array_shift() as the parameter $array expects a reference.
Loading history...
540
				unset( $post_views[0] );
541
				wp_cache_add( "get_top_posts_$count", $post_views, 'stats', 1200 );
542
			}
543
544
			return $this->get_posts( array_keys( $post_views ), $count, $types );
545
		}
546
547
		/**
548
		 * Filter the number of days used to calculate Top Posts for the Top Posts widget.
549
		 * We do not recommend accessing more than 10 days of results at one.
550
		 * When more than 10 days of results are accessed at once, results should be cached via the WordPress transients API.
551
		 * Querying for -1 days will give results for an infinite number of days.
552
		 *
553
		 * @module widgets
554
		 *
555
		 * @since 3.9.3
556
		 *
557
		 * @param int 2 Number of days. Default is 2.
558
		 * @param array $args The widget arguments.
559
		 */
560
		$days = (int) apply_filters( 'jetpack_top_posts_days', 2, $args );
561
562
		/** Handling situations where the number of days makes no sense - allows for unlimited days where $days = -1 */
563
		if ( 0 == $days || false == $days ) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $days of type integer to the boolean false. If you are specifically checking for 0, consider using something more explicit like === 0 instead.
Loading history...
564
			$days = 2;
565
		}
566
567
		$post_view_posts = stats_get_from_restapi( array(), 'top-posts?max=11&summarize=1&num=' . intval( $days ) );
568
569
		if ( ! isset( $post_view_posts->summary ) || empty( $post_view_posts->summary->postviews ) ) {
570
			return array();
571
		}
572
573
		$post_view_ids = array_filter( wp_list_pluck( $post_view_posts->summary->postviews, 'id' ) );
574
575
		if ( ! $post_view_ids ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $post_view_ids 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...
576
			return array();
577
		}
578
579
		return $this->get_posts( $post_view_ids, $count, $types );
580
	}
581
582
	/**
583
	 * Get some posts if no posts are found in the stats API
584
	 *
585
	 * @since 8.4.0 Added $count and $types
586
	 *
587
	 * @param int   $count The maximum number of posts to be returned.
588
	 * @param array $types The post types that should be returned.
589
	 * @return array
590
	 */
591
	public function get_fallback_posts( $count = 10, $types = array( 'post', 'page' ) ) {
592
		if ( current_user_can( 'edit_theme_options' ) ) {
593
			return array();
594
		}
595
596
		$post_query = new WP_Query();
597
598
		if ( ! is_array( $types ) || empty( $types ) ) {
599
			$types = array( 'post', 'page' );
600
		}
601
602
		$posts = $post_query->query(
603
			array(
604
				'posts_per_page' => $count,
605
				'post_status'    => 'publish',
606
				'post_type'      => $types,
607
				'no_found_rows'  => true,
608
				'fields'         => 'ids',
609
			)
610
		);
611
612
		if ( ! $posts ) {
613
			return array();
614
		}
615
616
		return $this->get_posts( $posts, $count, $types );
617
	}
618
619
	/**
620
	 * Get posts from an array of IDs
621
	 *
622
	 * @since 8.4.0 Added $types parameters
623
	 *
624
	 * @param array $post_ids The post IDs.
625
	 * @param int   $count The maximum number of posts to return.
626
	 * @param array $types The post types that should be returned. Optional. Defaults to 'post', 'page'.
627
	 * @return array
628
	 */
629
	public function get_posts( $post_ids, $count, $types = array( 'post', 'page' ) ) {
630
		$counter = 0;
631
632
		if ( ! is_array( $types ) || empty( $types ) ) {
633
			$types = array( 'post', 'page' );
634
		}
635
636
		$posts = array();
637
		foreach ( (array) $post_ids as $post_id ) {
638
			$post = get_post( $post_id );
639
640
			if ( ! $post ) {
641
				continue;
642
			}
643
644
			/**
645
			 * Attachment pages use the 'inherit' post status by default.
646
			 * To be able to remove attachment pages from private and password protect posts,
647
			 * we need to replace their post status by the parent post' status.
648
			 */
649 View Code Duplication
			if ( 'inherit' == $post->post_status && 'attachment' == $post->post_type ) {
650
				$post->post_status = get_post_status( $post_id );
651
			}
652
653
			// hide private and password protected posts
654
			if ( 'publish' != $post->post_status || ! empty( $post->post_password ) ) {
655
				continue;
656
			}
657
658
			// Filter by chosen Post Types.
659
			if ( ! in_array( $post->post_type, $types, true ) ) {
660
				continue;
661
			}
662
663
			// Both get HTML stripped etc on display
664
			if ( empty( $post->post_title ) ) {
665
				$title_source = $post->post_content;
666
				$title        = wp_html_excerpt( $title_source, 50 );
667
				$title       .= '&hellip;';
668
			} else {
669
				$title = $post->post_title;
670
			}
671
672
			$permalink = get_permalink( $post->ID );
673
674
			$post_type = $post->post_type;
675
676
			$posts[] = compact( 'title', 'permalink', 'post_id', 'post_type' );
677
			$counter++;
678
679
			if ( $counter == $count ) {
680
				break; // only need to load and show x number of likes
681
			}
682
		}
683
684
		/**
685
		 * Filter the Top Posts and Pages.
686
		 *
687
		 * @module widgets
688
		 *
689
		 * @since 3.0.0
690
		 *
691
		 * @param array $posts Array of the most popular posts.
692
		 * @param array $post_ids Array of Post IDs.
693
		 * @param string $count Number of Top Posts we want to display.
694
		 */
695
		return apply_filters( 'jetpack_widget_get_top_posts', $posts, $post_ids, $count );
696
	}
697
}
698
699
/**
700
 * Create a shortcode to display the widget anywhere.
701
 *
702
 * @since 3.9.2
703
 */
704
function jetpack_do_top_posts_widget( $instance ) {
705
	// Post Types can't be entered as an array in the shortcode parameters.
706
	if ( isset( $instance['types'] ) && is_array( $instance['types'] ) ) {
707
		$instance['types'] = implode( ',', $instance['types'] );
708
	}
709
710
	$instance = shortcode_atts(
711
		Jetpack_Top_Posts_Widget::defaults(),
712
		$instance,
713
		'jetpack_top_posts_widget'
714
	);
715
716
	// Add a class to allow styling
717
	$args = array(
718
		'before_widget' => sprintf( '<div class="%s">', 'jetpack_top_posts_widget' ),
719
	);
720
721
	ob_start();
722
	the_widget( 'Jetpack_Top_Posts_Widget', $instance, $args );
723
	$output = ob_get_clean();
724
725
	return $output;
726
}
727
add_shortcode( 'jetpack_top_posts_widget', 'jetpack_do_top_posts_widget' );
728