Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.94% covered (success)
94.94%
75 / 79
90.91% covered (success)
90.91%
10 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
Stats_Links
94.94% covered (success)
94.94%
75 / 79
90.91% covered (success)
90.91%
10 / 11
39.20
0.00% covered (danger)
0.00%
0 / 1
 register
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 open_retired_stats_page
55.56% covered (warning)
55.56%
5 / 9
0.00% covered (danger)
0.00%
0 / 1
3.79
 is_retired_stats_page_request
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 render_retired_stats_page
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
1
 legacy_route_path
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
7
 post_path
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 filter_url
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 dashboard_path
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 date_window_params
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
9
 post_url
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 route_url
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * Stats entry points outside the dashboard.
4 *
5 * @package automattic/jetpack-premium-analytics
6 */
7
8namespace Automattic\Jetpack\PremiumAnalytics;
9
10/**
11 * Sends links to Stats pages (the admin bar, the post list Views column, the newsletter action bar) to the matching
12 * dashboard page instead, and opens the dashboard for `admin.php?page=stats` once no plugin registers that page.
13 *
14 * @since 0.12.0
15 */
16class Stats_Links {
17
18    /**
19     * Query arg that carries the old `#!/stats/…` route back to the server.
20     */
21    const ROUTE_QUERY_ARG = 'stats_route';
22
23    /**
24     * Views of the old `#!/stats/<view>` routes, and the dashboard section each one opens.
25     */
26    private const LEGACY_SECTIONS = array(
27        'day'         => 'traffic',
28        'week'        => 'traffic',
29        'month'       => 'traffic',
30        'year'        => 'traffic',
31        'insights'    => 'insights',
32        'subscribers' => 'subscribers',
33        'store'       => 'woocommerce',
34        'ads'         => 'ads',
35    );
36
37    /**
38     * Claim the links. Idempotent, like the other register() calls.
39     *
40     * Outside the admin-chrome gate on purpose: the admin bar and the action bar also render on the front end, and Quick Edit re-renders the Views column over AJAX.
41     *
42     * @return void
43     */
44    public static function register() {
45        add_filter( 'jetpack_stats_url', array( __CLASS__, 'filter_url' ), 10, 2 );
46        // WordPress 7.2 answers an unregistered page on wp_admin_page_not_found and never reaches admin_page_access_denied.
47        add_action( 'wp_admin_page_not_found', array( __CLASS__, 'open_retired_stats_page' ) );
48        add_action( 'admin_page_access_denied', array( __CLASS__, 'open_retired_stats_page' ) );
49    }
50
51    /**
52     * Open the dashboard in place of `admin.php?page=stats` once no plugin registers that page.
53     *
54     * Before 7.2 core fires admin_page_access_denied for every denied admin page, a registered one the
55     * user may not open included; the capability check is what keeps that user on core's 403.
56     *
57     * @return void
58     */
59    public static function open_retired_stats_page() {
60        if ( ! self::is_retired_stats_page_request() ) {
61            return;
62        }
63
64        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only picks where to send the reader.
65        if ( isset( $_GET[ self::ROUTE_QUERY_ARG ] ) ) {
66            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only picks where to send the reader.
67            $route = sanitize_text_field( wp_unslash( $_GET[ self::ROUTE_QUERY_ARG ] ) );
68            wp_safe_redirect( Analytics::dashboard_url( self::legacy_route_path( $route ) ) );
69            exit( 0 );
70        }
71
72        nocache_headers();
73        self::render_retired_stats_page();
74        exit( 0 );
75    }
76
77    /**
78     * Whether this request is for `page=stats` with no classic Stats page to open, by a user who can read Stats here.
79     *
80     * @return bool
81     */
82    private static function is_retired_stats_page_request() {
83        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only picks where to send the reader.
84        $page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
85
86        return 'stats' === $page
87            && null === Classic_Stats::page_url()
88            && Capabilities::current_user_can_open_stats();
89    }
90
91    /**
92     * Print a page that hands the old `#!/stats/…` route back to the server, since the fragment never reaches it.
93     *
94     * @return void
95     */
96    private static function render_retired_stats_page() {
97        $script = sprintf(
98            'window.location.replace( window.location.pathname + window.location.search + "&%s=" + encodeURIComponent( window.location.hash ) );',
99            self::ROUTE_QUERY_ARG
100        );
101
102        ?>
103<!DOCTYPE html>
104<html <?php language_attributes(); ?>>
105<head>
106<meta charset="<?php echo esc_attr( get_bloginfo( 'charset' ) ); ?>">
107<title><?php echo esc_html__( 'Stats', 'jetpack-premium-analytics-pkg' ); ?></title>
108<noscript><meta http-equiv="refresh" content="0;url=<?php echo esc_url( Analytics::dashboard_url( '/' ) ); ?>"></noscript>
109        <?php wp_print_inline_script_tag( $script ); ?>
110</head>
111<body></body>
112</html>
113        <?php
114    }
115
116    /**
117     * The dashboard route for an old `#!/stats/…` route, or its root when it has no counterpart.
118     *
119     * @param string $route The old route, e.g. `#!/stats/post/123/9`.
120     * @return string
121     */
122    private static function legacy_route_path( $route ) {
123        if ( ! preg_match( '~^#!/stats/([^?]*)~', $route, $match ) ) {
124            return '/';
125        }
126
127        $segments = explode( '/', $match[1] );
128        $view     = $segments[0];
129
130        if ( 'post' === $view ) {
131            return self::post_path( $segments[1] ?? 0 );
132        }
133
134        // The email routes put the post ID after the metric and the period.
135        if ( 'email' === $view && in_array( $segments[1] ?? '', array( 'opens', 'clicks' ), true ) ) {
136            return self::post_path( $segments[3] ?? 0, 'email-' . $segments[1] );
137        }
138
139        if ( 'settings' === $view ) {
140            return '/settings';
141        }
142
143        return array_key_exists( $view, self::LEGACY_SECTIONS ) ? '/?section=' . self::LEGACY_SECTIONS[ $view ] : '/';
144    }
145
146    /**
147     * A post detail route, or the dashboard root when there is no real post.
148     *
149     * @param mixed  $post_id The post.
150     * @param string $section The post detail tab, or '' for its default.
151     * @return string
152     */
153    private static function post_path( $post_id, $section = '' ) {
154        $post_id = (int) $post_id;
155
156        if ( $post_id <= 0 ) {
157            return '/';
158        }
159
160        return '/post/' . $post_id . ( '' === $section ? '' : '?section=' . $section );
161    }
162
163    /**
164     * Point a Stats link at the dashboard page for the view it opens.
165     *
166     * @param string $url  Stats URL.
167     * @param array  $args The page the link opens: `view`, plus `id` for the `post` view, or `section` and a
168     *                     `range` of `from`/`to` days as `Y-m-d` for the `dashboard` view.
169     * @return string
170     */
171    public static function filter_url( $url, $args ) {
172        $view = is_array( $args ) ? ( $args['view'] ?? null ) : null;
173
174        if ( 'dashboard' === $view ) {
175            return self::route_url( $url, self::dashboard_path( $args ) );
176        }
177
178        if ( 'post' === $view ) {
179            return self::post_url( $url, $args['id'] ?? 0 );
180        }
181
182        return $url;
183    }
184
185    /**
186     * The dashboard root, opened on the section and the days the link names.
187     *
188     * @param array $args The link's `section` and `range`, both optional.
189     * @return string
190     */
191    private static function dashboard_path( array $args ) {
192        $query   = array();
193        $section = sanitize_key( $args['section'] ?? '' );
194
195        if ( '' !== $section ) {
196            $query['section'] = $section;
197        }
198
199        $query += self::date_window_params( $args['range'] ?? null );
200
201        return '/' . ( $query ? '?' . http_build_query( $query, '', '&', PHP_QUERY_RFC3986 ) : '' );
202    }
203
204    /**
205     * The dashboard's date params for a range of whole days, on the site's calendar.
206     *
207     * A "Last N days" window ending today is sent as its preset, so the date picker reads
208     * "Last 7 days" rather than two dates; the day counts mirror the dashboard's presets.
209     *
210     * @param mixed $range `from` and `to` days as `Y-m-d`.
211     * @return array `preset`, or `from` and `to`, or nothing for a range the dashboard cannot open.
212     */
213    private static function date_window_params( $range ) {
214        if ( ! is_array( $range ) || ! is_string( $range['from'] ?? null ) || ! is_string( $range['to'] ?? null ) ) {
215            return array();
216        }
217
218        $zone = wp_timezone();
219        $from = \DateTimeImmutable::createFromFormat( '!Y-m-d', $range['from'], $zone );
220        $to   = \DateTimeImmutable::createFromFormat( '!Y-m-d', $range['to'], $zone );
221
222        if ( ! $from || ! $to || $to < $from ) {
223            return array();
224        }
225
226        $today = ( new \DateTimeImmutable( 'now', $zone ) )->setTime( 0, 0 );
227        $days  = $from->diff( $to )->days + 1;
228
229        if ( $to->getTimestamp() === $today->getTimestamp() && in_array( $days, array( 7, 30, 90, 365 ), true ) ) {
230            return array( 'preset' => 'last-' . $days . '-days' );
231        }
232
233        return array(
234            'from' => $from->format( 'Y-m-d\TH:i:s.vP' ),
235            'to'   => $to->setTime( 23, 59, 59, 999999 )->format( 'Y-m-d\TH:i:s.vP' ),
236        );
237    }
238
239    /**
240     * The post detail page, or `$url` when there is no real post to show.
241     *
242     * @param string $url     Stats URL for the post.
243     * @param mixed  $post_id The post.
244     * @return string
245     */
246    private static function post_url( $url, $post_id ) {
247        $post_id = (int) $post_id;
248
249        if ( $post_id <= 0 ) {
250            return $url;
251        }
252
253        return self::route_url( $url, '/post/' . $post_id );
254    }
255
256    /**
257     * A dashboard route, or `$url` for a user who cannot read Stats there.
258     *
259     * Wins even where the link would otherwise point at Calypso: this dashboard is the site's
260     * analytics UI and exists only in wp-admin, so the admin-interface preference doesn't apply.
261     * Checked here even where the caller already gates on the same primitives: the filter is public.
262     *
263     * @param string $url  Stats URL.
264     * @param string $path Dashboard route.
265     * @return string
266     */
267    private static function route_url( $url, $path ) {
268        if ( ! Capabilities::current_user_can_open_stats() ) {
269            return $url;
270        }
271
272        return Analytics::dashboard_url( $path );
273    }
274}