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

1,759 lines 49.0 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, WordPress.Security.ValidatedSanitizedInput
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
277 /**
278 * Filter the parameters added to the AMP pixel tracking code.
279 *
280 * @module stats
281 *
282 * @since 10.9
283 *
284 * @param array $data Array of options about the site and page you're on.
285 */
286 $data = (array) apply_filters( 'jetpack_stats_footer_amp_data', $data );
287 stats_render_amp_footer( $data );
288 } else {
289
290 /**
291 * Filter the parameters added to the JavaScript stats tracking code.
292 *
293 * @module stats
294 *
295 * @since 10.9
296 *
297 * @param array $data Array of options about the site and page you're on.
298 */
299 $data = (array) apply_filters( 'jetpack_stats_footer_js_data', $data );
300 stats_render_footer( $data );
301 }
302
303 }
304
305 /**
306 * Render the stats footer
307 *
308 * @param array $data Array of data for the JS stats tracker.
309 */
310 function stats_render_footer( $data ) {
311 // phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedScript
312 // When there is a way to use defer with enqueue, we can move to it and inline the custom data.
313 $script = 'https://stats.wp.com/e-' . gmdate( 'YW' ) . '.js';
314 $data_stats_array = stats_array( $data );
315
316 $stats_footer = <<<END
317 <script src='{$script}' defer></script>
318 <script>
319 _stq = window._stq || [];
320 _stq.push([ 'view', {{$data_stats_array}} ]);
321 _stq.push([ 'clickTrackerInit', '{$data['blog']}', '{$data['post']}' ]);
322 </script>
323
324 END;
325 // phpcs:enable
326 print $stats_footer; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
327 }
328
329 /**
330 * Render the stats footer for AMP output.
331 *
332 * @param array $data Array of data for the AMP pixel tracker.
333 */
334 function stats_render_amp_footer( $data ) {
335 $data['host'] = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : ''; // input var ok.
336 $data['rand'] = 'RANDOM'; // AMP placeholder.
337 $data['ref'] = 'DOCUMENT_REFERRER'; // AMP placeholder.
338 $data = array_map( 'rawurlencode', $data );
339 $pixel_url = add_query_arg( $data, 'https://pixel.wp.com/g.gif' );
340
341 ?>
342 <amp-pixel src="<?php echo esc_url( $pixel_url ); ?>"></amp-pixel>
343 <?php
344 }
345
346 /**
347 * Stats Get Options.
348 *
349 * @access public
350 * @return array.
351 */
352 function stats_get_options() {
353 $options = get_option( 'stats_options' );
354
355 if ( ! isset( $options['version'] ) || $options['version'] < STATS_VERSION ) {
356 $options = stats_upgrade_options( $options );
357 }
358
359 return $options;
360 }
361
362 /**
363 * Get Stats Options.
364 *
365 * @access public
366 * @param mixed $option Option.
367 * @return mixed|null.
368 */
369 function stats_get_option( $option ) {
370 $options = stats_get_options();
371
372 if ( 'blog_id' === $option ) {
373 return Jetpack_Options::get_option( 'id' );
374 }
375
376 if ( isset( $options[ $option ] ) ) {
377 return $options[ $option ];
378 }
379
380 return null;
381 }
382
383 /**
384 * Stats Set Options.
385 *
386 * @access public
387 * @param mixed $option Option.
388 * @param mixed $value Value.
389 * @return bool.
390 */
391 function stats_set_option( $option, $value ) {
392 $options = stats_get_options();
393
394 $options[ $option ] = $value;
395
396 return stats_set_options( $options );
397 }
398
399 /**
400 * Stats Set Options.
401 *
402 * @access public
403 * @param mixed $options Options.
404 * @return bool
405 */
406 function stats_set_options( $options ) {
407 return update_option( 'stats_options', $options );
408 }
409
410 /**
411 * Stats Upgrade Options.
412 *
413 * @access public
414 * @param mixed $options Options.
415 * @return array|bool
416 */
417 function stats_upgrade_options( $options ) {
418 $defaults = array(
419 'admin_bar' => true,
420 'roles' => array( 'administrator' ),
421 'count_roles' => array(),
422 'blog_id' => Jetpack_Options::get_option( 'id' ),
423 'do_not_track' => true, // @todo
424 );
425
426 if ( isset( $options['reg_users'] ) ) {
427 if ( ! function_exists( 'get_editable_roles' ) ) {
428 require_once ABSPATH . 'wp-admin/includes/user.php';
429 }
430 if ( $options['reg_users'] ) {
431 $options['count_roles'] = array_keys( get_editable_roles() );
432 }
433 unset( $options['reg_users'] );
434 }
435
436 if ( is_array( $options ) && ! empty( $options ) ) {
437 $new_options = array_merge( $defaults, $options );
438 } else {
439 $new_options = $defaults;
440 }
441
442 $new_options['version'] = STATS_VERSION;
443
444 if ( ! stats_set_options( $new_options ) ) {
445 return false;
446 }
447
448 return $new_options;
449 }
450
451 /**
452 * Creates the "array" string used as part of the JS tracker.
453 *
454 * @access public
455 * @param array $kvs KVS.
456 * @return string
457 */
458 function stats_array( $kvs ) {
459 /**
460 * Filter the options added to the JavaScript Stats tracking code.
461 *
462 * @module stats
463 *
464 * @since 1.1.0
465 *
466 * @param array $kvs Array of options about the site and page you're on.
467 */
468 $kvs = (array) apply_filters( 'stats_array', $kvs );
469 $kvs = array_map( 'addslashes', $kvs );
470 $jskvs = array();
471 foreach ( $kvs as $k => $v ) {
472 $jskvs[] = "$k:'$v'";
473 }
474 return join( ',', $jskvs );
475 }
476
477 /**
478 * Admin Pages.
479 *
480 * @access public
481 * @return void
482 */
483 function stats_admin_menu() {
484 global $pagenow;
485
486 // If we're at an old Stats URL, redirect to the new one.
487 // Don't even bother with caps, menu_page_url(), etc. Just do it.
488 if ( 'index.php' === $pagenow && isset( $_GET['page'] ) && 'stats' === $_GET['page'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
489 $redirect_url = str_replace( array( '/wp-admin/index.php?', '/wp-admin/?' ), '/wp-admin/admin.php?', isset( $_SERVER['REQUEST_URI'] ) ? filter_var( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : null );
490 $relative_pos = strpos( $redirect_url, '/wp-admin/' );
491 if ( false !== $relative_pos ) {
492 wp_safe_redirect( admin_url( substr( $redirect_url, $relative_pos + 10 ) ) );
493 exit;
494 }
495 }
496
497 $hook = add_submenu_page( 'jetpack', __( 'Site Stats', 'jetpack' ), __( 'Site Stats', 'jetpack' ), 'view_stats', 'stats', 'jetpack_admin_ui_stats_report_page_wrapper' );
498 add_action( "load-$hook", 'stats_reports_load' );
499 }
500
501 /**
502 * Stats Admin Path.
503 *
504 * @access public
505 * @return string
506 */
507 function stats_admin_path() {
508 return Jetpack::module_configuration_url( __FILE__ );
509 }
510
511 /**
512 * Stats Reports Load.
513 *
514 * @access public
515 * @return void
516 */
517 function stats_reports_load() {
518 require_once __DIR__ . '/stats/class-jetpack-stats-upgrade-nudges.php';
519 Jetpack_Stats_Upgrade_Nudges::init();
520
521 wp_enqueue_script( 'jquery' );
522 wp_enqueue_script( 'postbox' );
523 wp_enqueue_script( 'underscore' );
524
525 Jetpack_Admin_Page::load_wrapper_styles();
526 add_action( 'admin_print_styles', 'stats_reports_css' );
527
528 if ( ! empty( $_GET['nojs'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
529 $parsed = wp_parse_url( admin_url() );
530 // Remember user doesn't want JS.
531 setcookie( 'stnojs', '1', time() + 172800, $parsed['path'], COOKIE_DOMAIN, is_ssl(), true ); // 2 days.
532 }
533
534 if ( ! empty( $_COOKIE['stnojs'] ) ) {
535 // Detect if JS is on. If so, remove cookie so next page load is via JS.
536 add_action( 'admin_print_footer_scripts', 'stats_js_remove_stnojs_cookie' );
537 } elseif ( ! isset( $_GET['noheader'] ) && empty( $_GET['nojs'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
538 // Normal page load. Load page content via JS.
539 add_action( 'admin_print_footer_scripts', 'stats_js_load_page_via_ajax' );
540 }
541 }
542
543 /**
544 * Stats Reports CSS.
545 *
546 * @access public
547 * @return void
548 */
549 function stats_reports_css() {
550 ?>
551 <style type="text/css">
552 #jp-stats-wrap, #jp-stats-report-bottom {
553 max-width: 1040px;
554 margin: 0 auto;
555 overflow: hidden;
556 }
557
558 #stats-loading-wrap p {
559 text-align: center;
560 font-size: 2em;
561 margin: 7.5em 15px 0 0;
562 height: 64px;
563 line-height: 64px;
564 }
565 </style>
566 <?php
567 }
568
569 /**
570 * Detect if JS is on. If so, remove cookie so next page load is via JS.
571 *
572 * @access public
573 * @return void
574 */
575 function stats_js_remove_stnojs_cookie() {
576 $parsed = wp_parse_url( admin_url() );
577 ?>
578 <script type="text/javascript">
579 /* <![CDATA[ */
580 document.cookie = 'stnojs=0; expires=Wed, 9 Mar 2011 16:55:50 UTC; path=<?php echo esc_js( $parsed['path'] ); ?>';
581 /* ]]> */
582 </script>
583 <?php
584 }
585
586 /**
587 * Normal page load. Load page content via JS.
588 *
589 * @access public
590 * @return void
591 */
592 function stats_js_load_page_via_ajax() {
593 ?>
594 <script type="text/javascript">
595 /* <![CDATA[ */
596 if ( -1 == document.location.href.indexOf( 'noheader' ) ) {
597 jQuery( function( $ ) {
598 $.get( document.location.href + '&noheader', function( responseText ) {
599 $( '#stats-loading-wrap' ).replaceWith( responseText );
600 $( '#jp-stats-wrap' )[0].dispatchEvent( new Event( 'stats-loaded' ) );
601 } );
602 } );
603 }
604 /* ]]> */
605 </script>
606 <?php
607 }
608
609 /**
610 * Jetpack Admin Page Wrapper.
611 */
612 function jetpack_admin_ui_stats_report_page_wrapper() {
613 if ( ! isset( $_GET['noheader'] ) && empty( $_GET['nojs'] ) && empty( $_COOKIE['stnojs'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
614 Jetpack_Admin_Page::wrap_ui( 'stats_reports_page', array( 'is-wide' => true ) );
615 } else {
616 stats_reports_page();
617 }
618
619 }
620
621 /**
622 * Stats Report Page.
623 *
624 * @access public
625 * @param bool $main_chart_only (default: false) Main Chart Only.
626 */
627 function stats_reports_page( $main_chart_only = false ) {
628
629 if ( isset( $_GET['dashboard'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
630 return stats_dashboard_widget_content();
631 }
632
633 $blog_id = stats_get_option( 'blog_id' );
634 $stats_url = Redirect::get_url( 'calypso-stats' );
635
636 if ( ! $main_chart_only && ! isset( $_GET['noheader'] ) && empty( $_GET['nojs'] ) && empty( $_COOKIE['stnojs'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
637 $nojs_url = add_query_arg( 'nojs', '1' );
638 $http = is_ssl() ? 'https' : 'http';
639 // Loading message. No JS fallback message.
640 ?>
641
642 <div id="jp-stats-wrap">
643 <div class="wrap">
644 <h2><?php esc_html_e( 'Site Stats', 'jetpack' ); ?>
645 <?php
646 if ( current_user_can( 'jetpack_manage_modules' ) ) :
647 $i18n_headers = jetpack_get_module_i18n( 'stats' );
648 ?>
649 <a
650 style="font-size:13px;"
651 href="<?php echo esc_url( admin_url( 'admin.php?page=jetpack#/settings?term=' . rawurlencode( $i18n_headers['name'] ) ) ); ?>"
652 >
653 <?php esc_html_e( 'Configure', 'jetpack' ); ?>
654 </a>
655 <?php
656 endif;
657
658 /**
659 * Sets external resource URL.
660 *
661 * @module stats
662 *
663 * @since 1.4.0
664 * @todo Clean up various uses of this filter. It's seemingly filtering different types of images in different places.
665 *
666 * @param string $args URL of external resource.
667 */
668 $static_url = apply_filters( 'jetpack_static_url', "{$http}://en.wordpress.com/i/loading/loading-64.gif" );
669 ?>
670 </h2>
671 </div>
672 <div id="stats-loading-wrap" class="wrap">
673 <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>
674 <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>
675 <p class="hide-if-js"><?php esc_html_e( 'Your Site Stats work better with JavaScript enabled.', 'jetpack' ); ?><br />
676 <a href="<?php echo esc_url( $nojs_url ); ?>"><?php esc_html_e( 'View Site Stats without JavaScript', 'jetpack' ); ?></a>.</p>
677 </div>
678 </div>
679 <?php
680 return;
681 }
682
683 $day = isset( $_GET['day'] ) && preg_match( '/^\d{4}-\d{2}-\d{2}$/', $_GET['day'] ) ? $_GET['day'] : false; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput
684 $q = array(
685 'noheader' => 'true',
686 'proxy' => '',
687 'page' => 'stats',
688 'day' => $day,
689 'blog' => $blog_id,
690 'charset' => get_option( 'blog_charset' ),
691 'color' => get_user_option( 'admin_color' ),
692 'ssl' => is_ssl(),
693 'j' => sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION ),
694 );
695 if ( get_locale() !== 'en_US' ) {
696 $q['jp_lang'] = get_locale();
697 }
698 // Only show the main chart, without extra header data, or metaboxes.
699 $q['main_chart_only'] = $main_chart_only;
700 $args = array(
701 'view' => array( 'referrers', 'postviews', 'searchterms', 'clicks', 'post', 'table' ),
702 'numdays' => 'int',
703 'day' => 'date',
704 'unit' => array( '1', '7', '31', 'human' ),
705 'humanize' => array( 'true' ),
706 'num' => 'int',
707 'summarize' => null,
708 'post' => 'int',
709 'width' => 'int',
710 'height' => 'int',
711 'data' => 'data',
712 'blog_subscribers' => 'int',
713 'comment_subscribers' => null,
714 'type' => array( 'wpcom', 'email', 'pending' ),
715 'pagenum' => 'int',
716 'masterbar' => null,
717 );
718 foreach ( $args as $var => $vals ) {
719 if ( ! isset( $_REQUEST[ $var ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
720 continue;
721 }
722 $val = wp_unslash( $_REQUEST[ $var ] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
723 if ( is_array( $vals ) ) {
724 if ( in_array( $val, $vals, true ) ) {
725 $q[ $var ] = $val;
726 }
727 } elseif ( 'int' === $vals ) {
728 $q[ $var ] = (int) $val;
729 } elseif ( 'date' === $vals ) {
730 if ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', $val ) ) {
731 $q[ $var ] = $val;
732 }
733 } elseif ( null === $vals ) {
734 $q[ $var ] = '';
735 } elseif ( 'data' === $vals ) {
736 if ( 'index.php' === substr( $val, 0, 9 ) ) {
737 $q[ $var ] = $val;
738 }
739 }
740 }
741
742 if ( isset( $_GET['chart'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
743 if ( preg_match( '/^[a-z0-9-]+$/', $_GET['chart'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput
744 $chart = sanitize_title( $_GET['chart'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput
745 $url = 'https://' . STATS_DASHBOARD_SERVER . "/wp-includes/charts/{$chart}.php";
746 }
747 } else {
748 $url = 'https://' . STATS_DASHBOARD_SERVER . '/wp-admin/index.php';
749 }
750
751 $url = add_query_arg( $q, $url );
752 $method = 'GET';
753 $timeout = 90;
754 $user_id = 0; // Means use the blog token.
755
756 $get = Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
757 $get_code = wp_remote_retrieve_response_code( $get );
758 if ( is_wp_error( $get ) || ( 2 !== (int) ( $get_code / 100 ) && 304 !== $get_code ) || empty( $get['body'] ) ) {
759 stats_print_wp_remote_error( $get, $url );
760 } else {
761 if ( ! empty( $get['headers']['content-type'] ) ) {
762 $type = $get['headers']['content-type'];
763 if ( substr( $type, 0, 5 ) === 'image' ) {
764 $img = $get['body'];
765 header( 'Content-Type: ' . $type );
766 header( 'Content-Length: ' . strlen( $img ) );
767 echo $img; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
768 die();
769 }
770 }
771 $body = stats_convert_post_titles( $get['body'] );
772 $body = stats_convert_chart_urls( $body );
773 $body = stats_convert_image_urls( $body );
774 $body = stats_convert_admin_urls( $body );
775 echo $body; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
776 }
777
778 if ( isset( $_GET['page'] ) && 'stats' === $_GET['page'] && ! isset( $_GET['chart'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
779 $tracking = new Tracking();
780 $tracking->record_user_event( 'wpa_page_view', array( 'path' => 'old_stats' ) );
781 }
782
783 if ( isset( $_GET['noheader'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
784 die;
785 }
786 }
787
788 /**
789 * Stats Convert Admin Urls.
790 *
791 * @access public
792 * @param mixed $html HTML.
793 * @return string
794 */
795 function stats_convert_admin_urls( $html ) {
796 return str_replace( 'index.php?page=stats', 'admin.php?page=stats', $html );
797 }
798
799 /**
800 * Stats Convert Image URLs.
801 *
802 * @access public
803 * @param mixed $html HTML.
804 * @return string
805 */
806 function stats_convert_image_urls( $html ) {
807 $url = set_url_scheme( 'https://' . STATS_DASHBOARD_SERVER );
808 $html = preg_replace( '|(["\'])(/i/stats.+)\\1|', '$1' . $url . '$2$1', $html );
809 return $html;
810 }
811
812 /**
813 * Callback for preg_replace_callback used in stats_convert_chart_urls()
814 *
815 * @since 5.6.0
816 *
817 * @param array $matches The matches resulting from the preg_replace_callback call.
818 * @return string The admin url for the chart.
819 */
820 function jetpack_stats_convert_chart_urls_callback( $matches ) {
821 // If there is a query string, change the beginning '?' to a '&' so it fits into the middle of this query string.
822 return 'admin.php?page=stats&noheader&chart=' . $matches[1] . str_replace( '?', '&', $matches[2] );
823 }
824
825 /**
826 * Stats Convert Chart URLs.
827 *
828 * @access public
829 * @param mixed $html HTML.
830 * @return string
831 */
832 function stats_convert_chart_urls( $html ) {
833 $html = preg_replace_callback(
834 '|https?://[-.a-z0-9]+/wp-includes/charts/([-.a-z0-9]+).php(\??)|',
835 'jetpack_stats_convert_chart_urls_callback',
836 $html
837 );
838 return $html;
839 }
840
841 /**
842 * Stats Convert Post Title HTML
843 *
844 * @access public
845 * @param mixed $html HTML.
846 * @return string
847 */
848 function stats_convert_post_titles( $html ) {
849 global $stats_posts;
850 $pattern = "<span class='post-(\d+)-link'>.*?</span>";
851 if ( ! preg_match_all( "!$pattern!", $html, $matches ) ) {
852 return $html;
853 }
854 $posts = get_posts(
855 array(
856 'include' => implode( ',', $matches[1] ),
857 'post_type' => 'any',
858 'post_status' => 'any',
859 'numberposts' => -1,
860 'suppress_filters' => false,
861 )
862 );
863 foreach ( $posts as $post ) {
864 $stats_posts[ $post->ID ] = $post;
865 }
866 $html = preg_replace_callback( "!$pattern!", 'stats_convert_post_title', $html );
867 return $html;
868 }
869
870 /**
871 * Stats Convert Post Title Matches.
872 *
873 * @access public
874 * @param mixed $matches Matches.
875 * @return string
876 */
877 function stats_convert_post_title( $matches ) {
878 global $stats_posts;
879 $post_id = $matches[1];
880 if ( isset( $stats_posts[ $post_id ] ) ) {
881 return '<a href="' . get_permalink( $post_id ) . '" target="_blank">' . get_the_title( $post_id ) . '</a>';
882 }
883 return $matches[0];
884 }
885
886 /**
887 * CSS to hide the tracking pixel smiley.
888 * It is now hidden for everyone (used to be visible if you had set the hide_smile option).
889 *
890 * @access public
891 * @return void
892 */
893 function stats_hide_smile_css() {
894 ?>
895 <style>img#wpstats{display:none}</style>
896 <?php
897 }
898
899 /**
900 * Stats Admin Bar Head.
901 *
902 * @access public
903 * @return void
904 */
905 function stats_admin_bar_head() {
906 if ( ! stats_get_option( 'admin_bar' ) ) {
907 return;
908 }
909
910 if ( ! current_user_can( 'view_stats' ) ) {
911 return;
912 }
913
914 if ( ! is_admin_bar_showing() ) {
915 return;
916 }
917
918 add_action( 'admin_bar_menu', 'stats_admin_bar_menu', 100 );
919 ?>
920
921 <style data-ampdevmode type='text/css'>
922 #wpadminbar .quicklinks li#wp-admin-bar-stats {
923 height: 32px;
924 }
925 #wpadminbar .quicklinks li#wp-admin-bar-stats a {
926 height: 32px;
927 padding: 0;
928 }
929 #wpadminbar .quicklinks li#wp-admin-bar-stats a div {
930 height: 32px;
931 width: 95px;
932 overflow: hidden;
933 margin: 0 10px;
934 }
935 #wpadminbar .quicklinks li#wp-admin-bar-stats a:hover div {
936 width: auto;
937 margin: 0 8px 0 10px;
938 }
939 #wpadminbar .quicklinks li#wp-admin-bar-stats a img {
940 height: 24px;
941 margin: 4px 0;
942 max-width: none;
943 border: none;
944 }
945 </style>
946 <?php
947 }
948
949 /**
950 * Gets the image source of the given stats chart.
951 *
952 * @param string $chart Name of the chart.
953 * @param array $args Extra list of argument to use in the image source.
954 * @return string An image source.
955 */
956 function stats_get_image_chart_src( $chart, $args = array() ) {
957 $url = add_query_arg( 'page', 'stats', admin_url( 'admin.php' ) );
958
959 return add_query_arg(
960 array_merge(
961 array(
962 'noheader' => '',
963 'proxy' => '',
964 'chart' => $chart,
965 ),
966 $args
967 ),
968 $url
969 );
970 }
971
972 /**
973 * Stats AdminBar.
974 *
975 * @access public
976 * @param mixed $wp_admin_bar WPAdminBar.
977 * @return void
978 */
979 function stats_admin_bar_menu( &$wp_admin_bar ) {
980 $img_src = esc_attr( stats_get_image_chart_src( 'admin-bar-hours-scale' ) );
981 $img_src_2x = esc_attr( stats_get_image_chart_src( 'admin-bar-hours-scale-2x' ) );
982 $alt = esc_attr( __( 'Stats', 'jetpack' ) );
983 $title = esc_attr( __( 'Views over 48 hours. Click for more Site Stats.', 'jetpack' ) );
984
985 $menu = array(
986 'id' => 'stats',
987 'href' => add_query_arg( 'page', 'stats', admin_url( 'admin.php' ) ), // no menu_page_url() blog-side.
988 'title' => "<div><img src='$img_src' srcset='$img_src 1x, $img_src_2x 2x' width='112' height='24' alt='$alt' title='$title'></div>",
989 );
990
991 $wp_admin_bar->add_menu( $menu );
992 }
993
994 /**
995 *
996 * Deprecated. The stats module should not update blog details. This is handled by Sync.
997 *
998 * Stats Update Blog.
999 *
1000 * @access public
1001 * @return void
1002 *
1003 * @deprecated since 10.3.
1004 */
1005 function stats_update_blog() {
1006 deprecated_function( __METHOD__, 'jetpack-10.3' );
1007 XMLRPC_Async_Call::add_call( 'jetpack.updateBlog', 0, stats_get_blog() );
1008 }
1009
1010 /**
1011 * Stats Get Blog.
1012 *
1013 * @access public
1014 * @return string
1015 */
1016 function stats_get_blog() {
1017 $home = wp_parse_url( trailingslashit( get_option( 'home' ) ) );
1018 $blog = array(
1019 'host' => $home['host'],
1020 'path' => $home['path'],
1021 'blogname' => get_option( 'blogname' ),
1022 'blogdescription' => get_option( 'blogdescription' ),
1023 'siteurl' => get_option( 'siteurl' ),
1024 'gmt_offset' => get_option( 'gmt_offset' ),
1025 'timezone_string' => get_option( 'timezone_string' ),
1026 'stats_version' => STATS_VERSION,
1027 'stats_api' => 'jetpack',
1028 'page_on_front' => get_option( 'page_on_front' ),
1029 'permalink_structure' => get_option( 'permalink_structure' ),
1030 'category_base' => get_option( 'category_base' ),
1031 'tag_base' => get_option( 'tag_base' ),
1032 );
1033 $blog = array_merge( stats_get_options(), $blog );
1034 unset( $blog['roles'], $blog['blog_id'] );
1035 return stats_esc_html_deep( $blog );
1036 }
1037
1038 /**
1039 * Modified from stripslashes_deep()
1040 *
1041 * @access public
1042 * @param mixed $value Value.
1043 * @return string
1044 */
1045 function stats_esc_html_deep( $value ) {
1046 if ( is_array( $value ) ) {
1047 $value = array_map( 'stats_esc_html_deep', $value );
1048 } elseif ( is_object( $value ) ) {
1049 $vars = get_object_vars( $value );
1050 foreach ( $vars as $key => $data ) {
1051 $value->{$key} = stats_esc_html_deep( $data );
1052 }
1053 } elseif ( is_string( $value ) ) {
1054 $value = esc_html( $value );
1055 }
1056
1057 return $value;
1058 }
1059
1060 /**
1061 * Stats xmlrpc_methods function.
1062 *
1063 * @access public
1064 * @param mixed $methods Methods.
1065 * @return array
1066 */
1067 function stats_xmlrpc_methods( $methods ) {
1068 $my_methods = array(
1069 'jetpack.getBlog' => 'stats_get_blog',
1070 );
1071
1072 return array_merge( $methods, $my_methods );
1073 }
1074
1075 /**
1076 * Stats Dashboard Widget Options.
1077 *
1078 * @access public
1079 * @return array
1080 */
1081 function stats_dashboard_widget_options() {
1082 $defaults = array(
1083 'chart' => 1,
1084 'top' => 1,
1085 'search' => 7,
1086 );
1087 $options = get_option( 'stats_dashboard_widget' );
1088 if ( ( ! $options ) || ! is_array( $options ) ) {
1089 $options = array();
1090 }
1091
1092 // Ignore obsolete option values.
1093 $intervals = array( 1, 7, 31, 90, 365 );
1094 foreach ( array( 'top', 'search' ) as $key ) {
1095 if ( isset( $options[ $key ] ) && ! in_array( (int) $options[ $key ], $intervals, true ) ) {
1096 unset( $options[ $key ] );
1097 }
1098 }
1099
1100 return array_merge( $defaults, $options );
1101 }
1102
1103 /**
1104 * Stats Dashboard Widget Control.
1105 *
1106 * @access public
1107 * @return void
1108 */
1109 function stats_dashboard_widget_control() {
1110 $periods = array(
1111 '1' => __( 'day', 'jetpack' ),
1112 '7' => __( 'week', 'jetpack' ),
1113 '31' => __( 'month', 'jetpack' ),
1114 );
1115 $intervals = array(
1116 '1' => __( 'the past day', 'jetpack' ),
1117 '7' => __( 'the past week', 'jetpack' ),
1118 '31' => __( 'the past month', 'jetpack' ),
1119 '90' => __( 'the past quarter', 'jetpack' ),
1120 '365' => __( 'the past year', 'jetpack' ),
1121 );
1122 $defaults = array(
1123 'top' => 1,
1124 'search' => 7,
1125 );
1126
1127 $options = stats_dashboard_widget_options();
1128
1129 if ( isset( $_SERVER['REQUEST_METHOD'] ) && 'post' === strtolower( filter_var( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) && isset( $_POST['widget_id'] ) && 'dashboard_stats' === $_POST['widget_id'] ) { // phpcs:ignore WordPress.Security.NonceVerification
1130 if ( isset( $periods[ $_POST['chart'] ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
1131 $options['chart'] = filter_var( wp_unslash( $_POST['chart'] ) ); // phpcs:ignore WordPress.Security.NonceVerification
1132 }
1133 foreach ( array( 'top', 'search' ) as $key ) {
1134 if ( isset( $intervals[ $_POST[ $key ] ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
1135 $options[ $key ] = filter_var( wp_unslash( $_POST[ $key ] ) ); // phpcs:ignore WordPress.Security.NonceVerification
1136 } else {
1137 $options[ $key ] = $defaults[ $key ];
1138 }
1139 }
1140 update_option( 'stats_dashboard_widget', $options );
1141 }
1142 ?>
1143 <p>
1144 <label for="chart"><?php esc_html_e( 'Chart stats by', 'jetpack' ); ?></label>
1145 <select id="chart" name="chart">
1146 <?php
1147 foreach ( $periods as $val => $label ) {
1148 ?>
1149 <option value="<?php echo esc_attr( $val ); ?>"<?php selected( $val, $options['chart'] ); ?>><?php echo esc_html( $label ); ?></option>
1150 <?php
1151 }
1152 ?>
1153 </select>.
1154 </p>
1155
1156 <p>
1157 <label for="top"><?php esc_html_e( 'Show top posts over', 'jetpack' ); ?></label>
1158 <select id="top" name="top">
1159 <?php
1160 foreach ( $intervals as $val => $label ) {
1161 ?>
1162 <option value="<?php echo esc_attr( $val ); ?>"<?php selected( $val, $options['top'] ); ?>><?php echo esc_html( $label ); ?></option>
1163 <?php
1164 }
1165 ?>
1166 </select>.
1167 </p>
1168
1169 <p>
1170 <label for="search"><?php esc_html_e( 'Show top search terms over', 'jetpack' ); ?></label>
1171 <select id="search" name="search">
1172 <?php
1173 foreach ( $intervals as $val => $label ) {
1174 ?>
1175 <option value="<?php echo esc_attr( $val ); ?>"<?php selected( $val, $options['search'] ); ?>><?php echo esc_html( $label ); ?></option>
1176 <?php
1177 }
1178 ?>
1179 </select>.
1180 </p>
1181 <?php
1182 }
1183
1184 /**
1185 * Jetpack Stats Dashboard Widget.
1186 *
1187 * @access public
1188 * @return void
1189 */
1190 function stats_jetpack_dashboard_widget() {
1191 ?>
1192 <form id="stats_dashboard_widget_control" action="<?php echo esc_url( admin_url() ); ?>" method="post">
1193 <?php stats_dashboard_widget_control(); ?>
1194 <?php wp_nonce_field( 'edit-dashboard-widget_dashboard_stats', 'dashboard-widget-nonce' ); ?>
1195 <input type="hidden" name="widget_id" value="dashboard_stats" />
1196 <?php submit_button( __( 'Submit', 'jetpack' ) ); ?>
1197 </form>
1198 <button type="button" class="handlediv js-toggle-stats_dashboard_widget_control" aria-expanded="true">
1199 <span class="screen-reader-text"><?php esc_html_e( 'Configure', 'jetpack' ); ?></span>
1200 <span class="toggle-indicator" aria-hidden="true"></span>
1201 </button>
1202 <div id="dashboard_stats">
1203 <div class="inside">
1204 <div style="height: 250px;"></div>
1205 </div>
1206 </div>
1207 <?php
1208 }
1209
1210 /**
1211 * JavaScript and CSS for dashboard widget.
1212 *
1213 * @access public
1214 * @return void
1215 */
1216 function stats_dashboard_head() {
1217 ?>
1218 <script type="text/javascript">
1219 /* <![CDATA[ */
1220 jQuery( function($) {
1221 var dashStats = jQuery( '#dashboard_stats div.inside' );
1222
1223 if ( dashStats.find( '.dashboard-widget-control-form' ).length ) {
1224 return;
1225 }
1226
1227 if ( ! dashStats.length ) {
1228 dashStats = jQuery( '#dashboard_stats div.dashboard-widget-content' );
1229 var h = parseInt( dashStats.parent().height() ) - parseInt( dashStats.prev().height() );
1230 var args = 'width=' + dashStats.width() + '&height=' + h.toString();
1231 } else {
1232 if ( jQuery('#dashboard_stats' ).hasClass('postbox') ) {
1233 var args = 'width=' + ( dashStats.prev().width() * 2 ).toString();
1234 } else {
1235 var args = 'width=' + ( dashStats.width() * 2 ).toString();
1236 }
1237 }
1238
1239 dashStats
1240 .not( '.dashboard-widget-control' )
1241 .load( 'admin.php?page=stats&noheader&dashboard&' + args );
1242
1243 jQuery( window ).one( 'resize', function() {
1244 jQuery( '#stat-chart' ).css( 'width', 'auto' );
1245 } );
1246
1247
1248 // Widget settings toggle container.
1249 var toggle = $( '.js-toggle-stats_dashboard_widget_control' );
1250
1251 // Move the toggle in the widget header.
1252 toggle.appendTo( '#jetpack_summary_widget .handle-actions' );
1253
1254 // Toggle settings when clicking on it.
1255 toggle.show().click( function( e ) {
1256 e.preventDefault();
1257 e.stopImmediatePropagation();
1258 $( this ).parent().toggleClass( 'controlVisible' );
1259 $( '#stats_dashboard_widget_control' ).slideToggle();
1260 } );
1261 } );
1262 /* ]]> */
1263 </script>
1264 <?php
1265 }
1266
1267 /**
1268 * Stats Dashboard Widget Content.
1269 *
1270 * @access public
1271 * @return void
1272 */
1273 function stats_dashboard_widget_content() {
1274 $width = isset( $_GET['width'] ) ? intval( $_GET['width'] ) / 2 : null; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1275 $height = isset( $_GET['height'] ) ? intval( $_GET['height'] ) - 36 : null; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1276 if ( ! $width || $width < 250 ) {
1277 $width = 370;
1278 }
1279 if ( ! $height || $height < 230 ) {
1280 $height = 180;
1281 }
1282
1283 $_width = $width - 5;
1284 $_height = $height - 5;
1285
1286 $options = stats_dashboard_widget_options();
1287 $blog_id = Jetpack_Options::get_option( 'id' );
1288
1289 $q = array(
1290 'noheader' => 'true',
1291 'proxy' => '',
1292 'blog' => $blog_id,
1293 'page' => 'stats',
1294 'chart' => '',
1295 'unit' => $options['chart'],
1296 'color' => get_user_option( 'admin_color' ),
1297 'width' => $_width,
1298 'height' => $_height,
1299 'ssl' => is_ssl(),
1300 'j' => sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION ),
1301 );
1302
1303 $url = 'https://' . STATS_DASHBOARD_SERVER . '/wp-admin/index.php';
1304
1305 $url = add_query_arg( $q, $url );
1306 $method = 'GET';
1307 $timeout = 90;
1308 $user_id = 0; // Means use the blog token.
1309
1310 $get = Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
1311 $get_code = wp_remote_retrieve_response_code( $get );
1312 if ( is_wp_error( $get ) || ( 2 !== (int) ( $get_code / 100 ) && 304 !== $get_code ) || empty( $get['body'] ) ) {
1313 stats_print_wp_remote_error( $get, $url );
1314 } else {
1315 $body = stats_convert_post_titles( $get['body'] );
1316 $body = stats_convert_chart_urls( $body );
1317 $body = stats_convert_image_urls( $body );
1318 echo $body; // phpcs:ignore WordPress.Security.EscapeOutput
1319 }
1320
1321 $post_ids = array();
1322
1323 $csv_end_date = current_time( 'Y-m-d' );
1324 $csv_args = array(
1325 'top' => "&limit=8&end=$csv_end_date",
1326 'search' => "&limit=5&end=$csv_end_date",
1327 );
1328
1329 $top_posts = stats_get_csv( 'postviews', "days=$options[top]$csv_args[top]" );
1330 foreach ( $top_posts as $i => $post ) {
1331 if ( 0 === $post['post_id'] ) {
1332 unset( $top_posts[ $i ] );
1333 continue;
1334 }
1335 $post_ids[] = $post['post_id'];
1336 }
1337
1338 // Cache.
1339 get_posts( array( 'include' => join( ',', array_unique( $post_ids ) ) ) );
1340
1341 $searches = array();
1342 $search_terms = stats_get_csv( 'searchterms', "days=$options[search]$csv_args[search]" );
1343 foreach ( $search_terms as $search_term ) {
1344 if ( 'encrypted_search_terms' === $search_term['searchterm'] ) {
1345 continue;
1346 }
1347 $searches[] = esc_html( $search_term['searchterm'] );
1348 }
1349
1350 ?>
1351 <div id="stats-info">
1352 <div id="top-posts" class='stats-section'>
1353 <div class="stats-section-inner">
1354 <h3 class="heading"><?php esc_html_e( 'Top Posts', 'jetpack' ); ?></h3>
1355 <?php
1356 if ( empty( $top_posts ) ) {
1357 ?>
1358 <p class="nothing"><?php esc_html_e( 'Sorry, nothing to report.', 'jetpack' ); ?></p>
1359 <?php
1360 } else {
1361 foreach ( $top_posts as $post ) {
1362 if ( ! get_post( $post['post_id'] ) ) {
1363 continue;
1364 }
1365 ?>
1366 <p>
1367 <?php
1368 printf(
1369 esc_html(
1370 /* Translators: Stats dashboard widget Post list with view count: "Post Title 1 View (or Views if plural)". */
1371 _n( '%1$s %2$s View', '%1$s %2$s Views', $post['views'], 'jetpack' )
1372 ),
1373 '<a href="' . esc_url( get_permalink( $post['post_id'] ) ) . '">' . esc_html( get_the_title( $post['post_id'] ) ) . '</a>',
1374 esc_html( number_format_i18n( $post['views'] ) )
1375 );
1376 ?>
1377 </p>
1378 <?php
1379 }
1380 }
1381 ?>
1382 </div>
1383 </div>
1384 <div id="top-search" class='stats-section'>
1385 <div class="stats-section-inner">
1386 <h3 class="heading"><?php esc_html_e( 'Top Searches', 'jetpack' ); ?></h3>
1387 <?php
1388 if ( empty( $searches ) ) {
1389 ?>
1390 <p class="nothing"><?php esc_html_e( 'Sorry, nothing to report.', 'jetpack' ); ?></p>
1391 <?php
1392 } else {
1393 foreach ( $searches as $search_term_item ) {
1394 printf(
1395 '<p>%s</p>',
1396 esc_html( $search_term_item )
1397 );
1398 }
1399 }
1400 ?>
1401 </div>
1402 </div>
1403 </div>
1404 <div class="clear"></div>
1405 <div class="stats-view-all">
1406 <?php
1407 $stats_day_url = Redirect::get_url( 'calypso-stats-day' );
1408 printf(
1409 '<a class="button" target="_blank" rel="noopener noreferrer" href="%1$s">%2$s</a>',
1410 esc_url( $stats_day_url ),
1411 esc_html__( 'View all stats', 'jetpack' )
1412 );
1413 ?>
1414 </div>
1415 <div class="clear"></div>
1416 <?php
1417 exit;
1418 }
1419
1420 /**
1421 * Stats Print WP Remote Error.
1422 *
1423 * @access public
1424 * @param mixed $get Get.
1425 * @param mixed $url URL.
1426 * @return void
1427 */
1428 function stats_print_wp_remote_error( $get, $url ) {
1429 $state_name = 'stats_remote_error_' . substr( md5( $url ), 0, 8 );
1430 $previous_error = Jetpack::state( $state_name );
1431 $error = md5( wp_json_encode( compact( 'get', 'url' ) ) );
1432 Jetpack::state( $state_name, $error );
1433 if ( $error !== $previous_error ) {
1434 ?>
1435 <div class="wrap">
1436 <p><?php esc_html_e( 'We were unable to get your stats just now. Please reload this page to try again.', 'jetpack' ); ?></p>
1437 </div>
1438 <?php
1439 return;
1440 }
1441 ?>
1442 <div class="wrap">
1443 <p>
1444 <?php
1445 printf(
1446 /* translators: placeholder is an a href for a support site. */
1447 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' ),
1448 sprintf(
1449 '<a href="https://support.wordpress.com/contact/?jetpack=needs-service">%s</a>',
1450 esc_html__( 'Jetpack Support', 'jetpack' )
1451 )
1452 );
1453 ?>
1454 </p>
1455 <pre>
1456 User Agent: "<?php echo isset( $_SERVER['HTTP_USER_AGENT'] ) ? esc_html( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized ?>"
1457 Page URL: "http<?php echo ( is_ssl() ? 's' : '' ) . '://' . esc_html( ( isset( $_SERVER['HTTP_HOST'] ) ? wp_unslash( $_SERVER['HTTP_HOST'] ) : '' ) . ( isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '' ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized ?>"
1458 API URL: "<?php echo esc_url( $url ); ?>"
1459 <?php
1460 if ( is_wp_error( $get ) ) {
1461 foreach ( $get->get_error_codes() as $code ) {
1462 foreach ( $get->get_error_messages( $code ) as $message ) {
1463 ?>
1464 <?php print esc_html( $code ) . ': "' . esc_html( $message ) . '"'; ?>
1465
1466 <?php
1467 }
1468 }
1469 } else {
1470 $get_code = wp_remote_retrieve_response_code( $get );
1471 $content_length = strlen( wp_remote_retrieve_body( $get ) );
1472 ?>
1473 Response code: "<?php print esc_html( $get_code ); ?>"
1474 Content length: "<?php print esc_html( $content_length ); ?>"
1475
1476 <?php
1477 }
1478 ?>
1479 </pre>
1480 </div>
1481 <?php
1482 }
1483
1484 /**
1485 * Get stats from WordPress.com
1486 *
1487 * @param string $table The stats which you want to retrieve: postviews, or searchterms.
1488 * @param array $args {
1489 * An associative array of arguments.
1490 *
1491 * @type bool $end The last day of the desired time frame. Format is 'Y-m-d' (e.g. 2007-05-01)
1492 * and default timezone is UTC date. Default value is Now.
1493 * @type string $days The length of the desired time frame. Default is 30. Maximum 90 days.
1494 * @type int $limit The maximum number of records to return. Default is 10. Maximum 100.
1495 * @type int $post_id The ID of the post to retrieve stats data for
1496 * @type string $summarize If present, summarizes all matching records. Default Null.
1497 *
1498 * }
1499 *
1500 * @return array {
1501 * An array of post view data, each post as an array
1502 *
1503 * array {
1504 * The post view data for a single post
1505 *
1506 * @type string $post_id The ID of the post
1507 * @type string $post_title The title of the post
1508 * @type string $post_permalink The permalink for the post
1509 * @type string $views The number of views for the post within the $num_days specified
1510 * }
1511 * }
1512 */
1513 function stats_get_csv( $table, $args = null ) {
1514 $defaults = array(
1515 'end' => false,
1516 'days' => false,
1517 'limit' => 3,
1518 'post_id' => false,
1519 'summarize' => '',
1520 );
1521
1522 $args = wp_parse_args( $args, $defaults );
1523 $args['table'] = $table;
1524 $args['blog_id'] = Jetpack_Options::get_option( 'id' );
1525
1526 $stats_csv_url = add_query_arg( $args, 'https://stats.wordpress.com/csv.php' );
1527
1528 $key = md5( $stats_csv_url );
1529
1530 // Get cache.
1531 $stats_cache = get_option( 'stats_cache' );
1532 if ( ! $stats_cache || ! is_array( $stats_cache ) ) {
1533 $stats_cache = array();
1534 }
1535
1536 // Return or expire this key.
1537 if ( isset( $stats_cache[ $key ] ) ) {
1538 $time = key( $stats_cache[ $key ] );
1539 if ( time() - $time < 300 ) {
1540 return $stats_cache[ $key ][ $time ];
1541 }
1542 unset( $stats_cache[ $key ] );
1543 }
1544
1545 $stats_rows = array();
1546 do {
1547 $stats = stats_get_remote_csv( $stats_csv_url );
1548 if ( ! $stats ) {
1549 break;
1550 }
1551
1552 $labels = array_shift( $stats );
1553
1554 if ( 0 === stripos( $labels[0], 'error' ) ) {
1555 break;
1556 }
1557
1558 $stats_rows = array();
1559 for ( $s = 0; isset( $stats[ $s ] ); $s++ ) {
1560 $row = array();
1561 foreach ( $labels as $col => $label ) {
1562 $row[ $label ] = $stats[ $s ][ $col ];
1563 }
1564 $stats_rows[] = $row;
1565 }
1566 } while ( 0 );
1567
1568 // Expire old keys.
1569 foreach ( $stats_cache as $k => $cache ) {
1570 if ( ! is_array( $cache ) || 300 < time() - key( $cache ) ) {
1571 unset( $stats_cache[ $k ] );
1572 }
1573 }
1574
1575 // Set cache.
1576 $stats_cache[ $key ] = array( time() => $stats_rows );
1577 update_option( 'stats_cache', $stats_cache );
1578
1579 return $stats_rows;
1580 }
1581
1582 /**
1583 * Stats get remote CSV.
1584 *
1585 * @access public
1586 * @param mixed $url URL.
1587 * @return array
1588 */
1589 function stats_get_remote_csv( $url ) {
1590 $method = 'GET';
1591 $timeout = 90;
1592 $user_id = 0; // Blog token.
1593
1594 $get = Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
1595 $get_code = wp_remote_retrieve_response_code( $get );
1596 if ( is_wp_error( $get ) || ( 2 !== (int) ( $get_code / 100 ) && 304 !== $get_code ) || empty( $get['body'] ) ) {
1597 return array(); // @todo: return an error?
1598 } else {
1599 return stats_str_getcsv( $get['body'] );
1600 }
1601 }
1602
1603 /**
1604 * Recursively run str_getcsv on the stats csv.
1605 *
1606 * @since 9.7.0 Remove custom handling since str_getcsv is available on all servers running this now.
1607 *
1608 * @param mixed $csv CSV.
1609 * @return array.
1610 */
1611 function stats_str_getcsv( $csv ) {
1612 $lines = str_getcsv( $csv, "\n" );
1613 return array_map( 'str_getcsv', $lines );
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, wp_json_encode( $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 ) {
1703 // Adds a stats link on the edit posts page.
1704 if ( ! current_user_can( 'view_stats' ) || ! ( new Connection_Manager( 'jetpack' ) )->is_user_connected() ) {
1705 return $columns;
1706 }
1707
1708 // Array-Fu to add before comments.
1709 $pos = array_search( 'comments', array_keys( $columns ), true );
1710
1711 // Fallback to the last position if the post type does not support comments.
1712 if ( ! is_int( $pos ) ) {
1713 $pos = count( $columns );
1714 }
1715
1716 // Final fallback, if the array was malformed by another plugin for example.
1717 if ( ! is_int( $pos ) ) {
1718 return $columns;
1719 }
1720
1721 $chunks = array_chunk( $columns, $pos, true );
1722 $chunks[0]['stats'] = esc_html__( 'Stats', 'jetpack' );
1723
1724 return call_user_func_array( 'array_merge', $chunks );
1725 }
1726
1727 /**
1728 * Set content for cell with link to an entry's stats in WordPress.com.
1729 *
1730 * @param string $column The name of the column to display.
1731 * @param int $post_id The current post ID.
1732 *
1733 * @since 4.7.0
1734 *
1735 * @return mixed
1736 */
1737 function jetpack_stats_post_table_cell( $column, $post_id ) {
1738 if ( 'stats' === $column ) {
1739 if ( 'publish' !== get_post_status( $post_id ) ) {
1740 printf(
1741 '<span aria-hidden="true">—</span><span class="screen-reader-text">%s</span>',
1742 esc_html__( 'No stats', 'jetpack' )
1743 );
1744 } else {
1745 $stats_post_url = Redirect::get_url(
1746 'calypso-stats-post',
1747 array(
1748 'path' => $post_id,
1749 )
1750 );
1751 printf(
1752 '<a href="%s" title="%s" class="dashicons dashicons-chart-bar" target="_blank"></a>',
1753 esc_url( $stats_post_url ),
1754 esc_html__( 'View stats for this post in WordPress.com', 'jetpack' )
1755 );
1756 }
1757 }
1758 }
1759