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