Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
96.40% covered (success)
96.40%
107 / 111
92.86% covered (success)
92.86%
13 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
Stats_Links
96.40% covered (success)
96.40%
107 / 111
92.86% covered (success)
92.86%
13 / 14
61
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%
31 / 31
100.00% covered (success)
100.00%
1 / 1
19
 legacy_range
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
5
 legacy_day
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
4
 path_with_query
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 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%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 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     * The old links' date params, as pairs of the first and the last day; the first pair that names a range wins.
62     */
63    private const LEGACY_RANGE_PARAMS = array(
64        array( 'chartStart', 'chartEnd' ),
65        array( 'startDate', 'endDate' ),
66    );
67
68    /**
69     * The Locations report's sections, which the old `geoMode` param names the same way.
70     */
71    private const LEGACY_GEO_MODES = array( 'countries', 'regions', 'cities' );
72
73    /**
74     * Claim the links. Idempotent, like the other register() calls.
75     *
76     * 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.
77     *
78     * @return void
79     */
80    public static function register() {
81        add_filter( 'jetpack_stats_url', array( __CLASS__, 'filter_url' ), 10, 2 );
82        // WordPress 7.2 answers an unregistered page on wp_admin_page_not_found and never reaches admin_page_access_denied.
83        add_action( 'wp_admin_page_not_found', array( __CLASS__, 'open_retired_stats_page' ) );
84        add_action( 'admin_page_access_denied', array( __CLASS__, 'open_retired_stats_page' ) );
85    }
86
87    /**
88     * Open the dashboard in place of `admin.php?page=stats` once no plugin registers that page.
89     *
90     * Before 7.2 core fires admin_page_access_denied for every denied admin page, a registered one the
91     * user may not open included; the capability check is what keeps that user on core's 403.
92     *
93     * @return void
94     */
95    public static function open_retired_stats_page() {
96        if ( ! self::is_retired_stats_page_request() ) {
97            return;
98        }
99
100        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only picks where to send the reader.
101        if ( isset( $_GET[ self::ROUTE_QUERY_ARG ] ) ) {
102            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only picks where to send the reader.
103            $route = sanitize_text_field( wp_unslash( $_GET[ self::ROUTE_QUERY_ARG ] ) );
104            wp_safe_redirect( Analytics::dashboard_url( self::legacy_route_path( $route ) ) );
105            exit( 0 );
106        }
107
108        nocache_headers();
109        self::render_retired_stats_page();
110        exit( 0 );
111    }
112
113    /**
114     * Whether this request is for `page=stats` with no classic Stats page to open, by a user who can read Stats here.
115     *
116     * @return bool
117     */
118    private static function is_retired_stats_page_request() {
119        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only picks where to send the reader.
120        $page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
121
122        return 'stats' === $page
123            && null === Classic_Stats::page_url()
124            && Capabilities::current_user_can_open_stats();
125    }
126
127    /**
128     * Print a page that hands the old `#!/stats/…` route back to the server, since the fragment never reaches it.
129     *
130     * @return void
131     */
132    private static function render_retired_stats_page() {
133        $script = sprintf(
134            'window.location.replace( window.location.pathname + window.location.search + "&%s=" + encodeURIComponent( window.location.hash ) );',
135            self::ROUTE_QUERY_ARG
136        );
137
138        ?>
139<!DOCTYPE html>
140<html <?php language_attributes(); ?>>
141<head>
142<meta charset="<?php echo esc_attr( get_bloginfo( 'charset' ) ); ?>">
143<title><?php echo esc_html__( 'Stats', 'jetpack-premium-analytics-pkg' ); ?></title>
144<noscript><meta http-equiv="refresh" content="0;url=<?php echo esc_url( Analytics::dashboard_url( '/' ) ); ?>"></noscript>
145        <?php wp_print_inline_script_tag( $script ); ?>
146</head>
147<body></body>
148</html>
149        <?php
150    }
151
152    /**
153     * The dashboard route for an old `#!/stats/…` route, or its root when it has no counterpart.
154     *
155     * @param string $route The old route, e.g. `#!/stats/post/123/9`.
156     * @return string
157     */
158    private static function legacy_route_path( $route ) {
159        if ( ! preg_match( '~^#!/stats/([^?]*)(?:\?(.*))?$~s', $route, $match ) ) {
160            return '/';
161        }
162
163        $segments = explode( '/', $match[1] );
164        $view     = $segments[0];
165        $query    = array();
166        wp_parse_str( $match[2] ?? '', $query );
167
168        if ( 'post' === $view ) {
169            return self::post_path( $segments[1] ?? 0 );
170        }
171
172        // The email routes put the post ID after the metric and the period.
173        if ( 'email' === $view && in_array( $segments[1] ?? '', array( 'opens', 'clicks' ), true ) ) {
174            return self::post_path( $segments[3] ?? 0, 'email-' . $segments[1] );
175        }
176
177        if ( 'settings' === $view ) {
178            return '/settings';
179        }
180
181        if ( 'follows' === $view && 'comment' === ( $segments[1] ?? '' ) ) {
182            return '/reports/comment-followers';
183        }
184
185        // A summary route names its module after the period, or alone when it leaves the period out.
186        $module = in_array( $view, self::LEGACY_PERIODS, true ) ? ( $segments[1] ?? '' ) : $view;
187        $window = self::date_window_params( self::legacy_range( $query ) );
188
189        // The video page names its video in the query, and has no report without one.
190        if ( 'videodetails' === $module ) {
191            $video_id = is_scalar( $query['post'] ?? null ) ? (int) $query['post'] : 0;
192
193            return $video_id > 0 ? '/report/video/' . $video_id : '/reports/videos';
194        }
195
196        if ( array_key_exists( $module, self::LEGACY_REPORTS ) ) {
197            $report = self::LEGACY_REPORTS[ $module ];
198            $params = array();
199
200            if ( 'locations' === $report && in_array( $query['geoMode'] ?? null, self::LEGACY_GEO_MODES, true ) ) {
201                $params['section'] = $query['geoMode'];
202            }
203
204            return self::path_with_query( '/reports/' . $report, $params + $window );
205        }
206
207        // The dashboard draws a window of one day by the hour, and an hourly link without days meant today.
208        if ( 'hour' === $view ) {
209            return self::path_with_query( '/', array( 'section' => 'traffic' ) + ( $window ? $window : array( 'preset' => 'today' ) ) );
210        }
211
212        if ( ! array_key_exists( $view, self::LEGACY_SECTIONS ) ) {
213            return '/';
214        }
215
216        $section = self::LEGACY_SECTIONS[ $view ];
217
218        // Only the Traffic page took the days from its link.
219        return self::path_with_query( '/', array( 'section' => $section ) + ( 'traffic' === $section ? $window : array() ) );
220    }
221
222    /**
223     * The days an old link names, or null when it names none.
224     *
225     * A lone `startDate` is left out: the old pages read it as the start of a period on some
226     * links and its end on others.
227     *
228     * @param array $query The old link's query.
229     * @return array|null `from` and `to` days as `Y-m-d`.
230     */
231    private static function legacy_range( array $query ) {
232        foreach ( self::LEGACY_RANGE_PARAMS as list( $from_param, $to_param ) ) {
233            $from = self::legacy_day( $query[ $from_param ] ?? null );
234            $to   = self::legacy_day( $query[ $to_param ] ?? null );
235
236            if ( null !== $from && null !== $to && $from <= $to ) {
237                return array(
238                    'from' => $from,
239                    'to'   => $to,
240                );
241            }
242        }
243
244        return null;
245    }
246
247    /**
248     * A day from an old link as `Y-m-d`, which the old pages also took without leading zeros.
249     *
250     * @param mixed $value The param's value.
251     * @return string|null
252     */
253    private static function legacy_day( $value ) {
254        if ( ! is_string( $value ) || ! preg_match( '/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value, $match ) || ! checkdate( (int) $match[2], (int) $match[3], (int) $match[1] ) ) {
255            return null;
256        }
257
258        return sprintf( '%04d-%02d-%02d', $match[1], $match[2], $match[3] );
259    }
260
261    /**
262     * A dashboard route with its query.
263     *
264     * @param string $path  The route.
265     * @param array  $query Its params.
266     * @return string
267     */
268    private static function path_with_query( $path, array $query ) {
269        return $path . ( $query ? '?' . http_build_query( $query, '', '&', PHP_QUERY_RFC3986 ) : '' );
270    }
271
272    /**
273     * A post detail route, or the dashboard root when there is no real post.
274     *
275     * @param mixed  $post_id The post.
276     * @param string $section The post detail tab, or '' for its default.
277     * @return string
278     */
279    private static function post_path( $post_id, $section = '' ) {
280        $post_id = (int) $post_id;
281
282        if ( $post_id <= 0 ) {
283            return '/';
284        }
285
286        return '/post/' . $post_id . ( '' === $section ? '' : '?section=' . $section );
287    }
288
289    /**
290     * Point a Stats link at the dashboard page for the view it opens.
291     *
292     * @param string $url  Stats URL.
293     * @param array  $args The page the link opens: `view`, plus `id` for the `post` view, or `section` and a
294     *                     `range` of `from`/`to` days as `Y-m-d` for the `dashboard` view.
295     * @return string
296     */
297    public static function filter_url( $url, $args ) {
298        $view = is_array( $args ) ? ( $args['view'] ?? null ) : null;
299
300        if ( 'dashboard' === $view ) {
301            return self::route_url( $url, self::dashboard_path( $args ) );
302        }
303
304        if ( 'post' === $view ) {
305            return self::post_url( $url, $args['id'] ?? 0 );
306        }
307
308        return $url;
309    }
310
311    /**
312     * The dashboard root, opened on the section and the days the link names.
313     *
314     * @param array $args The link's `section` and `range`, both optional.
315     * @return string
316     */
317    private static function dashboard_path( array $args ) {
318        $query   = array();
319        $section = sanitize_key( $args['section'] ?? '' );
320
321        if ( '' !== $section ) {
322            $query['section'] = $section;
323        }
324
325        return self::path_with_query( '/', $query + self::date_window_params( $args['range'] ?? null ) );
326    }
327
328    /**
329     * The dashboard's date params for a range of whole days, on the site's calendar.
330     *
331     * A "Last N days" window ending today is sent as its preset, so the date picker reads
332     * "Last 7 days" rather than two dates; the day counts mirror the dashboard's presets.
333     *
334     * @param mixed $range `from` and `to` days as `Y-m-d`.
335     * @return array `preset`, or `from` and `to`, or nothing for a range the dashboard cannot open.
336     */
337    private static function date_window_params( $range ) {
338        if ( ! is_array( $range ) || ! is_string( $range['from'] ?? null ) || ! is_string( $range['to'] ?? null ) ) {
339            return array();
340        }
341
342        $zone = wp_timezone();
343        $from = \DateTimeImmutable::createFromFormat( '!Y-m-d', $range['from'], $zone );
344        $to   = \DateTimeImmutable::createFromFormat( '!Y-m-d', $range['to'], $zone );
345
346        if ( ! $from || ! $to || $to < $from ) {
347            return array();
348        }
349
350        $today = ( new \DateTimeImmutable( 'now', $zone ) )->setTime( 0, 0 );
351        $days  = $from->diff( $to )->days + 1;
352
353        if ( $to->getTimestamp() === $today->getTimestamp() && in_array( $days, array( 7, 30, 90, 365 ), true ) ) {
354            return array( 'preset' => 'last-' . $days . '-days' );
355        }
356
357        return array(
358            'from' => $from->format( 'Y-m-d\TH:i:s.vP' ),
359            'to'   => $to->setTime( 23, 59, 59, 999999 )->format( 'Y-m-d\TH:i:s.vP' ),
360        );
361    }
362
363    /**
364     * The post detail page, or `$url` when there is no real post to show.
365     *
366     * @param string $url     Stats URL for the post.
367     * @param mixed  $post_id The post.
368     * @return string
369     */
370    private static function post_url( $url, $post_id ) {
371        $post_id = (int) $post_id;
372
373        if ( $post_id <= 0 ) {
374            return $url;
375        }
376
377        return self::route_url( $url, '/post/' . $post_id );
378    }
379
380    /**
381     * A dashboard route, or `$url` for a user who cannot read Stats there.
382     *
383     * Wins even where the link would otherwise point at Calypso: this dashboard is the site's
384     * analytics UI and exists only in wp-admin, so the admin-interface preference doesn't apply.
385     * Checked here even where the caller already gates on the same primitives: the filter is public.
386     *
387     * @param string $url  Stats URL.
388     * @param string $path Dashboard route.
389     * @return string
390     */
391    private static function route_url( $url, $path ) {
392        if ( ! Capabilities::current_user_can_open_stats() ) {
393            return $url;
394        }
395
396        return Analytics::dashboard_url( $path );
397    }
398}