Completed
Push — update/stats-page-branded ( 06fef4 )
by
unknown
14:25
created

stats.php ➔ stats_reports_load()   C

Complexity

Conditions 8
Paths 12

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 15
nc 12
nop 0
dl 0
loc 25
rs 5.3846
c 0
b 0
f 0
1
<?php
2
/**
3
 * Module Name: Site Stats
4
 * Module Description: Collect valuable traffic stats and insights.
5
 * Sort Order: 1
6
 * Recommendation Order: 2
7
 * First Introduced: 1.1
8
 * Requires Connection: Yes
9
 * Auto Activate: Yes
10
 * Module Tags: Site Stats, Recommended
11
 * Feature: Engagement
12
 * Additional Search Queries: statistics, tracking, analytics, views, traffic, stats
13
 *
14
 * @package Jetpack
15
 */
16
17
if ( defined( 'STATS_VERSION' ) ) {
18
	return;
19
}
20
21
define( 'STATS_VERSION', '9' );
22
defined( 'STATS_DASHBOARD_SERVER' ) or define( 'STATS_DASHBOARD_SERVER', 'dashboard.wordpress.com' );
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
23
24
add_action( 'jetpack_modules_loaded', 'stats_load' );
25
26
/**
27
 * Load Stats.
28
 *
29
 * @access public
30
 * @return void
31
 */
32
function stats_load() {
33
	Jetpack::enable_module_configurable( __FILE__ );
34
	Jetpack::module_configuration_load( __FILE__, 'stats_configuration_load' );
35
	Jetpack::module_configuration_head( __FILE__, 'stats_configuration_head' );
36
	Jetpack::module_configuration_screen( __FILE__, 'stats_configuration_screen' );
37
38
	// Generate the tracking code after wp() has queried for posts.
39
	add_action( 'template_redirect', 'stats_template_redirect', 1 );
40
41
	add_action( 'wp_head', 'stats_admin_bar_head', 100 );
42
43
	add_action( 'wp_head', 'stats_hide_smile_css' );
44
45
	add_action( 'jetpack_admin_menu', 'stats_admin_menu' );
46
47
	// Map stats caps.
48
	add_filter( 'map_meta_cap', 'stats_map_meta_caps', 10, 3 );
49
50
	if ( isset( $_GET['oldwidget'] ) ) {
51
		// Old one.
52
		add_action( 'wp_dashboard_setup', 'stats_register_dashboard_widget' );
53
	} else {
54
		add_action( 'admin_init', 'stats_merged_widget_admin_init' );
55
	}
56
57
	add_filter( 'jetpack_xmlrpc_methods', 'stats_xmlrpc_methods' );
58
59
	add_filter( 'pre_option_db_version', 'stats_ignore_db_version' );
60
61
	// Add an icon to see stats in WordPress.com for a particular post
62
	add_action( 'admin_print_styles-edit.php', 'jetpack_stats_load_admin_css' );
63
	add_filter( 'manage_posts_columns', 'jetpack_stats_post_table' );
64
	add_filter( 'manage_pages_columns', 'jetpack_stats_post_table' );
65
	add_action( 'manage_posts_custom_column', 'jetpack_stats_post_table_cell', 10, 2 );
66
	add_action( 'manage_pages_custom_column', 'jetpack_stats_post_table_cell', 10, 2 );
67
}
68
69
/**
70
 * Delay conditional for current_user_can to after init.
71
 *
72
 * @access public
73
 * @return void
74
 */
75
function stats_merged_widget_admin_init() {
76
	if ( current_user_can( 'view_stats' ) ) {
77
		add_action( 'load-index.php', 'stats_enqueue_dashboard_head' );
78
		add_action( 'wp_dashboard_setup', 'stats_register_widget_control_callback' ); // Hacky but works.
79
		add_action( 'jetpack_dashboard_widget', 'stats_jetpack_dashboard_widget' );
80
	}
81
}
82
83
/**
84
 * Enqueue Stats Dashboard
85
 *
86
 * @access public
87
 * @return void
88
 */
89
function stats_enqueue_dashboard_head() {
90
	add_action( 'admin_head', 'stats_dashboard_head' );
91
}
92
93
/**
94
 * Checks if filter is set and dnt is enabled.
95
 *
96
 * @return bool
97
 */
98
function jetpack_is_dnt_enabled() {
99
	/**
100
	 * Filter the option which decides honor DNT or not.
101
	 *
102
	 * @module stats
103
	 * @since 6.1.0
104
	 *
105
	 * @param bool false If config honors DNT and client doesn't want to tracked, false if not.
106
	 */
107
	if ( false === apply_filters( 'jetpack_honor_dnt_header_for_stats', false ) ) {
108
		return false;
109
	}
110
111
	foreach ( $_SERVER as $name => $value ) {
112
		if ( 'http_dnt' == strtolower( $name ) && 1 == $value ) {
113
			return true;
114
		}
115
	}
116
117
	return false;
118
}
119
120
/**
121
 * Prevent sparkline img requests being redirected to upgrade.php.
122
 * See wp-admin/admin.php where it checks $wp_db_version.
123
 *
124
 * @access public
125
 * @param mixed $version Version.
126
 * @return string $version.
127
 */
128
function stats_ignore_db_version( $version ) {
129
	if (
130
		is_admin() &&
131
		isset( $_GET['page'] ) && 'stats' === $_GET['page'] &&
132
		isset( $_GET['chart'] ) && strpos($_GET['chart'], 'admin-bar-hours') === 0
133
	) {
134
		global $wp_db_version;
135
		return $wp_db_version;
136
	}
137
	return $version;
138
}
139
140
/**
141
 * Maps view_stats cap to read cap as needed.
142
 *
143
 * @access public
144
 * @param mixed $caps Caps.
145
 * @param mixed $cap Cap.
146
 * @param mixed $user_id User ID.
147
 * @return array Possibly mapped capabilities for meta capability.
148
 */
149
function stats_map_meta_caps( $caps, $cap, $user_id ) {
150
	// Map view_stats to exists.
151
	if ( 'view_stats' === $cap ) {
152
		$user        = new WP_User( $user_id );
153
		$user_role   = array_shift( $user->roles );
154
		$stats_roles = stats_get_option( 'roles' );
155
156
		// Is the users role in the available stats roles?
157
		if ( is_array( $stats_roles ) && in_array( $user_role, $stats_roles ) ) {
158
			$caps = array( 'read' );
159
		}
160
	}
161
162
	return $caps;
163
}
164
165
/**
166
 * Stats Template Redirect.
167
 *
168
 * @access public
169
 * @return void
170
 */
171
function stats_template_redirect() {
172
	global $current_user, $stats_footer;
173
174
	if ( is_feed() || is_robots() || is_trackback() || is_preview() || jetpack_is_dnt_enabled() ) {
175
		return;
176
	}
177
178
	// Should we be counting this user's views?
179
	if ( ! empty( $current_user->ID ) ) {
180
		$count_roles = stats_get_option( 'count_roles' );
181
		if ( ! is_array( $count_roles ) || ! array_intersect( $current_user->roles, $count_roles ) ) {
182
			return;
183
		}
184
	}
185
186
	add_action( 'wp_footer', 'stats_footer', 101 );
187
	add_action( 'wp_head', 'stats_add_shutdown_action' );
188
189
	$script = 'https://stats.wp.com/e-' . gmdate( 'YW' ) . '.js';
190
	$data = stats_build_view_data();
191
	$data_stats_array = stats_array( $data );
192
193
	$stats_footer = <<<END
194
<script type='text/javascript' src='{$script}' async='async' defer='defer'></script>
195
<script type='text/javascript'>
196
	_stq = window._stq || [];
197
	_stq.push([ 'view', {{$data_stats_array}} ]);
198
	_stq.push([ 'clickTrackerInit', '{$data['blog']}', '{$data['post']}' ]);
199
</script>
200
201
END;
202
}
203
204
205
/**
206
 * Stats Build View Data.
207
 *
208
 * @access public
209
 * @return array.
0 ignored issues
show
Documentation introduced by
The doc-type array. could not be parsed: Unknown type name "array." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
210
 */
211
function stats_build_view_data() {
212
	global $wp_the_query;
213
214
	$blog = Jetpack_Options::get_option( 'id' );
215
	$tz = get_option( 'gmt_offset' );
216
	$v = 'ext';
217
	$blog_url = parse_url( site_url() );
218
	$srv = $blog_url['host'];
219
	$j = sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION );
220
	if ( $wp_the_query->is_single || $wp_the_query->is_page || $wp_the_query->is_posts_page ) {
221
		// Store and reset the queried_object and queried_object_id
222
		// Otherwise, redirect_canonical() will redirect to home_url( '/' ) for show_on_front = page sites where home_url() is not all lowercase.
223
		// Repro:
224
		// 1. Set home_url = https://ExamPle.com/
225
		// 2. Set show_on_front = page
226
		// 3. Set page_on_front = something
227
		// 4. Visit https://example.com/ !
228
		$queried_object = ( isset( $wp_the_query->queried_object ) ) ? $wp_the_query->queried_object : null;
229
		$queried_object_id = ( isset( $wp_the_query->queried_object_id ) ) ? $wp_the_query->queried_object_id : null;
230
		$post = $wp_the_query->get_queried_object_id();
231
		$wp_the_query->queried_object = $queried_object;
232
		$wp_the_query->queried_object_id = $queried_object_id;
233
	} else {
234
		$post = '0';
235
	}
236
237
	return compact( 'v', 'j', 'blog', 'post', 'tz', 'srv' );
238
}
239
240
/**
241
 * Stats Add Shutdown Action.
242
 *
243
 * @access public
244
 * @return void
245
 */
246
function stats_add_shutdown_action() {
247
	// Just in case wp_footer isn't in your theme.
248
	add_action( 'shutdown',  'stats_footer', 101 );
249
}
250
251
/**
252
 * Stats Footer.
253
 *
254
 * @access public
255
 * @return void
256
 */
257
function stats_footer() {
258
	global $stats_footer;
259
	print $stats_footer;
260
	$stats_footer = '';
261
}
262
263
/**
264
 * Stats Get Options.
265
 *
266
 * @access public
267
 * @return array.
0 ignored issues
show
Documentation introduced by
The doc-type array. could not be parsed: Unknown type name "array." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
268
 */
269
function stats_get_options() {
270
	$options = get_option( 'stats_options' );
271
272
	if ( ! isset( $options['version'] ) || $options['version'] < STATS_VERSION ) {
273
		$options = stats_upgrade_options( $options );
274
	}
275
276
	return $options;
277
}
278
279
/**
280
 * Get Stats Options.
281
 *
282
 * @access public
283
 * @param mixed $option Option.
284
 * @return mixed|null.
0 ignored issues
show
Documentation introduced by
The doc-type mixed|null. could not be parsed: Unknown type name "null." at position 6. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
285
 */
286
function stats_get_option( $option ) {
287
	$options = stats_get_options();
288
289
	if ( 'blog_id' === $option ) {
290
		return Jetpack_Options::get_option( 'id' );
291
	}
292
293
	if ( isset( $options[ $option ] ) ) {
294
		return $options[ $option ];
295
	}
296
297
	return null;
298
}
299
300
/**
301
 * Stats Set Options.
302
 *
303
 * @access public
304
 * @param mixed $option Option.
305
 * @param mixed $value Value.
306
 * @return bool.
0 ignored issues
show
Documentation introduced by
The doc-type bool. could not be parsed: Unknown type name "bool." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
307
 */
308
function stats_set_option( $option, $value ) {
309
	$options = stats_get_options();
310
311
	$options[ $option ] = $value;
312
313
	return stats_set_options( $options );
314
}
315
316
/**
317
 * Stats Set Options.
318
 *
319
 * @access public
320
 * @param mixed $options Options.
321
 * @return bool
322
 */
323
function stats_set_options( $options ) {
324
	return update_option( 'stats_options', $options );
325
}
326
327
/**
328
 * Stats Upgrade Options.
329
 *
330
 * @access public
331
 * @param mixed $options Options.
332
 * @return array|bool
333
 */
334
function stats_upgrade_options( $options ) {
335
	$defaults = array(
336
		'admin_bar'    => true,
337
		'roles'        => array( 'administrator' ),
338
		'count_roles'  => array(),
339
		'blog_id'      => Jetpack_Options::get_option( 'id' ),
340
		'do_not_track' => true, // @todo
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
341
		'hide_smile'   => true,
342
	);
343
344
	if ( isset( $options['reg_users'] ) ) {
345
		if ( ! function_exists( 'get_editable_roles' ) ) {
346
			require_once ABSPATH . 'wp-admin/includes/user.php';
347
		}
348
		if ( $options['reg_users'] ) {
349
			$options['count_roles'] = array_keys( get_editable_roles() );
350
		}
351
		unset( $options['reg_users'] );
352
	}
353
354
	if ( is_array( $options ) && ! empty( $options ) ) {
355
		$new_options = array_merge( $defaults, $options );
356
	} else { $new_options = $defaults;
357
	}
358
359
	$new_options['version'] = STATS_VERSION;
360
361
	if ( ! stats_set_options( $new_options ) ) {
362
		return false;
363
	}
364
365
	stats_update_blog();
366
367
	return $new_options;
368
}
369
370
/**
371
 * Stats Array.
372
 *
373
 * @access public
374
 * @param mixed $kvs KVS.
375
 * @return array
376
 */
377
function stats_array( $kvs ) {
378
	/**
379
	 * Filter the options added to the JavaScript Stats tracking code.
380
	 *
381
	 * @module stats
382
	 *
383
	 * @since 1.1.0
384
	 *
385
	 * @param array $kvs Array of options about the site and page you're on.
386
	 */
387
	$kvs = apply_filters( 'stats_array', $kvs );
388
	$kvs = array_map( 'addslashes', $kvs );
389
	foreach ( $kvs as $k => $v ) {
390
		$jskvs[] = "$k:'$v'";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$jskvs was never initialized. Although not strictly required by PHP, it is generally a good practice to add $jskvs = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
391
	}
392
	return join( ',', $jskvs );
0 ignored issues
show
Bug introduced by
The variable $jskvs 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...
393
}
394
395
/**
396
 * Admin Pages.
397
 *
398
 * @access public
399
 * @return void
400
 */
401
function stats_admin_menu() {
402
	global $pagenow;
403
404
	// If we're at an old Stats URL, redirect to the new one.
405
	// Don't even bother with caps, menu_page_url(), etc.  Just do it.
406
	if ( 'index.php' === $pagenow && isset( $_GET['page'] ) && 'stats' === $_GET['page'] ) {
407
		$redirect_url = str_replace( array( '/wp-admin/index.php?', '/wp-admin/?' ), '/wp-admin/admin.php?', $_SERVER['REQUEST_URI'] );
408
		$relative_pos = strpos( $redirect_url, '/wp-admin/' );
409
		if ( false !== $relative_pos ) {
410
			wp_safe_redirect( admin_url( substr( $redirect_url, $relative_pos + 10 ) ) );
411
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function stats_admin_menu() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
412
		}
413
	}
414
415
	$hook = add_submenu_page( 'jetpack', __( 'Site Stats', 'jetpack' ), __( 'Site Stats', 'jetpack' ), 'view_stats', 'stats', 'stats_reports_page' );
416
	add_action( "load-$hook", 'stats_reports_load' );
417
}
418
419
/**
420
 * Stats Admin Path.
421
 *
422
 * @access public
423
 * @return string
424
 */
425
function stats_admin_path() {
426
	return Jetpack::module_configuration_url( __FILE__ );
427
}
428
429
/**
430
 * Stats Reports Load.
431
 *
432
 * @access public
433
 * @return void
434
 */
435
function stats_reports_load() {
436
	wp_enqueue_script( 'jquery' );
437
	wp_enqueue_script( 'postbox' );
438
	wp_enqueue_script( 'underscore' );
439
440
	$rtl = is_rtl() ? '.rtl' : '';
441
	wp_enqueue_style( 'dops-css', plugins_url( "_inc/build/admin.dops-style$rtl.css", JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
442
	wp_enqueue_style( 'components-css', plugins_url( "_inc/build/style.min$rtl.css", JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
443
444
	add_action( 'admin_print_styles', 'stats_reports_css' );
445
446
	if ( isset( $_GET['nojs'] ) && $_GET['nojs'] ) {
447
		$parsed = parse_url( admin_url() );
448
		// Remember user doesn't want JS.
449
		setcookie( 'stnojs', '1', time() + 172800, $parsed['path'] ); // 2 days.
450
	}
451
452
	if ( isset( $_COOKIE['stnojs'] ) && $_COOKIE['stnojs'] ) {
453
		// Detect if JS is on.  If so, remove cookie so next page load is via JS.
454
		add_action( 'admin_print_footer_scripts', 'stats_js_remove_stnojs_cookie' );
455
	} else if ( ! isset( $_GET['noheader'] ) && empty( $_GET['nojs'] ) ) {
456
		// Normal page load.  Load page content via JS.
457
		add_action( 'admin_print_footer_scripts', 'stats_js_load_page_via_ajax' );
458
	}
459
}
460
461
/**
462
 * Stats Reports CSS.
463
 *
464
 * @access public
465
 * @return void
466
 */
467
function stats_reports_css() {
468
?>
469
<style type="text/css">
470
#wpcontent {
471
	padding-left: 0 !important;
472
}
473
474
#jp-stats-wrap {
475
	max-width: 720px;
476
	margin: 0 auto;
477
	overflow: hidden;
478
}
479
480
#stats-loading-wrap p {
481
	text-align: center;
482
	font-size: 2em;
483
	margin: 7.5em 15px 0 0;
484
	height: 64px;
485
	line-height: 64px;
486
}
487
</style>
488
<?php
489
}
490
491
492
/**
493
 * Detect if JS is on.  If so, remove cookie so next page load is via JS.
494
 *
495
 * @access public
496
 * @return void
497
 */
498
function stats_js_remove_stnojs_cookie() {
499
	$parsed = parse_url( admin_url() );
500
?>
501
<script type="text/javascript">
502
/* <![CDATA[ */
503
document.cookie = 'stnojs=0; expires=Wed, 9 Mar 2011 16:55:50 UTC; path=<?php echo esc_js( $parsed['path'] ); ?>';
504
/* ]]> */
505
</script>
506
<?php
507
}
508
509
/**
510
 * Normal page load.  Load page content via JS.
511
 *
512
 * @access public
513
 * @return void
514
 */
515
function stats_js_load_page_via_ajax() {
516
?>
517
<script type="text/javascript">
518
/* <![CDATA[ */
519
if ( -1 == document.location.href.indexOf( 'noheader' ) ) {
520
	jQuery( function( $ ) {
521
		$.get( document.location.href + '&noheader', function( responseText ) {
522
			$( '#stats-loading-wrap' ).replaceWith( responseText );
523
		} );
524
	} );
525
}
526
/* ]]> */
527
</script>
528
<?php
529
}
530
531
/**
532
 * Stats Report Page.
533
 *
534
 * @access public
535
 * @param bool $main_chart_only (default: false) Main Chart Only.
536
 */
537
function stats_reports_page( $main_chart_only = false ) {
538
539
	if ( isset( $_GET['dashboard'] ) ) {
540
		return stats_dashboard_widget_content();
541
	}
542
543
	$blog_id = stats_get_option( 'blog_id' );
544
	$domain = Jetpack::build_raw_urls( get_home_url() );
545
546
	$jetpack_admin_url = admin_url() . 'admin.php?page=jetpack';
547
548
	if ( ! $main_chart_only && ! isset( $_GET['noheader'] ) && empty( $_GET['nojs'] ) && empty( $_COOKIE['stnojs'] ) ) {
549
		$nojs_url = add_query_arg( 'nojs', '1' );
550
		$http = is_ssl() ? 'https' : 'http';
551
		// Loading message. No JS fallback message.
552
?>
553
<div id="jp-plugin-container">
554
	<div class="jp-masthead">
555
		<div class="jp-masthead__inside-container">
556
			<div class="jp-masthead__logo-container">
557
				<a class="jp-masthead__logo-link" href="<?php echo esc_url( $jetpack_admin_url ); ?>">
558
					<svg class="jetpack-logo__masthead" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" height="32" viewBox="0 0 118 32"><path fill="#00BE28" d="M16,0C7.2,0,0,7.2,0,16s7.2,16,16,16s16-7.2,16-16S24.8,0,16,0z M15,19H7l8-16V19z M17,29V13h8L17,29z"></path><path d="M41.3,26.6c-0.5-0.7-0.9-1.4-1.3-2.1c2.3-1.4,3-2.5,3-4.6V8h-3V6h6v13.4C46,22.8,45,24.8,41.3,26.6z"></path><path d="M65,18.4c0,1.1,0.8,1.3,1.4,1.3c0.5,0,2-0.2,2.6-0.4v2.1c-0.9,0.3-2.5,0.5-3.7,0.5c-1.5,0-3.2-0.5-3.2-3.1V12H60v-2h2.1V7.1 H65V10h4v2h-4V18.4z"></path><path d="M71,10h3v1.3c1.1-0.8,1.9-1.3,3.3-1.3c2.5,0,4.5,1.8,4.5,5.6s-2.2,6.3-5.8,6.3c-0.9,0-1.3-0.1-2-0.3V28h-3V10z M76.5,12.3 c-0.8,0-1.6,0.4-2.5,1.2v5.9c0.6,0.1,0.9,0.2,1.8,0.2c2,0,3.2-1.3,3.2-3.9C79,13.4,78.1,12.3,76.5,12.3z"></path><path d="M93,22h-3v-1.5c-0.9,0.7-1.9,1.5-3.5,1.5c-1.5,0-3.1-1.1-3.1-3.2c0-2.9,2.5-3.4,4.2-3.7l2.4-0.3v-0.3c0-1.5-0.5-2.3-2-2.3 c-0.7,0-2.3,0.5-3.7,1.1L84,11c1.2-0.4,3-1,4.4-1c2.7,0,4.6,1.4,4.6,4.7L93,22z M90,16.4l-2.2,0.4c-0.7,0.1-1.4,0.5-1.4,1.6 c0,0.9,0.5,1.4,1.3,1.4s1.5-0.5,2.3-1V16.4z"></path><path d="M104.5,21.3c-1.1,0.4-2.2,0.6-3.5,0.6c-4.2,0-5.9-2.4-5.9-5.9c0-3.7,2.3-6,6.1-6c1.4,0,2.3,0.2,3.2,0.5V13 c-0.8-0.3-2-0.6-3.2-0.6c-1.7,0-3.2,0.9-3.2,3.6c0,2.9,1.5,3.8,3.3,3.8c0.9,0,1.9-0.2,3.2-0.7V21.3z"></path><path d="M110,15.2c0.2-0.3,0.2-0.8,3.8-5.2h3.7l-4.6,5.7l5,6.3h-3.7l-4.2-5.8V22h-3V6h3V15.2z"></path><path d="M58.5,21.3c-1.5,0.5-2.7,0.6-4.2,0.6c-3.6,0-5.8-1.8-5.8-6c0-3.1,1.9-5.9,5.5-5.9s4.9,2.5,4.9,4.9c0,0.8,0,1.5-0.1,2h-7.3 c0.1,2.5,1.5,2.8,3.6,2.8c1.1,0,2.2-0.3,3.4-0.7C58.5,19,58.5,21.3,58.5,21.3z M56,15c0-1.4-0.5-2.9-2-2.9c-1.4,0-2.3,1.3-2.4,2.9 C51.6,15,56,15,56,15z"></path></svg>
559
				</a>
560
			</div>
561
			<div class="jp-masthead__nav"><span class="dops-button-group"><a href="<?php echo esc_url( $jetpack_admin_url ); ?>" type="button" class="dops-button is-compact"><?php esc_html_e( 'Dashboard', 'jetpack' ); ?></a><a href="<?php echo esc_url( $jetpack_admin_url . '#/settings' ); ?>" type="button" class="dops-button is-compact"><?php esc_html_e( 'Settings', 'jetpack' ); ?></a></span></div>
562
		</div>
563
	</div>
564
	<div id="jp-stats-wrap">
565
<div class="wrap">
566
	<h2><?php esc_html_e( 'Site Stats', 'jetpack' ); ?> <?php if ( current_user_can( 'jetpack_manage_modules' ) ) : ?><a style="font-size:13px;" href="<?php echo esc_url( admin_url( 'admin.php?page=jetpack&configure=stats' ) ); ?>"><?php esc_html_e( 'Configure', 'jetpack' ); ?></a><?php endif; ?></h2>
567
</div>
568
<div id="stats-loading-wrap" class="wrap">
569
<p class="hide-if-no-js"><img width="32" height="32" alt="<?php esc_attr_e( 'Loading&hellip;', 'jetpack' ); ?>" src="<?php
570
		echo esc_url(
571
			/**
572
			 * Sets external resource URL.
573
			 *
574
			 * @module stats
575
			 *
576
			 * @since 1.4.0
577
			 *
578
			 * @param string $args URL of external resource.
579
			 */
580
			apply_filters( 'jetpack_static_url', "{$http}://en.wordpress.com/i/loading/loading-64.gif" )
581
		); ?>" /></p>
582
<p style="font-size: 11pt; margin: 0;"><a href="https://wordpress.com/stats/<?php echo esc_attr( $domain ); ?>" target="_blank"><?php esc_html_e( 'View stats on WordPress.com right now', 'jetpack' ); ?></a></p>
583
<p class="hide-if-js"><?php esc_html_e( 'Your Site Stats work better with JavaScript enabled.', 'jetpack' ); ?><br />
584
<a href="<?php echo esc_url( $nojs_url ); ?>"><?php esc_html_e( 'View Site Stats without JavaScript', 'jetpack' ); ?></a>.</p>
585
</div>
586
</div>
587
<div class="jp-footer">
588
	<ul class="jp-footer__links">
589
		<li class="jp-footer__link-item">
590
			<a href="https://jetpack.com" target="_blank" rel="noopener noreferrer" class="jp-footer__link" title="<?php esc_html_e( 'Jetpack version', 'jetpack' ); ?>">Jetpack <?php echo JETPACK__VERSION; ?></a>
591
		</li>
592
		<li class="jp-footer__link-item">
593
			<a href="https://wordpress.com/tos/" target="_blank" rel="noopener noreferrer" title="<?php esc_html__( 'WordPress.com Terms of Service', 'jetpack' ); ?>" class="jp-footer__link"><?php echo esc_html_x( 'Terms', 'Navigation item', 'jetpack' ); ?></a>
594
		</li>
595
		<li class="jp-footer__link-item">
596
			<a href="<?php echo esc_url( $jetpack_admin_url . '#/privacy' ); ?>" rel="noopener noreferrer" title="<?php esc_html_e( 'Automattic\'s Privacy Policy', 'jetpack' ); ?>" class="jp-footer__link"><?php echo esc_html_x( 'Privacy', 'Navigation item', 'jetpack' ); ?></a>
597
		</li>
598
		<li class="jp-footer__link-item">
599
			<a href="<?php echo esc_url( admin_url() . 'admin.php?page=jetpack-debugger' ); ?>" title="<?php esc_html_e( 'Test your site\'s compatibility with Jetpack.', 'jetpack' ); ?>" class="jp-footer__link"><?php echo esc_html_x( 'Debug', 'Navigation item', 'jetpack' ); ?></a>
600
		</li>
601
	</ul>
602
</div>
603
</div>
604
<?php
605
		return;
606
	}
607
608
	$day = isset( $_GET['day'] ) && preg_match( '/^\d{4}-\d{2}-\d{2}$/', $_GET['day'] ) ? $_GET['day'] : false;
609
	$q = array(
610
		'noheader' => 'true',
611
		'proxy' => '',
612
		'page' => 'stats',
613
		'day' => $day,
614
		'blog' => $blog_id,
615
		'charset' => get_option( 'blog_charset' ),
616
		'color' => get_user_option( 'admin_color' ),
617
		'ssl' => is_ssl(),
618
		'j' => sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION ),
619
	);
620
	if ( get_locale() !== 'en_US' ) {
621
		$q['jp_lang'] = get_locale();
622
	}
623
	// Only show the main chart, without extra header data, or metaboxes.
624
	$q['main_chart_only'] = $main_chart_only;
625
	$args = array(
626
		'view' => array( 'referrers', 'postviews', 'searchterms', 'clicks', 'post', 'table' ),
627
		'numdays' => 'int',
628
		'day' => 'date',
629
		'unit' => array( 1, 7, 31, 'human' ),
630
		'humanize' => array( 'true' ),
631
		'num' => 'int',
632
		'summarize' => null,
633
		'post' => 'int',
634
		'width' => 'int',
635
		'height' => 'int',
636
		'data' => 'data',
637
		'blog_subscribers' => 'int',
638
		'comment_subscribers' => null,
639
		'type' => array( 'wpcom', 'email', 'pending' ),
640
		'pagenum' => 'int',
641
	);
642
	foreach ( $args as $var => $vals ) {
643
		if ( ! isset( $_REQUEST[$var] ) )
644
			continue;
645
		if ( is_array( $vals ) ) {
646
			if ( in_array( $_REQUEST[$var], $vals ) )
647
				$q[$var] = $_REQUEST[$var];
648
		} elseif ( 'int' === $vals ) {
649
			$q[$var] = intval( $_REQUEST[$var] );
650
		} elseif ( 'date' === $vals ) {
651
			if ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', $_REQUEST[$var] ) )
652
				$q[$var] = $_REQUEST[$var];
653
		} elseif ( null === $vals ) {
654
			$q[$var] = '';
655
		} elseif ( 'data' === $vals ) {
656
			if ( 'index.php' === substr( $_REQUEST[$var], 0, 9 ) )
657
				$q[$var] = $_REQUEST[$var];
658
		}
659
	}
660
661
	if ( isset( $_GET['chart'] ) ) {
662
		if ( preg_match( '/^[a-z0-9-]+$/', $_GET['chart'] ) ) {
663
			$chart = sanitize_title( $_GET['chart'] );
664
			$url = 'https://' . STATS_DASHBOARD_SERVER . "/wp-includes/charts/{$chart}.php";
665
		}
666
	} else {
667
		$url = 'https://' . STATS_DASHBOARD_SERVER . "/wp-admin/index.php";
668
	}
669
670
	$url = add_query_arg( $q, $url );
0 ignored issues
show
Bug introduced by
The variable $url 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...
671
	$method = 'GET';
672
	$timeout = 90;
673
	$user_id = JETPACK_MASTER_USER; // means send the wp.com user_id
674
675
	$get = Jetpack_Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
676
	$get_code = wp_remote_retrieve_response_code( $get );
677
	if ( is_wp_error( $get ) || ( 2 !== intval( $get_code / 100 ) && 304 !== $get_code ) || empty( $get['body'] ) ) {
678
		stats_print_wp_remote_error( $get, $url );
679
	} else {
680
		if ( ! empty( $get['headers']['content-type'] ) ) {
681
			$type = $get['headers']['content-type'];
682
			if ( substr( $type, 0, 5 ) === 'image' ) {
683
				$img = $get['body'];
684
				header( 'Content-Type: ' . $type );
685
				header( 'Content-Length: ' . strlen( $img ) );
686
				echo $img;
687
				die();
0 ignored issues
show
Coding Style Compatibility introduced by
The function stats_reports_page() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
688
			}
689
		}
690
		$body = stats_convert_post_titles( $get['body'] );
691
		$body = stats_convert_chart_urls( $body );
692
		$body = stats_convert_image_urls( $body );
693
		$body = stats_convert_admin_urls( $body );
694
		echo $body;
695
	}
696
697
	if ( isset( $_GET['page'] ) && 'stats' === $_GET['page'] && ! isset( $_GET['chart'] ) ) {
698
		JetpackTracking::record_user_event( 'wpa_page_view', array( 'path' => 'old_stats' ) );
699
	}
700
701
	if ( isset( $_GET['noheader'] ) ) {
702
		die;
0 ignored issues
show
Coding Style Compatibility introduced by
The function stats_reports_page() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
703
	}
704
}
705
706
/**
707
 * Stats Convert Admin Urls.
708
 *
709
 * @access public
710
 * @param mixed $html HTML.
711
 * @return string
712
 */
713
function stats_convert_admin_urls( $html ) {
714
	return str_replace( 'index.php?page=stats', 'admin.php?page=stats', $html );
715
}
716
717
/**
718
 * Stats Convert Image URLs.
719
 *
720
 * @access public
721
 * @param mixed $html HTML.
722
 * @return string
723
 */
724
function stats_convert_image_urls( $html ) {
725
	$url = set_url_scheme( 'https://' . STATS_DASHBOARD_SERVER );
726
	$html = preg_replace( '|(["\'])(/i/stats.+)\\1|', '$1' . $url . '$2$1', $html );
727
	return $html;
728
}
729
730
/**
731
 * Callback for preg_replace_callback used in stats_convert_chart_urls()
732
 *
733
 * @since 5.6.0
734
 *
735
 * @param  array  $matches The matches resulting from the preg_replace_callback call.
736
 * @return string          The admin url for the chart.
737
 */
738
function jetpack_stats_convert_chart_urls_callback( $matches ) {
739
	// If there is a query string, change the beginning '?' to a '&' so it fits into the middle of this query string.
740
	return 'admin.php?page=stats&noheader&chart=' . $matches[1] . str_replace( '?', '&', $matches[2] );
741
}
742
743
/**
744
 * Stats Convert Chart URLs.
745
 *
746
 * @access public
747
 * @param mixed $html HTML.
748
 * @return string
749
 */
750
function stats_convert_chart_urls( $html ) {
751
	$html = preg_replace_callback(
752
		'|https?://[-.a-z0-9]+/wp-includes/charts/([-.a-z0-9]+).php(\??)|',
753
		'jetpack_stats_convert_chart_urls_callback',
754
		$html
755
	);
756
	return $html;
757
}
758
759
/**
760
 * Stats Convert Post Title HTML
761
 *
762
 * @access public
763
 * @param mixed $html HTML.
764
 * @return string
765
 */
766
function stats_convert_post_titles( $html ) {
767
	global $stats_posts;
768
	$pattern = "<span class='post-(\d+)-link'>.*?</span>";
769
	if ( ! preg_match_all( "!$pattern!", $html, $matches ) ) {
770
		return $html;
771
	}
772
	$posts = get_posts(
773
		array(
774
			'include' => implode( ',', $matches[1] ),
775
			'post_type' => 'any',
776
			'post_status' => 'any',
777
			'numberposts' => -1,
778
			'suppress_filters' => false,
779
		)
780
	);
781
	foreach ( $posts as $post ) {
782
		$stats_posts[ $post->ID ] = $post;
783
	}
784
	$html = preg_replace_callback( "!$pattern!", 'stats_convert_post_title', $html );
785
	return $html;
786
}
787
788
/**
789
 * Stats Convert Post Title Matches.
790
 *
791
 * @access public
792
 * @param mixed $matches Matches.
793
 * @return string
794
 */
795
function stats_convert_post_title( $matches ) {
796
	global $stats_posts;
797
	$post_id = $matches[1];
798
	if ( isset( $stats_posts[$post_id] ) )
799
		return '<a href="' . get_permalink( $post_id ) . '" target="_blank">' . get_the_title( $post_id ) . '</a>';
800
	return $matches[0];
801
}
802
803
/**
804
 * Stats Configuration Load.
805
 *
806
 * @access public
807
 * @return void
808
 */
809
function stats_configuration_load() {
810
	if ( isset( $_POST['action'] ) && 'save_options' === $_POST['action'] && $_POST['_wpnonce'] === wp_create_nonce( 'stats' ) ) {
811
		$options = stats_get_options();
812
		$options['admin_bar']  = isset( $_POST['admin_bar']  ) && $_POST['admin_bar'];
813
		$options['hide_smile'] = isset( $_POST['hide_smile'] ) && $_POST['hide_smile'];
814
815
		$options['roles'] = array( 'administrator' );
816 View Code Duplication
		foreach ( get_editable_roles() as $role => $details ) {
817
			if ( isset( $_POST["role_$role"] ) && $_POST["role_$role"] ) {
818
				$options['roles'][] = $role;
819
			}
820
		}
821
822
		$options['count_roles'] = array();
823 View Code Duplication
		foreach ( get_editable_roles() as $role => $details ) {
824
			if ( isset( $_POST["count_role_$role"] ) && $_POST["count_role_$role"] ) {
825
				$options['count_roles'][] = $role;
826
			}
827
		}
828
829
		stats_set_options( $options );
830
		stats_update_blog();
831
		Jetpack::state( 'message', 'module_configured' );
832
		wp_safe_redirect( Jetpack::module_configuration_url( 'stats' ) );
833
		exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function stats_configuration_load() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
834
	}
835
}
836
837
/**
838
 * Stats Configuration Head.
839
 *
840
 * @access public
841
 * @return void
842
 */
843
function stats_configuration_head() {
844
?>
845
	<style type="text/css">
846
		#statserror {
847
			border: 1px solid #766;
848
			background-color: #d22;
849
			padding: 1em 3em;
850
		}
851
		.stats-smiley {
852
			vertical-align: 1px;
853
		}
854
	</style>
855
	<?php
856
}
857
858
/**
859
 * Stats Configuration Screen.
860
 *
861
 * @access public
862
 * @return void
863
 */
864
function stats_configuration_screen() {
865
	$options = stats_get_options();
866
?>
867
	<div class="narrow">
868
		<p><?php printf( __( 'Visit <a href="%s">Site Stats</a> to see your stats.', 'jetpack' ), esc_url( menu_page_url( 'stats', false ) ) ); ?></p>
869
		<form method="post">
870
		<input type='hidden' name='action' value='save_options' />
871
		<?php wp_nonce_field( 'stats' ); ?>
872
		<table id="menu" class="form-table">
873
		<tr valign="top"><th scope="row"><label for="admin_bar"><?php esc_html_e( 'Admin bar' , 'jetpack' ); ?></label></th>
874
		<td><label><input type='checkbox'<?php checked( $options['admin_bar'] ); ?> name='admin_bar' id='admin_bar' /> <?php esc_html_e( 'Put a chart showing 48 hours of views in the admin bar.', 'jetpack' ); ?></label></td></tr>
875
		<tr valign="top"><th scope="row"><?php esc_html_e( 'Registered users', 'jetpack' ); ?></th>
876
		<td>
877
			<?php esc_html_e( "Count the page views of registered users who are logged in.", 'jetpack' ); ?><br/>
878
			<?php
879
	$count_roles = stats_get_option( 'count_roles' );
880
	foreach ( get_editable_roles() as $role => $details ) {
881
?>
882
				<label><input type='checkbox' name='count_role_<?php echo $role; ?>'<?php checked( in_array( $role, $count_roles ) ); ?> /> <?php echo translate_user_role( $details['name'] ); ?></label><br/>
883
				<?php
884
	}
885
?>
886
		</td></tr>
887
		<tr valign="top"><th scope="row"><?php esc_html_e( 'Smiley' , 'jetpack' ); ?></th>
888
		<td><label><input type='checkbox'<?php checked( isset( $options['hide_smile'] ) && $options['hide_smile'] ); ?> name='hide_smile' id='hide_smile' /> <?php esc_html_e( 'Hide the stats smiley face image.', 'jetpack' ); ?></label><br /> <span class="description"><?php echo wp_kses( __( 'The image helps collect stats and <strong>makes the world a better place</strong> but should still work when hidden', 'jetpack' ), array( 'strong' => array() ) ); ?> <img class="stats-smiley" alt="<?php esc_attr_e( 'Smiley face', 'jetpack' ); ?>" src="<?php echo esc_url( plugins_url( 'images/stats-smiley.gif', dirname( __FILE__ ) ) ); ?>" width="6" height="5" /></span></td></tr>
889
		<tr valign="top"><th scope="row"><?php esc_html_e( 'Report visibility' , 'jetpack' ); ?></th>
890
		<td>
891
			<?php esc_html_e( 'Select the roles that will be able to view stats reports.', 'jetpack' ); ?><br/>
892
			<?php
893
	$stats_roles = stats_get_option( 'roles' );
894
	foreach ( get_editable_roles() as $role => $details ) {
895
?>
896
				<label><input type='checkbox' <?php if ( 'administrator' === $role ) echo "disabled='disabled' "; ?>name='role_<?php echo $role; ?>'<?php checked( 'administrator' === $role || in_array( $role, $stats_roles ) ); ?> /> <?php echo translate_user_role( $details['name'] ); ?></label><br/>
897
				<?php
898
	}
899
?>
900
		</td></tr>
901
		</table>
902
		<p class="submit"><input type='submit' class='button-primary' value='<?php echo esc_attr( __( 'Save configuration', 'jetpack' ) ); ?>' /></p>
903
		</form>
904
	</div>
905
	<?php
906
}
907
908
/**
909
 * Stats Hide Smile.
910
 *
911
 * @access public
912
 * @return void
913
 */
914
function stats_hide_smile_css() {
915
	$options = stats_get_options();
916
	if ( isset( $options['hide_smile'] ) && $options['hide_smile'] ) {
917
?>
918
<style type='text/css'>img#wpstats{display:none}</style><?php
919
	}
920
}
921
922
/**
923
 * Stats Admin Bar Head.
924
 *
925
 * @access public
926
 * @return void
927
 */
928
function stats_admin_bar_head() {
929
	if ( ! stats_get_option( 'admin_bar' ) )
930
		return;
931
932
	if ( ! current_user_can( 'view_stats' ) )
933
		return;
934
935
	if ( function_exists( 'is_admin_bar_showing' ) && ! is_admin_bar_showing() ) {
936
		return;
937
	}
938
939
	add_action( 'admin_bar_menu', 'stats_admin_bar_menu', 100 );
940
?>
941
942
<style type='text/css'>
943
#wpadminbar .quicklinks li#wp-admin-bar-stats {
944
	height: 32px;
945
}
946
#wpadminbar .quicklinks li#wp-admin-bar-stats a {
947
	height: 32px;
948
	padding: 0;
949
}
950
#wpadminbar .quicklinks li#wp-admin-bar-stats a div {
951
	height: 32px;
952
	width: 95px;
953
	overflow: hidden;
954
	margin: 0 10px;
955
}
956
#wpadminbar .quicklinks li#wp-admin-bar-stats a:hover div {
957
	width: auto;
958
	margin: 0 8px 0 10px;
959
}
960
#wpadminbar .quicklinks li#wp-admin-bar-stats a img {
961
	height: 24px;
962
	padding: 4px 0;
963
	max-width: none;
964
	border: none;
965
}
966
</style>
967
<?php
968
}
969
970
/**
971
 * Stats AdminBar.
972
 *
973
 * @access public
974
 * @param mixed $wp_admin_bar WPAdminBar.
975
 * @return void
976
 */
977
function stats_admin_bar_menu( &$wp_admin_bar ) {
978
	$url = add_query_arg( 'page', 'stats', admin_url( 'admin.php' ) ); // no menu_page_url() blog-side.
979
980
	$img_src = esc_attr( add_query_arg( array( 'noheader' => '', 'proxy' => '', 'chart' => 'admin-bar-hours-scale' ), $url ) );
981
	$img_src_2x = esc_attr( add_query_arg( array( 'noheader' => '', 'proxy' => '', 'chart' => 'admin-bar-hours-scale-2x' ), $url ) );
982
983
	$alt = esc_attr( __( 'Stats', 'jetpack' ) );
984
985
	$title = esc_attr( __( 'Views over 48 hours. Click for more Site Stats.', 'jetpack' ) );
986
987
	$menu = array( 'id' => 'stats', 'title' => "<div><script type='text/javascript'>var src;if(typeof(window.devicePixelRatio)=='undefined'||window.devicePixelRatio<2){src='$img_src';}else{src='$img_src_2x';}document.write('<img src=\''+src+'\' alt=\'$alt\' title=\'$title\' />');</script></div>", 'href' => $url );
988
989
	$wp_admin_bar->add_menu( $menu );
990
}
991
992
/**
993
 * Stats Update Blog.
994
 *
995
 * @access public
996
 * @return void
997
 */
998
function stats_update_blog() {
999
	Jetpack::xmlrpc_async_call( 'jetpack.updateBlog', stats_get_blog() );
1000
}
1001
1002
/**
1003
 * Stats Get Blog.
1004
 *
1005
 * @access public
1006
 * @return string
1007
 */
1008
function stats_get_blog() {
1009
	$home = parse_url( trailingslashit( get_option( 'home' ) ) );
1010
	$blog = array(
1011
		'host'                => $home['host'],
1012
		'path'                => $home['path'],
1013
		'blogname'            => get_option( 'blogname' ),
1014
		'blogdescription'     => get_option( 'blogdescription' ),
1015
		'siteurl'             => get_option( 'siteurl' ),
1016
		'gmt_offset'          => get_option( 'gmt_offset' ),
1017
		'timezone_string'     => get_option( 'timezone_string' ),
1018
		'stats_version'       => STATS_VERSION,
1019
		'stats_api'           => 'jetpack',
1020
		'page_on_front'       => get_option( 'page_on_front' ),
1021
		'permalink_structure' => get_option( 'permalink_structure' ),
1022
		'category_base'       => get_option( 'category_base' ),
1023
		'tag_base'            => get_option( 'tag_base' ),
1024
	);
1025
	$blog = array_merge( stats_get_options(), $blog );
1026
	unset( $blog['roles'], $blog['blog_id'] );
1027
	return stats_esc_html_deep( $blog );
1028
}
1029
1030
/**
1031
 * Modified from stripslashes_deep()
1032
 *
1033
 * @access public
1034
 * @param mixed $value Value.
1035
 * @return string
1036
 */
1037
function stats_esc_html_deep( $value ) {
1038
	if ( is_array( $value ) ) {
1039
		$value = array_map( 'stats_esc_html_deep', $value );
1040
	} elseif ( is_object( $value ) ) {
1041
		$vars = get_object_vars( $value );
1042
		foreach ( $vars as $key => $data ) {
1043
			$value->{$key} = stats_esc_html_deep( $data );
1044
		}
1045
	} elseif ( is_string( $value ) ) {
1046
		$value = esc_html( $value );
1047
	}
1048
1049
	return $value;
1050
}
1051
1052
/**
1053
 * Stats xmlrpc_methods function.
1054
 *
1055
 * @access public
1056
 * @param mixed $methods Methods.
1057
 * @return array
1058
 */
1059
function stats_xmlrpc_methods( $methods ) {
1060
	$my_methods = array(
1061
		'jetpack.getBlog' => 'stats_get_blog',
1062
	);
1063
1064
	return array_merge( $methods, $my_methods );
1065
}
1066
1067
/**
1068
 * Register Stats Dashboard Widget.
1069
 *
1070
 * @access public
1071
 * @return void
1072
 */
1073
function stats_register_dashboard_widget() {
1074
	if ( ! current_user_can( 'view_stats' ) )
1075
		return;
1076
1077
	// With wp_dashboard_empty: we load in the content after the page load via JS.
1078
	wp_add_dashboard_widget( 'dashboard_stats', __( 'Site Stats', 'jetpack' ), 'wp_dashboard_empty', 'stats_dashboard_widget_control' );
1079
1080
	add_action( 'admin_head', 'stats_dashboard_head' );
1081
}
1082
1083
/**
1084
 * Stats Dashboard Widget Options.
1085
 *
1086
 * @access public
1087
 * @return array
1088
 */
1089
function stats_dashboard_widget_options() {
1090
	$defaults = array( 'chart' => 1, 'top' => 1, 'search' => 7 );
1091
	if ( ( ! $options = get_option( 'stats_dashboard_widget' ) ) || ! is_array( $options ) ) {
1092
		$options = array();
1093
	}
1094
1095
	// Ignore obsolete option values.
1096
	$intervals = array( 1, 7, 31, 90, 365 );
1097
	foreach ( array( 'top', 'search' ) as $key ) {
1098
		if ( isset( $options[ $key ] ) && ! in_array( $options[ $key ], $intervals ) ) {
1099
			unset( $options[ $key ] );
1100
		}
1101
	}
1102
1103
		return array_merge( $defaults, $options );
1104
}
1105
1106
/**
1107
 * Stats Dashboard Widget Control.
1108
 *
1109
 * @access public
1110
 * @return void
1111
 */
1112
function stats_dashboard_widget_control() {
1113
	$periods   = array(
1114
		'1' => __( 'day', 'jetpack' ),
1115
		'7' => __( 'week', 'jetpack' ),
1116
		'31' => __( 'month', 'jetpack' ),
1117
	);
1118
	$intervals = array(
1119
		'1' => __( 'the past day', 'jetpack' ),
1120
		'7' => __( 'the past week', 'jetpack' ),
1121
		'31' => __( 'the past month', 'jetpack' ),
1122
		'90' => __( 'the past quarter', 'jetpack' ),
1123
		'365' => __( 'the past year', 'jetpack' ),
1124
	);
1125
	$defaults = array(
1126
		'top' => 1,
1127
		'search' => 7,
1128
	);
1129
1130
	$options = stats_dashboard_widget_options();
1131
1132
	if ( 'post' === strtolower( $_SERVER['REQUEST_METHOD'] ) && isset( $_POST['widget_id'] ) && 'dashboard_stats' === $_POST['widget_id'] ) {
1133
		if ( isset( $periods[ $_POST['chart'] ] ) ) {
1134
			$options['chart'] = $_POST['chart'];
1135
		}
1136
		foreach ( array( 'top', 'search' ) as $key ) {
1137
			if ( isset( $intervals[ $_POST[ $key ] ] ) ) {
1138
				$options[ $key ] = $_POST[ $key ];
1139
			} else { $options[ $key ] = $defaults[ $key ];
1140
			}
1141
		}
1142
		update_option( 'stats_dashboard_widget', $options );
1143
	}
1144
?>
1145
	<p>
1146
	<label for="chart"><?php esc_html_e( 'Chart stats by' , 'jetpack' ); ?></label>
1147
	<select id="chart" name="chart">
1148
	<?php
1149
	foreach ( $periods as $val => $label ) {
1150
?>
1151
		<option value="<?php echo $val; ?>"<?php selected( $val, $options['chart'] ); ?>><?php echo esc_html( $label ); ?></option>
1152
		<?php
1153
	}
1154
?>
1155
	</select>.
1156
	</p>
1157
1158
	<p>
1159
	<label for="top"><?php esc_html_e( 'Show top posts over', 'jetpack' ); ?></label>
1160
	<select id="top" name="top">
1161
	<?php
1162 View Code Duplication
	foreach ( $intervals as $val => $label ) {
1163
?>
1164
		<option value="<?php echo $val; ?>"<?php selected( $val, $options['top'] ); ?>><?php echo esc_html( $label ); ?></option>
1165
		<?php
1166
	}
1167
?>
1168
	</select>.
1169
	</p>
1170
1171
	<p>
1172
	<label for="search"><?php esc_html_e( 'Show top search terms over', 'jetpack' ); ?></label>
1173
	<select id="search" name="search">
1174
	<?php
1175 View Code Duplication
	foreach ( $intervals as $val => $label ) {
1176
?>
1177
		<option value="<?php echo $val; ?>"<?php selected( $val, $options['search'] ); ?>><?php echo esc_html( $label ); ?></option>
1178
		<?php
1179
	}
1180
?>
1181
	</select>.
1182
	</p>
1183
	<?php
1184
}
1185
1186
/**
1187
 * Jetpack Stats Dashboard Widget.
1188
 *
1189
 * @access public
1190
 * @return void
1191
 */
1192
function stats_jetpack_dashboard_widget() {
1193
?>
1194
	<form id="stats_dashboard_widget_control" action="<?php echo esc_url( admin_url() ); ?>" method="post">
1195
		<?php stats_dashboard_widget_control(); ?>
1196
		<?php wp_nonce_field( 'edit-dashboard-widget_dashboard_stats', 'dashboard-widget-nonce' ); ?>
1197
		<input type="hidden" name="widget_id" value="dashboard_stats" />
1198
		<?php submit_button( __( 'Submit', 'jetpack' ) ); ?>
1199
	</form>
1200
	<span id="js-toggle-stats_dashboard_widget_control">
1201
		<?php esc_html_e( 'Configure', 'jetpack' ); ?>
1202
	</span>
1203
	<div id="dashboard_stats">
1204
		<div class="inside">
1205
			<div style="height: 250px;"></div>
1206
		</div>
1207
	</div>
1208
	<script>
1209
		jQuery(document).ready(function($){
1210
			var $toggle = $('#js-toggle-stats_dashboard_widget_control');
1211
1212
			$toggle.parent().prev().append( $toggle );
1213
			$toggle.show().click(function(e){
1214
				e.preventDefault();
1215
				e.stopImmediatePropagation();
1216
				$(this).parent().toggleClass('controlVisible');
1217
				$('#stats_dashboard_widget_control').slideToggle();
1218
			});
1219
		});
1220
	</script>
1221
	<style>
1222
		#js-toggle-stats_dashboard_widget_control {
1223
			display: none;
1224
			float: right;
1225
			margin-top: 0.2em;
1226
			font-weight: 400;
1227
			color: #444;
1228
			font-size: .8em;
1229
			text-decoration: underline;
1230
			cursor: pointer;
1231
		}
1232
		#stats_dashboard_widget_control {
1233
			display: none;
1234
			padding: 0 10px;
1235
			overflow: hidden;
1236
		}
1237
		#stats_dashboard_widget_control .button-primary {
1238
			float: right;
1239
		}
1240
		#dashboard_stats {
1241
			box-sizing: border-box;
1242
			width: 100%;
1243
			padding: 0 10px;
1244
		}
1245
	</style>
1246
	<?php
1247
}
1248
1249
/**
1250
 * Register Stats Widget Control Callback.
1251
 *
1252
 * @access public
1253
 * @return void
1254
 */
1255
function stats_register_widget_control_callback() {
1256
	$GLOBALS['wp_dashboard_control_callbacks']['dashboard_stats'] = 'stats_dashboard_widget_control';
1257
}
1258
1259
/**
1260
 * JavaScript and CSS for dashboard widget.
1261
 *
1262
 * @access public
1263
 * @return void
1264
 */
1265
function stats_dashboard_head() { ?>
1266
<script type="text/javascript">
1267
/* <![CDATA[ */
1268
jQuery( function($) {
1269
	var dashStats = jQuery( '#dashboard_stats div.inside' );
1270
1271
	if ( dashStats.find( '.dashboard-widget-control-form' ).length ) {
1272
		return;
1273
	}
1274
1275
	if ( ! dashStats.length ) {
1276
		dashStats = jQuery( '#dashboard_stats div.dashboard-widget-content' );
1277
		var h = parseInt( dashStats.parent().height() ) - parseInt( dashStats.prev().height() );
1278
		var args = 'width=' + dashStats.width() + '&height=' + h.toString();
1279
	} else {
1280
		if ( jQuery('#dashboard_stats' ).hasClass('postbox') ) {
1281
			var args = 'width=' + ( dashStats.prev().width() * 2 ).toString();
1282
		} else {
1283
			var args = 'width=' + ( dashStats.width() * 2 ).toString();
1284
		}
1285
	}
1286
1287
	dashStats
1288
		.not( '.dashboard-widget-control' )
1289
		.load( 'admin.php?page=stats&noheader&dashboard&' + args );
1290
1291
	jQuery( window ).one( 'resize', function() {
1292
		jQuery( '#stat-chart' ).css( 'width', 'auto' );
1293
	} );
1294
} );
1295
/* ]]> */
1296
</script>
1297
<style type="text/css">
1298
/* <![CDATA[ */
1299
#stat-chart {
1300
	background: none !important;
1301
}
1302
#dashboard_stats .inside {
1303
	margin: 10px 0 0 0 !important;
1304
}
1305
#dashboard_stats #stats-graph {
1306
	margin: 0;
1307
}
1308
#stats-info {
1309
	border-top: 1px solid #dfdfdf;
1310
	margin: 7px -10px 0 -10px;
1311
	padding: 10px;
1312
	background: #fcfcfc;
1313
	-moz-box-shadow:inset 0 1px 0 #fff;
1314
	-webkit-box-shadow:inset 0 1px 0 #fff;
1315
	box-shadow:inset 0 1px 0 #fff;
1316
	overflow: hidden;
1317
	border-radius: 0 0 2px 2px;
1318
	-webkit-border-radius: 0 0 2px 2px;
1319
	-moz-border-radius: 0 0 2px 2px;
1320
	-khtml-border-radius: 0 0 2px 2px;
1321
}
1322
#stats-info #top-posts, #stats-info #top-search {
1323
	float: left;
1324
	width: 50%;
1325
}
1326
#stats-info #top-posts {
1327
	padding-right: 3%;
1328
}
1329
#top-posts .stats-section-inner p {
1330
	white-space: nowrap;
1331
	overflow: hidden;
1332
}
1333
#top-posts .stats-section-inner p a {
1334
	overflow: hidden;
1335
	text-overflow: ellipsis;
1336
}
1337
#stats-info div#active {
1338
	border-top: 1px solid #dfdfdf;
1339
	margin: 0 -10px;
1340
	padding: 10px 10px 0 10px;
1341
	-moz-box-shadow:inset 0 1px 0 #fff;
1342
	-webkit-box-shadow:inset 0 1px 0 #fff;
1343
	box-shadow:inset 0 1px 0 #fff;
1344
	overflow: hidden;
1345
}
1346
#top-search p {
1347
	color: #999;
1348
}
1349
#stats-info h3 {
1350
	font-size: 1em;
1351
	margin: 0 0 .5em 0 !important;
1352
}
1353
#stats-info p {
1354
	margin: 0 0 .25em;
1355
	color: #999;
1356
}
1357
#stats-info p.widget-loading {
1358
	margin: 1em 0 0;
1359
	color: #333;
1360
}
1361
#stats-info p a {
1362
	display: block;
1363
}
1364
#stats-info p a.button {
1365
	display: inline;
1366
}
1367
/* ]]> */
1368
</style>
1369
<?php
1370
}
1371
1372
/**
1373
 * Stats Dashboard Widget Content.
1374
 *
1375
 * @access public
1376
 * @return void
1377
 */
1378
function stats_dashboard_widget_content() {
1379
	if ( ! isset( $_GET['width'] ) || ( ! $width = (int) ( $_GET['width'] / 2 ) ) || $width < 250 ) {
1380
		$width = 370;
1381
	}
1382
	if ( ! isset( $_GET['height'] ) || ( ! $height = (int) $_GET['height'] - 36 ) || $height < 230 ) {
1383
		$height = 180;
1384
	}
1385
1386
	$_width  = $width  - 5;
1387
	$_height = $height - ( $GLOBALS['is_winIE'] ? 16 : 5 ); // Hack!
1388
1389
	$options = stats_dashboard_widget_options();
1390
	$blog_id = Jetpack_Options::get_option( 'id' );
1391
1392
	$q = array(
1393
		'noheader' => 'true',
1394
		'proxy' => '',
1395
		'blog' => $blog_id,
1396
		'page' => 'stats',
1397
		'chart' => '',
1398
		'unit' => $options['chart'],
1399
		'color' => get_user_option( 'admin_color' ),
1400
		'width' => $_width,
1401
		'height' => $_height,
1402
		'ssl' => is_ssl(),
1403
		'j' => sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION ),
1404
	);
1405
1406
	$url = 'https://' . STATS_DASHBOARD_SERVER . "/wp-admin/index.php";
1407
1408
	$url = add_query_arg( $q, $url );
1409
	$method = 'GET';
1410
	$timeout = 90;
1411
	$user_id = JETPACK_MASTER_USER;
1412
1413
	$get = Jetpack_Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
1414
	$get_code = wp_remote_retrieve_response_code( $get );
1415
	if ( is_wp_error( $get ) || ( 2 !== intval( $get_code / 100 ) && 304 !== $get_code ) || empty( $get['body'] ) ) {
1416
		stats_print_wp_remote_error( $get, $url );
1417
	} else {
1418
		$body = stats_convert_post_titles( $get['body'] );
1419
		$body = stats_convert_chart_urls( $body );
1420
		$body = stats_convert_image_urls( $body );
1421
		echo $body;
1422
	}
1423
1424
	$post_ids = array();
1425
1426
	$csv_end_date = date( 'Y-m-d', current_time( 'timestamp' ) );
1427
	$csv_args = array( 'top' => "&limit=8&end=$csv_end_date", 'search' => "&limit=5&end=$csv_end_date" );
1428
	/* Translators: Stats dashboard widget postviews list: "$post_title $views Views". */
1429
	$printf = __( '%1$s %2$s Views' , 'jetpack' );
1430
1431
	foreach ( $top_posts = stats_get_csv( 'postviews', "days=$options[top]$csv_args[top]" ) as $i => $post ) {
1432
		if ( 0 === $post['post_id'] ) {
1433
			unset( $top_posts[$i] );
1434
			continue;
1435
		}
1436
		$post_ids[] = $post['post_id'];
1437
	}
1438
1439
	// Cache.
1440
	get_posts( array( 'include' => join( ',', array_unique( $post_ids ) ) ) );
1441
1442
	$searches = array();
1443
	foreach ( $search_terms = stats_get_csv( 'searchterms', "days=$options[search]$csv_args[search]" ) as $search_term ) {
1444
		if ( 'encrypted_search_terms' === $search_term['searchterm'] ) {
1445
			continue;
1446
		}
1447
		$searches[] = esc_html( $search_term['searchterm'] );
1448
	}
1449
1450
?>
1451
<a class="button" href="admin.php?page=stats"><?php  esc_html_e( 'View All', 'jetpack' ); ?></a>
1452
<div id="stats-info">
1453
	<div id="top-posts" class='stats-section'>
1454
		<div class="stats-section-inner">
1455
		<h3 class="heading"><?php  esc_html_e( 'Top Posts' , 'jetpack' ); ?></h3>
1456
		<?php
1457
	if ( empty( $top_posts ) ) {
1458
?>
1459
			<p class="nothing"><?php  esc_html_e( 'Sorry, nothing to report.', 'jetpack' ); ?></p>
1460
			<?php
1461
	} else {
1462
		foreach ( $top_posts as $post ) {
1463
			if ( ! get_post( $post['post_id'] ) ) {
1464
				continue;
1465
			}
1466
?>
1467
				<p><?php printf(
1468
				$printf,
1469
				'<a href="' . get_permalink( $post['post_id'] ) . '">' . get_the_title( $post['post_id'] ) . '</a>',
1470
				number_format_i18n( $post['views'] )
1471
			); ?></p>
1472
				<?php
1473
		}
1474
	}
1475
?>
1476
		</div>
1477
	</div>
1478
	<div id="top-search" class='stats-section'>
1479
		<div class="stats-section-inner">
1480
		<h3 class="heading"><?php  esc_html_e( 'Top Searches' , 'jetpack' ); ?></h3>
1481
		<?php
1482
	if ( empty( $searches ) ) {
1483
?>
1484
			<p class="nothing"><?php  esc_html_e( 'Sorry, nothing to report.', 'jetpack' ); ?></p>
1485
			<?php
1486
	} else {
1487
?>
1488
			<p><?php echo join( ',&nbsp; ', $searches );?></p>
1489
			<?php
1490
	}
1491
?>
1492
		</div>
1493
	</div>
1494
</div>
1495
<div class="clear"></div>
1496
<?php
1497
	exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function stats_dashboard_widget_content() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
1498
}
1499
1500
/**
1501
 * Stats Print WP Remote Error.
1502
 *
1503
 * @access public
1504
 * @param mixed $get Get.
1505
 * @param mixed $url URL.
1506
 * @return void
1507
 */
1508
function stats_print_wp_remote_error( $get, $url ) {
1509
	$state_name = 'stats_remote_error_' . substr( md5( $url ), 0, 8 );
1510
	$previous_error = Jetpack::state( $state_name );
1511
	$error = md5( serialize( compact( 'get', 'url' ) ) );
1512
	Jetpack::state( $state_name, $error );
1513
	if ( $error !== $previous_error ) {
1514
?>
1515
	<div class="wrap">
1516
	<p><?php esc_html_e( 'We were unable to get your stats just now. Please reload this page to try again.', 'jetpack' ); ?></p>
1517
	</div>
1518
<?php
1519
		return;
1520
	}
1521
?>
1522
	<div class="wrap">
1523
	<p><?php printf( __( 'We were unable to get your stats just now. Please reload this page to try again. If this error persists, please <a href="%1$s" target="_blank">contact support</a>. In your report please include the information below.', 'jetpack' ), 'https://support.wordpress.com/contact/?jetpack=needs-service' ); ?></p>
1524
	<pre>
1525
	User Agent: "<?php echo esc_html( $_SERVER['HTTP_USER_AGENT'] ); ?>"
1526
	Page URL: "http<?php echo (is_ssl()?'s':'') . '://' . esc_html( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); ?>"
1527
	API URL: "<?php echo esc_url( $url ); ?>"
1528
<?php
1529
if ( is_wp_error( $get ) ) {
1530
	foreach ( $get->get_error_codes() as $code ) {
1531
		foreach ( $get->get_error_messages( $code ) as $message ) {
1532
?>
1533
<?php print $code . ': "' . $message . '"' ?>
1534
1535
<?php
1536
		}
1537
	}
1538
} else {
1539
	$get_code = wp_remote_retrieve_response_code( $get );
1540
	$content_length = strlen( wp_remote_retrieve_body( $get ) );
1541
?>
1542
Response code: "<?php print $get_code ?>"
1543
Content length: "<?php print $content_length ?>"
1544
1545
<?php
1546
}
1547
	?></pre>
1548
	</div>
1549
	<?php
1550
}
1551
1552
/**
1553
 * Get stats from WordPress.com
1554
 *
1555
 * @param string $table The stats which you want to retrieve: postviews, or searchterms.
1556
 * @param array  $args {
0 ignored issues
show
Documentation introduced by
Should the type for parameter $args not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
1557
 *      An associative array of arguments.
1558
 *
1559
 *      @type bool    $end        The last day of the desired time frame. Format is 'Y-m-d' (e.g. 2007-05-01)
1560
 *                                and default timezone is UTC date. Default value is Now.
1561
 *      @type string  $days       The length of the desired time frame. Default is 30. Maximum 90 days.
1562
 *      @type int     $limit      The maximum number of records to return. Default is 10. Maximum 100.
1563
 *      @type int     $post_id    The ID of the post to retrieve stats data for
1564
 *      @type string  $summarize  If present, summarizes all matching records. Default Null.
1565
 *
1566
 * }
1567
 *
1568
 * @return array {
1569
 *      An array of post view data, each post as an array
1570
 *
1571
 *      array {
1572
 *          The post view data for a single post
1573
 *
1574
 *          @type string  $post_id         The ID of the post
1575
 *          @type string  $post_title      The title of the post
1576
 *          @type string  $post_permalink  The permalink for the post
1577
 *          @type string  $views           The number of views for the post within the $num_days specified
1578
 *      }
1579
 * }
1580
 */
1581
function stats_get_csv( $table, $args = null ) {
1582
	$defaults = array( 'end' => false, 'days' => false, 'limit' => 3, 'post_id' => false, 'summarize' => '' );
1583
1584
	$args = wp_parse_args( $args, $defaults );
1585
	$args['table'] = $table;
1586
	$args['blog_id'] = Jetpack_Options::get_option( 'id' );
1587
1588
	$stats_csv_url = add_query_arg( $args, 'https://stats.wordpress.com/csv.php' );
1589
1590
	$key = md5( $stats_csv_url );
1591
1592
	// Get cache.
1593
	$stats_cache = get_option( 'stats_cache' );
1594
	if ( ! $stats_cache || ! is_array( $stats_cache ) ) {
1595
		$stats_cache = array();
1596
	}
1597
1598
	// Return or expire this key.
1599
	if ( isset( $stats_cache[ $key ] ) ) {
1600
		$time = key( $stats_cache[ $key ] );
1601
		if ( time() - $time < 300 ) {
1602
			return $stats_cache[ $key ][ $time ];
1603
		}
1604
		unset( $stats_cache[ $key ] );
1605
	}
1606
1607
	$stats_rows = array();
1608
	do {
1609
		if ( ! $stats = stats_get_remote_csv( $stats_csv_url ) ) {
1610
			break;
1611
		}
1612
1613
		$labels = array_shift( $stats );
1614
1615
		if ( 0 === stripos( $labels[0], 'error' ) ) {
1616
			break;
1617
		}
1618
1619
		$stats_rows = array();
1620
		for ( $s = 0; isset( $stats[ $s ] ); $s++ ) {
1621
			$row = array();
1622
			foreach ( $labels as $col => $label ) {
1623
				$row[ $label ] = $stats[ $s ][ $col ];
1624
			}
1625
			$stats_rows[] = $row;
1626
		}
1627
	} while ( 0 );
1628
1629
	// Expire old keys.
1630 View Code Duplication
	foreach ( $stats_cache as $k => $cache ) {
1631
		if ( ! is_array( $cache ) || 300 < time() - key( $cache ) ) {
1632
			unset( $stats_cache[ $k ] );
1633
		}
1634
	}
1635
1636
		// Set cache.
1637
		$stats_cache[ $key ] = array( time() => $stats_rows );
1638
	update_option( 'stats_cache', $stats_cache );
1639
1640
	return $stats_rows;
1641
}
1642
1643
/**
1644
 * Stats get remote CSV.
1645
 *
1646
 * @access public
1647
 * @param mixed $url URL.
1648
 * @return array
1649
 */
1650
function stats_get_remote_csv( $url ) {
1651
	$method = 'GET';
1652
	$timeout = 90;
1653
	$user_id = JETPACK_MASTER_USER;
1654
1655
	$get = Jetpack_Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
1656
	$get_code = wp_remote_retrieve_response_code( $get );
1657
	if ( is_wp_error( $get ) || ( 2 !== intval( $get_code / 100 ) && 304 !== $get_code ) || empty( $get['body'] ) ) {
1658
		return array(); // @todo: return an error?
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
1659
	} else {
1660
		return stats_str_getcsv( $get['body'] );
1661
	}
1662
}
1663
1664
/**
1665
 * Rather than parsing the csv and its special cases, we create a new file and do fgetcsv on it.
1666
 *
1667
 * @access public
1668
 * @param mixed $csv CSV.
1669
 * @return array.
0 ignored issues
show
Documentation introduced by
The doc-type array. could not be parsed: Unknown type name "array." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1670
 */
1671
function stats_str_getcsv( $csv ) {
1672
	if ( function_exists( 'str_getcsv' ) ) {
1673
		$lines = str_getcsv( $csv, "\n" );
1674
		return array_map( 'str_getcsv', $lines );
1675
	}
1676
	if ( ! $temp = tmpfile() ) { // The tmpfile() automatically unlinks.
1677
		return false;
1678
	}
1679
1680
	$data = array();
1681
1682
	fwrite( $temp, $csv, strlen( $csv ) );
1683
	fseek( $temp, 0 );
1684
	while ( false !== $row = fgetcsv( $temp, 2000 ) ) {
1685
		$data[] = $row;
1686
	}
1687
	fclose( $temp );
1688
1689
	return $data;
1690
}
1691
1692
/**
1693
 * Abstract out building the rest api stats path.
1694
 *
1695
 * @param  string $resource Resource.
1696
 * @return string
1697
 */
1698
function jetpack_stats_api_path( $resource = '' ) {
1699
	$resource = ltrim( $resource, '/' );
1700
	return sprintf( '/sites/%d/stats/%s', stats_get_option( 'blog_id' ), $resource );
1701
}
1702
1703
/**
1704
 * Fetches stats data from the REST API.  Caches locally for 5 minutes.
1705
 *
1706
 * @link: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/
1707
 * @access public
1708
 * @param array  $args (default: array())  The args that are passed to the endpoint.
1709
 * @param string $resource (default: '') Optional sub-endpoint following /stats/.
1710
 * @return array|WP_Error.
0 ignored issues
show
Documentation introduced by
The doc-type array|WP_Error. could not be parsed: Unknown type name "WP_Error." at position 6. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1711
 */
1712
function stats_get_from_restapi( $args = array(), $resource = '' ) {
1713
	$endpoint    = jetpack_stats_api_path( $resource );
1714
	$api_version = '1.1';
1715
	$args        = wp_parse_args( $args, array() );
1716
	$cache_key   = md5( implode( '|', array( $endpoint, $api_version, serialize( $args ) ) ) );
1717
1718
	// Get cache.
1719
	$stats_cache = Jetpack_Options::get_option( 'restapi_stats_cache', array() );
1720
	if ( ! is_array( $stats_cache ) ) {
1721
		$stats_cache = array();
1722
	}
1723
1724
	// Return or expire this key.
1725
	if ( isset( $stats_cache[ $cache_key ] ) ) {
1726
		$time = key( $stats_cache[ $cache_key ] );
1727
		if ( time() - $time < ( 5 * MINUTE_IN_SECONDS ) ) {
1728
			$cached_stats = $stats_cache[ $cache_key ][ $time ];
1729
			$cached_stats = (object) array_merge( array( 'cached_at' => $time ), (array) $cached_stats );
1730
			return $cached_stats;
1731
		}
1732
		unset( $stats_cache[ $cache_key ] );
1733
	}
1734
1735
	// Do the dirty work.
1736
	$response = Jetpack_Client::wpcom_json_api_request_as_blog( $endpoint, $api_version, $args );
1737
	if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
1738
		// If bad, just return it, don't cache.
1739
		return $response;
1740
	}
1741
1742
	$data = json_decode( wp_remote_retrieve_body( $response ) );
1743
1744
	// Expire old keys.
1745 View Code Duplication
	foreach ( $stats_cache as $k => $cache ) {
1746
		if ( ! is_array( $cache ) || ( 5 * MINUTE_IN_SECONDS ) < time() - key( $cache ) ) {
1747
			unset( $stats_cache[ $k ] );
1748
		}
1749
	}
1750
1751
	// Set cache.
1752
	$stats_cache[ $cache_key ] = array(
1753
		time() => $data,
1754
	);
1755
	Jetpack_Options::update_option( 'restapi_stats_cache', $stats_cache, false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1756
1757
	return $data;
1758
}
1759
1760
/**
1761
 * Load CSS needed for Stats column width in WP-Admin area.
1762
 *
1763
 * @since 4.7.0
1764
 */
1765
function jetpack_stats_load_admin_css() {
1766
	?>
1767
	<style type="text/css">
1768
		.fixed .column-stats {
1769
			width: 5em;
1770
		}
1771
	</style>
1772
	<?php
1773
}
1774
1775
/**
1776
 * Set header for column that allows to go to WordPress.com to see an entry's stats.
1777
 *
1778
 * @param array $columns An array of column names.
1779
 *
1780
 * @since 4.7.0
1781
 *
1782
 * @return mixed
1783
 */
1784
function jetpack_stats_post_table( $columns ) { // Adds a stats link on the edit posts page
1785
	if ( ! current_user_can( 'view_stats' ) || ! Jetpack::is_user_connected() ) {
1786
		return $columns;
1787
	}
1788
	// Array-Fu to add before comments
1789
	$pos = array_search( 'comments', array_keys( $columns ) );
1790
	if ( ! is_int( $pos ) ) {
1791
		return $columns;
1792
	}
1793
	$chunks             = array_chunk( $columns, $pos, true );
1794
	$chunks[0]['stats'] = esc_html__( 'Stats', 'jetpack' );
1795
1796
	return call_user_func_array( 'array_merge', $chunks );
1797
}
1798
1799
/**
1800
 * Set content for cell with link to an entry's stats in WordPress.com.
1801
 *
1802
 * @param string $column  The name of the column to display.
1803
 * @param int    $post_id The current post ID.
1804
 *
1805
 * @since 4.7.0
1806
 *
1807
 * @return mixed
1808
 */
1809
function jetpack_stats_post_table_cell( $column, $post_id ) {
1810
	if ( 'stats' == $column ) {
1811
		if ( 'publish' != get_post_status( $post_id ) ) {
1812
			printf(
1813
				'<span aria-hidden="true">—</span><span class="screen-reader-text">%s</span>',
1814
				esc_html__( 'No stats', 'jetpack' )
1815
			);
1816
		} else {
1817
			printf(
1818
				'<a href="%s" title="%s" class="dashicons dashicons-chart-bar" target="_blank"></a>',
1819
				esc_url( "https://wordpress.com/stats/post/$post_id/" . Jetpack::build_raw_urls( get_home_url() ) ),
1820
				esc_html__( 'View stats for this post in WordPress.com', 'jetpack' )
1821
			);
1822
		}
1823
	}
1824
}
1825