Completed
Push — master-stable ( 2b1ae0...26d031 )
by
unknown
08:17
created

Jetpack_Top_Posts_Widget::get_posts()   C

Complexity

Conditions 9
Paths 12

Size

Total Lines 59
Code Lines 24

Duplication

Lines 3
Ratio 5.08 %

Importance

Changes 0
Metric Value
cc 9
eloc 24
nc 12
nop 2
dl 3
loc 59
rs 6.9133
c 0
b 0
f 0

How to fix   Long Method   

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 View Code Duplication
		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
		$title = stripslashes( $instance['title'] );
68
69
		$count = isset( $instance['count'] ) ? (int) $instance['count'] : 10;
70
		if ( $count < 1 || 10 < $count ) {
71
			$count = 10;
72
		}
73
74
		$allowed_post_types = array_values( get_post_types( array( 'public' => true ) ) );
75
		$types = isset( $instance['types'] ) ? (array) $instance['types'] : array( 'post', 'page' );
76
77
		// 'likes' are not available in Jetpack
78
		$ordering = isset( $instance['ordering'] ) && 'likes' === $instance['ordering'] ? 'likes' : 'views';
79
80 View Code Duplication
		if ( isset( $instance['display'] ) && in_array( $instance['display'], array( 'grid', 'list', 'text'  ) ) ) {
81
			$display = $instance['display'];
82
		} else {
83
			$display = 'text';
84
		}
85
86
		?>
87
88
		<p>
89
			<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php esc_html_e( 'Title:', 'jetpack' ); ?></label>
90
			<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 ); ?>" />
91
		</p>
92
93
		<p>
94
			<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>
95
			<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" />
96
		</p>
97
98
		<?php if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) : ?>
99
		<p>
100
			<label><?php esc_html_e( 'Order Top Posts &amp; Pages By:', 'jetpack' ); ?></label>
101
			<ul>
102
				<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>
103
				<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>
104
			</ul>
105
		</p>
106
		<?php endif; ?>
107
108
		<p>
109
			<label for="<?php echo $this->get_field_id( 'types' ); ?>"><?php esc_html_e( 'Types of pages to display:', 'jetpack' ); ?></label>
110
			<ul>
111
				<?php foreach( $allowed_post_types as $type ) {
112
					// Get the Post Type name to display next to the checkbox
113
					$post_type_object = get_post_type_object( $type );
114
					$label = $post_type_object->labels->name;
115
116
					$checked = '';
117
					if ( in_array( $type, $types ) ) {
118
						$checked = 'checked="checked" ';
119
					} ?>
120
121
					<li><label>
122
						<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; ?>>
123
						<?php echo esc_html( $label ); ?>
124
					</label></li>
125
126
				<?php } // End foreach ?>
127
			</ul>
128
		</p>
129
130
		<p>
131
			<label><?php esc_html_e( 'Display as:', 'jetpack' ); ?></label>
132
			<ul>
133
				<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>
134
				<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>
135
				<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>
136
			</ul>
137
		</p><?php
138
139
		/**
140
		 * Fires after the fields are displayed in the Top Posts Widget settings in wp-admin.
141
		 *
142
		 * Allow adding extra content after the fields are displayed.
143
		 *
144
		 * @module widgets
145
		 *
146
		 * @since 3.9.3
147
		 *
148
		 * @param array $args {
149
		 *     @param array $instance The widget instance.
150
		 *     @param object $this The class object.
151
		 * }
152
		 */
153
		do_action( 'jetpack_widget_top_posts_after_fields', array( $instance, $this ) );
154
	}
155
156
	/**
157
	 * Explains how the statics are calculated.
158
	 */
159
	function stats_explanation() {
160
		?>
161
162
		<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><?php
163
	}
164
165
	function update( $new_instance, $old_instance ) {
166
		$instance = array();
167
		$instance['title'] = wp_kses( $new_instance['title'], array() );
168
		if ( $instance['title'] === $this->default_title ) {
169
			$instance['title'] = false; // Store as false in case of language change
170
		}
171
172
		$instance['count'] = (int) $new_instance['count'];
173
		if ( $instance['count'] < 1 || 10 < $instance['count'] ) {
174
			$instance['count'] = 10;
175
		}
176
177
		// 'likes' are not available in Jetpack
178
		$instance['ordering'] = isset( $new_instance['ordering'] ) && 'likes' == $new_instance['ordering'] ? 'likes' : 'views';
179
180
		$allowed_post_types = array_values( get_post_types( array( 'public' => true ) ) );
181
		$instance['types'] = $new_instance['types'];
182
		foreach( $new_instance['types'] as $key => $type ) {
183
			if ( ! in_array( $type, $allowed_post_types ) ) {
184
				unset( $new_instance['types'][ $key ] );
185
			}
186
		}
187
188 View Code Duplication
		if ( isset( $new_instance['display'] ) && in_array( $new_instance['display'], array( 'grid', 'list', 'text'  ) ) ) {
189
			$instance['display'] = $new_instance['display'];
190
		} else {
191
			$instance['display'] = 'text';
192
		}
193
194
		/**
195
		 * Filters Top Posts Widget settings before they're saved.
196
		 *
197
		 * @module widgets
198
		 *
199
		 * @since 3.9.3
200
		 *
201
		 * @param array $instance The santized widget instance. Only contains data processed by the current widget.
202
		 * @param array $new_instance The new widget instance before sanitization.
203
		 */
204
		$instance = apply_filters( 'jetpack_top_posts_saving', $instance, $new_instance );
205
206
		return $instance;
207
	}
208
209
	function widget( $args, $instance ) {
210
		/** This action is documented in modules/widgets/gravatar-profile.php */
211
		do_action( 'jetpack_stats_extra', 'widget_view', 'top_posts' );
212
213
		$instance = wp_parse_args( (array) $instance, $this->defaults() );
214
215
		$title = isset( $instance['title' ] ) ? $instance['title'] : false;
216
		if ( false === $title ) {
217
			$title = $this->default_title;
218
		}
219
		/** This filter is documented in core/src/wp-includes/default-widgets.php */
220
		$title = apply_filters( 'widget_title', $title );
221
222
		$count = isset( $instance['count'] ) ? (int) $instance['count'] : false;
223
		if ( $count < 1 || 10 < $count ) {
224
			$count = 10;
225
		}
226
		/**
227
		 * Control the number of displayed posts.
228
		 *
229
		 * @module widgets
230
		 *
231
		 * @since 3.3.0
232
		 *
233
		 * @param string $count Number of Posts displayed in the Top Posts widget. Default is 10.
234
		 */
235
		$count = apply_filters( 'jetpack_top_posts_widget_count', $count );
236
237
		$types = isset( $instance['types'] ) ? (array) $instance['types'] : array( 'post', 'page' );
238
239
		// 'likes' are not available in Jetpack
240
		$ordering = isset( $instance['ordering'] ) && 'likes' == $instance['ordering'] ? 'likes' : 'views';
241
242 View Code Duplication
		if ( isset( $instance['display'] ) && in_array( $instance['display'], array( 'grid', 'list', 'text'  ) ) ) {
243
			$display = $instance['display'];
244
		} else {
245
			$display = 'text';
246
		}
247
248
		if ( 'text' != $display ) {
249
			$get_image_options = array(
250
				'fallback_to_avatars' => true,
251
				/** This filter is documented in modules/stats.php */
252
				'gravatar_default' => apply_filters( 'jetpack_static_url', set_url_scheme( 'https://en.wordpress.com/i/logo/white-gray-80.png' ) ),
253
				'avatar_size' => 40,
254
				'width' => null,
255
				'height' => null,
256
			);
257
			if ( 'grid' == $display ) {
258
				$get_image_options['avatar_size'] = 200;
259
			}
260
			/**
261
			 * Top Posts Widget Image options.
262
			 *
263
			 * @module widgets
264
			 *
265
			 * @since 1.8.0
266
			 *
267
			 * @param array $get_image_options {
268
			 * Array of Image options.
269
			 * @type bool true Should we default to Gravatars when no image is found? Default is true.
270
			 * @type string $gravatar_default Default Image URL if no Gravatar is found.
271
			 * @type int $avatar_size Default Image size.
272
			 * @type mixed $width Image width, not set by default and $avatar_size is used instead.
273
			 * @type mixed $height Image height, not set by default and $avatar_size is used instead.
274
			 * }
275
			 */
276
			$get_image_options = apply_filters( 'jetpack_top_posts_widget_image_options', $get_image_options );
277
		}
278
279
		if ( function_exists( 'wpl_get_blogs_most_liked_posts' ) && 'likes' == $ordering ) {
280
			$posts = $this->get_by_likes( $count );
281
		} else {
282
			$posts = $this->get_by_views( $count, $args );
283
		}
284
285
		// Filter the returned posts. Remove all posts that do not match the chosen Post Types.
286
		if ( isset( $types ) ) {
287
			foreach ( $posts as $k => $post ) {
288
				if ( ! in_array( $post['post_type'], $types ) ) {
289
					unset( $posts[$k] );
290
				}
291
			}
292
		}
293
294
		if ( ! $posts ) {
295
			$posts = $this->get_fallback_posts();
296
		}
297
298
		echo $args['before_widget'];
299
		if ( ! empty( $title ) )
300
			echo $args['before_title'] . $title . $args['after_title'];
301
302
		if ( ! $posts ) {
303 View Code Duplication
			if ( current_user_can( 'edit_theme_options' ) ) {
304
				echo '<p>' . sprintf(
305
					__( 'There are no posts to display. <a href="%s" target="_blank">Want more traffic?</a>', 'jetpack' ),
306
					'https://jetpack.com/support/getting-more-views-and-traffic/'
307
				) . '</p>';
308
			}
309
310
			echo $args['after_widget'];
311
			return;
312
		}
313
314
		switch ( $display ) {
315
		case 'list' :
316
		case 'grid' :
317
			// Keep the avatar_size as default dimensions for backward compatibility.
318
			$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...
319
			$height = (int) $get_image_options['avatar_size'];
320
321
			// Check if the user has changed the width.
322
			if ( ! empty( $get_image_options['width'] ) ) {
323
				$width  = (int) $get_image_options['width'];
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 2 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
324
			}
325
326
			// Check if the user has changed the height.
327
			if ( ! empty( $get_image_options['height'] ) ) {
328
				$height = (int) $get_image_options['height'];
329
			}
330
331
			foreach ( $posts as &$post ) {
332
				$image = Jetpack_PostImages::get_image(
333
					$post['post_id'],
334
					array(
335
						'fallback_to_avatars' => true,
336
						'avatar_size'         => (int) $get_image_options['avatar_size'],
337
					)
338
				);
339
				$post['image'] = $image['src'];
340
				if ( 'blavatar' != $image['from'] && 'gravatar' != $image['from'] ) {
341
					$post['image'] = jetpack_photon_url( $post['image'], array( 'resize' => "$width,$height" ) );
342
				}
343
			}
344
345
			unset( $post );
346
347
			if ( 'grid' == $display ) {
348
				echo "<div class='widgets-grid-layout no-grav'>\n";
349
				foreach ( $posts as $post ) :
350
				?>
351
					<div class="widget-grid-view-image">
352
						<?php
353
						/**
354
						 * Fires before each Top Post result, inside <li>.
355
						 *
356
						 * @module widgets
357
						 *
358
						 * @since 3.2.0
359
						 *
360
						 * @param string $post['post_id'] Post ID.
361
						 */
362
						do_action( 'jetpack_widget_top_posts_before_post', $post['post_id'] );
363
364
						/**
365
						 * Filter the permalink of items in the Top Posts widget.
366
						 *
367
						 * @module widgets
368
						 *
369
						 * @since 4.4.0
370
						 *
371
						 * @param string $post['permalink'] Post permalink.
372
						 * @param array  $post              Post array.
373
						 */
374
						$filtered_permalink = apply_filters( 'jetpack_top_posts_widget_permalink', $post['permalink'], $post );
375
376
						?>
377
						<a href="<?php echo esc_url( $filtered_permalink ); ?>" title="<?php echo esc_attr( wp_kses( $post['title'], array() ) ); ?>" class="bump-view" data-bump-view="tp">
378
							<img width="<?php echo absint( $width ); ?>" height="<?php echo absint( $height ); ?>" src="<?php echo esc_url( $post['image'] ); ?>" alt="<?php echo esc_attr( wp_kses( $post['title'], array() ) ); ?>" data-pin-nopin="true" />
379
						</a>
380
						<?php
381
						/**
382
						 * Fires after each Top Post result, inside <li>.
383
						 *
384
						 * @module widgets
385
						 *
386
						 * @since 3.2.0
387
						 *
388
						 * @param string $post['post_id'] Post ID.
389
						 */
390
						do_action( 'jetpack_widget_top_posts_after_post', $post['post_id'] );
391
						?>
392
					</div>
393
				<?php
394
				endforeach;
395
				echo "</div>\n";
396
			} else {
397
				echo "<ul class='widgets-list-layout no-grav'>\n";
398
				foreach ( $posts as $post ) :
399
				?>
400
					<li>
401
						<?php
402
						/** This action is documented in modules/widgets/top-posts.php */
403
						do_action( 'jetpack_widget_top_posts_before_post', $post['post_id'] );
404
405
						/** This filter is documented in modules/widgets/top-posts.php */
406
						$filtered_permalink = apply_filters( 'jetpack_top_posts_widget_permalink', $post['permalink'], $post );
407
						?>
408
						<a href="<?php echo esc_url( $filtered_permalink ); ?>" title="<?php echo esc_attr( wp_kses( $post['title'], array() ) ); ?>" class="bump-view" data-bump-view="tp">
409
							<img width="<?php echo absint( $width ); ?>" height="<?php echo absint( $height ); ?>" src="<?php echo esc_url( $post['image'] ); ?>" class='widgets-list-layout-blavatar' alt="<?php echo esc_attr( wp_kses( $post['title'], array() ) ); ?>" data-pin-nopin="true" />
410
						</a>
411
						<div class="widgets-list-layout-links">
412
							<a href="<?php echo esc_url( $filtered_permalink ); ?>" class="bump-view" data-bump-view="tp">
413
								<?php echo esc_html( wp_kses( $post['title'], array() ) ); ?>
414
							</a>
415
						</div>
416
						<?php
417
						/** This action is documented in modules/widgets/top-posts.php */
418
						do_action( 'jetpack_widget_top_posts_after_post', $post['post_id'] );
419
						?>
420
					</li>
421
				<?php
422
				endforeach;
423
				echo "</ul>\n";
424
			}
425
			break;
426
		default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
427
			echo '<ul>';
428
			foreach ( $posts as $post ) :
429
			?>
430
				<li>
431
					<?php
432
					/** This action is documented in modules/widgets/top-posts.php */
433
					do_action( 'jetpack_widget_top_posts_before_post', $post['post_id'] );
434
435
					/** This filter is documented in modules/widgets/top-posts.php */
436
					$filtered_permalink = apply_filters( 'jetpack_top_posts_widget_permalink', $post['permalink'], $post );
437
					?>
438
					<a href="<?php echo esc_url( $filtered_permalink ); ?>" class="bump-view" data-bump-view="tp">
439
						<?php echo esc_html( wp_kses( $post['title'], array() ) ); ?>
440
					</a>
441
					<?php
442
					/** This action is documented in modules/widgets/top-posts.php */
443
					do_action( 'jetpack_widget_top_posts_after_post', $post['post_id'] );
444
					?>
445
				</li>
446
			<?php
447
			endforeach;
448
			echo '</ul>';
449
		}
450
451
		echo $args['after_widget'];
452
	}
453
454
	public static function defaults() {
455
		return array(
456
			'title'    => esc_html__( 'Top Posts &amp; Pages', 'jetpack' ),
457
			'count'    => absint( 10 ),
458
			'types'    => array( 'post', 'page' ),
459
			'ordering' => 'views',
460
			'display'  => 'text',
461
		);
462
	}
463
464
	/*
465
	 * Get most liked posts
466
	 *
467
	 * ONLY TO BE USED IN WPCOM
468
	 */
469
	function get_by_likes( $count ) {
470
		$post_likes = wpl_get_blogs_most_liked_posts();
471
		if ( !$post_likes ) {
472
			return array();
473
		}
474
475
		return $this->get_posts( array_keys( $post_likes ), $count );
476
	}
477
478
	function get_by_views( $count, $args ) {
479
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
480
			global $wpdb;
481
482
			$post_views = wp_cache_get( "get_top_posts_$count", 'stats' );
483
			if ( false === $post_views ) {
484
				$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...
485
				unset( $post_views[0] );
486
				wp_cache_add( "get_top_posts_$count", $post_views, 'stats', 1200);
487
			}
488
489
			return $this->get_posts( array_keys( $post_views ), $count );
490
		}
491
492
		/**
493
		 * Filter the number of days used to calculate Top Posts for the Top Posts widget.
494
		 * We do not recommend accessing more than 10 days of results at one.
495
		 * When more than 10 days of results are accessed at once, results should be cached via the WordPress transients API.
496
		 * Querying for -1 days will give results for an infinite number of days.
497
		 *
498
		 * @module widgets
499
		 *
500
		 * @since 3.9.3
501
		 *
502
		 * @param int 2 Number of days. Default is 2.
503
		 * @param array $args The widget arguments.
504
		 */
505
		$days = (int) apply_filters( 'jetpack_top_posts_days', 2, $args );
506
507
		/** Handling situations where the number of days makes no sense - allows for unlimited days where $days = -1 */
508
		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...
509
			$days = 2;
510
		}
511
512
		$post_view_posts = stats_get_from_restapi( array(), 'top-posts?max=11&summarize=1&num=' . absint( $days ) );
513
514
		if ( ! isset( $post_view_posts->summary ) || empty( $post_view_posts->summary->postviews ) ) {
515
			return array();
516
		}
517
518
		$post_view_ids = array_filter( wp_list_pluck( $post_view_posts->summary->postviews, 'id' ) );
519
520
		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...
521
			return array();
522
		}
523
524
		return $this->get_posts( $post_view_ids, $count );
525
	}
526
527
	function get_fallback_posts() {
528
		if ( current_user_can( 'edit_theme_options' ) ) {
529
			return array();
530
		}
531
532
		$post_query = new WP_Query;
533
534
		$posts = $post_query->query( array(
535
			'posts_per_page' => 1,
536
			'post_status' => 'publish',
537
			'post_type' => array( 'post', 'page' ),
538
			'no_found_rows' => true,
539
		) );
540
541
		if ( ! $posts ) {
542
			return array();
543
		}
544
545
		$post = array_pop( $posts );
546
547
		return $this->get_posts( $post->ID, 1 );
548
	}
549
550
	function get_posts( $post_ids, $count ) {
551
		$counter = 0;
552
553
		$posts = array();
554
		foreach ( (array) $post_ids as $post_id ) {
555
			$post = get_post( $post_id );
556
557
			if ( ! $post ) {
558
				continue;
559
			}
560
561
			/**
562
			 * Attachment pages use the 'inherit' post status by default.
563
			 * To be able to remove attachment pages from private and password protect posts,
564
			 * we need to replace their post status by the parent post' status.
565
			 */
566 View Code Duplication
			if ( 'inherit' == $post->post_status && 'attachment' == $post->post_type ) {
567
				$post->post_status = get_post_status( $post_id );
568
			}
569
570
			// hide private and password protected posts
571
			if ( 'publish' != $post->post_status || ! empty( $post->post_password ) ) {
572
				continue;
573
			}
574
575
			// Both get HTML stripped etc on display
576
			if ( empty( $post->post_title ) ) {
577
				$title_source = $post->post_content;
578
				$title = wp_html_excerpt( $title_source, 50 );
579
				$title .= '&hellip;';
580
			} else {
581
				$title = $post->post_title;
582
			}
583
584
			$permalink = get_permalink( $post->ID );
585
586
			$post_type = $post->post_type;
587
588
			$posts[] = compact( 'title', 'permalink', 'post_id', 'post_type' );
589
			$counter++;
590
591
			if ( $counter == $count ) {
592
				break; // only need to load and show x number of likes
593
			}
594
		}
595
596
		/**
597
		 * Filter the Top Posts and Pages.
598
		 *
599
		 * @module widgets
600
		 *
601
		 * @since 3.0.0
602
		 *
603
		 * @param array $posts Array of the most popular posts.
604
		 * @param array $post_ids Array of Post IDs.
605
		 * @param string $count Number of Top Posts we want to display.
606
		 */
607
		return apply_filters( 'jetpack_widget_get_top_posts', $posts, $post_ids, $count );
608
	}
609
}
610
611
/**
612
 * Create a shortcode to display the widget anywhere.
613
 *
614
 * @since 3.9.2
615
 */
616
function jetpack_do_top_posts_widget( $instance ) {
617
	// Post Types can't be entered as an array in the shortcode parameters.
618
	if ( isset( $instance['types'] ) && is_array( $instance['types'] ) ) {
619
		$instance['types'] = implode( ',', $instance['types'] );
620
	}
621
622
	$instance = shortcode_atts(
623
		Jetpack_Top_Posts_Widget::defaults(),
624
		$instance,
625
		'jetpack_top_posts_widget'
626
	);
627
628
	// Add a class to allow styling
629
	$args = array(
630
		'before_widget' => sprintf( '<div class="%s">', 'jetpack_top_posts_widget' ),
631
	);
632
633
	ob_start();
634
	the_widget( 'Jetpack_Top_Posts_Widget', $instance, $args );
635
	$output = ob_get_clean();
636
637
	return $output;
638
}
639
add_shortcode( 'jetpack_top_posts_widget', 'jetpack_do_top_posts_widget' );
640