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

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