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

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

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