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

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