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