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

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