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