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