Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
95.35% covered (success)
95.35%
82 / 86
90.91% covered (success)
90.91%
10 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
Stats_Links
95.35% covered (success)
95.35%
82 / 86
90.91% covered (success)
90.91%
10 / 11
44
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%
18 / 18
100.00% covered (success)
100.00%
1 / 1
12
 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     * Periods of the old `#!/stats/<period>/<module>` summary routes.
39     */
40    private const LEGACY_PERIODS = array( 'hour', 'day', 'week', 'month', 'year' );
41
42    /**
43     * Modules of the old summary routes, and the report each one opens.
44     */
45    private const LEGACY_REPORTS = array(
46        'posts'         => 'posts',
47        'referrers'     => 'referrers',
48        'clicks'        => 'clicks',
49        'countryviews'  => 'locations',
50        'locations'     => 'locations',
51        'authors'       => 'authors',
52        'videoplays'    => 'videos',
53        'filedownloads' => 'downloads',
54        'searchterms'   => 'search-terms',
55        'annualstats'   => 'annual-insights',
56        'utm'           => 'utm',
57        'emails'        => 'emails',
58    );
59
60    /**
61     * Claim the links. Idempotent, like the other register() calls.
62     *
63     * 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.
64     *
65     * @return void
66     */
67    public static function register() {
68        add_filter( 'jetpack_stats_url', array( __CLASS__, 'filter_url' ), 10, 2 );
69        // WordPress 7.2 answers an unregistered page on wp_admin_page_not_found and never reaches admin_page_access_denied.
70        add_action( 'wp_admin_page_not_found', array( __CLASS__, 'open_retired_stats_page' ) );
71        add_action( 'admin_page_access_denied', array( __CLASS__, 'open_retired_stats_page' ) );
72    }
73
74    /**
75     * Open the dashboard in place of `admin.php?page=stats` once no plugin registers that page.
76     *
77     * Before 7.2 core fires admin_page_access_denied for every denied admin page, a registered one the
78     * user may not open included; the capability check is what keeps that user on core's 403.
79     *
80     * @return void
81     */
82    public static function open_retired_stats_page() {
83        if ( ! self::is_retired_stats_page_request() ) {
84            return;
85        }
86
87        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only picks where to send the reader.
88        if ( isset( $_GET[ self::ROUTE_QUERY_ARG ] ) ) {
89            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only picks where to send the reader.
90            $route = sanitize_text_field( wp_unslash( $_GET[ self::ROUTE_QUERY_ARG ] ) );
91            wp_safe_redirect( Analytics::dashboard_url( self::legacy_route_path( $route ) ) );
92            exit( 0 );
93        }
94
95        nocache_headers();
96        self::render_retired_stats_page();
97        exit( 0 );
98    }
99
100    /**
101     * Whether this request is for `page=stats` with no classic Stats page to open, by a user who can read Stats here.
102     *
103     * @return bool
104     */
105    private static function is_retired_stats_page_request() {
106        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only picks where to send the reader.
107        $page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
108
109        return 'stats' === $page
110            && null === Classic_Stats::page_url()
111            && Capabilities::current_user_can_open_stats();
112    }
113
114    /**
115     * Print a page that hands the old `#!/stats/…` route back to the server, since the fragment never reaches it.
116     *
117     * @return void
118     */
119    private static function render_retired_stats_page() {
120        $script = sprintf(
121            'window.location.replace( window.location.pathname + window.location.search + "&%s=" + encodeURIComponent( window.location.hash ) );',
122            self::ROUTE_QUERY_ARG
123        );
124
125        ?>
126<!DOCTYPE html>
127<html <?php language_attributes(); ?>>
128<head>
129<meta charset="<?php echo esc_attr( get_bloginfo( 'charset' ) ); ?>">
130<title><?php echo esc_html__( 'Stats', 'jetpack-premium-analytics-pkg' ); ?></title>
131<noscript><meta http-equiv="refresh" content="0;url=<?php echo esc_url( Analytics::dashboard_url( '/' ) ); ?>"></noscript>
132        <?php wp_print_inline_script_tag( $script ); ?>
133</head>
134<body></body>
135</html>
136        <?php
137    }
138
139    /**
140     * The dashboard route for an old `#!/stats/…` route, or its root when it has no counterpart.
141     *
142     * @param string $route The old route, e.g. `#!/stats/post/123/9`.
143     * @return string
144     */
145    private static function legacy_route_path( $route ) {
146        if ( ! preg_match( '~^#!/stats/([^?]*)~', $route, $match ) ) {
147            return '/';
148        }
149
150        $segments = explode( '/', $match[1] );
151        $view     = $segments[0];
152
153        if ( 'post' === $view ) {
154            return self::post_path( $segments[1] ?? 0 );
155        }
156
157        // The email routes put the post ID after the metric and the period.
158        if ( 'email' === $view && in_array( $segments[1] ?? '', array( 'opens', 'clicks' ), true ) ) {
159            return self::post_path( $segments[3] ?? 0, 'email-' . $segments[1] );
160        }
161
162        if ( 'settings' === $view ) {
163            return '/settings';
164        }
165
166        if ( 'follows' === $view && 'comment' === ( $segments[1] ?? '' ) ) {
167            return '/reports/comment-followers';
168        }
169
170        // A summary route names its module after the period, or alone when it leaves the period out.
171        $module = in_array( $view, self::LEGACY_PERIODS, true ) ? ( $segments[1] ?? '' ) : $view;
172
173        if ( array_key_exists( $module, self::LEGACY_REPORTS ) ) {
174            return '/reports/' . self::LEGACY_REPORTS[ $module ];
175        }
176
177        // The dashboard draws a window of one day by the hour.
178        if ( 'hour' === $view ) {
179            return '/?section=traffic&preset=today';
180        }
181
182        return array_key_exists( $view, self::LEGACY_SECTIONS ) ? '/?section=' . self::LEGACY_SECTIONS[ $view ] : '/';
183    }
184
185    /**
186     * A post detail route, or the dashboard root when there is no real post.
187     *
188     * @param mixed  $post_id The post.
189     * @param string $section The post detail tab, or '' for its default.
190     * @return string
191     */
192    private static function post_path( $post_id, $section = '' ) {
193        $post_id = (int) $post_id;
194
195        if ( $post_id <= 0 ) {
196            return '/';
197        }
198
199        return '/post/' . $post_id . ( '' === $section ? '' : '?section=' . $section );
200    }
201
202    /**
203     * Point a Stats link at the dashboard page for the view it opens.
204     *
205     * @param string $url  Stats URL.
206     * @param array  $args The page the link opens: `view`, plus `id` for the `post` view, or `section` and a
207     *                     `range` of `from`/`to` days as `Y-m-d` for the `dashboard` view.
208     * @return string
209     */
210    public static function filter_url( $url, $args ) {
211        $view = is_array( $args ) ? ( $args['view'] ?? null ) : null;
212
213        if ( 'dashboard' === $view ) {
214            return self::route_url( $url, self::dashboard_path( $args ) );
215        }
216
217        if ( 'post' === $view ) {
218            return self::post_url( $url, $args['id'] ?? 0 );
219        }
220
221        return $url;
222    }
223
224    /**
225     * The dashboard root, opened on the section and the days the link names.
226     *
227     * @param array $args The link's `section` and `range`, both optional.
228     * @return string
229     */
230    private static function dashboard_path( array $args ) {
231        $query   = array();
232        $section = sanitize_key( $args['section'] ?? '' );
233
234        if ( '' !== $section ) {
235            $query['section'] = $section;
236        }
237
238        $query += self::date_window_params( $args['range'] ?? null );
239
240        return '/' . ( $query ? '?' . http_build_query( $query, '', '&', PHP_QUERY_RFC3986 ) : '' );
241    }
242
243    /**
244     * The dashboard's date params for a range of whole days, on the site's calendar.
245     *
246     * A "Last N days" window ending today is sent as its preset, so the date picker reads
247     * "Last 7 days" rather than two dates; the day counts mirror the dashboard's presets.
248     *
249     * @param mixed $range `from` and `to` days as `Y-m-d`.
250     * @return array `preset`, or `from` and `to`, or nothing for a range the dashboard cannot open.
251     */
252    private static function date_window_params( $range ) {
253        if ( ! is_array( $range ) || ! is_string( $range['from'] ?? null ) || ! is_string( $range['to'] ?? null ) ) {
254            return array();
255        }
256
257        $zone = wp_timezone();
258        $from = \DateTimeImmutable::createFromFormat( '!Y-m-d', $range['from'], $zone );
259        $to   = \DateTimeImmutable::createFromFormat( '!Y-m-d', $range['to'], $zone );
260
261        if ( ! $from || ! $to || $to < $from ) {
262            return array();
263        }
264
265        $today = ( new \DateTimeImmutable( 'now', $zone ) )->setTime( 0, 0 );
266        $days  = $from->diff( $to )->days + 1;
267
268        if ( $to->getTimestamp() === $today->getTimestamp() && in_array( $days, array( 7, 30, 90, 365 ), true ) ) {
269            return array( 'preset' => 'last-' . $days . '-days' );
270        }
271
272        return array(
273            'from' => $from->format( 'Y-m-d\TH:i:s.vP' ),
274            'to'   => $to->setTime( 23, 59, 59, 999999 )->format( 'Y-m-d\TH:i:s.vP' ),
275        );
276    }
277
278    /**
279     * The post detail page, or `$url` when there is no real post to show.
280     *
281     * @param string $url     Stats URL for the post.
282     * @param mixed  $post_id The post.
283     * @return string
284     */
285    private static function post_url( $url, $post_id ) {
286        $post_id = (int) $post_id;
287
288        if ( $post_id <= 0 ) {
289            return $url;
290        }
291
292        return self::route_url( $url, '/post/' . $post_id );
293    }
294
295    /**
296     * A dashboard route, or `$url` for a user who cannot read Stats there.
297     *
298     * Wins even where the link would otherwise point at Calypso: this dashboard is the site's
299     * analytics UI and exists only in wp-admin, so the admin-interface preference doesn't apply.
300     * Checked here even where the caller already gates on the same primitives: the filter is public.
301     *
302     * @param string $url  Stats URL.
303     * @param string $path Dashboard route.
304     * @return string
305     */
306    private static function route_url( $url, $path ) {
307        if ( ! Capabilities::current_user_can_open_stats() ) {
308            return $url;
309        }
310
311        return Analytics::dashboard_url( $path );
312    }
313}