PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 3.6.4
Jetpack – WP Security, Backup, Speed, & Growth v3.6.4
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 3.6.4, at modules/stats.php

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