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

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