PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 13.4.4
Jetpack – WP Security, Backup, Speed, & Growth v13.4.4
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / modules / stats.php

stats.php in Jetpack – WP Security, Backup, Speed, & Growth 13.4.4, at modules/stats.php

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