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