PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 10.4.2
Jetpack – WP Security, Backup, Speed, & Growth v10.4.2
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / modules / stats.php

stats.php in Jetpack – WP Security, Backup, Speed, & Growth 10.4.2, at modules/stats.php

1,701 lines 47.4 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 'masterbar' => null,
667 );
668 foreach ( $args as $var => $vals ) {
669 if ( ! isset( $_REQUEST[ $var ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
670 continue;
671 }
672 if ( is_array( $vals ) ) {
673 if ( in_array( $_REQUEST[ $var ], $vals, true ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
674 $q[ $var ] = $_REQUEST[ $var ]; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
675 }
676 } elseif ( 'int' === $vals ) {
677 $q[ $var ] = (int) $_REQUEST[ $var ]; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
678 } elseif ( 'date' === $vals ) {
679 if ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', $_REQUEST[ $var ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
680 $q[ $var ] = $_REQUEST[ $var ]; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
681 }
682 } elseif ( null === $vals ) {
683 $q[ $var ] = '';
684 } elseif ( 'data' === $vals ) {
685 if ( 'index.php' === substr( $_REQUEST[ $var ], 0, 9 ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
686 $q[ $var ] = $_REQUEST[ $var ];// phpcs:ignore WordPress.Security.NonceVerification.Recommended
687 }
688 }
689 }
690
691 if ( isset( $_GET['chart'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
692 if ( preg_match( '/^[a-z0-9-]+$/', $_GET['chart'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
693 $chart = sanitize_title( $_GET['chart'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
694 $url = 'https://' . STATS_DASHBOARD_SERVER . "/wp-includes/charts/{$chart}.php";
695 }
696 } else {
697 $url = 'https://' . STATS_DASHBOARD_SERVER . '/wp-admin/index.php';
698 }
699
700 $url = add_query_arg( $q, $url );
701 $method = 'GET';
702 $timeout = 90;
703 $user_id = 0; // Means use the blog token.
704
705 $get = Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
706 $get_code = wp_remote_retrieve_response_code( $get );
707 if ( is_wp_error( $get ) || ( 2 !== (int) ( $get_code / 100 ) && 304 !== $get_code ) || empty( $get['body'] ) ) {
708 stats_print_wp_remote_error( $get, $url );
709 } else {
710 if ( ! empty( $get['headers']['content-type'] ) ) {
711 $type = $get['headers']['content-type'];
712 if ( substr( $type, 0, 5 ) === 'image' ) {
713 $img = $get['body'];
714 header( 'Content-Type: ' . $type );
715 header( 'Content-Length: ' . strlen( $img ) );
716 echo $img; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
717 die();
718 }
719 }
720 $body = stats_convert_post_titles( $get['body'] );
721 $body = stats_convert_chart_urls( $body );
722 $body = stats_convert_image_urls( $body );
723 $body = stats_convert_admin_urls( $body );
724 echo $body; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
725 }
726
727 if ( isset( $_GET['page'] ) && 'stats' === $_GET['page'] && ! isset( $_GET['chart'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
728 $tracking = new Tracking();
729 $tracking->record_user_event( 'wpa_page_view', array( 'path' => 'old_stats' ) );
730 }
731
732 if ( isset( $_GET['noheader'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
733 die;
734 }
735 }
736
737 /**
738 * Stats Convert Admin Urls.
739 *
740 * @access public
741 * @param mixed $html HTML.
742 * @return string
743 */
744 function stats_convert_admin_urls( $html ) {
745 return str_replace( 'index.php?page=stats', 'admin.php?page=stats', $html );
746 }
747
748 /**
749 * Stats Convert Image URLs.
750 *
751 * @access public
752 * @param mixed $html HTML.
753 * @return string
754 */
755 function stats_convert_image_urls( $html ) {
756 $url = set_url_scheme( 'https://' . STATS_DASHBOARD_SERVER );
757 $html = preg_replace( '|(["\'])(/i/stats.+)\\1|', '$1' . $url . '$2$1', $html );
758 return $html;
759 }
760
761 /**
762 * Callback for preg_replace_callback used in stats_convert_chart_urls()
763 *
764 * @since 5.6.0
765 *
766 * @param array $matches The matches resulting from the preg_replace_callback call.
767 * @return string The admin url for the chart.
768 */
769 function jetpack_stats_convert_chart_urls_callback( $matches ) {
770 // If there is a query string, change the beginning '?' to a '&' so it fits into the middle of this query string.
771 return 'admin.php?page=stats&noheader&chart=' . $matches[1] . str_replace( '?', '&', $matches[2] );
772 }
773
774 /**
775 * Stats Convert Chart URLs.
776 *
777 * @access public
778 * @param mixed $html HTML.
779 * @return string
780 */
781 function stats_convert_chart_urls( $html ) {
782 $html = preg_replace_callback(
783 '|https?://[-.a-z0-9]+/wp-includes/charts/([-.a-z0-9]+).php(\??)|',
784 'jetpack_stats_convert_chart_urls_callback',
785 $html
786 );
787 return $html;
788 }
789
790 /**
791 * Stats Convert Post Title HTML
792 *
793 * @access public
794 * @param mixed $html HTML.
795 * @return string
796 */
797 function stats_convert_post_titles( $html ) {
798 global $stats_posts;
799 $pattern = "<span class='post-(\d+)-link'>.*?</span>";
800 if ( ! preg_match_all( "!$pattern!", $html, $matches ) ) {
801 return $html;
802 }
803 $posts = get_posts(
804 array(
805 'include' => implode( ',', $matches[1] ),
806 'post_type' => 'any',
807 'post_status' => 'any',
808 'numberposts' => -1,
809 'suppress_filters' => false,
810 )
811 );
812 foreach ( $posts as $post ) {
813 $stats_posts[ $post->ID ] = $post;
814 }
815 $html = preg_replace_callback( "!$pattern!", 'stats_convert_post_title', $html );
816 return $html;
817 }
818
819 /**
820 * Stats Convert Post Title Matches.
821 *
822 * @access public
823 * @param mixed $matches Matches.
824 * @return string
825 */
826 function stats_convert_post_title( $matches ) {
827 global $stats_posts;
828 $post_id = $matches[1];
829 if ( isset( $stats_posts[ $post_id ] ) ) {
830 return '<a href="' . get_permalink( $post_id ) . '" target="_blank">' . get_the_title( $post_id ) . '</a>';
831 }
832 return $matches[0];
833 }
834
835 /**
836 * Stats Hide Smile.
837 *
838 * @access public
839 * @return void
840 */
841 function stats_hide_smile_css() {
842 $options = stats_get_options();
843 if ( isset( $options['hide_smile'] ) && $options['hide_smile'] ) {
844 ?>
845 <style type='text/css'>img#wpstats{display:none}</style>
846 <?php
847 }
848 }
849
850 /**
851 * Stats Admin Bar Head.
852 *
853 * @access public
854 * @return void
855 */
856 function stats_admin_bar_head() {
857 if ( ! stats_get_option( 'admin_bar' ) ) {
858 return;
859 }
860
861 if ( ! current_user_can( 'view_stats' ) ) {
862 return;
863 }
864
865 if ( ! is_admin_bar_showing() ) {
866 return;
867 }
868
869 add_action( 'admin_bar_menu', 'stats_admin_bar_menu', 100 );
870 ?>
871
872 <style data-ampdevmode type='text/css'>
873 #wpadminbar .quicklinks li#wp-admin-bar-stats {
874 height: 32px;
875 }
876 #wpadminbar .quicklinks li#wp-admin-bar-stats a {
877 height: 32px;
878 padding: 0;
879 }
880 #wpadminbar .quicklinks li#wp-admin-bar-stats a div {
881 height: 32px;
882 width: 95px;
883 overflow: hidden;
884 margin: 0 10px;
885 }
886 #wpadminbar .quicklinks li#wp-admin-bar-stats a:hover div {
887 width: auto;
888 margin: 0 8px 0 10px;
889 }
890 #wpadminbar .quicklinks li#wp-admin-bar-stats a img {
891 height: 24px;
892 margin: 4px 0;
893 max-width: none;
894 border: none;
895 }
896 </style>
897 <?php
898 }
899
900 /**
901 * Gets the image source of the given stats chart.
902 *
903 * @param string $chart Name of the chart.
904 * @param array $args Extra list of argument to use in the image source.
905 * @return string An image source.
906 */
907 function stats_get_image_chart_src( $chart, $args = array() ) {
908 $url = add_query_arg( 'page', 'stats', admin_url( 'admin.php' ) );
909
910 return add_query_arg(
911 array_merge(
912 array(
913 'noheader' => '',
914 'proxy' => '',
915 'chart' => $chart,
916 ),
917 $args
918 ),
919 $url
920 );
921 }
922
923 /**
924 * Stats AdminBar.
925 *
926 * @access public
927 * @param mixed $wp_admin_bar WPAdminBar.
928 * @return void
929 */
930 function stats_admin_bar_menu( &$wp_admin_bar ) {
931 $img_src = esc_attr( stats_get_image_chart_src( 'admin-bar-hours-scale' ) );
932 $img_src_2x = esc_attr( stats_get_image_chart_src( 'admin-bar-hours-scale-2x' ) );
933 $alt = esc_attr( __( 'Stats', 'jetpack' ) );
934 $title = esc_attr( __( 'Views over 48 hours. Click for more Site Stats.', 'jetpack' ) );
935
936 $menu = array(
937 'id' => 'stats',
938 'href' => add_query_arg( 'page', 'stats', admin_url( 'admin.php' ) ), // no menu_page_url() blog-side.
939 'title' => "<div><img src='$img_src' srcset='$img_src 1x, $img_src_2x 2x' width='112' height='24' alt='$alt' title='$title'></div>",
940 );
941
942 $wp_admin_bar->add_menu( $menu );
943 }
944
945 /**
946 *
947 * Deprecated. The stats module should not update blog details. This is handled by Sync.
948 *
949 * Stats Update Blog.
950 *
951 * @access public
952 * @return void
953 *
954 * @deprecated since 10.3.
955 */
956 function stats_update_blog() {
957 deprecated_function( __METHOD__, 'jetpack-10.3' );
958 XMLRPC_Async_Call::add_call( 'jetpack.updateBlog', 0, stats_get_blog() );
959 }
960
961 /**
962 * Stats Get Blog.
963 *
964 * @access public
965 * @return string
966 */
967 function stats_get_blog() {
968 $home = wp_parse_url( trailingslashit( get_option( 'home' ) ) );
969 $blog = array(
970 'host' => $home['host'],
971 'path' => $home['path'],
972 'blogname' => get_option( 'blogname' ),
973 'blogdescription' => get_option( 'blogdescription' ),
974 'siteurl' => get_option( 'siteurl' ),
975 'gmt_offset' => get_option( 'gmt_offset' ),
976 'timezone_string' => get_option( 'timezone_string' ),
977 'stats_version' => STATS_VERSION,
978 'stats_api' => 'jetpack',
979 'page_on_front' => get_option( 'page_on_front' ),
980 'permalink_structure' => get_option( 'permalink_structure' ),
981 'category_base' => get_option( 'category_base' ),
982 'tag_base' => get_option( 'tag_base' ),
983 );
984 $blog = array_merge( stats_get_options(), $blog );
985 unset( $blog['roles'], $blog['blog_id'] );
986 return stats_esc_html_deep( $blog );
987 }
988
989 /**
990 * Modified from stripslashes_deep()
991 *
992 * @access public
993 * @param mixed $value Value.
994 * @return string
995 */
996 function stats_esc_html_deep( $value ) {
997 if ( is_array( $value ) ) {
998 $value = array_map( 'stats_esc_html_deep', $value );
999 } elseif ( is_object( $value ) ) {
1000 $vars = get_object_vars( $value );
1001 foreach ( $vars as $key => $data ) {
1002 $value->{$key} = stats_esc_html_deep( $data );
1003 }
1004 } elseif ( is_string( $value ) ) {
1005 $value = esc_html( $value );
1006 }
1007
1008 return $value;
1009 }
1010
1011 /**
1012 * Stats xmlrpc_methods function.
1013 *
1014 * @access public
1015 * @param mixed $methods Methods.
1016 * @return array
1017 */
1018 function stats_xmlrpc_methods( $methods ) {
1019 $my_methods = array(
1020 'jetpack.getBlog' => 'stats_get_blog',
1021 );
1022
1023 return array_merge( $methods, $my_methods );
1024 }
1025
1026 /**
1027 * Stats Dashboard Widget Options.
1028 *
1029 * @access public
1030 * @return array
1031 */
1032 function stats_dashboard_widget_options() {
1033 $defaults = array(
1034 'chart' => 1,
1035 'top' => 1,
1036 'search' => 7,
1037 );
1038 $options = get_option( 'stats_dashboard_widget' );
1039 if ( ( ! $options ) || ! is_array( $options ) ) {
1040 $options = array();
1041 }
1042
1043 // Ignore obsolete option values.
1044 $intervals = array( 1, 7, 31, 90, 365 );
1045 foreach ( array( 'top', 'search' ) as $key ) {
1046 if ( isset( $options[ $key ] ) && ! in_array( (int) $options[ $key ], $intervals, true ) ) {
1047 unset( $options[ $key ] );
1048 }
1049 }
1050
1051 return array_merge( $defaults, $options );
1052 }
1053
1054 /**
1055 * Stats Dashboard Widget Control.
1056 *
1057 * @access public
1058 * @return void
1059 */
1060 function stats_dashboard_widget_control() {
1061 $periods = array(
1062 '1' => __( 'day', 'jetpack' ),
1063 '7' => __( 'week', 'jetpack' ),
1064 '31' => __( 'month', 'jetpack' ),
1065 );
1066 $intervals = array(
1067 '1' => __( 'the past day', 'jetpack' ),
1068 '7' => __( 'the past week', 'jetpack' ),
1069 '31' => __( 'the past month', 'jetpack' ),
1070 '90' => __( 'the past quarter', 'jetpack' ),
1071 '365' => __( 'the past year', 'jetpack' ),
1072 );
1073 $defaults = array(
1074 'top' => 1,
1075 'search' => 7,
1076 );
1077
1078 $options = stats_dashboard_widget_options();
1079
1080 if ( 'post' === strtolower( $_SERVER['REQUEST_METHOD'] ) && isset( $_POST['widget_id'] ) && 'dashboard_stats' === $_POST['widget_id'] ) { // phpcs:ignore WordPress.Security.NonceVerification
1081 if ( isset( $periods[ $_POST['chart'] ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
1082 $options['chart'] = $_POST['chart']; // phpcs:ignore WordPress.Security.NonceVerification
1083 }
1084 foreach ( array( 'top', 'search' ) as $key ) {
1085 if ( isset( $intervals[ $_POST[ $key ] ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
1086 $options[ $key ] = $_POST[ $key ]; // phpcs:ignore WordPress.Security.NonceVerification
1087 } else {
1088 $options[ $key ] = $defaults[ $key ];
1089 }
1090 }
1091 update_option( 'stats_dashboard_widget', $options );
1092 }
1093 ?>
1094 <p>
1095 <label for="chart"><?php esc_html_e( 'Chart stats by', 'jetpack' ); ?></label>
1096 <select id="chart" name="chart">
1097 <?php
1098 foreach ( $periods as $val => $label ) {
1099 ?>
1100 <option value="<?php echo esc_attr( $val ); ?>"<?php selected( $val, $options['chart'] ); ?>><?php echo esc_html( $label ); ?></option>
1101 <?php
1102 }
1103 ?>
1104 </select>.
1105 </p>
1106
1107 <p>
1108 <label for="top"><?php esc_html_e( 'Show top posts over', 'jetpack' ); ?></label>
1109 <select id="top" name="top">
1110 <?php
1111 foreach ( $intervals as $val => $label ) {
1112 ?>
1113 <option value="<?php echo esc_attr( $val ); ?>"<?php selected( $val, $options['top'] ); ?>><?php echo esc_html( $label ); ?></option>
1114 <?php
1115 }
1116 ?>
1117 </select>.
1118 </p>
1119
1120 <p>
1121 <label for="search"><?php esc_html_e( 'Show top search terms over', 'jetpack' ); ?></label>
1122 <select id="search" name="search">
1123 <?php
1124 foreach ( $intervals as $val => $label ) {
1125 ?>
1126 <option value="<?php echo esc_attr( $val ); ?>"<?php selected( $val, $options['search'] ); ?>><?php echo esc_html( $label ); ?></option>
1127 <?php
1128 }
1129 ?>
1130 </select>.
1131 </p>
1132 <?php
1133 }
1134
1135 /**
1136 * Jetpack Stats Dashboard Widget.
1137 *
1138 * @access public
1139 * @return void
1140 */
1141 function stats_jetpack_dashboard_widget() {
1142 ?>
1143 <form id="stats_dashboard_widget_control" action="<?php echo esc_url( admin_url() ); ?>" method="post">
1144 <?php stats_dashboard_widget_control(); ?>
1145 <?php wp_nonce_field( 'edit-dashboard-widget_dashboard_stats', 'dashboard-widget-nonce' ); ?>
1146 <input type="hidden" name="widget_id" value="dashboard_stats" />
1147 <?php submit_button( __( 'Submit', 'jetpack' ) ); ?>
1148 </form>
1149 <button type="button" class="handlediv js-toggle-stats_dashboard_widget_control" aria-expanded="true">
1150 <span class="screen-reader-text"><?php esc_html_e( 'Configure', 'jetpack' ); ?></span>
1151 <span class="toggle-indicator" aria-hidden="true"></span>
1152 </button>
1153 <div id="dashboard_stats">
1154 <div class="inside">
1155 <div style="height: 250px;"></div>
1156 </div>
1157 </div>
1158 <?php
1159 }
1160
1161 /**
1162 * JavaScript and CSS for dashboard widget.
1163 *
1164 * @access public
1165 * @return void
1166 */
1167 function stats_dashboard_head() {
1168 ?>
1169 <script type="text/javascript">
1170 /* <![CDATA[ */
1171 jQuery( function($) {
1172 var dashStats = jQuery( '#dashboard_stats div.inside' );
1173
1174 if ( dashStats.find( '.dashboard-widget-control-form' ).length ) {
1175 return;
1176 }
1177
1178 if ( ! dashStats.length ) {
1179 dashStats = jQuery( '#dashboard_stats div.dashboard-widget-content' );
1180 var h = parseInt( dashStats.parent().height() ) - parseInt( dashStats.prev().height() );
1181 var args = 'width=' + dashStats.width() + '&height=' + h.toString();
1182 } else {
1183 if ( jQuery('#dashboard_stats' ).hasClass('postbox') ) {
1184 var args = 'width=' + ( dashStats.prev().width() * 2 ).toString();
1185 } else {
1186 var args = 'width=' + ( dashStats.width() * 2 ).toString();
1187 }
1188 }
1189
1190 dashStats
1191 .not( '.dashboard-widget-control' )
1192 .load( 'admin.php?page=stats&noheader&dashboard&' + args );
1193
1194 jQuery( window ).one( 'resize', function() {
1195 jQuery( '#stat-chart' ).css( 'width', 'auto' );
1196 } );
1197
1198
1199 // Widget settings toggle container.
1200 var toggle = $( '.js-toggle-stats_dashboard_widget_control' );
1201
1202 // Move the toggle in the widget header.
1203 toggle.appendTo( '#jetpack_summary_widget .handle-actions' );
1204
1205 // Toggle settings when clicking on it.
1206 toggle.show().click( function( e ) {
1207 e.preventDefault();
1208 e.stopImmediatePropagation();
1209 $( this ).parent().toggleClass( 'controlVisible' );
1210 $( '#stats_dashboard_widget_control' ).slideToggle();
1211 } );
1212 } );
1213 /* ]]> */
1214 </script>
1215 <?php
1216 }
1217
1218 /**
1219 * Stats Dashboard Widget Content.
1220 *
1221 * @access public
1222 * @return void
1223 */
1224 function stats_dashboard_widget_content() {
1225 $width = isset( $_GET['width'] ) ? (int) ( $_GET['width'] / 2 ) : null; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1226 $height = isset( $_GET['height'] ) ? (int) $_GET['height'] - 36 : null; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1227 if ( ! $width || $width < 250 ) {
1228 $width = 370;
1229 }
1230 if ( ! $height || $height < 230 ) {
1231 $height = 180;
1232 }
1233
1234 $_width = $width - 5;
1235 $_height = $height - ( $GLOBALS['is_winIE'] ? 16 : 5 ); // Hack! @todo Remove WordPress 5.8 is minimum. IE should be fully deprecated.
1236
1237 $options = stats_dashboard_widget_options();
1238 $blog_id = Jetpack_Options::get_option( 'id' );
1239
1240 $q = array(
1241 'noheader' => 'true',
1242 'proxy' => '',
1243 'blog' => $blog_id,
1244 'page' => 'stats',
1245 'chart' => '',
1246 'unit' => $options['chart'],
1247 'color' => get_user_option( 'admin_color' ),
1248 'width' => $_width,
1249 'height' => $_height,
1250 'ssl' => is_ssl(),
1251 'j' => sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION ),
1252 );
1253
1254 $url = 'https://' . STATS_DASHBOARD_SERVER . '/wp-admin/index.php';
1255
1256 $url = add_query_arg( $q, $url );
1257 $method = 'GET';
1258 $timeout = 90;
1259 $user_id = 0; // Means use the blog token.
1260
1261 $get = Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
1262 $get_code = wp_remote_retrieve_response_code( $get );
1263 if ( is_wp_error( $get ) || ( 2 !== (int) ( $get_code / 100 ) && 304 !== $get_code ) || empty( $get['body'] ) ) {
1264 stats_print_wp_remote_error( $get, $url );
1265 } else {
1266 $body = stats_convert_post_titles( $get['body'] );
1267 $body = stats_convert_chart_urls( $body );
1268 $body = stats_convert_image_urls( $body );
1269 echo $body; // phpcs:ignore WordPress.Security.EscapeOutput
1270 }
1271
1272 $post_ids = array();
1273
1274 $csv_end_date = current_time( 'Y-m-d' );
1275 $csv_args = array(
1276 'top' => "&limit=8&end=$csv_end_date",
1277 'search' => "&limit=5&end=$csv_end_date",
1278 );
1279
1280 $top_posts = stats_get_csv( 'postviews', "days=$options[top]$csv_args[top]" );
1281 foreach ( $top_posts as $i => $post ) {
1282 if ( 0 === $post['post_id'] ) {
1283 unset( $top_posts[ $i ] );
1284 continue;
1285 }
1286 $post_ids[] = $post['post_id'];
1287 }
1288
1289 // Cache.
1290 get_posts( array( 'include' => join( ',', array_unique( $post_ids ) ) ) );
1291
1292 $searches = array();
1293 $search_terms = stats_get_csv( 'searchterms', "days=$options[search]$csv_args[search]" );
1294 foreach ( $search_terms as $search_term ) {
1295 if ( 'encrypted_search_terms' === $search_term['searchterm'] ) {
1296 continue;
1297 }
1298 $searches[] = esc_html( $search_term['searchterm'] );
1299 }
1300
1301 ?>
1302 <div id="stats-info">
1303 <div id="top-posts" class='stats-section'>
1304 <div class="stats-section-inner">
1305 <h3 class="heading"><?php esc_html_e( 'Top Posts', 'jetpack' ); ?></h3>
1306 <?php
1307 if ( empty( $top_posts ) ) {
1308 ?>
1309 <p class="nothing"><?php esc_html_e( 'Sorry, nothing to report.', 'jetpack' ); ?></p>
1310 <?php
1311 } else {
1312 foreach ( $top_posts as $post ) {
1313 if ( ! get_post( $post['post_id'] ) ) {
1314 continue;
1315 }
1316 ?>
1317 <p>
1318 <?php
1319 printf(
1320 esc_html(
1321 /* Translators: Stats dashboard widget Post list with view count: "Post Title 1 View (or Views if plural)". */
1322 _n( '%1$s %2$s View', '%1$s %2$s Views', $post['views'], 'jetpack' )
1323 ),
1324 '<a href="' . esc_url( get_permalink( $post['post_id'] ) ) . '">' . esc_html( get_the_title( $post['post_id'] ) ) . '</a>',
1325 esc_html( number_format_i18n( $post['views'] ) )
1326 );
1327 ?>
1328 </p>
1329 <?php
1330 }
1331 }
1332 ?>
1333 </div>
1334 </div>
1335 <div id="top-search" class='stats-section'>
1336 <div class="stats-section-inner">
1337 <h3 class="heading"><?php esc_html_e( 'Top Searches', 'jetpack' ); ?></h3>
1338 <?php
1339 if ( empty( $searches ) ) {
1340 ?>
1341 <p class="nothing"><?php esc_html_e( 'Sorry, nothing to report.', 'jetpack' ); ?></p>
1342 <?php
1343 } else {
1344 foreach ( $searches as $search_term_item ) {
1345 printf(
1346 '<p>%s</p>',
1347 esc_html( $search_term_item )
1348 );
1349 }
1350 }
1351 ?>
1352 </div>
1353 </div>
1354 </div>
1355 <div class="clear"></div>
1356 <div class="stats-view-all">
1357 <?php
1358 $stats_day_url = Redirect::get_url( 'calypso-stats-day' );
1359 printf(
1360 '<a class="button" target="_blank" rel="noopener noreferrer" href="%1$s">%2$s</a>',
1361 esc_url( $stats_day_url ),
1362 esc_html__( 'View all stats', 'jetpack' )
1363 );
1364 ?>
1365 </div>
1366 <div class="clear"></div>
1367 <?php
1368 exit;
1369 }
1370
1371 /**
1372 * Stats Print WP Remote Error.
1373 *
1374 * @access public
1375 * @param mixed $get Get.
1376 * @param mixed $url URL.
1377 * @return void
1378 */
1379 function stats_print_wp_remote_error( $get, $url ) {
1380 $state_name = 'stats_remote_error_' . substr( md5( $url ), 0, 8 );
1381 $previous_error = Jetpack::state( $state_name );
1382 $error = md5( wp_json_encode( compact( 'get', 'url' ) ) );
1383 Jetpack::state( $state_name, $error );
1384 if ( $error !== $previous_error ) {
1385 ?>
1386 <div class="wrap">
1387 <p><?php esc_html_e( 'We were unable to get your stats just now. Please reload this page to try again.', 'jetpack' ); ?></p>
1388 </div>
1389 <?php
1390 return;
1391 }
1392 ?>
1393 <div class="wrap">
1394 <p>
1395 <?php
1396 printf(
1397 /* translators: placeholder is an a href for a support site. */
1398 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' ),
1399 sprintf(
1400 '<a href="https://support.wordpress.com/contact/?jetpack=needs-service">%s</a>',
1401 esc_html__( 'Jetpack Support', 'jetpack' )
1402 )
1403 );
1404 ?>
1405 </p>
1406 <pre>
1407 User Agent: "<?php echo esc_html( $_SERVER['HTTP_USER_AGENT'] ); ?>"
1408 Page URL: "http<?php echo ( is_ssl() ? 's' : '' ) . '://' . esc_html( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); ?>"
1409 API URL: "<?php echo esc_url( $url ); ?>"
1410 <?php
1411 if ( is_wp_error( $get ) ) {
1412 foreach ( $get->get_error_codes() as $code ) {
1413 foreach ( $get->get_error_messages( $code ) as $message ) {
1414 ?>
1415 <?php print esc_html( $code ) . ': "' . esc_html( $message ) . '"'; ?>
1416
1417 <?php
1418 }
1419 }
1420 } else {
1421 $get_code = wp_remote_retrieve_response_code( $get );
1422 $content_length = strlen( wp_remote_retrieve_body( $get ) );
1423 ?>
1424 Response code: "<?php print esc_html( $get_code ); ?>"
1425 Content length: "<?php print esc_html( $content_length ); ?>"
1426
1427 <?php
1428 }
1429 ?>
1430 </pre>
1431 </div>
1432 <?php
1433 }
1434
1435 /**
1436 * Get stats from WordPress.com
1437 *
1438 * @param string $table The stats which you want to retrieve: postviews, or searchterms.
1439 * @param array $args {
1440 * An associative array of arguments.
1441 *
1442 * @type bool $end The last day of the desired time frame. Format is 'Y-m-d' (e.g. 2007-05-01)
1443 * and default timezone is UTC date. Default value is Now.
1444 * @type string $days The length of the desired time frame. Default is 30. Maximum 90 days.
1445 * @type int $limit The maximum number of records to return. Default is 10. Maximum 100.
1446 * @type int $post_id The ID of the post to retrieve stats data for
1447 * @type string $summarize If present, summarizes all matching records. Default Null.
1448 *
1449 * }
1450 *
1451 * @return array {
1452 * An array of post view data, each post as an array
1453 *
1454 * array {
1455 * The post view data for a single post
1456 *
1457 * @type string $post_id The ID of the post
1458 * @type string $post_title The title of the post
1459 * @type string $post_permalink The permalink for the post
1460 * @type string $views The number of views for the post within the $num_days specified
1461 * }
1462 * }
1463 */
1464 function stats_get_csv( $table, $args = null ) {
1465 $defaults = array(
1466 'end' => false,
1467 'days' => false,
1468 'limit' => 3,
1469 'post_id' => false,
1470 'summarize' => '',
1471 );
1472
1473 $args = wp_parse_args( $args, $defaults );
1474 $args['table'] = $table;
1475 $args['blog_id'] = Jetpack_Options::get_option( 'id' );
1476
1477 $stats_csv_url = add_query_arg( $args, 'https://stats.wordpress.com/csv.php' );
1478
1479 $key = md5( $stats_csv_url );
1480
1481 // Get cache.
1482 $stats_cache = get_option( 'stats_cache' );
1483 if ( ! $stats_cache || ! is_array( $stats_cache ) ) {
1484 $stats_cache = array();
1485 }
1486
1487 // Return or expire this key.
1488 if ( isset( $stats_cache[ $key ] ) ) {
1489 $time = key( $stats_cache[ $key ] );
1490 if ( time() - $time < 300 ) {
1491 return $stats_cache[ $key ][ $time ];
1492 }
1493 unset( $stats_cache[ $key ] );
1494 }
1495
1496 $stats_rows = array();
1497 do {
1498 $stats = stats_get_remote_csv( $stats_csv_url );
1499 if ( ! $stats ) {
1500 break;
1501 }
1502
1503 $labels = array_shift( $stats );
1504
1505 if ( 0 === stripos( $labels[0], 'error' ) ) {
1506 break;
1507 }
1508
1509 $stats_rows = array();
1510 for ( $s = 0; isset( $stats[ $s ] ); $s++ ) {
1511 $row = array();
1512 foreach ( $labels as $col => $label ) {
1513 $row[ $label ] = $stats[ $s ][ $col ];
1514 }
1515 $stats_rows[] = $row;
1516 }
1517 } while ( 0 );
1518
1519 // Expire old keys.
1520 foreach ( $stats_cache as $k => $cache ) {
1521 if ( ! is_array( $cache ) || 300 < time() - key( $cache ) ) {
1522 unset( $stats_cache[ $k ] );
1523 }
1524 }
1525
1526 // Set cache.
1527 $stats_cache[ $key ] = array( time() => $stats_rows );
1528 update_option( 'stats_cache', $stats_cache );
1529
1530 return $stats_rows;
1531 }
1532
1533 /**
1534 * Stats get remote CSV.
1535 *
1536 * @access public
1537 * @param mixed $url URL.
1538 * @return array
1539 */
1540 function stats_get_remote_csv( $url ) {
1541 $method = 'GET';
1542 $timeout = 90;
1543 $user_id = 0; // Blog token.
1544
1545 $get = Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
1546 $get_code = wp_remote_retrieve_response_code( $get );
1547 if ( is_wp_error( $get ) || ( 2 !== (int) ( $get_code / 100 ) && 304 !== $get_code ) || empty( $get['body'] ) ) {
1548 return array(); // @todo: return an error?
1549 } else {
1550 return stats_str_getcsv( $get['body'] );
1551 }
1552 }
1553
1554 /**
1555 * Recursively run str_getcsv on the stats csv.
1556 *
1557 * @since 9.7.0 Remove custom handling since str_getcsv is available on all servers running this now.
1558 *
1559 * @param mixed $csv CSV.
1560 * @return array.
1561 */
1562 function stats_str_getcsv( $csv ) {
1563 $lines = str_getcsv( $csv, "\n" );
1564 return array_map( 'str_getcsv', $lines );
1565 }
1566
1567 /**
1568 * Abstract out building the rest api stats path.
1569 *
1570 * @param string $resource Resource.
1571 * @return string
1572 */
1573 function jetpack_stats_api_path( $resource = '' ) {
1574 $resource = ltrim( $resource, '/' );
1575 return sprintf( '/sites/%d/stats/%s', stats_get_option( 'blog_id' ), $resource );
1576 }
1577
1578 /**
1579 * Fetches stats data from the REST API. Caches locally for 5 minutes.
1580 *
1581 * @link: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/
1582 * @access public
1583 * @param array $args (default: array()) The args that are passed to the endpoint.
1584 * @param string $resource (default: '') Optional sub-endpoint following /stats/.
1585 * @return array|WP_Error.
1586 */
1587 function stats_get_from_restapi( $args = array(), $resource = '' ) {
1588 $endpoint = jetpack_stats_api_path( $resource );
1589 $api_version = '1.1';
1590 $args = wp_parse_args( $args, array() );
1591 $cache_key = md5( implode( '|', array( $endpoint, $api_version, wp_json_encode( $args ) ) ) );
1592
1593 $transient_name = "jetpack_restapi_stats_cache_{$cache_key}";
1594
1595 $stats_cache = get_transient( $transient_name );
1596
1597 // Return or expire this key.
1598 if ( $stats_cache ) {
1599 $time = key( $stats_cache );
1600 $data = $stats_cache[ $time ]; // WP_Error or string (JSON encoded object).
1601
1602 if ( is_wp_error( $data ) ) {
1603 return $data;
1604 }
1605
1606 return (object) array_merge( array( 'cached_at' => $time ), (array) json_decode( $data ) );
1607 }
1608
1609 // Do the dirty work.
1610 $response = Client::wpcom_json_api_request_as_blog( $endpoint, $api_version, $args );
1611 if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
1612 // WP_Error.
1613 $data = is_wp_error( $response ) ? $response : new WP_Error( 'stats_error' );
1614 // WP_Error.
1615 $return = $data;
1616 } else {
1617 // string (JSON encoded object).
1618 $data = wp_remote_retrieve_body( $response );
1619 // object (rare: null on JSON failure).
1620 $return = json_decode( $data );
1621 }
1622
1623 // To reduce size in storage: store with time as key, store JSON encoded data (unless error).
1624 set_transient( $transient_name, array( time() => $data ), 5 * MINUTE_IN_SECONDS );
1625
1626 return $return;
1627 }
1628
1629 /**
1630 * Load CSS needed for Stats column width in WP-Admin area.
1631 *
1632 * @since 4.7.0
1633 */
1634 function jetpack_stats_load_admin_css() {
1635 ?>
1636 <style type="text/css">
1637 .fixed .column-stats {
1638 width: 5em;
1639 }
1640 </style>
1641 <?php
1642 }
1643
1644 /**
1645 * Set header for column that allows to go to WordPress.com to see an entry's stats.
1646 *
1647 * @param array $columns An array of column names.
1648 *
1649 * @since 4.7.0
1650 *
1651 * @return mixed
1652 */
1653 function jetpack_stats_post_table( $columns ) {
1654 // Adds a stats link on the edit posts page.
1655 if ( ! current_user_can( 'view_stats' ) || ! ( new Connection_Manager( 'jetpack' ) )->is_user_connected() ) {
1656 return $columns;
1657 }
1658 // Array-Fu to add before comments.
1659 $pos = array_search( 'comments', array_keys( $columns ), true );
1660 if ( ! is_int( $pos ) ) {
1661 return $columns;
1662 }
1663 $chunks = array_chunk( $columns, $pos, true );
1664 $chunks[0]['stats'] = esc_html__( 'Stats', 'jetpack' );
1665
1666 return call_user_func_array( 'array_merge', $chunks );
1667 }
1668
1669 /**
1670 * Set content for cell with link to an entry's stats in WordPress.com.
1671 *
1672 * @param string $column The name of the column to display.
1673 * @param int $post_id The current post ID.
1674 *
1675 * @since 4.7.0
1676 *
1677 * @return mixed
1678 */
1679 function jetpack_stats_post_table_cell( $column, $post_id ) {
1680 if ( 'stats' === $column ) {
1681 if ( 'publish' !== get_post_status( $post_id ) ) {
1682 printf(
1683 '<span aria-hidden="true">—</span><span class="screen-reader-text">%s</span>',
1684 esc_html__( 'No stats', 'jetpack' )
1685 );
1686 } else {
1687 $stats_post_url = Redirect::get_url(
1688 'calypso-stats-post',
1689 array(
1690 'path' => $post_id,
1691 )
1692 );
1693 printf(
1694 '<a href="%s" title="%s" class="dashicons dashicons-chart-bar" target="_blank"></a>',
1695 esc_url( $stats_post_url ),
1696 esc_html__( 'View stats for this post in WordPress.com', 'jetpack' )
1697 );
1698 }
1699 }
1700 }
1701