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

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