PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 4.2.5
Jetpack – WP Security, Backup, Speed, & Growth v4.2.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.2.5, at modules/stats.php

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