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

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