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

1,824 lines 49.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 valuable traffic stats and insights.
5 * Sort Order: 1
6 * Recommendation Order: 2
7 * First Introduced: 1.1
8 * Requires Connection: Yes
9 * Auto Activate: Yes
10 * Module Tags: Site Stats, Recommended
11 * Feature: Engagement
12 * Additional Search Queries: statistics, tracking, analytics, views, traffic, stats
13 *
14 * @package Jetpack
15 */
16
17 if ( defined( 'STATS_VERSION' ) ) {
18 return;
19 }
20
21 define( 'STATS_VERSION', '9' );
22 defined( 'STATS_DASHBOARD_SERVER' ) or define( 'STATS_DASHBOARD_SERVER', 'dashboard.wordpress.com' );
23
24 add_action( 'jetpack_modules_loaded', 'stats_load' );
25
26 /**
27 * Load Stats.
28 *
29 * @access public
30 * @return void
31 */
32 function stats_load() {
33 Jetpack::enable_module_configurable( __FILE__ );
34 Jetpack::module_configuration_load( __FILE__, 'stats_configuration_load' );
35 Jetpack::module_configuration_head( __FILE__, 'stats_configuration_head' );
36 Jetpack::module_configuration_screen( __FILE__, 'stats_configuration_screen' );
37
38 // Generate the tracking code after wp() has queried for posts.
39 add_action( 'template_redirect', 'stats_template_redirect', 1 );
40
41 add_action( 'wp_head', 'stats_admin_bar_head', 100 );
42
43 add_action( 'wp_head', 'stats_hide_smile_css' );
44
45 add_action( 'jetpack_admin_menu', 'stats_admin_menu' );
46
47 // Map stats caps.
48 add_filter( 'map_meta_cap', 'stats_map_meta_caps', 10, 3 );
49
50 if ( isset( $_GET['oldwidget'] ) ) {
51 // Old one.
52 add_action( 'wp_dashboard_setup', 'stats_register_dashboard_widget' );
53 } else {
54 add_action( 'admin_init', 'stats_merged_widget_admin_init' );
55 }
56
57 add_filter( 'jetpack_xmlrpc_methods', 'stats_xmlrpc_methods' );
58
59 add_filter( 'pre_option_db_version', 'stats_ignore_db_version' );
60
61 // Add an icon to see stats in WordPress.com for a particular post
62 add_action( 'admin_print_styles-edit.php', 'jetpack_stats_load_admin_css' );
63 add_filter( 'manage_posts_columns', 'jetpack_stats_post_table' );
64 add_filter( 'manage_pages_columns', 'jetpack_stats_post_table' );
65 add_action( 'manage_posts_custom_column', 'jetpack_stats_post_table_cell', 10, 2 );
66 add_action( 'manage_pages_custom_column', 'jetpack_stats_post_table_cell', 10, 2 );
67 }
68
69 /**
70 * Delay conditional for current_user_can to after init.
71 *
72 * @access public
73 * @return void
74 */
75 function stats_merged_widget_admin_init() {
76 if ( current_user_can( 'view_stats' ) ) {
77 add_action( 'load-index.php', 'stats_enqueue_dashboard_head' );
78 add_action( 'wp_dashboard_setup', 'stats_register_widget_control_callback' ); // Hacky but works.
79 add_action( 'jetpack_dashboard_widget', 'stats_jetpack_dashboard_widget' );
80 }
81 }
82
83 /**
84 * Enqueue Stats Dashboard
85 *
86 * @access public
87 * @return void
88 */
89 function stats_enqueue_dashboard_head() {
90 add_action( 'admin_head', 'stats_dashboard_head' );
91 }
92
93 /**
94 * Checks if filter is set and dnt is enabled.
95 *
96 * @return bool
97 */
98 function jetpack_is_dnt_enabled() {
99 /**
100 * Filter the option which decides honor DNT or not.
101 *
102 * @module stats
103 * @since 6.1.0
104 *
105 * @param bool false Honors DNT for clients who don't want to be tracked. Defaults to false. Set to true to enable.
106 */
107 if ( false === apply_filters( 'jetpack_honor_dnt_header_for_stats', false ) ) {
108 return false;
109 }
110
111 foreach ( $_SERVER as $name => $value ) {
112 if ( 'http_dnt' == strtolower( $name ) && 1 == $value ) {
113 return true;
114 }
115 }
116
117 return false;
118 }
119
120 /**
121 * Prevent sparkline img requests being redirected to upgrade.php.
122 * See wp-admin/admin.php where it checks $wp_db_version.
123 *
124 * @access public
125 * @param mixed $version Version.
126 * @return string $version.
127 */
128 function stats_ignore_db_version( $version ) {
129 if (
130 is_admin() &&
131 isset( $_GET['page'] ) && 'stats' === $_GET['page'] &&
132 isset( $_GET['chart'] ) && strpos($_GET['chart'], 'admin-bar-hours') === 0
133 ) {
134 global $wp_db_version;
135 return $wp_db_version;
136 }
137 return $version;
138 }
139
140 /**
141 * Maps view_stats cap to read cap as needed.
142 *
143 * @access public
144 * @param mixed $caps Caps.
145 * @param mixed $cap Cap.
146 * @param mixed $user_id User ID.
147 * @return array Possibly mapped capabilities for meta capability.
148 */
149 function stats_map_meta_caps( $caps, $cap, $user_id ) {
150 // Map view_stats to exists.
151 if ( 'view_stats' === $cap ) {
152 $user = new WP_User( $user_id );
153 $user_role = array_shift( $user->roles );
154 $stats_roles = stats_get_option( 'roles' );
155
156 // Is the users role in the available stats roles?
157 if ( is_array( $stats_roles ) && in_array( $user_role, $stats_roles ) ) {
158 $caps = array( 'read' );
159 }
160 }
161
162 return $caps;
163 }
164
165 /**
166 * Stats Template Redirect.
167 *
168 * @access public
169 * @return void
170 */
171 function stats_template_redirect() {
172 global $current_user, $rendered_stats_footer;
173
174 if ( is_feed() || is_robots() || is_trackback() || is_preview() || jetpack_is_dnt_enabled() ) {
175 return;
176 }
177
178 // Should we be counting this user's views?
179 if ( ! empty( $current_user->ID ) ) {
180 $count_roles = stats_get_option( 'count_roles' );
181 if ( ! is_array( $count_roles ) || ! array_intersect( $current_user->roles, $count_roles ) ) {
182 return;
183 }
184 }
185
186 add_action( 'wp_footer', 'stats_footer', 101 );
187 add_action( 'wp_head', 'stats_add_shutdown_action' );
188
189 $rendered_stats_footer = false;
190 }
191
192
193 /**
194 * Stats Build View Data.
195 *
196 * @access public
197 * @return array.
198 */
199 function stats_build_view_data() {
200 global $wp_the_query;
201
202 $blog = Jetpack_Options::get_option( 'id' );
203 $tz = get_option( 'gmt_offset' );
204 $v = 'ext';
205 $blog_url = parse_url( site_url() );
206 $srv = $blog_url['host'];
207 $j = sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION );
208 if ( $wp_the_query->is_single || $wp_the_query->is_page || $wp_the_query->is_posts_page ) {
209 // Store and reset the queried_object and queried_object_id
210 // Otherwise, redirect_canonical() will redirect to home_url( '/' ) for show_on_front = page sites where home_url() is not all lowercase.
211 // Repro:
212 // 1. Set home_url = https://ExamPle.com/
213 // 2. Set show_on_front = page
214 // 3. Set page_on_front = something
215 // 4. Visit https://example.com/ !
216 $queried_object = ( isset( $wp_the_query->queried_object ) ) ? $wp_the_query->queried_object : null;
217 $queried_object_id = ( isset( $wp_the_query->queried_object_id ) ) ? $wp_the_query->queried_object_id : null;
218 $post = $wp_the_query->get_queried_object_id();
219 $wp_the_query->queried_object = $queried_object;
220 $wp_the_query->queried_object_id = $queried_object_id;
221 } else {
222 $post = '0';
223 }
224
225 return compact( 'v', 'j', 'blog', 'post', 'tz', 'srv' );
226 }
227
228 /**
229 * Stats Add Shutdown Action.
230 *
231 * @access public
232 * @return void
233 */
234 function stats_add_shutdown_action() {
235 // Just in case wp_footer isn't in your theme.
236 add_action( 'shutdown', 'stats_footer', 101 );
237 }
238
239 /**
240 * Stats Footer.
241 *
242 * @access public
243 * @return void
244 */
245 function stats_footer() {
246 global $rendered_stats_footer;
247
248 if ( ! $rendered_stats_footer ) {
249 $data = stats_build_view_data();
250 if ( Jetpack_AMP_Support::is_amp_request() ) {
251 stats_render_amp_footer( $data );
252 } else {
253 stats_render_footer( $data );
254 }
255 $rendered_stats_footer = true;
256 }
257 }
258
259 function stats_render_footer( $data ) {
260 $script = 'https://stats.wp.com/e-' . gmdate( 'YW' ) . '.js';
261 $data_stats_array = stats_array( $data );
262
263 $stats_footer = <<<END
264 <script type='text/javascript' src='{$script}' async='async' defer='defer'></script>
265 <script type='text/javascript'>
266 _stq = window._stq || [];
267 _stq.push([ 'view', {{$data_stats_array}} ]);
268 _stq.push([ 'clickTrackerInit', '{$data['blog']}', '{$data['post']}' ]);
269 </script>
270
271 END;
272 print $stats_footer;
273 }
274
275 function stats_render_amp_footer( $data ) {
276 $data['host'] = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : ''; // input var ok.
277 $data['rand'] = 'RANDOM'; // AMP placeholder.
278 $data['ref'] = 'DOCUMENT_REFERRER'; // AMP placeholder.
279 $data = array_map( 'rawurlencode', $data );
280 $pixel_url = add_query_arg( $data, 'https://pixel.wp.com/g.gif' );
281
282 ?>
283 <amp-pixel src="<?php echo esc_url( $pixel_url ); ?>"></amp-pixel>
284 <?php
285 }
286
287 /**
288 * Stats Get Options.
289 *
290 * @access public
291 * @return array.
292 */
293 function stats_get_options() {
294 $options = get_option( 'stats_options' );
295
296 if ( ! isset( $options['version'] ) || $options['version'] < STATS_VERSION ) {
297 $options = stats_upgrade_options( $options );
298 }
299
300 return $options;
301 }
302
303 /**
304 * Get Stats Options.
305 *
306 * @access public
307 * @param mixed $option Option.
308 * @return mixed|null.
309 */
310 function stats_get_option( $option ) {
311 $options = stats_get_options();
312
313 if ( 'blog_id' === $option ) {
314 return Jetpack_Options::get_option( 'id' );
315 }
316
317 if ( isset( $options[ $option ] ) ) {
318 return $options[ $option ];
319 }
320
321 return null;
322 }
323
324 /**
325 * Stats Set Options.
326 *
327 * @access public
328 * @param mixed $option Option.
329 * @param mixed $value Value.
330 * @return bool.
331 */
332 function stats_set_option( $option, $value ) {
333 $options = stats_get_options();
334
335 $options[ $option ] = $value;
336
337 return stats_set_options( $options );
338 }
339
340 /**
341 * Stats Set Options.
342 *
343 * @access public
344 * @param mixed $options Options.
345 * @return bool
346 */
347 function stats_set_options( $options ) {
348 return update_option( 'stats_options', $options );
349 }
350
351 /**
352 * Stats Upgrade Options.
353 *
354 * @access public
355 * @param mixed $options Options.
356 * @return array|bool
357 */
358 function stats_upgrade_options( $options ) {
359 $defaults = array(
360 'admin_bar' => true,
361 'roles' => array( 'administrator' ),
362 'count_roles' => array(),
363 'blog_id' => Jetpack_Options::get_option( 'id' ),
364 'do_not_track' => true, // @todo
365 'hide_smile' => true,
366 );
367
368 if ( isset( $options['reg_users'] ) ) {
369 if ( ! function_exists( 'get_editable_roles' ) ) {
370 require_once ABSPATH . 'wp-admin/includes/user.php';
371 }
372 if ( $options['reg_users'] ) {
373 $options['count_roles'] = array_keys( get_editable_roles() );
374 }
375 unset( $options['reg_users'] );
376 }
377
378 if ( is_array( $options ) && ! empty( $options ) ) {
379 $new_options = array_merge( $defaults, $options );
380 } else { $new_options = $defaults;
381 }
382
383 $new_options['version'] = STATS_VERSION;
384
385 if ( ! stats_set_options( $new_options ) ) {
386 return false;
387 }
388
389 stats_update_blog();
390
391 return $new_options;
392 }
393
394 /**
395 * Stats Array.
396 *
397 * @access public
398 * @param mixed $kvs KVS.
399 * @return array
400 */
401 function stats_array( $kvs ) {
402 /**
403 * Filter the options added to the JavaScript Stats tracking code.
404 *
405 * @module stats
406 *
407 * @since 1.1.0
408 *
409 * @param array $kvs Array of options about the site and page you're on.
410 */
411 $kvs = apply_filters( 'stats_array', $kvs );
412 $kvs = array_map( 'addslashes', $kvs );
413 foreach ( $kvs as $k => $v ) {
414 $jskvs[] = "$k:'$v'";
415 }
416 return join( ',', $jskvs );
417 }
418
419 /**
420 * Admin Pages.
421 *
422 * @access public
423 * @return void
424 */
425 function stats_admin_menu() {
426 global $pagenow;
427
428 // If we're at an old Stats URL, redirect to the new one.
429 // Don't even bother with caps, menu_page_url(), etc. Just do it.
430 if ( 'index.php' === $pagenow && isset( $_GET['page'] ) && 'stats' === $_GET['page'] ) {
431 $redirect_url = str_replace( array( '/wp-admin/index.php?', '/wp-admin/?' ), '/wp-admin/admin.php?', $_SERVER['REQUEST_URI'] );
432 $relative_pos = strpos( $redirect_url, '/wp-admin/' );
433 if ( false !== $relative_pos ) {
434 wp_safe_redirect( admin_url( substr( $redirect_url, $relative_pos + 10 ) ) );
435 exit;
436 }
437 }
438
439 $hook = add_submenu_page( 'jetpack', __( 'Site Stats', 'jetpack' ), __( 'Site Stats', 'jetpack' ), 'view_stats', 'stats', 'jetpack_admin_ui_stats_report_page_wrapper' );
440 add_action( "load-$hook", 'stats_reports_load' );
441 }
442
443 /**
444 * Stats Admin Path.
445 *
446 * @access public
447 * @return string
448 */
449 function stats_admin_path() {
450 return Jetpack::module_configuration_url( __FILE__ );
451 }
452
453 /**
454 * Stats Reports Load.
455 *
456 * @access public
457 * @return void
458 */
459 function stats_reports_load() {
460 wp_enqueue_script( 'jquery' );
461 wp_enqueue_script( 'postbox' );
462 wp_enqueue_script( 'underscore' );
463
464 Jetpack_Admin_Page::load_wrapper_styles();
465 add_action( 'admin_print_styles', 'stats_reports_css' );
466
467 if ( isset( $_GET['nojs'] ) && $_GET['nojs'] ) {
468 $parsed = parse_url( admin_url() );
469 // Remember user doesn't want JS.
470 setcookie( 'stnojs', '1', time() + 172800, $parsed['path'] ); // 2 days.
471 }
472
473 if ( isset( $_COOKIE['stnojs'] ) && $_COOKIE['stnojs'] ) {
474 // Detect if JS is on. If so, remove cookie so next page load is via JS.
475 add_action( 'admin_print_footer_scripts', 'stats_js_remove_stnojs_cookie' );
476 } else if ( ! isset( $_GET['noheader'] ) && empty( $_GET['nojs'] ) ) {
477 // Normal page load. Load page content via JS.
478 add_action( 'admin_print_footer_scripts', 'stats_js_load_page_via_ajax' );
479 }
480 }
481
482 /**
483 * Stats Reports CSS.
484 *
485 * @access public
486 * @return void
487 */
488 function stats_reports_css() {
489 ?>
490 <style type="text/css">
491 #jp-stats-wrap {
492 max-width: 1040px;
493 margin: 0 auto;
494 overflow: hidden;
495 }
496
497 #stats-loading-wrap p {
498 text-align: center;
499 font-size: 2em;
500 margin: 7.5em 15px 0 0;
501 height: 64px;
502 line-height: 64px;
503 }
504 </style>
505 <?php
506 }
507
508
509 /**
510 * Detect if JS is on. If so, remove cookie so next page load is via JS.
511 *
512 * @access public
513 * @return void
514 */
515 function stats_js_remove_stnojs_cookie() {
516 $parsed = parse_url( admin_url() );
517 ?>
518 <script type="text/javascript">
519 /* <![CDATA[ */
520 document.cookie = 'stnojs=0; expires=Wed, 9 Mar 2011 16:55:50 UTC; path=<?php echo esc_js( $parsed['path'] ); ?>';
521 /* ]]> */
522 </script>
523 <?php
524 }
525
526 /**
527 * Normal page load. Load page content via JS.
528 *
529 * @access public
530 * @return void
531 */
532 function stats_js_load_page_via_ajax() {
533 ?>
534 <script type="text/javascript">
535 /* <![CDATA[ */
536 if ( -1 == document.location.href.indexOf( 'noheader' ) ) {
537 jQuery( function( $ ) {
538 $.get( document.location.href + '&noheader', function( responseText ) {
539 $( '#stats-loading-wrap' ).replaceWith( responseText );
540 } );
541 } );
542 }
543 /* ]]> */
544 </script>
545 <?php
546 }
547
548 function jetpack_admin_ui_stats_report_page_wrapper() {
549 if( ! isset( $_GET['noheader'] ) && empty( $_GET['nojs'] ) && empty( $_COOKIE['stnojs'] ) ) {
550 Jetpack_Admin_Page::wrap_ui( 'stats_reports_page', array( 'is-wide' => true ) );
551 } else {
552 stats_reports_page();
553 }
554
555 }
556
557 /**
558 * Stats Report Page.
559 *
560 * @access public
561 * @param bool $main_chart_only (default: false) Main Chart Only.
562 */
563 function stats_reports_page( $main_chart_only = false ) {
564
565 if ( isset( $_GET['dashboard'] ) ) {
566 return stats_dashboard_widget_content();
567 }
568
569 $blog_id = stats_get_option( 'blog_id' );
570 $domain = Jetpack::build_raw_urls( get_home_url() );
571
572 $jetpack_admin_url = admin_url() . 'admin.php?page=jetpack';
573
574 if ( ! $main_chart_only && ! isset( $_GET['noheader'] ) && empty( $_GET['nojs'] ) && empty( $_COOKIE['stnojs'] ) ) {
575 $nojs_url = add_query_arg( 'nojs', '1' );
576 $http = is_ssl() ? 'https' : 'http';
577 // Loading message. No JS fallback message.
578 ?>
579
580 <div id="jp-stats-wrap">
581 <div class="wrap">
582 <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>
583 </div>
584 <div id="stats-loading-wrap" class="wrap">
585 <p class="hide-if-no-js"><img width="32" height="32" alt="<?php esc_attr_e( 'Loading&hellip;', 'jetpack' ); ?>" src="<?php
586 echo esc_url(
587 /**
588 * Sets external resource URL.
589 *
590 * @module stats
591 *
592 * @since 1.4.0
593 *
594 * @param string $args URL of external resource.
595 */
596 apply_filters( 'jetpack_static_url', "{$http}://en.wordpress.com/i/loading/loading-64.gif" )
597 ); ?>" /></p>
598 <p style="font-size: 11pt; margin: 0;"><a href="https://wordpress.com/stats/<?php echo esc_attr( $domain ); ?>" target="_blank"><?php esc_html_e( 'View stats on WordPress.com right now', 'jetpack' ); ?></a></p>
599 <p class="hide-if-js"><?php esc_html_e( 'Your Site Stats work better with JavaScript enabled.', 'jetpack' ); ?><br />
600 <a href="<?php echo esc_url( $nojs_url ); ?>"><?php esc_html_e( 'View Site Stats without JavaScript', 'jetpack' ); ?></a>.</p>
601 </div>
602 </div>
603 <?php
604 return;
605 }
606
607 $day = isset( $_GET['day'] ) && preg_match( '/^\d{4}-\d{2}-\d{2}$/', $_GET['day'] ) ? $_GET['day'] : false;
608 $q = array(
609 'noheader' => 'true',
610 'proxy' => '',
611 'page' => 'stats',
612 'day' => $day,
613 'blog' => $blog_id,
614 'charset' => get_option( 'blog_charset' ),
615 'color' => get_user_option( 'admin_color' ),
616 'ssl' => is_ssl(),
617 'j' => sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION ),
618 );
619 if ( get_locale() !== 'en_US' ) {
620 $q['jp_lang'] = get_locale();
621 }
622 // Only show the main chart, without extra header data, or metaboxes.
623 $q['main_chart_only'] = $main_chart_only;
624 $args = array(
625 'view' => array( 'referrers', 'postviews', 'searchterms', 'clicks', 'post', 'table' ),
626 'numdays' => 'int',
627 'day' => 'date',
628 'unit' => array( 1, 7, 31, 'human' ),
629 'humanize' => array( 'true' ),
630 'num' => 'int',
631 'summarize' => null,
632 'post' => 'int',
633 'width' => 'int',
634 'height' => 'int',
635 'data' => 'data',
636 'blog_subscribers' => 'int',
637 'comment_subscribers' => null,
638 'type' => array( 'wpcom', 'email', 'pending' ),
639 'pagenum' => 'int',
640 );
641 foreach ( $args as $var => $vals ) {
642 if ( ! isset( $_REQUEST[$var] ) )
643 continue;
644 if ( is_array( $vals ) ) {
645 if ( in_array( $_REQUEST[$var], $vals ) )
646 $q[$var] = $_REQUEST[$var];
647 } elseif ( 'int' === $vals ) {
648 $q[$var] = intval( $_REQUEST[$var] );
649 } elseif ( 'date' === $vals ) {
650 if ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', $_REQUEST[$var] ) )
651 $q[$var] = $_REQUEST[$var];
652 } elseif ( null === $vals ) {
653 $q[$var] = '';
654 } elseif ( 'data' === $vals ) {
655 if ( 'index.php' === substr( $_REQUEST[$var], 0, 9 ) )
656 $q[$var] = $_REQUEST[$var];
657 }
658 }
659
660 if ( isset( $_GET['chart'] ) ) {
661 if ( preg_match( '/^[a-z0-9-]+$/', $_GET['chart'] ) ) {
662 $chart = sanitize_title( $_GET['chart'] );
663 $url = 'https://' . STATS_DASHBOARD_SERVER . "/wp-includes/charts/{$chart}.php";
664 }
665 } else {
666 $url = 'https://' . STATS_DASHBOARD_SERVER . "/wp-admin/index.php";
667 }
668
669 $url = add_query_arg( $q, $url );
670 $method = 'GET';
671 $timeout = 90;
672 $user_id = JETPACK_MASTER_USER; // means send the wp.com user_id
673
674 $get = Jetpack_Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
675 $get_code = wp_remote_retrieve_response_code( $get );
676 if ( is_wp_error( $get ) || ( 2 !== intval( $get_code / 100 ) && 304 !== $get_code ) || empty( $get['body'] ) ) {
677 stats_print_wp_remote_error( $get, $url );
678 } else {
679 if ( ! empty( $get['headers']['content-type'] ) ) {
680 $type = $get['headers']['content-type'];
681 if ( substr( $type, 0, 5 ) === 'image' ) {
682 $img = $get['body'];
683 header( 'Content-Type: ' . $type );
684 header( 'Content-Length: ' . strlen( $img ) );
685 echo $img;
686 die();
687 }
688 }
689 $body = stats_convert_post_titles( $get['body'] );
690 $body = stats_convert_chart_urls( $body );
691 $body = stats_convert_image_urls( $body );
692 $body = stats_convert_admin_urls( $body );
693 echo $body;
694 }
695
696 if ( isset( $_GET['page'] ) && 'stats' === $_GET['page'] && ! isset( $_GET['chart'] ) ) {
697 JetpackTracking::record_user_event( 'wpa_page_view', array( 'path' => 'old_stats' ) );
698 }
699
700 if ( isset( $_GET['noheader'] ) ) {
701 die;
702 }
703 }
704
705 /**
706 * Stats Convert Admin Urls.
707 *
708 * @access public
709 * @param mixed $html HTML.
710 * @return string
711 */
712 function stats_convert_admin_urls( $html ) {
713 return str_replace( 'index.php?page=stats', 'admin.php?page=stats', $html );
714 }
715
716 /**
717 * Stats Convert Image URLs.
718 *
719 * @access public
720 * @param mixed $html HTML.
721 * @return string
722 */
723 function stats_convert_image_urls( $html ) {
724 $url = set_url_scheme( 'https://' . STATS_DASHBOARD_SERVER );
725 $html = preg_replace( '|(["\'])(/i/stats.+)\\1|', '$1' . $url . '$2$1', $html );
726 return $html;
727 }
728
729 /**
730 * Callback for preg_replace_callback used in stats_convert_chart_urls()
731 *
732 * @since 5.6.0
733 *
734 * @param array $matches The matches resulting from the preg_replace_callback call.
735 * @return string The admin url for the chart.
736 */
737 function jetpack_stats_convert_chart_urls_callback( $matches ) {
738 // If there is a query string, change the beginning '?' to a '&' so it fits into the middle of this query string.
739 return 'admin.php?page=stats&noheader&chart=' . $matches[1] . str_replace( '?', '&', $matches[2] );
740 }
741
742 /**
743 * Stats Convert Chart URLs.
744 *
745 * @access public
746 * @param mixed $html HTML.
747 * @return string
748 */
749 function stats_convert_chart_urls( $html ) {
750 $html = preg_replace_callback(
751 '|https?://[-.a-z0-9]+/wp-includes/charts/([-.a-z0-9]+).php(\??)|',
752 'jetpack_stats_convert_chart_urls_callback',
753 $html
754 );
755 return $html;
756 }
757
758 /**
759 * Stats Convert Post Title HTML
760 *
761 * @access public
762 * @param mixed $html HTML.
763 * @return string
764 */
765 function stats_convert_post_titles( $html ) {
766 global $stats_posts;
767 $pattern = "<span class='post-(\d+)-link'>.*?</span>";
768 if ( ! preg_match_all( "!$pattern!", $html, $matches ) ) {
769 return $html;
770 }
771 $posts = get_posts(
772 array(
773 'include' => implode( ',', $matches[1] ),
774 'post_type' => 'any',
775 'post_status' => 'any',
776 'numberposts' => -1,
777 'suppress_filters' => false,
778 )
779 );
780 foreach ( $posts as $post ) {
781 $stats_posts[ $post->ID ] = $post;
782 }
783 $html = preg_replace_callback( "!$pattern!", 'stats_convert_post_title', $html );
784 return $html;
785 }
786
787 /**
788 * Stats Convert Post Title Matches.
789 *
790 * @access public
791 * @param mixed $matches Matches.
792 * @return string
793 */
794 function stats_convert_post_title( $matches ) {
795 global $stats_posts;
796 $post_id = $matches[1];
797 if ( isset( $stats_posts[$post_id] ) )
798 return '<a href="' . get_permalink( $post_id ) . '" target="_blank">' . get_the_title( $post_id ) . '</a>';
799 return $matches[0];
800 }
801
802 /**
803 * Stats Configuration Load.
804 *
805 * @access public
806 * @return void
807 */
808 function stats_configuration_load() {
809 if ( isset( $_POST['action'] ) && 'save_options' === $_POST['action'] && $_POST['_wpnonce'] === wp_create_nonce( 'stats' ) ) {
810 $options = stats_get_options();
811 $options['admin_bar'] = isset( $_POST['admin_bar'] ) && $_POST['admin_bar'];
812 $options['hide_smile'] = isset( $_POST['hide_smile'] ) && $_POST['hide_smile'];
813
814 $options['roles'] = array( 'administrator' );
815 foreach ( get_editable_roles() as $role => $details ) {
816 if ( isset( $_POST["role_$role"] ) && $_POST["role_$role"] ) {
817 $options['roles'][] = $role;
818 }
819 }
820
821 $options['count_roles'] = array();
822 foreach ( get_editable_roles() as $role => $details ) {
823 if ( isset( $_POST["count_role_$role"] ) && $_POST["count_role_$role"] ) {
824 $options['count_roles'][] = $role;
825 }
826 }
827
828 stats_set_options( $options );
829 stats_update_blog();
830 Jetpack::state( 'message', 'module_configured' );
831 wp_safe_redirect( Jetpack::module_configuration_url( 'stats' ) );
832 exit;
833 }
834 }
835
836 /**
837 * Stats Configuration Head.
838 *
839 * @access public
840 * @return void
841 */
842 function stats_configuration_head() {
843 ?>
844 <style type="text/css">
845 #statserror {
846 border: 1px solid #766;
847 background-color: #d22;
848 padding: 1em 3em;
849 }
850 .stats-smiley {
851 vertical-align: 1px;
852 }
853 </style>
854 <?php
855 }
856
857 /**
858 * Stats Configuration Screen.
859 *
860 * @access public
861 * @return void
862 */
863 function stats_configuration_screen() {
864 $options = stats_get_options();
865 ?>
866 <div class="narrow">
867 <p><?php printf( __( 'Visit <a href="%s">Site Stats</a> to see your stats.', 'jetpack' ), esc_url( menu_page_url( 'stats', false ) ) ); ?></p>
868 <form method="post">
869 <input type='hidden' name='action' value='save_options' />
870 <?php wp_nonce_field( 'stats' ); ?>
871 <table id="menu" class="form-table">
872 <tr valign="top"><th scope="row"><label for="admin_bar"><?php esc_html_e( 'Admin bar' , 'jetpack' ); ?></label></th>
873 <td><label><input type='checkbox'<?php checked( $options['admin_bar'] ); ?> name='admin_bar' id='admin_bar' /> <?php esc_html_e( 'Put a chart showing 48 hours of views in the admin bar.', 'jetpack' ); ?></label></td></tr>
874 <tr valign="top"><th scope="row"><?php esc_html_e( 'Registered users', 'jetpack' ); ?></th>
875 <td>
876 <?php esc_html_e( "Count the page views of registered users who are logged in.", 'jetpack' ); ?><br/>
877 <?php
878 $count_roles = stats_get_option( 'count_roles' );
879 foreach ( get_editable_roles() as $role => $details ) {
880 ?>
881 <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/>
882 <?php
883 }
884 ?>
885 </td></tr>
886 <tr valign="top"><th scope="row"><?php esc_html_e( 'Smiley' , 'jetpack' ); ?></th>
887 <td><label><input type='checkbox'<?php checked( isset( $options['hide_smile'] ) && $options['hide_smile'] ); ?> name='hide_smile' id='hide_smile' /> <?php esc_html_e( 'Hide the stats smiley face image.', 'jetpack' ); ?></label><br /> <span class="description"><?php echo wp_kses( __( 'The image helps collect stats and <strong>makes the world a better place</strong> but should still work when hidden', 'jetpack' ), array( 'strong' => array() ) ); ?> <img class="stats-smiley" alt="<?php esc_attr_e( 'Smiley face', 'jetpack' ); ?>" src="<?php echo esc_url( plugins_url( 'images/stats-smiley.gif', dirname( __FILE__ ) ) ); ?>" width="6" height="5" /></span></td></tr>
888 <tr valign="top"><th scope="row"><?php esc_html_e( 'Report visibility' , 'jetpack' ); ?></th>
889 <td>
890 <?php esc_html_e( 'Select the roles that will be able to view stats reports.', 'jetpack' ); ?><br/>
891 <?php
892 $stats_roles = stats_get_option( 'roles' );
893 foreach ( get_editable_roles() as $role => $details ) {
894 ?>
895 <label><input type='checkbox' <?php if ( 'administrator' === $role ) echo "disabled='disabled' "; ?>name='role_<?php echo $role; ?>'<?php checked( 'administrator' === $role || in_array( $role, $stats_roles ) ); ?> /> <?php echo translate_user_role( $details['name'] ); ?></label><br/>
896 <?php
897 }
898 ?>
899 </td></tr>
900 </table>
901 <p class="submit"><input type='submit' class='button-primary' value='<?php echo esc_attr( __( 'Save configuration', 'jetpack' ) ); ?>' /></p>
902 </form>
903 </div>
904 <?php
905 }
906
907 /**
908 * Stats Hide Smile.
909 *
910 * @access public
911 * @return void
912 */
913 function stats_hide_smile_css() {
914 $options = stats_get_options();
915 if ( isset( $options['hide_smile'] ) && $options['hide_smile'] ) {
916 ?>
917 <style type='text/css'>img#wpstats{display:none}</style><?php
918 }
919 }
920
921 /**
922 * Stats Admin Bar Head.
923 *
924 * @access public
925 * @return void
926 */
927 function stats_admin_bar_head() {
928 if ( ! stats_get_option( 'admin_bar' ) )
929 return;
930
931 if ( ! current_user_can( 'view_stats' ) )
932 return;
933
934 if ( function_exists( 'is_admin_bar_showing' ) && ! is_admin_bar_showing() ) {
935 return;
936 }
937
938 add_action( 'admin_bar_menu', 'stats_admin_bar_menu', 100 );
939 ?>
940
941 <style type='text/css'>
942 #wpadminbar .quicklinks li#wp-admin-bar-stats {
943 height: 32px;
944 }
945 #wpadminbar .quicklinks li#wp-admin-bar-stats a {
946 height: 32px;
947 padding: 0;
948 }
949 #wpadminbar .quicklinks li#wp-admin-bar-stats a div {
950 height: 32px;
951 width: 95px;
952 overflow: hidden;
953 margin: 0 10px;
954 }
955 #wpadminbar .quicklinks li#wp-admin-bar-stats a:hover div {
956 width: auto;
957 margin: 0 8px 0 10px;
958 }
959 #wpadminbar .quicklinks li#wp-admin-bar-stats a img {
960 height: 24px;
961 padding: 4px 0;
962 max-width: none;
963 border: none;
964 }
965 </style>
966 <?php
967 }
968
969 /**
970 * Stats AdminBar.
971 *
972 * @access public
973 * @param mixed $wp_admin_bar WPAdminBar.
974 * @return void
975 */
976 function stats_admin_bar_menu( &$wp_admin_bar ) {
977 $url = add_query_arg( 'page', 'stats', admin_url( 'admin.php' ) ); // no menu_page_url() blog-side.
978
979 $img_src = esc_attr( add_query_arg( array( 'noheader' => '', 'proxy' => '', 'chart' => 'admin-bar-hours-scale' ), $url ) );
980 $img_src_2x = esc_attr( add_query_arg( array( 'noheader' => '', 'proxy' => '', 'chart' => 'admin-bar-hours-scale-2x' ), $url ) );
981
982 $alt = esc_attr( __( 'Stats', 'jetpack' ) );
983
984 $title = esc_attr( __( 'Views over 48 hours. Click for more Site Stats.', 'jetpack' ) );
985
986 $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 );
987
988 $wp_admin_bar->add_menu( $menu );
989 }
990
991 /**
992 * Stats Update Blog.
993 *
994 * @access public
995 * @return void
996 */
997 function stats_update_blog() {
998 Jetpack::xmlrpc_async_call( 'jetpack.updateBlog', stats_get_blog() );
999 }
1000
1001 /**
1002 * Stats Get Blog.
1003 *
1004 * @access public
1005 * @return string
1006 */
1007 function stats_get_blog() {
1008 $home = parse_url( trailingslashit( get_option( 'home' ) ) );
1009 $blog = array(
1010 'host' => $home['host'],
1011 'path' => $home['path'],
1012 'blogname' => get_option( 'blogname' ),
1013 'blogdescription' => get_option( 'blogdescription' ),
1014 'siteurl' => get_option( 'siteurl' ),
1015 'gmt_offset' => get_option( 'gmt_offset' ),
1016 'timezone_string' => get_option( 'timezone_string' ),
1017 'stats_version' => STATS_VERSION,
1018 'stats_api' => 'jetpack',
1019 'page_on_front' => get_option( 'page_on_front' ),
1020 'permalink_structure' => get_option( 'permalink_structure' ),
1021 'category_base' => get_option( 'category_base' ),
1022 'tag_base' => get_option( 'tag_base' ),
1023 );
1024 $blog = array_merge( stats_get_options(), $blog );
1025 unset( $blog['roles'], $blog['blog_id'] );
1026 return stats_esc_html_deep( $blog );
1027 }
1028
1029 /**
1030 * Modified from stripslashes_deep()
1031 *
1032 * @access public
1033 * @param mixed $value Value.
1034 * @return string
1035 */
1036 function stats_esc_html_deep( $value ) {
1037 if ( is_array( $value ) ) {
1038 $value = array_map( 'stats_esc_html_deep', $value );
1039 } elseif ( is_object( $value ) ) {
1040 $vars = get_object_vars( $value );
1041 foreach ( $vars as $key => $data ) {
1042 $value->{$key} = stats_esc_html_deep( $data );
1043 }
1044 } elseif ( is_string( $value ) ) {
1045 $value = esc_html( $value );
1046 }
1047
1048 return $value;
1049 }
1050
1051 /**
1052 * Stats xmlrpc_methods function.
1053 *
1054 * @access public
1055 * @param mixed $methods Methods.
1056 * @return array
1057 */
1058 function stats_xmlrpc_methods( $methods ) {
1059 $my_methods = array(
1060 'jetpack.getBlog' => 'stats_get_blog',
1061 );
1062
1063 return array_merge( $methods, $my_methods );
1064 }
1065
1066 /**
1067 * Register Stats Dashboard Widget.
1068 *
1069 * @access public
1070 * @return void
1071 */
1072 function stats_register_dashboard_widget() {
1073 if ( ! current_user_can( 'view_stats' ) )
1074 return;
1075
1076 // With wp_dashboard_empty: we load in the content after the page load via JS.
1077 wp_add_dashboard_widget( 'dashboard_stats', __( 'Site Stats', 'jetpack' ), 'wp_dashboard_empty', 'stats_dashboard_widget_control' );
1078
1079 add_action( 'admin_head', 'stats_dashboard_head' );
1080 }
1081
1082 /**
1083 * Stats Dashboard Widget Options.
1084 *
1085 * @access public
1086 * @return array
1087 */
1088 function stats_dashboard_widget_options() {
1089 $defaults = array( 'chart' => 1, 'top' => 1, 'search' => 7 );
1090 if ( ( ! $options = get_option( 'stats_dashboard_widget' ) ) || ! is_array( $options ) ) {
1091 $options = array();
1092 }
1093
1094 // Ignore obsolete option values.
1095 $intervals = array( 1, 7, 31, 90, 365 );
1096 foreach ( array( 'top', 'search' ) as $key ) {
1097 if ( isset( $options[ $key ] ) && ! in_array( $options[ $key ], $intervals ) ) {
1098 unset( $options[ $key ] );
1099 }
1100 }
1101
1102 return array_merge( $defaults, $options );
1103 }
1104
1105 /**
1106 * Stats Dashboard Widget Control.
1107 *
1108 * @access public
1109 * @return void
1110 */
1111 function stats_dashboard_widget_control() {
1112 $periods = array(
1113 '1' => __( 'day', 'jetpack' ),
1114 '7' => __( 'week', 'jetpack' ),
1115 '31' => __( 'month', 'jetpack' ),
1116 );
1117 $intervals = array(
1118 '1' => __( 'the past day', 'jetpack' ),
1119 '7' => __( 'the past week', 'jetpack' ),
1120 '31' => __( 'the past month', 'jetpack' ),
1121 '90' => __( 'the past quarter', 'jetpack' ),
1122 '365' => __( 'the past year', 'jetpack' ),
1123 );
1124 $defaults = array(
1125 'top' => 1,
1126 'search' => 7,
1127 );
1128
1129 $options = stats_dashboard_widget_options();
1130
1131 if ( 'post' === strtolower( $_SERVER['REQUEST_METHOD'] ) && isset( $_POST['widget_id'] ) && 'dashboard_stats' === $_POST['widget_id'] ) {
1132 if ( isset( $periods[ $_POST['chart'] ] ) ) {
1133 $options['chart'] = $_POST['chart'];
1134 }
1135 foreach ( array( 'top', 'search' ) as $key ) {
1136 if ( isset( $intervals[ $_POST[ $key ] ] ) ) {
1137 $options[ $key ] = $_POST[ $key ];
1138 } else { $options[ $key ] = $defaults[ $key ];
1139 }
1140 }
1141 update_option( 'stats_dashboard_widget', $options );
1142 }
1143 ?>
1144 <p>
1145 <label for="chart"><?php esc_html_e( 'Chart stats by' , 'jetpack' ); ?></label>
1146 <select id="chart" name="chart">
1147 <?php
1148 foreach ( $periods as $val => $label ) {
1149 ?>
1150 <option value="<?php echo $val; ?>"<?php selected( $val, $options['chart'] ); ?>><?php echo esc_html( $label ); ?></option>
1151 <?php
1152 }
1153 ?>
1154 </select>.
1155 </p>
1156
1157 <p>
1158 <label for="top"><?php esc_html_e( 'Show top posts over', 'jetpack' ); ?></label>
1159 <select id="top" name="top">
1160 <?php
1161 foreach ( $intervals as $val => $label ) {
1162 ?>
1163 <option value="<?php echo $val; ?>"<?php selected( $val, $options['top'] ); ?>><?php echo esc_html( $label ); ?></option>
1164 <?php
1165 }
1166 ?>
1167 </select>.
1168 </p>
1169
1170 <p>
1171 <label for="search"><?php esc_html_e( 'Show top search terms over', 'jetpack' ); ?></label>
1172 <select id="search" name="search">
1173 <?php
1174 foreach ( $intervals as $val => $label ) {
1175 ?>
1176 <option value="<?php echo $val; ?>"<?php selected( $val, $options['search'] ); ?>><?php echo esc_html( $label ); ?></option>
1177 <?php
1178 }
1179 ?>
1180 </select>.
1181 </p>
1182 <?php
1183 }
1184
1185 /**
1186 * Jetpack Stats Dashboard Widget.
1187 *
1188 * @access public
1189 * @return void
1190 */
1191 function stats_jetpack_dashboard_widget() {
1192 ?>
1193 <form id="stats_dashboard_widget_control" action="<?php echo esc_url( admin_url() ); ?>" method="post">
1194 <?php stats_dashboard_widget_control(); ?>
1195 <?php wp_nonce_field( 'edit-dashboard-widget_dashboard_stats', 'dashboard-widget-nonce' ); ?>
1196 <input type="hidden" name="widget_id" value="dashboard_stats" />
1197 <?php submit_button( __( 'Submit', 'jetpack' ) ); ?>
1198 </form>
1199 <span id="js-toggle-stats_dashboard_widget_control">
1200 <?php esc_html_e( 'Configure', 'jetpack' ); ?>
1201 </span>
1202 <div id="dashboard_stats">
1203 <div class="inside">
1204 <div style="height: 250px;"></div>
1205 </div>
1206 </div>
1207 <script>
1208 jQuery(document).ready(function($){
1209 var $toggle = $('#js-toggle-stats_dashboard_widget_control');
1210
1211 $toggle.parent().prev().append( $toggle );
1212 $toggle.show().click(function(e){
1213 e.preventDefault();
1214 e.stopImmediatePropagation();
1215 $(this).parent().toggleClass('controlVisible');
1216 $('#stats_dashboard_widget_control').slideToggle();
1217 });
1218 });
1219 </script>
1220 <style>
1221 #js-toggle-stats_dashboard_widget_control {
1222 display: none;
1223 float: right;
1224 margin-top: 0.2em;
1225 font-weight: 400;
1226 color: #444;
1227 font-size: .8em;
1228 text-decoration: underline;
1229 cursor: pointer;
1230 }
1231 #stats_dashboard_widget_control {
1232 display: none;
1233 padding: 0 10px;
1234 overflow: hidden;
1235 }
1236 #stats_dashboard_widget_control .button-primary {
1237 float: right;
1238 }
1239 #dashboard_stats {
1240 box-sizing: border-box;
1241 width: 100%;
1242 padding: 0 10px;
1243 }
1244 </style>
1245 <?php
1246 }
1247
1248 /**
1249 * Register Stats Widget Control Callback.
1250 *
1251 * @access public
1252 * @return void
1253 */
1254 function stats_register_widget_control_callback() {
1255 $GLOBALS['wp_dashboard_control_callbacks']['dashboard_stats'] = 'stats_dashboard_widget_control';
1256 }
1257
1258 /**
1259 * JavaScript and CSS for dashboard widget.
1260 *
1261 * @access public
1262 * @return void
1263 */
1264 function stats_dashboard_head() { ?>
1265 <script type="text/javascript">
1266 /* <![CDATA[ */
1267 jQuery( function($) {
1268 var dashStats = jQuery( '#dashboard_stats div.inside' );
1269
1270 if ( dashStats.find( '.dashboard-widget-control-form' ).length ) {
1271 return;
1272 }
1273
1274 if ( ! dashStats.length ) {
1275 dashStats = jQuery( '#dashboard_stats div.dashboard-widget-content' );
1276 var h = parseInt( dashStats.parent().height() ) - parseInt( dashStats.prev().height() );
1277 var args = 'width=' + dashStats.width() + '&height=' + h.toString();
1278 } else {
1279 if ( jQuery('#dashboard_stats' ).hasClass('postbox') ) {
1280 var args = 'width=' + ( dashStats.prev().width() * 2 ).toString();
1281 } else {
1282 var args = 'width=' + ( dashStats.width() * 2 ).toString();
1283 }
1284 }
1285
1286 dashStats
1287 .not( '.dashboard-widget-control' )
1288 .load( 'admin.php?page=stats&noheader&dashboard&' + args );
1289
1290 jQuery( window ).one( 'resize', function() {
1291 jQuery( '#stat-chart' ).css( 'width', 'auto' );
1292 } );
1293 } );
1294 /* ]]> */
1295 </script>
1296 <style type="text/css">
1297 /* <![CDATA[ */
1298 #stat-chart {
1299 background: none !important;
1300 }
1301 #dashboard_stats .inside {
1302 margin: 10px 0 0 0 !important;
1303 }
1304 #dashboard_stats #stats-graph {
1305 margin: 0;
1306 }
1307 #stats-info {
1308 border-top: 1px solid #dfdfdf;
1309 margin: 7px -10px 0 -10px;
1310 padding: 10px;
1311 background: #fcfcfc;
1312 -moz-box-shadow:inset 0 1px 0 #fff;
1313 -webkit-box-shadow:inset 0 1px 0 #fff;
1314 box-shadow:inset 0 1px 0 #fff;
1315 overflow: hidden;
1316 border-radius: 0 0 2px 2px;
1317 -webkit-border-radius: 0 0 2px 2px;
1318 -moz-border-radius: 0 0 2px 2px;
1319 -khtml-border-radius: 0 0 2px 2px;
1320 }
1321 #stats-info #top-posts, #stats-info #top-search {
1322 float: left;
1323 width: 50%;
1324 }
1325 #stats-info #top-posts {
1326 padding-right: 3%;
1327 }
1328 #top-posts .stats-section-inner p {
1329 white-space: nowrap;
1330 overflow: hidden;
1331 }
1332 #top-posts .stats-section-inner p a {
1333 overflow: hidden;
1334 text-overflow: ellipsis;
1335 }
1336 #stats-info div#active {
1337 border-top: 1px solid #dfdfdf;
1338 margin: 0 -10px;
1339 padding: 10px 10px 0 10px;
1340 -moz-box-shadow:inset 0 1px 0 #fff;
1341 -webkit-box-shadow:inset 0 1px 0 #fff;
1342 box-shadow:inset 0 1px 0 #fff;
1343 overflow: hidden;
1344 }
1345 #top-search p {
1346 color: #999;
1347 }
1348 #stats-info h3 {
1349 font-size: 1em;
1350 margin: 0 0 .5em 0 !important;
1351 }
1352 #stats-info p {
1353 margin: 0 0 .25em;
1354 color: #999;
1355 }
1356 #stats-info p.widget-loading {
1357 margin: 1em 0 0;
1358 color: #333;
1359 }
1360 #stats-info p a {
1361 display: block;
1362 }
1363 #stats-info p a.button {
1364 display: inline;
1365 }
1366 /* ]]> */
1367 </style>
1368 <?php
1369 }
1370
1371 /**
1372 * Stats Dashboard Widget Content.
1373 *
1374 * @access public
1375 * @return void
1376 */
1377 function stats_dashboard_widget_content() {
1378 if ( ! isset( $_GET['width'] ) || ( ! $width = (int) ( $_GET['width'] / 2 ) ) || $width < 250 ) {
1379 $width = 370;
1380 }
1381 if ( ! isset( $_GET['height'] ) || ( ! $height = (int) $_GET['height'] - 36 ) || $height < 230 ) {
1382 $height = 180;
1383 }
1384
1385 $_width = $width - 5;
1386 $_height = $height - ( $GLOBALS['is_winIE'] ? 16 : 5 ); // Hack!
1387
1388 $options = stats_dashboard_widget_options();
1389 $blog_id = Jetpack_Options::get_option( 'id' );
1390
1391 $q = array(
1392 'noheader' => 'true',
1393 'proxy' => '',
1394 'blog' => $blog_id,
1395 'page' => 'stats',
1396 'chart' => '',
1397 'unit' => $options['chart'],
1398 'color' => get_user_option( 'admin_color' ),
1399 'width' => $_width,
1400 'height' => $_height,
1401 'ssl' => is_ssl(),
1402 'j' => sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION ),
1403 );
1404
1405 $url = 'https://' . STATS_DASHBOARD_SERVER . "/wp-admin/index.php";
1406
1407 $url = add_query_arg( $q, $url );
1408 $method = 'GET';
1409 $timeout = 90;
1410 $user_id = JETPACK_MASTER_USER;
1411
1412 $get = Jetpack_Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
1413 $get_code = wp_remote_retrieve_response_code( $get );
1414 if ( is_wp_error( $get ) || ( 2 !== intval( $get_code / 100 ) && 304 !== $get_code ) || empty( $get['body'] ) ) {
1415 stats_print_wp_remote_error( $get, $url );
1416 } else {
1417 $body = stats_convert_post_titles( $get['body'] );
1418 $body = stats_convert_chart_urls( $body );
1419 $body = stats_convert_image_urls( $body );
1420 echo $body;
1421 }
1422
1423 $post_ids = array();
1424
1425 $csv_end_date = date( 'Y-m-d', current_time( 'timestamp' ) );
1426 $csv_args = array( 'top' => "&limit=8&end=$csv_end_date", 'search' => "&limit=5&end=$csv_end_date" );
1427 /* Translators: Stats dashboard widget postviews list: "$post_title $views Views". */
1428 $printf = __( '%1$s %2$s Views' , 'jetpack' );
1429
1430 foreach ( $top_posts = stats_get_csv( 'postviews', "days=$options[top]$csv_args[top]" ) as $i => $post ) {
1431 if ( 0 === $post['post_id'] ) {
1432 unset( $top_posts[$i] );
1433 continue;
1434 }
1435 $post_ids[] = $post['post_id'];
1436 }
1437
1438 // Cache.
1439 get_posts( array( 'include' => join( ',', array_unique( $post_ids ) ) ) );
1440
1441 $searches = array();
1442 foreach ( $search_terms = stats_get_csv( 'searchterms', "days=$options[search]$csv_args[search]" ) as $search_term ) {
1443 if ( 'encrypted_search_terms' === $search_term['searchterm'] ) {
1444 continue;
1445 }
1446 $searches[] = esc_html( $search_term['searchterm'] );
1447 }
1448
1449 ?>
1450 <a class="button" href="admin.php?page=stats"><?php esc_html_e( 'View All', 'jetpack' ); ?></a>
1451 <div id="stats-info">
1452 <div id="top-posts" class='stats-section'>
1453 <div class="stats-section-inner">
1454 <h3 class="heading"><?php esc_html_e( 'Top Posts' , 'jetpack' ); ?></h3>
1455 <?php
1456 if ( empty( $top_posts ) ) {
1457 ?>
1458 <p class="nothing"><?php esc_html_e( 'Sorry, nothing to report.', 'jetpack' ); ?></p>
1459 <?php
1460 } else {
1461 foreach ( $top_posts as $post ) {
1462 if ( ! get_post( $post['post_id'] ) ) {
1463 continue;
1464 }
1465 ?>
1466 <p><?php printf(
1467 $printf,
1468 '<a href="' . get_permalink( $post['post_id'] ) . '">' . get_the_title( $post['post_id'] ) . '</a>',
1469 number_format_i18n( $post['views'] )
1470 ); ?></p>
1471 <?php
1472 }
1473 }
1474 ?>
1475 </div>
1476 </div>
1477 <div id="top-search" class='stats-section'>
1478 <div class="stats-section-inner">
1479 <h3 class="heading"><?php esc_html_e( 'Top Searches' , 'jetpack' ); ?></h3>
1480 <?php
1481 if ( empty( $searches ) ) {
1482 ?>
1483 <p class="nothing"><?php esc_html_e( 'Sorry, nothing to report.', 'jetpack' ); ?></p>
1484 <?php
1485 } else {
1486 ?>
1487 <p><?php echo join( ',&nbsp; ', $searches );?></p>
1488 <?php
1489 }
1490 ?>
1491 </div>
1492 </div>
1493 </div>
1494 <div class="clear"></div>
1495 <?php
1496 exit;
1497 }
1498
1499 /**
1500 * Stats Print WP Remote Error.
1501 *
1502 * @access public
1503 * @param mixed $get Get.
1504 * @param mixed $url URL.
1505 * @return void
1506 */
1507 function stats_print_wp_remote_error( $get, $url ) {
1508 $state_name = 'stats_remote_error_' . substr( md5( $url ), 0, 8 );
1509 $previous_error = Jetpack::state( $state_name );
1510 $error = md5( serialize( compact( 'get', 'url' ) ) );
1511 Jetpack::state( $state_name, $error );
1512 if ( $error !== $previous_error ) {
1513 ?>
1514 <div class="wrap">
1515 <p><?php esc_html_e( 'We were unable to get your stats just now. Please reload this page to try again.', 'jetpack' ); ?></p>
1516 </div>
1517 <?php
1518 return;
1519 }
1520 ?>
1521 <div class="wrap">
1522 <p><?php printf( __( 'We were unable to get your stats just now. Please reload this page to try again. If this error persists, please <a href="%1$s" target="_blank">contact support</a>. In your report please include the information below.', 'jetpack' ), 'https://support.wordpress.com/contact/?jetpack=needs-service' ); ?></p>
1523 <pre>
1524 User Agent: "<?php echo esc_html( $_SERVER['HTTP_USER_AGENT'] ); ?>"
1525 Page URL: "http<?php echo (is_ssl()?'s':'') . '://' . esc_html( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); ?>"
1526 API URL: "<?php echo esc_url( $url ); ?>"
1527 <?php
1528 if ( is_wp_error( $get ) ) {
1529 foreach ( $get->get_error_codes() as $code ) {
1530 foreach ( $get->get_error_messages( $code ) as $message ) {
1531 ?>
1532 <?php print $code . ': "' . $message . '"' ?>
1533
1534 <?php
1535 }
1536 }
1537 } else {
1538 $get_code = wp_remote_retrieve_response_code( $get );
1539 $content_length = strlen( wp_remote_retrieve_body( $get ) );
1540 ?>
1541 Response code: "<?php print $get_code ?>"
1542 Content length: "<?php print $content_length ?>"
1543
1544 <?php
1545 }
1546 ?></pre>
1547 </div>
1548 <?php
1549 }
1550
1551 /**
1552 * Get stats from WordPress.com
1553 *
1554 * @param string $table The stats which you want to retrieve: postviews, or searchterms.
1555 * @param array $args {
1556 * An associative array of arguments.
1557 *
1558 * @type bool $end The last day of the desired time frame. Format is 'Y-m-d' (e.g. 2007-05-01)
1559 * and default timezone is UTC date. Default value is Now.
1560 * @type string $days The length of the desired time frame. Default is 30. Maximum 90 days.
1561 * @type int $limit The maximum number of records to return. Default is 10. Maximum 100.
1562 * @type int $post_id The ID of the post to retrieve stats data for
1563 * @type string $summarize If present, summarizes all matching records. Default Null.
1564 *
1565 * }
1566 *
1567 * @return array {
1568 * An array of post view data, each post as an array
1569 *
1570 * array {
1571 * The post view data for a single post
1572 *
1573 * @type string $post_id The ID of the post
1574 * @type string $post_title The title of the post
1575 * @type string $post_permalink The permalink for the post
1576 * @type string $views The number of views for the post within the $num_days specified
1577 * }
1578 * }
1579 */
1580 function stats_get_csv( $table, $args = null ) {
1581 $defaults = array( 'end' => false, 'days' => false, 'limit' => 3, 'post_id' => false, 'summarize' => '' );
1582
1583 $args = wp_parse_args( $args, $defaults );
1584 $args['table'] = $table;
1585 $args['blog_id'] = Jetpack_Options::get_option( 'id' );
1586
1587 $stats_csv_url = add_query_arg( $args, 'https://stats.wordpress.com/csv.php' );
1588
1589 $key = md5( $stats_csv_url );
1590
1591 // Get cache.
1592 $stats_cache = get_option( 'stats_cache' );
1593 if ( ! $stats_cache || ! is_array( $stats_cache ) ) {
1594 $stats_cache = array();
1595 }
1596
1597 // Return or expire this key.
1598 if ( isset( $stats_cache[ $key ] ) ) {
1599 $time = key( $stats_cache[ $key ] );
1600 if ( time() - $time < 300 ) {
1601 return $stats_cache[ $key ][ $time ];
1602 }
1603 unset( $stats_cache[ $key ] );
1604 }
1605
1606 $stats_rows = array();
1607 do {
1608 if ( ! $stats = stats_get_remote_csv( $stats_csv_url ) ) {
1609 break;
1610 }
1611
1612 $labels = array_shift( $stats );
1613
1614 if ( 0 === stripos( $labels[0], 'error' ) ) {
1615 break;
1616 }
1617
1618 $stats_rows = array();
1619 for ( $s = 0; isset( $stats[ $s ] ); $s++ ) {
1620 $row = array();
1621 foreach ( $labels as $col => $label ) {
1622 $row[ $label ] = $stats[ $s ][ $col ];
1623 }
1624 $stats_rows[] = $row;
1625 }
1626 } while ( 0 );
1627
1628 // Expire old keys.
1629 foreach ( $stats_cache as $k => $cache ) {
1630 if ( ! is_array( $cache ) || 300 < time() - key( $cache ) ) {
1631 unset( $stats_cache[ $k ] );
1632 }
1633 }
1634
1635 // Set cache.
1636 $stats_cache[ $key ] = array( time() => $stats_rows );
1637 update_option( 'stats_cache', $stats_cache );
1638
1639 return $stats_rows;
1640 }
1641
1642 /**
1643 * Stats get remote CSV.
1644 *
1645 * @access public
1646 * @param mixed $url URL.
1647 * @return array
1648 */
1649 function stats_get_remote_csv( $url ) {
1650 $method = 'GET';
1651 $timeout = 90;
1652 $user_id = JETPACK_MASTER_USER;
1653
1654 $get = Jetpack_Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
1655 $get_code = wp_remote_retrieve_response_code( $get );
1656 if ( is_wp_error( $get ) || ( 2 !== intval( $get_code / 100 ) && 304 !== $get_code ) || empty( $get['body'] ) ) {
1657 return array(); // @todo: return an error?
1658 } else {
1659 return stats_str_getcsv( $get['body'] );
1660 }
1661 }
1662
1663 /**
1664 * Rather than parsing the csv and its special cases, we create a new file and do fgetcsv on it.
1665 *
1666 * @access public
1667 * @param mixed $csv CSV.
1668 * @return array.
1669 */
1670 function stats_str_getcsv( $csv ) {
1671 if ( function_exists( 'str_getcsv' ) ) {
1672 $lines = str_getcsv( $csv, "\n" ); // phpcs:ignore PHPCompatibility.PHP.NewFunctions.str_getcsvFound
1673 return array_map( 'str_getcsv', $lines );
1674 }
1675 if ( ! $temp = tmpfile() ) { // The tmpfile() automatically unlinks.
1676 return false;
1677 }
1678
1679 $data = array();
1680
1681 fwrite( $temp, $csv, strlen( $csv ) );
1682 fseek( $temp, 0 );
1683 while ( false !== $row = fgetcsv( $temp, 2000 ) ) {
1684 $data[] = $row;
1685 }
1686 fclose( $temp );
1687
1688 return $data;
1689 }
1690
1691 /**
1692 * Abstract out building the rest api stats path.
1693 *
1694 * @param string $resource Resource.
1695 * @return string
1696 */
1697 function jetpack_stats_api_path( $resource = '' ) {
1698 $resource = ltrim( $resource, '/' );
1699 return sprintf( '/sites/%d/stats/%s', stats_get_option( 'blog_id' ), $resource );
1700 }
1701
1702 /**
1703 * Fetches stats data from the REST API. Caches locally for 5 minutes.
1704 *
1705 * @link: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/
1706 * @access public
1707 * @param array $args (default: array()) The args that are passed to the endpoint.
1708 * @param string $resource (default: '') Optional sub-endpoint following /stats/.
1709 * @return array|WP_Error.
1710 */
1711 function stats_get_from_restapi( $args = array(), $resource = '' ) {
1712 $endpoint = jetpack_stats_api_path( $resource );
1713 $api_version = '1.1';
1714 $args = wp_parse_args( $args, array() );
1715 $cache_key = md5( implode( '|', array( $endpoint, $api_version, serialize( $args ) ) ) );
1716
1717 // Get cache.
1718 $stats_cache = Jetpack_Options::get_option( 'restapi_stats_cache', array() );
1719 if ( ! is_array( $stats_cache ) ) {
1720 $stats_cache = array();
1721 }
1722
1723 // Return or expire this key.
1724 if ( isset( $stats_cache[ $cache_key ] ) ) {
1725 $time = key( $stats_cache[ $cache_key ] );
1726 if ( time() - $time < ( 5 * MINUTE_IN_SECONDS ) ) {
1727 $cached_stats = $stats_cache[ $cache_key ][ $time ];
1728 $cached_stats = (object) array_merge( array( 'cached_at' => $time ), (array) $cached_stats );
1729 return $cached_stats;
1730 }
1731 unset( $stats_cache[ $cache_key ] );
1732 }
1733
1734 // Do the dirty work.
1735 $response = Jetpack_Client::wpcom_json_api_request_as_blog( $endpoint, $api_version, $args );
1736 if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
1737 // If bad, just return it, don't cache.
1738 return $response;
1739 }
1740
1741 $data = json_decode( wp_remote_retrieve_body( $response ) );
1742
1743 // Expire old keys.
1744 foreach ( $stats_cache as $k => $cache ) {
1745 if ( ! is_array( $cache ) || ( 5 * MINUTE_IN_SECONDS ) < time() - key( $cache ) ) {
1746 unset( $stats_cache[ $k ] );
1747 }
1748 }
1749
1750 // Set cache.
1751 $stats_cache[ $cache_key ] = array(
1752 time() => $data,
1753 );
1754 Jetpack_Options::update_option( 'restapi_stats_cache', $stats_cache, false );
1755
1756 return $data;
1757 }
1758
1759 /**
1760 * Load CSS needed for Stats column width in WP-Admin area.
1761 *
1762 * @since 4.7.0
1763 */
1764 function jetpack_stats_load_admin_css() {
1765 ?>
1766 <style type="text/css">
1767 .fixed .column-stats {
1768 width: 5em;
1769 }
1770 </style>
1771 <?php
1772 }
1773
1774 /**
1775 * Set header for column that allows to go to WordPress.com to see an entry's stats.
1776 *
1777 * @param array $columns An array of column names.
1778 *
1779 * @since 4.7.0
1780 *
1781 * @return mixed
1782 */
1783 function jetpack_stats_post_table( $columns ) { // Adds a stats link on the edit posts page
1784 if ( ! current_user_can( 'view_stats' ) || ! Jetpack::is_user_connected() ) {
1785 return $columns;
1786 }
1787 // Array-Fu to add before comments
1788 $pos = array_search( 'comments', array_keys( $columns ) );
1789 if ( ! is_int( $pos ) ) {
1790 return $columns;
1791 }
1792 $chunks = array_chunk( $columns, $pos, true );
1793 $chunks[0]['stats'] = esc_html__( 'Stats', 'jetpack' );
1794
1795 return call_user_func_array( 'array_merge', $chunks );
1796 }
1797
1798 /**
1799 * Set content for cell with link to an entry's stats in WordPress.com.
1800 *
1801 * @param string $column The name of the column to display.
1802 * @param int $post_id The current post ID.
1803 *
1804 * @since 4.7.0
1805 *
1806 * @return mixed
1807 */
1808 function jetpack_stats_post_table_cell( $column, $post_id ) {
1809 if ( 'stats' == $column ) {
1810 if ( 'publish' != get_post_status( $post_id ) ) {
1811 printf(
1812 '<span aria-hidden="true">—</span><span class="screen-reader-text">%s</span>',
1813 esc_html__( 'No stats', 'jetpack' )
1814 );
1815 } else {
1816 printf(
1817 '<a href="%s" title="%s" class="dashicons dashicons-chart-bar" target="_blank"></a>',
1818 esc_url( "https://wordpress.com/stats/post/$post_id/" . Jetpack::build_raw_urls( get_home_url() ) ),
1819 esc_html__( 'View stats for this post in WordPress.com', 'jetpack' )
1820 );
1821 }
1822 }
1823 }
1824