Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
93.94% covered (success)
93.94%
186 / 198
89.47% covered (warning)
89.47%
17 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
Admin_Bar
93.94% covered (success)
93.94%
186 / 198
89.47% covered (warning)
89.47%
17 / 19
45.45
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
1
 can_see_chart
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
 use_seven_day_chart
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 maybe_add_chart_node
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 maybe_add_chart
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 add_chart_node
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
2
 get_seven_day_panel_html
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
1
 get_seven_day_traffic_url
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_seven_day_chart
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
1
 add_site_menu_link
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
 get_dashboard_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_chart_src
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 serve_chart
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
3.14
 maybe_serve_chart
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 send_chart
9.09% covered (danger)
9.09%
1 / 11
0.00% covered (danger)
0.00%
0 / 1
5.01
 fetch_chart
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
5
 ignore_db_version
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_requested_chart
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_chart_param
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * Stats in the WordPress admin bar.
4 *
5 * @package automattic/jetpack-stats-admin
6 */
7
8namespace Automattic\Jetpack\Stats_Admin;
9
10use Automattic\Jetpack\Assets;
11use Automattic\Jetpack\Connection\Client;
12use Automattic\Jetpack\Constants;
13use Automattic\Jetpack\Feature_Flags\Feature_Flags;
14use Automattic\Jetpack\Stats\Options as Stats_Options;
15use Automattic\Jetpack\Status\Host;
16
17/**
18 * Adds the views chart and a Stats link to the admin bar.
19 */
20class Admin_Bar {
21    /**
22     * The admin bar charts WordPress.com draws, at 1x and 2x.
23     *
24     * @var string[]
25     */
26    const CHARTS = array( 'admin-bar-hours-scale', 'admin-bar-hours-scale-2x' );
27
28    /**
29     * The admin-post.php action that serves a chart.
30     *
31     * @var string
32     */
33    const CHART_ACTION = 'jetpack_stats_admin_bar_chart';
34
35    /**
36     * How long, in seconds, the browser may reuse a chart image. Short, because the chart's last bar is the current hour.
37     *
38     * @var int
39     */
40    const CHART_MAX_AGE = 300;
41
42    /**
43     * The handle of the 7-day chart script and style.
44     *
45     * @var string
46     */
47    const SCRIPT_HANDLE = 'jetpack-stats-admin-bar';
48
49    /**
50     * The feature flag that swaps the 48-hour image for the 7-day chart.
51     *
52     * @var string
53     */
54    const SEVEN_DAY_CHART_FLAG = 'jetpack-stats-admin-bar-seven-day-chart';
55
56    /**
57     * How many days the chart shows, ending today.
58     *
59     * @var int
60     */
61    const SEVEN_DAY_CHART_DAYS = 7;
62
63    /**
64     * Register the hooks.
65     *
66     * @return void
67     */
68    public static function init() {
69        Feature_Flags::register(
70            self::SEVEN_DAY_CHART_FLAG,
71            array(
72                'default'     => false,
73                'description' => 'Show a 7-day views chart in the admin bar, with views and visitors on hover, instead of the 48-hour image.',
74                'owner'       => 'jetpack-stats',
75            )
76        );
77
78        add_action( 'admin_bar_menu', array( __CLASS__, 'maybe_add_chart_node' ), 100 );
79        add_action( 'admin_bar_init', array( __CLASS__, 'maybe_add_chart' ) );
80        add_action( 'wp_before_admin_bar_render', array( __CLASS__, 'add_site_menu_link' ) );
81        add_action( 'admin_init', array( __CLASS__, 'maybe_serve_chart' ), 1 );
82        add_action( 'admin_post_' . self::CHART_ACTION, array( __CLASS__, 'serve_chart' ) );
83        add_filter( 'pre_option_db_version', array( __CLASS__, 'ignore_db_version' ) );
84    }
85
86    /**
87     * Whether the current user should see the views chart.
88     *
89     * @return bool
90     */
91    private static function can_see_chart() {
92        return is_user_logged_in() && Stats_Options::get_option( 'admin_bar' ) && current_user_can( 'view_stats' );
93    }
94
95    /**
96     * Whether the admin bar shows the 7-day chart instead of the 48-hour image.
97     *
98     * @return bool
99     */
100    private static function use_seven_day_chart() {
101        return Feature_Flags::is_enabled( self::SEVEN_DAY_CHART_FLAG );
102    }
103
104    /**
105     * Add the views chart when the current user should see it.
106     *
107     * Hooked to admin_bar_menu because a REST request fires no page head, and the admin-bar endpoint needs this node.
108     *
109     * @param \WP_Admin_Bar $wp_admin_bar The admin bar.
110     * @return void
111     */
112    public static function maybe_add_chart_node( $wp_admin_bar ) {
113        if ( self::can_see_chart() ) {
114            self::add_chart_node( $wp_admin_bar );
115        }
116    }
117
118    /**
119     * Add the views chart styles to the admin bar stylesheet when the current user should see the chart.
120     *
121     * @return void
122     */
123    public static function maybe_add_chart() {
124        if ( ! self::can_see_chart() ) {
125            return;
126        }
127
128        if ( self::use_seven_day_chart() ) {
129            self::enqueue_seven_day_chart();
130            return;
131        }
132
133        wp_add_inline_style(
134            'admin-bar',
135            '#wpadminbar .quicklinks li#wp-admin-bar-stats { height: 32px; }
136#wpadminbar .quicklinks li#wp-admin-bar-stats a { height: 32px; padding: 0; }
137#wpadminbar .quicklinks li#wp-admin-bar-stats a div { height: 32px; width: 95px; overflow: hidden; margin: 0 10px; }
138#wpadminbar .quicklinks li#wp-admin-bar-stats a:hover div { width: auto; margin: 0 8px 0 10px; }
139#wpadminbar .quicklinks li#wp-admin-bar-stats a img { height: 24px; margin: 4px 0; max-width: none; border: none; }'
140        );
141    }
142
143    /**
144     * Add the views chart, linked to the Stats dashboard.
145     *
146     * @param \WP_Admin_Bar $wp_admin_bar The admin bar.
147     * @return void
148     */
149    public static function add_chart_node( $wp_admin_bar ) {
150        if ( self::use_seven_day_chart() ) {
151            $wp_admin_bar->add_menu(
152                array(
153                    'id'    => 'stats',
154                    'href'  => self::get_dashboard_url(),
155                    'title' => '<span id="jetpack-stats-admin-bar-chart" class="jp-stats-admin-bar-chart" aria-hidden="true"></span><span class="jp-stats-admin-bar-label">' . esc_html__( 'Stats', 'jetpack-stats-admin' ) . '</span>',
156                    'meta'  => array(
157                        'menu_title' => __( 'Stats', 'jetpack-stats-admin' ),
158                        'class'      => 'menupop',
159                        'html'       => self::get_seven_day_panel_html(),
160                    ),
161                )
162            );
163            return;
164        }
165
166        $img_src    = esc_attr( self::get_chart_src( 'admin-bar-hours-scale' ) );
167        $img_src_2x = esc_attr( self::get_chart_src( 'admin-bar-hours-scale-2x' ) );
168        $alt        = esc_attr__( 'Stats', 'jetpack-stats-admin' );
169        $title      = esc_attr__( 'Views over 48 hours. Click for more Jetpack Stats.', 'jetpack-stats-admin' );
170
171        $wp_admin_bar->add_menu(
172            array(
173                'id'    => 'stats',
174                'href'  => self::get_dashboard_url(),
175                'title' => "<div><img fetchpriority='low' loading='lazy' decoding='async' src='$img_src' srcset='$img_src 1x, $img_src_2x 2x' width='112' height='24' alt='$alt' title='$title'></div>",
176                // A client that reads the admin bar as data, like the omnibar, shows this instead of the image markup.
177                'meta'  => array( 'menu_title' => __( 'Stats', 'jetpack-stats-admin' ) ),
178            )
179        );
180    }
181
182    /**
183     * The hover panel of the 7-day chart. The script fills in the bars and totals once stats load.
184     *
185     * @return string
186     */
187    private static function get_seven_day_panel_html() {
188        $metric = static function ( $key, $label ) {
189            return sprintf( '<div class="jp-stats-admin-bar-panel__metric"><dt>%s</dt><dd data-metric="%s">–</dd></div>', esc_html( $label ), esc_attr( $key ) );
190        };
191
192        return '<div class="ab-sub-wrapper"><div id="jetpack-stats-admin-bar-panel" class="jp-stats-admin-bar-panel">'
193            . '<div class="jp-stats-admin-bar-panel__title">' . esc_html(
194                sprintf(
195                    /* translators: %d: Number of days. */
196                    _n( 'Last %d day', 'Last %d days', self::SEVEN_DAY_CHART_DAYS, 'jetpack-stats-admin' ),
197                    self::SEVEN_DAY_CHART_DAYS
198                )
199            ) . '</div>'
200            . '<span class="ab-label jp-stats-admin-bar-panel__bars" aria-hidden="true"></span>'
201            . '<dl class="jp-stats-admin-bar-panel__metrics">'
202            . $metric( 'views', __( 'Views', 'jetpack-stats-admin' ) )
203            . $metric( 'visitors', __( 'Visitors', 'jetpack-stats-admin' ) )
204            . '</dl>'
205            . '<p class="jp-stats-admin-bar-panel__error" hidden>' . esc_html__( 'Stats are unavailable right now.', 'jetpack-stats-admin' ) . '</p>'
206            . '</div>'
207            . '<ul class="ab-submenu jp-stats-admin-bar-panel__footer"><li><a class="ab-item" href="' . esc_url( self::get_seven_day_traffic_url() ) . '">' . esc_html__( 'View all stats', 'jetpack-stats-admin' ) . '</a></li></ul>'
208            . '</div>';
209    }
210
211    /**
212     * The Traffic page for the days the chart shows, ending today in the site's timezone.
213     *
214     * @return string
215     */
216    private static function get_seven_day_traffic_url() {
217        $today = new \DateTimeImmutable( 'now', wp_timezone() );
218        $start = $today->modify( '-' . ( self::SEVEN_DAY_CHART_DAYS - 1 ) . ' days' )->format( 'Y-m-d' );
219        $end   = $today->format( 'Y-m-d' );
220        $url   = admin_url( 'admin.php?page=stats#!/stats/day/' . (int) \Jetpack_Options::get_option( 'id' ) . "?chartStart=$start&chartEnd=$end" );
221
222        /** This filter is documented in src/class-admin-bar.php */
223        return apply_filters(
224            'jetpack_stats_url',
225            $url,
226            array(
227                'view'    => 'dashboard',
228                'section' => 'traffic',
229                'range'   => array(
230                    'from' => $start,
231                    'to'   => $end,
232                ),
233            )
234        );
235    }
236
237    /**
238     * Enqueue the script that draws the 7-day chart and fills the hover panel.
239     *
240     * @return void
241     */
242    private static function enqueue_seven_day_chart() {
243        Assets::register_script(
244            self::SCRIPT_HANDLE,
245            '../build/admin-bar.js',
246            __FILE__,
247            array(
248                'in_footer' => true,
249                'css_path'  => '../build/admin-bar.css',
250                'enqueue'   => true,
251            )
252        );
253
254        $config = array(
255            'restUrl' => add_query_arg(
256                array(
257                    'unit'        => 'day',
258                    'quantity'    => self::SEVEN_DAY_CHART_DAYS,
259                    'stat_fields' => 'views,visitors',
260                ),
261                rest_url( 'jetpack/v4/stats-app/sites/' . (int) \Jetpack_Options::get_option( 'id' ) . '/stats/visits' )
262            ),
263            'nonce'   => wp_create_nonce( 'wp_rest' ),
264            'days'    => self::SEVEN_DAY_CHART_DAYS,
265        );
266
267        wp_add_inline_script(
268            self::SCRIPT_HANDLE,
269            'window.jetpackStatsAdminBar = ' . wp_json_encode( $config, JSON_HEX_TAG | JSON_HEX_AMP ) . ';',
270            'before'
271        );
272    }
273
274    /**
275     * Add a Stats link to the site-name menu, next to Dashboard.
276     *
277     * @return void
278     */
279    public static function add_site_menu_link() {
280        global $wp_admin_bar;
281
282        // WordPress.com adds its own Stats link to this menu.
283        if (
284            ! is_object( $wp_admin_bar ) ||
285            ! $wp_admin_bar->get_node( 'dashboard' ) ||
286            ! current_user_can( 'view_stats' ) ||
287            ( new Host() )->is_wpcom_platform()
288        ) {
289            return;
290        }
291
292        $wp_admin_bar->add_node(
293            array(
294                'parent' => 'site-name',
295                'id'     => 'jetpack-stats',
296                'title'  => __( 'Stats', 'jetpack-stats-admin' ),
297                'href'   => self::get_dashboard_url(),
298            )
299        );
300    }
301
302    /**
303     * Where the admin bar's Stats links go.
304     *
305     * @return string
306     */
307    private static function get_dashboard_url() {
308        /**
309         * Filters a link to a Stats page, so a newer analytics dashboard can claim it.
310         *
311         * `$args['view']` names the page the link opens: `dashboard`, or `post` with the post in `$args['id']`.
312         * A `dashboard` link may carry a `section` and a `range` of `from`/`to` days as `Y-m-d`.
313         * Return `$url` unchanged for a view the dashboard has no page for.
314         *
315         * @since 0.39.0
316         * @since 0.40.0 The `dashboard` view may carry a `section` and a `range`.
317         *
318         * @param string $url  The Stats URL.
319         * @param array  $args The page the link opens.
320         */
321        return apply_filters( 'jetpack_stats_url', admin_url( 'admin.php?page=stats' ), array( 'view' => 'dashboard' ) );
322    }
323
324    /**
325     * Get the local URL that serves a chart image.
326     *
327     * Served by admin-post.php, because admin.php returns 403 for a page slug no plugin registers.
328     *
329     * @param string $chart One of the CHARTS.
330     * @return string
331     */
332    public static function get_chart_src( $chart ) {
333        return add_query_arg(
334            array(
335                'action' => self::CHART_ACTION,
336                'chart'  => $chart,
337            ),
338            admin_url( 'admin-post.php' )
339        );
340    }
341
342    /**
343     * Serve the chart an admin-post.php request asks for, or end it with an error status.
344     *
345     * @since 0.39.1
346     *
347     * @return void
348     */
349    public static function serve_chart() {
350        $chart = self::get_chart_param();
351        if ( null === $chart ) {
352            wp_die( '', '', 400 );
353            return;
354        }
355
356        if ( ! self::can_see_chart() ) {
357            wp_die( '', '', 403 );
358            return;
359        }
360
361        self::send_chart( $chart );
362    }
363
364    /**
365     * Serve a chart and stop, when a legacy `admin.php?page=stats` request asks for one.
366     *
367     * @return void
368     */
369    public static function maybe_serve_chart() {
370        // URLs with `proxy` come from the Jetpack plugin's deprecated stats_get_image_chart_src(), and its own handler forwards their extra parameters.
371        if ( isset( $_GET['proxy'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- An image request carries no nonce, and it changes nothing.
372            return;
373        }
374
375        $chart = self::get_requested_chart();
376        if ( null === $chart || ! self::can_see_chart() ) {
377            return;
378        }
379
380        self::send_chart( $chart );
381    }
382
383    /**
384     * Send a chart image fetched from WordPress.com, and stop.
385     *
386     * The browser cannot fetch the chart from WordPress.com directly, because only the blog token can read it.
387     *
388     * @param string $chart One of the CHARTS.
389     * @return never
390     */
391    private static function send_chart( $chart ) {
392        $image = self::fetch_chart( $chart );
393        if ( null === $image ) {
394            status_header( 502 );
395            exit( 0 );
396        }
397
398        // Replaces the no-store headers admin.php and admin-post.php send, so the browser reuses the chart across page views.
399        header_remove( 'Expires' );
400        header_remove( 'Pragma' );
401        header( 'Cache-Control: private, max-age=' . self::CHART_MAX_AGE );
402        header( 'Content-Type: ' . $image['type'] );
403        header( 'Content-Length: ' . strlen( $image['body'] ) );
404        echo $image['body']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Binary image data.
405        exit( 0 );
406    }
407
408    /**
409     * Fetch a chart image from WordPress.com with the blog token.
410     *
411     * @param string $chart One of the CHARTS.
412     * @return array{type: string, body: string}|null The image, or null when WordPress.com did not return one.
413     */
414    public static function fetch_chart( $chart ) {
415        $server = Constants::get_constant( 'STATS_DASHBOARD_SERVER' ) ?? 'dashboard.wordpress.com';
416
417        // WordPress.com accepts the blog token on this file only when `page`, `proxy` and `blog` are all present.
418        $url = add_query_arg(
419            array(
420                'page'  => 'stats',
421                'proxy' => '',
422                'blog'  => Stats_Options::get_option( 'blog_id' ),
423            ),
424            "https://{$server}/wp-includes/charts/{$chart}.php"
425        );
426
427        $response = Client::remote_request(
428            array(
429                'url'     => $url,
430                'method'  => 'GET',
431                'timeout' => 90,
432                'user_id' => 0,
433            )
434        );
435
436        // A failed request has the code '', which PHP 8 cannot divide.
437        $code = (int) wp_remote_retrieve_response_code( $response );
438        $type = wp_remote_retrieve_header( $response, 'content-type' );
439        $body = wp_remote_retrieve_body( $response );
440        if ( 2 !== (int) ( $code / 100 ) || ! is_string( $type ) || ! str_starts_with( $type, 'image/' ) || '' === $body ) {
441            return null;
442        }
443
444        return array(
445            'type' => $type,
446            'body' => $body,
447        );
448    }
449
450    /**
451     * Keep chart requests from redirecting to upgrade.php while a database upgrade is pending.
452     *
453     * @see wp-admin/admin.php, which compares the stored `db_version` with `$wp_db_version`.
454     *
455     * @param mixed $version The stored database version.
456     * @return mixed
457     */
458    public static function ignore_db_version( $version ) {
459        if ( is_admin() && null !== self::get_requested_chart() ) {
460            global $wp_db_version;
461            return $wp_db_version;
462        }
463
464        return $version;
465    }
466
467    /**
468     * Get the chart a legacy `page=stats` request asks for.
469     *
470     * @return string|null One of the CHARTS, or null when the request is not a `page=stats` chart request.
471     */
472    private static function get_requested_chart() {
473        if ( ! isset( $_GET['page'] ) || 'stats' !== $_GET['page'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- An image request carries no nonce, and it changes nothing.
474            return null;
475        }
476
477        return self::get_chart_param();
478    }
479
480    /**
481     * Get the chart in the request's `chart` parameter.
482     *
483     * @return string|null One of the CHARTS, or null when the parameter names none.
484     */
485    private static function get_chart_param() {
486        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- An image request carries no nonce, and it changes nothing.
487        if ( ! isset( $_GET['chart'] ) ) {
488            return null;
489        }
490
491        $chart = sanitize_key( wp_unslash( $_GET['chart'] ) );
492        // phpcs:enable WordPress.Security.NonceVerification.Recommended
493
494        return in_array( $chart, self::CHARTS, true ) ? $chart : null;
495    }
496}