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

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