PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 4.4.5
Jetpack – WP Security, Backup, Speed, & Growth v4.4.5
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / modules / stats.php

stats.php in Jetpack – WP Security, Backup, Speed, & Growth 4.4.5, at modules/stats.php

1,346 lines 40.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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
15 if ( defined( 'STATS_VERSION' ) ) {
16 return;
17 }
18
19 define( 'STATS_VERSION', '9' );
20 defined( 'STATS_DASHBOARD_SERVER' ) or define( 'STATS_DASHBOARD_SERVER', 'dashboard.wordpress.com' );
21
22 add_action( 'jetpack_modules_loaded', 'stats_load' );
23
24 function stats_load() {
25 global $wp_roles;
26
27 Jetpack::enable_module_configurable( __FILE__ );
28 Jetpack::module_configuration_load( __FILE__, 'stats_configuration_load' );
29 Jetpack::module_configuration_head( __FILE__, 'stats_configuration_head' );
30 Jetpack::module_configuration_screen( __FILE__, 'stats_configuration_screen' );
31
32 // Generate the tracking code after wp() has queried for posts.
33 add_action( 'template_redirect', 'stats_template_redirect', 1 );
34
35 add_action( 'wp_head', 'stats_admin_bar_head', 100 );
36
37 add_action( 'wp_head', 'stats_hide_smile_css' );
38
39 add_action( 'jetpack_admin_menu', 'stats_admin_menu' );
40
41 // Map stats caps
42 add_filter( 'map_meta_cap', 'stats_map_meta_caps', 10, 4 );
43
44 if ( isset( $_GET['oldwidget'] ) ) {
45 // Old one.
46 add_action( 'wp_dashboard_setup', 'stats_register_dashboard_widget' );
47 } else {
48 add_action( 'admin_init', 'stats_merged_widget_admin_init' );
49 }
50
51 add_filter( 'jetpack_xmlrpc_methods', 'stats_xmlrpc_methods' );
52
53
54 add_filter( 'pre_option_db_version', 'stats_ignore_db_version' );
55 }
56
57 /**
58 * Delay conditional for current_user_can to after init.
59 */
60 function stats_merged_widget_admin_init() {
61 if ( current_user_can( 'view_stats' ) ) {
62 add_action( 'load-index.php', 'stats_enqueue_dashboard_head' );
63 add_action( 'wp_dashboard_setup', 'stats_register_widget_control_callback' ); // hacky but works
64 add_action( 'jetpack_dashboard_widget', 'stats_jetpack_dashboard_widget' );
65 }
66 }
67
68 function stats_enqueue_dashboard_head() {
69 add_action( 'admin_head', 'stats_dashboard_head' );
70 }
71
72 /**
73 * Prevent sparkline img requests being redirected to upgrade.php.
74 * See wp-admin/admin.php where it checks $wp_db_version.
75 */
76 function stats_ignore_db_version( $version ) {
77 if (
78 is_admin() &&
79 isset( $_GET['page'] ) && $_GET['page'] == 'stats' &&
80 isset( $_GET['chart'] ) && strpos($_GET['chart'], 'admin-bar-hours') === 0
81 ) {
82 global $wp_db_version;
83 return $wp_db_version;
84 }
85 return $version;
86 }
87
88 /**
89 * Maps view_stats cap to read cap as needed
90 *
91 * @return array Possibly mapped capabilities for meta capability
92 */
93 function stats_map_meta_caps( $caps, $cap, $user_id, $args ) {
94 // Map view_stats to exists
95 if ( 'view_stats' == $cap ) {
96 $user = new WP_User( $user_id );
97 $user_role = array_shift( $user->roles );
98 $stats_roles = stats_get_option( 'roles' );
99
100 // Is the users role in the available stats roles?
101 if ( is_array( $stats_roles ) && in_array( $user_role, $stats_roles ) ) {
102 $caps = array( 'read' );
103 }
104 }
105
106 return $caps;
107 }
108
109 function stats_template_redirect() {
110 global $current_user, $stats_footer;
111
112 if ( is_feed() || is_robots() || is_trackback() || is_preview() )
113 return;
114
115 // Should we be counting this user's views?
116 if ( !empty( $current_user->ID ) ) {
117 $count_roles = stats_get_option( 'count_roles' );
118 if ( ! array_intersect( $current_user->roles, $count_roles ) )
119 return;
120 }
121
122 add_action( 'wp_footer', 'stats_footer', 101 );
123 add_action( 'wp_head', 'stats_add_shutdown_action' );
124
125 $script = set_url_scheme( '//stats.wp.com/e-' . gmdate( 'YW' ) . '.js' );
126 $data = stats_build_view_data();
127 $data_stats_array = stats_array( $data );
128
129 $stats_footer = <<<END
130 <script type='text/javascript' src='{$script}' async defer></script>
131 <script type='text/javascript'>
132 _stq = window._stq || [];
133 _stq.push([ 'view', {{$data_stats_array}} ]);
134 _stq.push([ 'clickTrackerInit', '{$data['blog']}', '{$data['post']}' ]);
135 </script>
136
137 END;
138 }
139
140 function stats_build_view_data() {
141 global $wp_the_query;
142
143 $blog = Jetpack_Options::get_option( 'id' );
144 $tz = get_option( 'gmt_offset' );
145 $v = 'ext';
146 $blog_url = parse_url( site_url() );
147 $srv = $blog_url['host'];
148 $j = sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION );
149 if ( $wp_the_query->is_single || $wp_the_query->is_page || $wp_the_query->is_posts_page ) {
150 // Store and reset the queried_object and queried_object_id
151 // Otherwise, redirect_canonical() will redirect to home_url( '/' ) for show_on_front = page sites where home_url() is not all lowercase.
152 // Repro:
153 // 1. Set home_url = http://ExamPle.com/
154 // 2. Set show_on_front = page
155 // 3. Set page_on_front = something
156 // 4. Visit http://example.com/
157
158 $queried_object = ( isset( $wp_the_query->queried_object ) ) ? $wp_the_query->queried_object : null;
159 $queried_object_id = ( isset( $wp_the_query->queried_object_id ) ) ? $wp_the_query->queried_object_id : null;
160 $post = $wp_the_query->get_queried_object_id();
161 $wp_the_query->queried_object = $queried_object;
162 $wp_the_query->queried_object_id = $queried_object_id;
163 } else {
164 $post = '0';
165 }
166
167 return compact( 'v', 'j', 'blog', 'post', 'tz', 'srv' );
168 }
169
170 function stats_add_shutdown_action() {
171 // just in case wp_footer isn't in your theme
172 add_action( 'shutdown', 'stats_footer', 101 );
173 }
174
175 function stats_footer() {
176 global $stats_footer;
177 print $stats_footer;
178 $stats_footer = '';
179 }
180
181 function stats_get_options() {
182 $options = get_option( 'stats_options' );
183
184 if ( ! isset( $options['version'] ) || $options['version'] < STATS_VERSION ) {
185 $options = stats_upgrade_options( $options );
186 }
187
188 return $options;
189 }
190
191 function stats_get_option( $option ) {
192 $options = stats_get_options();
193
194 if ( $option == 'blog_id' )
195 return Jetpack_Options::get_option( 'id' );
196
197 if ( isset( $options[$option] ) )
198 return $options[$option];
199
200 return null;
201 }
202
203 function stats_set_option( $option, $value ) {
204 $options = stats_get_options();
205
206 $options[$option] = $value;
207
208 return stats_set_options($options);
209 }
210
211 function stats_set_options($options) {
212 return update_option( 'stats_options', $options );
213 }
214
215 function stats_upgrade_options( $options ) {
216 $defaults = array(
217 'admin_bar' => true,
218 'roles' => array( 'administrator' ),
219 'count_roles' => array(),
220 'blog_id' => Jetpack_Options::get_option( 'id' ),
221 'do_not_track' => true, // @todo
222 'hide_smile' => true,
223 );
224
225 if ( isset( $options['reg_users'] ) ) {
226 if ( ! function_exists( 'get_editable_roles' ) )
227 require_once( ABSPATH . 'wp-admin/includes/user.php' );
228 if ( $options['reg_users'] )
229 $options['count_roles'] = array_keys( get_editable_roles() );
230 unset( $options['reg_users'] );
231 }
232
233 if ( is_array( $options ) && !empty( $options ) )
234 $new_options = array_merge( $defaults, $options );
235 else
236 $new_options = $defaults;
237
238 $new_options['version'] = STATS_VERSION;
239
240 if ( ! stats_set_options( $new_options ) ) {
241 return false;
242 }
243
244 stats_update_blog();
245
246 return $new_options;
247 }
248
249 function stats_array( $kvs ) {
250 /**
251 * Filter the options added to the JavaScript Stats tracking code.
252 *
253 * @module stats
254 *
255 * @since 1.1.0
256 *
257 * @param array $kvs Array of options about the site and page you're on.
258 */
259 $kvs = apply_filters( 'stats_array', $kvs );
260 $kvs = array_map( 'addslashes', $kvs );
261 foreach ( $kvs as $k => $v )
262 $jskvs[] = "$k:'$v'";
263 return join( ',', $jskvs );
264 }
265
266 /**
267 * Admin Pages
268 */
269 function stats_admin_menu() {
270 global $pagenow;
271
272 // If we're at an old Stats URL, redirect to the new one.
273 // Don't even bother with caps, menu_page_url(), etc. Just do it.
274 if ( 'index.php' == $pagenow && isset( $_GET['page'] ) && 'stats' == $_GET['page'] ) {
275 $redirect_url = str_replace( array( '/wp-admin/index.php?', '/wp-admin/?' ), '/wp-admin/admin.php?', $_SERVER['REQUEST_URI'] );
276 $relative_pos = strpos( $redirect_url, '/wp-admin/' );
277 if ( false !== $relative_pos ) {
278 wp_safe_redirect( admin_url( substr( $redirect_url, $relative_pos + 10 ) ) );
279 exit;
280 }
281 }
282
283 $hook = add_submenu_page( 'jetpack', __( 'Site Stats', 'jetpack' ), __( 'Site Stats', 'jetpack' ), 'view_stats', 'stats', 'stats_reports_page' );
284 add_action( "load-$hook", 'stats_reports_load' );
285 }
286
287 function stats_admin_path() {
288 return Jetpack::module_configuration_url( __FILE__ );
289 }
290
291 function stats_reports_load() {
292 wp_enqueue_script( 'jquery' );
293 wp_enqueue_script( 'postbox' );
294 wp_enqueue_script( 'underscore' );
295
296 add_action( 'admin_print_styles', 'stats_reports_css' );
297
298 if ( isset( $_GET['nojs'] ) && $_GET['nojs'] ) {
299 $parsed = parse_url( admin_url() );
300 // Remember user doesn't want JS
301 setcookie( 'stnojs', '1', time() + 172800, $parsed['path'] ); // 2 days
302 }
303
304 if ( isset( $_COOKIE['stnojs'] ) && $_COOKIE['stnojs'] ) {
305 // Detect if JS is on. If so, remove cookie so next page load is via JS
306 add_action( 'admin_print_footer_scripts', 'stats_js_remove_stnojs_cookie' );
307 } else if ( !isset( $_GET['noheader'] ) && empty( $_GET['nojs'] ) ) {
308 // Normal page load. Load page content via JS.
309 add_action( 'admin_print_footer_scripts', 'stats_js_load_page_via_ajax' );
310 }
311 }
312
313 function stats_reports_css() {
314 ?>
315 <style type="text/css">
316 #stats-loading-wrap p {
317 text-align: center;
318 font-size: 2em;
319 margin: 7.5em 15px 0 0;
320 height: 64px;
321 line-height: 64px;
322 }
323 </style>
324 <?php
325 }
326
327 // Detect if JS is on. If so, remove cookie so next page load is via JS.
328 function stats_js_remove_stnojs_cookie() {
329 $parsed = parse_url( admin_url() );
330 ?>
331 <script type="text/javascript">
332 /* <![CDATA[ */
333 document.cookie = 'stnojs=0; expires=Wed, 9 Mar 2011 16:55:50 UTC; path=<?php echo esc_js( $parsed['path'] ); ?>';
334 /* ]]> */
335 </script>
336 <?php
337 }
338
339 // Normal page load. Load page content via JS.
340 function stats_js_load_page_via_ajax() {
341 ?>
342 <script type="text/javascript">
343 /* <![CDATA[ */
344 if ( -1 == document.location.href.indexOf( 'noheader' ) ) {
345 jQuery( function( $ ) {
346 $.get( document.location.href + '&noheader', function( responseText ) {
347 $( '#stats-loading-wrap' ).replaceWith( responseText );
348 } );
349 } );
350 }
351 /* ]]> */
352 </script>
353 <?php
354 }
355
356 function stats_reports_page( $main_chart_only = false ) {
357 if ( isset( $_GET['dashboard'] ) )
358 return stats_dashboard_widget_content();
359
360 $blog_id = stats_get_option( 'blog_id' );
361 $domain = Jetpack::build_raw_urls( get_home_url() );
362
363 if ( ! $main_chart_only && !isset( $_GET['noheader'] ) && empty( $_GET['nojs'] ) && empty( $_COOKIE['stnojs'] ) ) {
364 $nojs_url = add_query_arg( 'nojs', '1' );
365 $http = is_ssl() ? 'https' : 'http';
366 // Loading message
367 // No JS fallback message
368 ?>
369 <div class="wrap">
370 <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>
371 </div>
372 <div id="stats-loading-wrap" class="wrap">
373 <p class="hide-if-no-js"><img width="32" height="32" alt="<?php esc_attr_e( 'Loading&hellip;', 'jetpack' ); ?>" src="<?php
374 echo esc_url(
375 /**
376 * Sets external resource URL.
377 *
378 * @module stats
379 *
380 * @since 1.4.0
381 *
382 * @param string $args URL of external resource.
383 */
384 apply_filters( 'jetpack_static_url', "{$http}://en.wordpress.com/i/loading/loading-64.gif" )
385 ); ?>" /></p>
386 <p style="font-size: 11pt; margin: 0;"><a href="https://wordpress.com/stats/<?php echo $domain; ?>" target="_blank"><?php esc_html_e( 'View stats on WordPress.com right now', 'jetpack' ); ?></a></p>
387 <p class="hide-if-js"><?php esc_html_e( 'Your Site Stats work better with JavaScript enabled.', 'jetpack' ); ?><br />
388 <a href="<?php echo esc_url( $nojs_url ); ?>"><?php esc_html_e( 'View Site Stats without JavaScript', 'jetpack' ); ?></a>.</p>
389 </div>
390 <?php
391 return;
392 }
393
394 $day = isset( $_GET['day'] ) && preg_match( '/^\d{4}-\d{2}-\d{2}$/', $_GET['day'] ) ? $_GET['day'] : false;
395 $q = array(
396 'noheader' => 'true',
397 'proxy' => '',
398 'page' => 'stats',
399 'day' => $day,
400 'blog' => $blog_id,
401 'charset' => get_option( 'blog_charset' ),
402 'color' => get_user_option( 'admin_color' ),
403 'ssl' => is_ssl(),
404 'j' => sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION ),
405 );
406 if ( get_locale() !== 'en_US' ) {
407 $q['jp_lang'] = get_locale();
408 }
409 // Only show the main chart, without extra header data, or metaboxes.
410 $q['main_chart_only'] = $main_chart_only;
411 $args = array(
412 'view' => array( 'referrers', 'postviews', 'searchterms', 'clicks', 'post', 'table' ),
413 'numdays' => 'int',
414 'day' => 'date',
415 'unit' => array( 1, 7, 31, 'human' ),
416 'humanize' => array( 'true' ),
417 'num' => 'int',
418 'summarize' => null,
419 'post' => 'int',
420 'width' => 'int',
421 'height' => 'int',
422 'data' => 'data',
423 'blog_subscribers' => 'int',
424 'comment_subscribers' => null,
425 'type' => array( 'wpcom', 'email', 'pending' ),
426 'pagenum' => 'int',
427 );
428 foreach ( $args as $var => $vals ) {
429 if ( !isset( $_REQUEST[$var] ) )
430 continue;
431 if ( is_array( $vals ) ) {
432 if ( in_array( $_REQUEST[$var], $vals ) )
433 $q[$var] = $_REQUEST[$var];
434 } elseif ( $vals == 'int' ) {
435 $q[$var] = intval( $_REQUEST[$var] );
436 } elseif ( $vals == 'date' ) {
437 if ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', $_REQUEST[$var] ) )
438 $q[$var] = $_REQUEST[$var];
439 } elseif ( $vals == null ) {
440 $q[$var] = '';
441 } elseif ( $vals == 'data' ) {
442 if ( substr( $_REQUEST[$var], 0, 9 ) == 'index.php' )
443 $q[$var] = $_REQUEST[$var];
444 }
445 }
446
447 if ( isset( $_GET['chart'] ) ) {
448 if ( preg_match( '/^[a-z0-9-]+$/', $_GET['chart'] ) ) {
449 $chart = sanitize_title( $_GET['chart'] );
450 $url = 'https://' . STATS_DASHBOARD_SERVER . "/wp-includes/charts/{$chart}.php";
451 }
452 } else {
453 $url = 'https://' . STATS_DASHBOARD_SERVER . "/wp-admin/index.php";
454 }
455
456 $url = add_query_arg( $q, $url );
457 $method = 'GET';
458 $timeout = 90;
459 $user_id = JETPACK_MASTER_USER; // means send the wp.com user_id
460
461 $get = Jetpack_Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
462 $get_code = wp_remote_retrieve_response_code( $get );
463 if ( is_wp_error( $get ) || ( 2 != intval( $get_code / 100 ) && 304 != $get_code ) || empty( $get['body'] ) ) {
464 stats_print_wp_remote_error( $get, $url );
465 } else {
466 if ( !empty( $get['headers']['content-type'] ) ) {
467 $type = $get['headers']['content-type'];
468 if ( substr( $type, 0, 5 ) == 'image' ) {
469 $img = $get['body'];
470 header( 'Content-Type: ' . $type );
471 header( 'Content-Length: ' . strlen( $img ) );
472 echo $img;
473 die();
474 }
475 }
476 $body = stats_convert_post_titles( $get['body'] );
477 $body = stats_convert_chart_urls( $body );
478 $body = stats_convert_image_urls( $body );
479 $body = stats_convert_admin_urls( $body );
480 echo $body;
481 }
482
483 if ( isset( $_GET['page'] ) && 'stats' === $_GET['page'] && ! isset( $_GET['chart'] ) ) {
484 JetpackTracking::record_user_event( 'wpa_page_view', array( 'path' => 'old_stats' ) );
485 }
486
487 if ( isset( $_GET['noheader'] ) )
488 die;
489 }
490
491 function stats_convert_admin_urls( $html ) {
492 return str_replace( 'index.php?page=stats', 'admin.php?page=stats', $html );
493 }
494
495 function stats_convert_image_urls( $html ) {
496 $url = set_url_scheme( 'https://' . STATS_DASHBOARD_SERVER );
497 $html = preg_replace( '|(["\'])(/i/stats.+)\\1|', '$1' . $url . '$2$1', $html );
498 return $html;
499 }
500
501 function stats_convert_chart_urls( $html ) {
502 $html = preg_replace_callback( '|https?://[-.a-z0-9]+/wp-includes/charts/([-.a-z0-9]+).php(\??)|',
503 create_function(
504 '$matches',
505 // If there is a query string, change the beginning '?' to a '&' so it fits into the middle of this query string
506 'return "admin.php?page=stats&noheader&chart=" . $matches[1] . str_replace( "?", "&", $matches[2] );'
507 ),
508 $html );
509 return $html;
510 }
511
512 function stats_convert_post_titles( $html ) {
513 global $wpdb, $stats_posts;
514 $pattern = "<span class='post-(\d+)-link'>.*?</span>";
515 if ( !preg_match_all( "!$pattern!", $html, $matches ) )
516 return $html;
517 $posts = get_posts( array(
518 'include' => implode( ',', $matches[1] ),
519 'post_type' => 'any',
520 'post_status' => 'any',
521 'numberposts' => -1,
522 ));
523 foreach ( $posts as $post )
524 $stats_posts[$post->ID] = $post;
525 $html = preg_replace_callback( "!$pattern!", 'stats_convert_post_title', $html );
526 return $html;
527 }
528
529 function stats_convert_post_title( $matches ) {
530 global $stats_posts;
531 $post_id = $matches[1];
532 if ( isset( $stats_posts[$post_id] ) )
533 return '<a href="' . get_permalink( $post_id ) . '" target="_blank">' . get_the_title( $post_id ) . '</a>';
534 return $matches[0];
535 }
536
537 function stats_configuration_load() {
538 if ( isset( $_POST['action'] ) && $_POST['action'] == 'save_options' && $_POST['_wpnonce'] == wp_create_nonce( 'stats' ) ) {
539 $options = stats_get_options();
540 $options['admin_bar'] = isset( $_POST['admin_bar'] ) && $_POST['admin_bar'];
541 $options['hide_smile'] = isset( $_POST['hide_smile'] ) && $_POST['hide_smile'];
542
543 $options['roles'] = array( 'administrator' );
544 foreach ( get_editable_roles() as $role => $details )
545 if ( isset( $_POST["role_$role"] ) && $_POST["role_$role"] )
546 $options['roles'][] = $role;
547
548 $options['count_roles'] = array();
549 foreach ( get_editable_roles() as $role => $details )
550 if ( isset( $_POST["count_role_$role"] ) && $_POST["count_role_$role"] )
551 $options['count_roles'][] = $role;
552
553 stats_set_options( $options );
554 stats_update_blog();
555 Jetpack::state( 'message', 'module_configured' );
556 wp_safe_redirect( Jetpack::module_configuration_url( 'stats' ) );
557 exit;
558 }
559 }
560
561 function stats_configuration_head() {
562 ?>
563 <style type="text/css">
564 #statserror {
565 border: 1px solid #766;
566 background-color: #d22;
567 padding: 1em 3em;
568 }
569 .stats-smiley {
570 vertical-align: 1px;
571 }
572 </style>
573 <?php
574 }
575
576 function stats_configuration_screen() {
577 $options = stats_get_options();
578 ?>
579 <div class="narrow">
580 <p><?php printf( __( 'Visit <a href="%s">Site Stats</a> to see your stats.', 'jetpack' ), esc_url( menu_page_url( 'stats', false ) ) ); ?></p>
581 <form method="post">
582 <input type='hidden' name='action' value='save_options' />
583 <?php wp_nonce_field( 'stats' ); ?>
584 <table id="menu" class="form-table">
585 <tr valign="top"><th scope="row"><label for="admin_bar"><?php _e( 'Admin bar' , 'jetpack' ); ?></label></th>
586 <td><label><input type='checkbox'<?php checked( $options['admin_bar'] ); ?> name='admin_bar' id='admin_bar' /> <?php _e( "Put a chart showing 48 hours of views in the admin bar.", 'jetpack' ); ?></label></td></tr>
587 <tr valign="top"><th scope="row"><?php _e( 'Registered users', 'jetpack' ); ?></th>
588 <td>
589 <?php _e( "Count the page views of registered users who are logged in.", 'jetpack' ); ?><br/>
590 <?php
591 $count_roles = stats_get_option( 'count_roles' );
592 foreach ( get_editable_roles() as $role => $details ) {
593 ?>
594 <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/>
595 <?php
596 }
597 ?>
598 </td></tr>
599 <tr valign="top"><th scope="row"><?php _e( 'Smiley' , 'jetpack' ); ?></th>
600 <td><label><input type='checkbox'<?php checked( isset( $options['hide_smile'] ) && $options['hide_smile'] ); ?> name='hide_smile' id='hide_smile' /> <?php _e( 'Hide the stats smiley face image.', 'jetpack' ); ?></label><br /> <span class="description"><?php _e( 'The image helps collect stats and <strong>makes the world a better place</strong> but should still work when hidden', 'jetpack' ); ?> <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>
601 <tr valign="top"><th scope="row"><?php _e( 'Report visibility' , 'jetpack' ); ?></th>
602 <td>
603 <?php _e( 'Select the roles that will be able to view stats reports.', 'jetpack' ); ?><br/>
604 <?php
605 $stats_roles = stats_get_option( 'roles' );
606 foreach ( get_editable_roles() as $role => $details ) {
607 ?>
608 <label><input type='checkbox' <?php if ( $role == 'administrator' ) echo "disabled='disabled' "; ?>name='role_<?php echo $role; ?>'<?php checked( $role == 'administrator' || in_array( $role, $stats_roles ) ); ?> /> <?php echo translate_user_role( $details['name'] ); ?></label><br/>
609 <?php
610 }
611 ?>
612 </td></tr>
613 </table>
614 <p class="submit"><input type='submit' class='button-primary' value='<?php echo esc_attr( __( 'Save configuration', 'jetpack' ) ); ?>' /></p>
615 </form>
616 </div>
617 <?php
618 }
619
620 function stats_hide_smile_css() {
621 $options = stats_get_options();
622 if ( isset( $options['hide_smile'] ) && $options['hide_smile'] ) {
623 ?>
624 <style type='text/css'>img#wpstats{display:none}</style><?php
625 }
626 }
627
628 function stats_admin_bar_head() {
629 if ( !stats_get_option( 'admin_bar' ) )
630 return;
631
632 if ( !current_user_can( 'view_stats' ) )
633 return;
634
635 if ( function_exists( 'is_admin_bar_showing' ) && !is_admin_bar_showing() ) {
636 return;
637 }
638
639 add_action( 'admin_bar_menu', 'stats_admin_bar_menu', 100 );
640 ?>
641
642 <style type='text/css'>
643 #wpadminbar .quicklinks li#wp-admin-bar-stats {
644 height: 28px;
645 }
646 #wpadminbar .quicklinks li#wp-admin-bar-stats a {
647 height: 28px;
648 padding: 0;
649 }
650 #wpadminbar .quicklinks li#wp-admin-bar-stats a div {
651 height: 28px;
652 width: 95px;
653 overflow: hidden;
654 margin: 0 10px;
655 }
656 #wpadminbar .quicklinks li#wp-admin-bar-stats a:hover div {
657 width: auto;
658 margin: 0 8px 0 10px;
659 }
660 #wpadminbar .quicklinks li#wp-admin-bar-stats a img {
661 height: 24px;
662 padding: 2px 0;
663 max-width: none;
664 border: none;
665 }
666 </style>
667 <?php
668 }
669
670 function stats_admin_bar_menu( &$wp_admin_bar ) {
671 $url = add_query_arg( 'page', 'stats', admin_url( 'admin.php' ) ); // no menu_page_url() blog-side.
672
673 $img_src = esc_attr( add_query_arg( array( 'noheader'=>'', 'proxy'=>'', 'chart'=>'admin-bar-hours-scale' ), $url ) );
674 $img_src_2x = esc_attr( add_query_arg( array( 'noheader'=>'', 'proxy'=>'', 'chart'=>'admin-bar-hours-scale-2x' ), $url ) );
675
676 $alt = esc_attr( __( 'Stats', 'jetpack' ) );
677
678 $title = esc_attr( __( 'Views over 48 hours. Click for more Site Stats.', 'jetpack' ) );
679
680 $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 );
681
682 $wp_admin_bar->add_menu( $menu );
683 }
684
685 function stats_update_blog() {
686 Jetpack::xmlrpc_async_call( 'jetpack.updateBlog', stats_get_blog() );
687 }
688
689 function stats_get_blog() {
690 $home = parse_url( trailingslashit( get_option( 'home' ) ) );
691 $blog = array(
692 'host' => $home['host'],
693 'path' => $home['path'],
694 'blogname' => get_option( 'blogname' ),
695 'blogdescription' => get_option( 'blogdescription' ),
696 'siteurl' => get_option( 'siteurl' ),
697 'gmt_offset' => get_option( 'gmt_offset' ),
698 'timezone_string' => get_option( 'timezone_string' ),
699 'stats_version' => STATS_VERSION,
700 'stats_api' => 'jetpack',
701 'page_on_front' => get_option( 'page_on_front' ),
702 'permalink_structure' => get_option( 'permalink_structure' ),
703 'category_base' => get_option( 'category_base' ),
704 'tag_base' => get_option( 'tag_base' ),
705 );
706 $blog = array_merge( stats_get_options(), $blog );
707 unset( $blog['roles'], $blog['blog_id'] );
708 return stats_esc_html_deep( $blog );
709 }
710
711 /**
712 * Modified from stripslashes_deep()
713 */
714 function stats_esc_html_deep( $value ) {
715 if ( is_array( $value ) ) {
716 $value = array_map( 'stats_esc_html_deep', $value );
717 } elseif ( is_object( $value ) ) {
718 $vars = get_object_vars( $value );
719 foreach ( $vars as $key => $data ) {
720 $value->{$key} = stats_esc_html_deep( $data );
721 }
722 } elseif ( is_string( $value ) ) {
723 $value = esc_html( $value );
724 }
725
726 return $value;
727 }
728
729 function stats_xmlrpc_methods( $methods ) {
730 $my_methods = array(
731 'jetpack.getBlog' => 'stats_get_blog',
732 );
733
734 return array_merge( $methods, $my_methods );
735 }
736
737 function stats_register_dashboard_widget() {
738 if ( ! current_user_can( 'view_stats' ) )
739 return;
740
741 // wp_dashboard_empty: we load in the content after the page load via JS
742 wp_add_dashboard_widget( 'dashboard_stats', __( 'Site Stats', 'jetpack' ), 'wp_dashboard_empty', 'stats_dashboard_widget_control' );
743
744 add_action( 'admin_head', 'stats_dashboard_head' );
745 }
746
747 function stats_dashboard_widget_options() {
748 $defaults = array( 'chart' => 1, 'top' => 1, 'search' => 7 );
749 if ( ( !$options = get_option( 'stats_dashboard_widget' ) ) || !is_array( $options ) )
750 $options = array();
751
752 // Ignore obsolete option values
753 $intervals = array( 1, 7, 31, 90, 365 );
754 foreach ( array( 'top', 'search' ) as $key )
755 if ( isset( $options[$key] ) && !in_array( $options[$key], $intervals ) )
756 unset( $options[$key] );
757
758 return array_merge( $defaults, $options );
759 }
760
761 function stats_dashboard_widget_control() {
762 $periods = array(
763 '1' => __( 'day', 'jetpack' ),
764 '7' => __( 'week', 'jetpack' ),
765 '31' => __( 'month', 'jetpack' ),
766 );
767 $intervals = array(
768 '1' => __( 'the past day', 'jetpack' ),
769 '7' => __( 'the past week', 'jetpack' ),
770 '31' => __( 'the past month', 'jetpack' ),
771 '90' => __( 'the past quarter', 'jetpack' ),
772 '365' => __( 'the past year', 'jetpack' ),
773 );
774 $defaults = array(
775 'top' => 1,
776 'search' => 7,
777 );
778
779 $options = stats_dashboard_widget_options();
780
781 if ( 'post' == strtolower( $_SERVER['REQUEST_METHOD'] ) && isset( $_POST['widget_id'] ) && 'dashboard_stats' == $_POST['widget_id'] ) {
782 if ( isset( $periods[ $_POST['chart'] ] ) )
783 $options['chart'] = $_POST['chart'];
784 foreach ( array( 'top', 'search' ) as $key ) {
785 if ( isset( $intervals[ $_POST[$key] ] ) )
786 $options[$key] = $_POST[$key];
787 else
788 $options[$key] = $defaults[$key];
789 }
790 update_option( 'stats_dashboard_widget', $options );
791 }
792 ?>
793 <p>
794 <label for="chart"><?php _e( 'Chart stats by' , 'jetpack' ); ?></label>
795 <select id="chart" name="chart">
796 <?php
797 foreach ( $periods as $val => $label ) {
798 ?>
799 <option value="<?php echo $val; ?>"<?php selected( $val, $options['chart'] ); ?>><?php echo esc_html( $label ); ?></option>
800 <?php
801 }
802 ?>
803 </select>.
804 </p>
805
806 <p>
807 <label for="top"><?php _e( 'Show top posts over', 'jetpack' ); ?></label>
808 <select id="top" name="top">
809 <?php
810 foreach ( $intervals as $val => $label ) {
811 ?>
812 <option value="<?php echo $val; ?>"<?php selected( $val, $options['top'] ); ?>><?php echo esc_html( $label ); ?></option>
813 <?php
814 }
815 ?>
816 </select>.
817 </p>
818
819 <p>
820 <label for="search"><?php _e( 'Show top search terms over', 'jetpack' ); ?></label>
821 <select id="search" name="search">
822 <?php
823 foreach ( $intervals as $val => $label ) {
824 ?>
825 <option value="<?php echo $val; ?>"<?php selected( $val, $options['search'] ); ?>><?php echo esc_html( $label ); ?></option>
826 <?php
827 }
828 ?>
829 </select>.
830 </p>
831 <?php
832 }
833
834 function stats_jetpack_dashboard_widget() {
835 ?>
836 <form id="stats_dashboard_widget_control" action="<?php echo esc_url( admin_url() ); ?>" method="post">
837 <?php stats_dashboard_widget_control(); ?>
838 <?php wp_nonce_field( 'edit-dashboard-widget_dashboard_stats', 'dashboard-widget-nonce' ); ?>
839 <input type="hidden" name="widget_id" value="dashboard_stats" />
840 <?php submit_button( __( 'Submit', 'jetpack' ) ); ?>
841 </form>
842 <span id="js-toggle-stats_dashboard_widget_control">
843 <?php esc_html_e( 'Configure', 'jetpack' ); ?>
844 </span>
845 <div id="dashboard_stats">
846 <div class="inside">
847 <div style="height: 250px;"></div>
848 </div>
849 </div>
850 <script>
851 jQuery(document).ready(function($){
852 var $toggle = $('#js-toggle-stats_dashboard_widget_control');
853
854 $toggle.parent().prev().append( $toggle );
855 $toggle.show().click(function(e){
856 e.preventDefault();
857 e.stopImmediatePropagation();
858 $(this).parent().toggleClass('controlVisible');
859 $('#stats_dashboard_widget_control').slideToggle();
860 });
861 });
862 </script>
863 <style>
864 #js-toggle-stats_dashboard_widget_control {
865 display: none;
866 float: right;
867 margin-top: 0.2em;
868 font-weight: 400;
869 color: #444;
870 font-size: .8em;
871 text-decoration: underline;
872 cursor: pointer;
873 }
874 #stats_dashboard_widget_control {
875 display: none;
876 padding: 0 10px;
877 overflow: hidden;
878 }
879 #stats_dashboard_widget_control .button-primary {
880 float: right;
881 }
882 #dashboard_stats {
883 box-sizing: border-box;
884 width: 100%;
885 padding: 0 10px;
886 }
887 </style>
888 <?php
889 }
890
891 function stats_register_widget_control_callback() {
892 $GLOBALS['wp_dashboard_control_callbacks']['dashboard_stats'] = 'stats_dashboard_widget_control';
893 }
894 // JavaScript and CSS for dashboard widget
895 function stats_dashboard_head() { ?>
896 <script type="text/javascript">
897 /* <![CDATA[ */
898 jQuery( function($) {
899 var dashStats = jQuery( '#dashboard_stats div.inside' );
900
901 if ( dashStats.find( '.dashboard-widget-control-form' ).length ) {
902 return;
903 }
904
905 if ( ! dashStats.length ) {
906 dashStats = jQuery( '#dashboard_stats div.dashboard-widget-content' );
907 var h = parseInt( dashStats.parent().height() ) - parseInt( dashStats.prev().height() );
908 var args = 'width=' + dashStats.width() + '&height=' + h.toString();
909 } else {
910 if ( jQuery('#dashboard_stats' ).hasClass('postbox') ) {
911 var args = 'width=' + ( dashStats.prev().width() * 2 ).toString();
912 } else {
913 var args = 'width=' + ( dashStats.width() * 2 ).toString();
914 }
915 }
916
917 dashStats
918 .not( '.dashboard-widget-control' )
919 .load( 'admin.php?page=stats&noheader&dashboard&' + args );
920
921 jQuery( window ).one( 'resize', function() {
922 jQuery( '#stat-chart' ).css( 'width', 'auto' );
923 } );
924 } );
925 /* ]]> */
926 </script>
927 <style type="text/css">
928 /* <![CDATA[ */
929 #stat-chart {
930 background: none !important;
931 }
932 #dashboard_stats .inside {
933 margin: 10px 0 0 0 !important;
934 }
935 #dashboard_stats #stats-graph {
936 margin: 0;
937 }
938 #stats-info {
939 border-top: 1px solid #dfdfdf;
940 margin: 7px -10px 0 -10px;
941 padding: 10px;
942 background: #fcfcfc;
943 -moz-box-shadow:inset 0 1px 0 #fff;
944 -webkit-box-shadow:inset 0 1px 0 #fff;
945 box-shadow:inset 0 1px 0 #fff;
946 overflow: hidden;
947 border-radius: 0 0 2px 2px;
948 -webkit-border-radius: 0 0 2px 2px;
949 -moz-border-radius: 0 0 2px 2px;
950 -khtml-border-radius: 0 0 2px 2px;
951 }
952 #stats-info #top-posts, #stats-info #top-search {
953 float: left;
954 width: 50%;
955 }
956 #top-posts .stats-section-inner p {
957 white-space: nowrap;
958 overflow: hidden;
959 }
960 #top-posts .stats-section-inner p a {
961 overflow: hidden;
962 text-overflow: ellipsis;
963 }
964 #stats-info div#active {
965 border-top: 1px solid #dfdfdf;
966 margin: 0 -10px;
967 padding: 10px 10px 0 10px;
968 -moz-box-shadow:inset 0 1px 0 #fff;
969 -webkit-box-shadow:inset 0 1px 0 #fff;
970 box-shadow:inset 0 1px 0 #fff;
971 overflow: hidden;
972 }
973 #top-search p {
974 color: #999;
975 }
976 #stats-info h3 {
977 font-size: 1em;
978 margin: 0 0 .5em 0 !important;
979 }
980 #stats-info p {
981 margin: 0 0 .25em;
982 color: #999;
983 }
984 #stats-info p.widget-loading {
985 margin: 1em 0 0;
986 color: #333;
987 }
988 #stats-info p a {
989 display: block;
990 }
991 #stats-info p a.button {
992 display: inline;
993 }
994 /* ]]> */
995 </style>
996 <?php
997 }
998
999 function stats_dashboard_widget_content() {
1000 if ( !isset( $_GET['width'] ) || ( !$width = (int) ( $_GET['width'] / 2 ) ) || $width < 250 )
1001 $width = 370;
1002 if ( !isset( $_GET['height'] ) || ( !$height = (int) $_GET['height'] - 36 ) || $height < 230 )
1003 $height = 180;
1004
1005 $_width = $width - 5;
1006 $_height = $height - ( $GLOBALS['is_winIE'] ? 16 : 5 ); // hack!
1007
1008 $options = stats_dashboard_widget_options();
1009 $blog_id = Jetpack_Options::get_option( 'id' );
1010
1011 $q = array(
1012 'noheader' => 'true',
1013 'proxy' => '',
1014 'blog' => $blog_id,
1015 'page' => 'stats',
1016 'chart' => '',
1017 'unit' => $options['chart'],
1018 'color' => get_user_option( 'admin_color' ),
1019 'width' => $_width,
1020 'height' => $_height,
1021 'ssl' => is_ssl(),
1022 'j' => sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION ),
1023 );
1024
1025 $url = 'https://' . STATS_DASHBOARD_SERVER . "/wp-admin/index.php";
1026
1027 $url = add_query_arg( $q, $url );
1028 $method = 'GET';
1029 $timeout = 90;
1030 $user_id = JETPACK_MASTER_USER;
1031
1032 $get = Jetpack_Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
1033 $get_code = wp_remote_retrieve_response_code( $get );
1034 if ( is_wp_error( $get ) || ( 2 != intval( $get_code / 100 ) && 304 != $get_code ) || empty( $get['body'] ) ) {
1035 stats_print_wp_remote_error( $get, $url );
1036 } else {
1037 $body = stats_convert_post_titles($get['body']);
1038 $body = stats_convert_chart_urls($body);
1039 $body = stats_convert_image_urls($body);
1040 echo $body;
1041 }
1042
1043 $post_ids = array();
1044
1045 $csv_end_date = date( 'Y-m-d', current_time( 'timestamp' ) );
1046 $csv_args = array( 'top' => "&limit=8&end=$csv_end_date", 'search' => "&limit=5&end=$csv_end_date" );
1047 /* translators: Stats dashboard widget postviews list: "$post_title $views Views" */
1048 $printf = __( '%1$s %2$s Views' , 'jetpack' );
1049
1050 foreach ( $top_posts = stats_get_csv( 'postviews', "days=$options[top]$csv_args[top]" ) as $i => $post ) {
1051 if ( $post['post_id'] == 0 ) {
1052 unset( $top_posts[$i] );
1053 continue;
1054 }
1055 $post_ids[] = $post['post_id'];
1056 }
1057
1058 // cache
1059 get_posts( array( 'include' => join( ',', array_unique( $post_ids ) ) ) );
1060
1061 $searches = array();
1062 foreach ( $search_terms = stats_get_csv( 'searchterms', "days=$options[search]$csv_args[search]" ) as $search_term ) {
1063 if ( $search_term['searchterm'] == 'encrypted_search_terms' )
1064 continue;
1065 $searches[] = esc_html( $search_term['searchterm'] );
1066 }
1067
1068 ?>
1069 <a class="button" href="admin.php?page=stats"><?php _e( 'View All', 'jetpack' ); ?></a>
1070 <div id="stats-info">
1071 <div id="top-posts" class='stats-section'>
1072 <div class="stats-section-inner">
1073 <h3 class="heading"><?php _e( 'Top Posts' , 'jetpack' ); ?></h3>
1074 <?php
1075 if ( empty( $top_posts ) ) {
1076 ?>
1077 <p class="nothing"><?php _e( 'Sorry, nothing to report.', 'jetpack' ); ?></p>
1078 <?php
1079 } else {
1080 foreach ( $top_posts as $post ) {
1081 if ( !get_post( $post['post_id'] ) )
1082 continue;
1083 ?>
1084 <p><?php printf(
1085 $printf,
1086 '<a href="' . get_permalink( $post['post_id'] ) . '">' . get_the_title( $post['post_id'] ) . '</a>',
1087 number_format_i18n( $post['views'] )
1088 ); ?></p>
1089 <?php
1090 }
1091 }
1092 ?>
1093 </div>
1094 </div>
1095 <div id="top-search" class='stats-section'>
1096 <div class="stats-section-inner">
1097 <h3 class="heading"><?php _e( 'Top Searches' , 'jetpack' ); ?></h3>
1098 <?php
1099 if ( empty( $searches ) ) {
1100 ?>
1101 <p class="nothing"><?php _e( 'Sorry, nothing to report.', 'jetpack' ); ?></p>
1102 <?php
1103 } else {
1104 ?>
1105 <p><?php echo join( ',&nbsp; ', $searches );?></p>
1106 <?php
1107 }
1108 ?>
1109 </div>
1110 </div>
1111 </div>
1112 <div class="clear"></div>
1113 <?php
1114 exit;
1115 }
1116
1117 function stats_print_wp_remote_error( $get, $url ) {
1118 $state_name = 'stats_remote_error_' . substr( md5( $url ), 0, 8 );
1119 $previous_error = Jetpack::state( $state_name );
1120 $error = md5( serialize( compact( 'get', 'url' ) ) );
1121 Jetpack::state( $state_name, $error );
1122 if ( $error !== $previous_error ) {
1123 ?>
1124 <div class="wrap">
1125 <p><?php _e( 'We were unable to get your stats just now. Please reload this page to try again.', 'jetpack' ); ?></p>
1126 </div>
1127 <?php
1128 return;
1129 }
1130 ?>
1131 <div class="wrap">
1132 <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' ), 'http://support.wordpress.com/contact/?jetpack=needs-service' ); ?></p>
1133 <pre>
1134 User Agent: "<?php echo esc_html( $_SERVER['HTTP_USER_AGENT'] ); ?>"
1135 Page URL: "http<?php echo (is_ssl()?'s':'') . '://' . esc_html( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); ?>"
1136 API URL: "<?php echo esc_url( $url ); ?>"
1137 <?php
1138 if ( is_wp_error( $get ) ) {
1139 foreach ( $get->get_error_codes() as $code ) {
1140 foreach ( $get->get_error_messages($code) as $message ) {
1141 ?>
1142 <?php print $code . ': "' . $message . '"' ?>
1143
1144 <?php
1145 }
1146 }
1147 } else {
1148 $get_code = wp_remote_retrieve_response_code( $get );
1149 $content_length = strlen( wp_remote_retrieve_body( $get ) );
1150 ?>
1151 Response code: "<?php print $get_code ?>"
1152 Content length: "<?php print $content_length ?>"
1153
1154 <?php
1155 }
1156 ?></pre>
1157 </div>
1158 <?php
1159 }
1160
1161 /**
1162 * Get stats from WordPress.com
1163 *
1164 * @param string $table The stats which you want to retrieve: postviews, or searchterms
1165 * @param array $args {
1166 * An associative array of arguments.
1167 *
1168 * @type bool $end The last day of the desired time frame. Format is 'Y-m-d' (e.g. 2007-05-01)
1169 * and default timezone is UTC date. Default value is Now.
1170 * @type string $days The length of the desired time frame. Default is 30. Maximum 90 days.
1171 * @type int $limit The maximum number of records to return. Default is 10. Maximum 100.
1172 * @type int $post_id The ID of the post to retrieve stats data for
1173 * @type string $summarize If present, summarizes all matching records. Default Null.
1174 *
1175 * }
1176 *
1177 * @return array {
1178 * An array of post view data, each post as an array
1179 *
1180 * array {
1181 * The post view data for a single post
1182 *
1183 * @type string $post_id The ID of the post
1184 * @type string $post_title The title of the post
1185 * @type string $post_permalink The permalink for the post
1186 * @type string $views The number of views for the post within the $num_days specified
1187 * }
1188 * }
1189 */
1190 function stats_get_csv( $table, $args = null ) {
1191 $defaults = array( 'end' => false, 'days' => false, 'limit' => 3, 'post_id' => false, 'summarize' => '' );
1192
1193 $args = wp_parse_args( $args, $defaults );
1194 $args['table'] = $table;
1195 $args['blog_id'] = Jetpack_Options::get_option( 'id' );
1196
1197 $stats_csv_url = add_query_arg( $args, 'http://stats.wordpress.com/csv.php' );
1198
1199 $key = md5( $stats_csv_url );
1200
1201 // Get cache
1202 $stats_cache = get_option( 'stats_cache' );
1203 if ( !$stats_cache || !is_array( $stats_cache ) )
1204 $stats_cache = array();
1205
1206 // Return or expire this key
1207 if ( isset( $stats_cache[$key] ) ) {
1208 $time = key( $stats_cache[$key] );
1209 if ( time() - $time < 300 )
1210 return $stats_cache[$key][$time];
1211 unset( $stats_cache[$key] );
1212 }
1213
1214 $stats_rows = array();
1215 do {
1216 if ( !$stats = stats_get_remote_csv( $stats_csv_url ) )
1217 break;
1218
1219 $labels = array_shift( $stats );
1220
1221 if ( 0 === stripos( $labels[0], 'error' ) )
1222 break;
1223
1224 $stats_rows = array();
1225 for ( $s = 0; isset( $stats[$s] ); $s++ ) {
1226 $row = array();
1227 foreach ( $labels as $col => $label )
1228 $row[$label] = $stats[$s][$col];
1229 $stats_rows[] = $row;
1230 }
1231 } while( 0 );
1232
1233 // Expire old keys
1234 foreach ( $stats_cache as $k => $cache )
1235 if ( !is_array( $cache ) || 300 < time() - key($cache) )
1236 unset( $stats_cache[$k] );
1237
1238 // Set cache
1239 $stats_cache[$key] = array( time() => $stats_rows );
1240 update_option( 'stats_cache', $stats_cache );
1241
1242 return $stats_rows;
1243 }
1244
1245 function stats_get_remote_csv( $url ) {
1246 $method = 'GET';
1247 $timeout = 90;
1248 $user_id = JETPACK_MASTER_USER;
1249
1250 $get = Jetpack_Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
1251 $get_code = wp_remote_retrieve_response_code( $get );
1252 if ( is_wp_error( $get ) || ( 2 != intval( $get_code / 100 ) && 304 != $get_code ) || empty( $get['body'] ) ) {
1253 return array(); // @todo: return an error?
1254 } else {
1255 return stats_str_getcsv( $get['body'] );
1256 }
1257 }
1258
1259 // rather than parsing the csv and its special cases, we create a new file and do fgetcsv on it.
1260 function stats_str_getcsv( $csv ) {
1261 if ( function_exists( 'str_getcsv' ) ) {
1262 $lines = str_getcsv( $csv, "\n" );
1263 return array_map( 'str_getcsv', $lines );
1264 }
1265 if ( !$temp = tmpfile() ) // tmpfile() automatically unlinks
1266 return false;
1267
1268 $data = array();
1269
1270 fwrite( $temp, $csv, strlen( $csv ) );
1271 fseek( $temp, 0 );
1272 while ( false !== $row = fgetcsv( $temp, 2000 ) )
1273 $data[] = $row;
1274 fclose( $temp );
1275
1276 return $data;
1277 }
1278
1279 /**
1280 * Abstract out building the rest api stats path.
1281 *
1282 * @param string $resource
1283 * @return string
1284 */
1285 function jetpack_stats_api_path( $resource = '' ) {
1286 $resource = ltrim( $resource, '/' );
1287 return sprintf( '/sites/%d/stats/%s', stats_get_option( 'blog_id' ), $resource );
1288 }
1289
1290 /**
1291 * Fetches stats data from the REST API. Caches locally for 5 minutes.
1292 *
1293 * @link: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/
1294 *
1295 * @param array|string $args The args that are passed to the endpoint
1296 * @param string $resource Optional sub-endpoint following /stats/
1297 * @return array|WP_Error
1298 */
1299 function stats_get_from_restapi( $args = array(), $resource = '' ) {
1300 $endpoint = jetpack_stats_api_path( $resource );
1301 $api_version = '1.1';
1302 $args = wp_parse_args( $args, array() );
1303 $cache_key = md5( implode( '|', array( $endpoint, $api_version, serialize( $args ) ) ) );
1304
1305 // Get cache
1306 $stats_cache = Jetpack_Options::get_option( 'restapi_stats_cache', array() );
1307 if ( ! is_array( $stats_cache ) ) {
1308 $stats_cache = array();
1309 }
1310
1311 // Return or expire this key
1312 if ( isset( $stats_cache[ $cache_key ] ) ) {
1313 $time = key( $stats_cache[ $cache_key ] );
1314 if ( time() - $time < ( 5 * MINUTE_IN_SECONDS ) ) {
1315 $cached_stats = $stats_cache[ $cache_key ][ $time ];
1316 $cached_stats = (object) array_merge( array( 'cached_at' => $time ), (array) $cached_stats );
1317 return $cached_stats;
1318 }
1319 unset( $stats_cache[ $cache_key ] );
1320 }
1321
1322 // Do the dirty work.
1323 $response = Jetpack_Client::wpcom_json_api_request_as_blog( $endpoint, $api_version, $args );
1324 if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
1325 // If bad, just return it, don't cache.
1326 return $response;
1327 }
1328
1329 $data = json_decode( wp_remote_retrieve_body( $response ) );
1330
1331 // Expire old keys
1332 foreach ( $stats_cache as $k => $cache ) {
1333 if ( ! is_array( $cache ) || ( 5 * MINUTE_IN_SECONDS ) < time() - key( $cache ) ) {
1334 unset( $stats_cache[ $k ] );
1335 }
1336 }
1337
1338 // Set cache
1339 $stats_cache[ $cache_key ] = array(
1340 time() => $data,
1341 );
1342 Jetpack_Options::update_option( 'restapi_stats_cache', $stats_cache, false );
1343
1344 return $data;
1345 }
1346