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

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