Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
93.21% covered (success)
93.21%
206 / 221
79.49% covered (warning)
79.49%
31 / 39
CRAP
0.00% covered (danger)
0.00%
0 / 1
Analytics
93.21% covered (success)
93.21%
206 / 221
79.49% covered (warning)
79.49%
31 / 39
80.95
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
2
 is_initialized
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 load_dashboard_surface
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 load_dashboard
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 renders_admin_chrome
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 init_wpcom_simple
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
2.02
 apply_options
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 register_pre_connection_stats_page_replacement
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 boot_shared_services
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 dashboard_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 register_script_data
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 add_script_data
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 site_timezone
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 format_gmt_offset
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 register_sync_bootstrap
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 register_local_api
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 load_dashboard_components
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
1
 register_dashboard_support_routes
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 load_build
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 build_entry_path
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 load_section_registry
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 register_polyfills
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 remove_full_page_interceptor
37.50% covered (danger)
37.50%
3 / 8
0.00% covered (danger)
0.00%
0 / 1
5.20
 widget_manifest_path
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 register_admin_page
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 register_admin_shell_member
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 add_admin_shell_member
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
2.00
 load_as_admin_shell_guest
60.00% covered (warning)
60.00%
3 / 5
0.00% covered (danger)
0.00%
0 / 1
3.58
 redirect_denied_dashboard_request
50.00% covered (danger)
50.00%
1 / 2
0.00% covered (danger)
0.00%
0 / 1
1.12
 is_dashboard_request
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 renders_dashboard
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 register_admin_menu
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
5
 register_replayed_admin_menu
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 add_dashboard_menu_entry
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
2.15
 render_missing_build_notice
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 menu_title
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
6
 enqueue_i18n_loader
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 enqueue_tracks_transport
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 add_tracks_identity_script_data
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2/**
3 * Analytics package main class.
4 *
5 * @package automattic/jetpack-premium-analytics
6 */
7
8namespace Automattic\Jetpack\PremiumAnalytics;
9
10use Automattic\Jetpack\Admin_UI\Admin_Menu;
11use Automattic\Jetpack\Admin_UI\Admin_Shell;
12use Automattic\Jetpack\Connection\Manager as Connection_Manager;
13use Automattic\Jetpack\PremiumAnalytics\Reports\Export\Export;
14use Automattic\Jetpack\PremiumAnalytics\REST\Api_Proxy_Controller;
15use Automattic\Jetpack\PremiumAnalytics\REST\Notices_Controller;
16use Automattic\Jetpack\PremiumAnalytics\Sync\Sync_Status_Tracker;
17use Automattic\Jetpack\Status\Host;
18use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
19
20/**
21 * Main Analytics class.
22 *
23 * Loads the wp-build output and registers the dashboard's admin page.
24 */
25class Analytics {
26
27    const PACKAGE_VERSION = '0.18.0';
28
29    /**
30     * Whether the class has been initialized.
31     *
32     * @var bool
33     */
34    private static $initialized = false;
35
36    /**
37     * Menu title override for the admin page. Null falls back to the package's own
38     * translated label, resolved on admin_menu — init runs far too early to translate.
39     *
40     * @var string|\Closure|null
41     */
42    private static $menu_title = null;
43
44    /**
45     * The menu label once resolved, so the menu and the missing-build notice can't
46     * disagree if a caller hands us a closure that returns something different
47     * each call. Reset whenever $menu_title is assigned.
48     *
49     * @var string|null
50     */
51    private static $resolved_menu_title = null;
52
53    /**
54     * Whether the host has this dashboard replace stats-admin's pre-connection Stats page.
55     *
56     * @var bool
57     */
58    private static $replaces_pre_connection_stats_page = false;
59
60    /**
61     * Path to the wp-build entry point. Null uses the generated build.
62     *
63     * A test seam: `build/` is gitignored and test-php runs no build step, so tests redirect this
64     * instead. Private, so — unlike the widget manifest's path — it needs no filter to stay out of reach.
65     *
66     * @var string|null
67     */
68    private static $build_entry = null;
69
70    /**
71     * Initialize the Analytics app on a connected Jetpack site.
72     *
73     * Registers the full local surface: the site serves the WPCOM data proxy,
74     * notices, sync bootstrap, and the dashboard support routes itself.
75     *
76     * Hosts call this on every request once the flag is on, never only on admin ones: the
77     * store-event tracker listens on the front end. {@see self::load_dashboard_surface()} is what
78     * keeps the admin-only work off those requests.
79     *
80     * @param array $options Optional configuration options.
81     *                       Supported keys:
82     *                       - menu_title (string|\Closure): Admin menu label. Defaults to
83     *                         the package's own translated label. Pass a closure to supply
84     *                         a translated label of your own: it runs on admin_menu, where
85     *                         a textdomain can load, unlike init time.
86     *                       - replaces_pre_connection_stats_page (bool): Stop stats-admin from
87     *                         registering its own Stats page while the site is not connected, so
88     *                         this dashboard is the only Stats entry. Defaults to whether classic
89     *                         Stats is retired.
90     *                       A later call still applies its options, so a host that calls this after
91     *                       another plugin did keeps its configuration.
92     * @return void
93     */
94    public static function init( $options = array() ) {
95        self::apply_options( $options );
96        if ( self::$initialized ) {
97            return;
98        }
99        self::$initialized = true;
100
101        self::register_sync_bootstrap();
102        self::register_local_api();
103
104        // Piggybacks on the Jetpack Stats module; checks Jetpack connection state.
105        Jetpack_Stats_Tracker::configure();
106        self::register_pre_connection_stats_page_replacement();
107
108        self::boot_shared_services();
109        self::register_dashboard_support_routes();
110        self::load_dashboard_surface();
111        self::register_admin_shell_member();
112    }
113
114    /**
115     * Whether Stats v2 booted in this request, whichever plugin or platform booted it.
116     *
117     * @since 0.16.0
118     *
119     * @return bool
120     */
121    public static function is_initialized() {
122        return self::$initialized;
123    }
124
125    /**
126     * Load the dashboard render surface, on the requests that can render it.
127     *
128     * With the rollout flag on, init() runs on every request — including every WPCOM public-api
129     * request on Simple — so this stays gated for visitors who never use it (REST excluded; see load_build()).
130     *
131     * @return void
132     */
133    private static function load_dashboard_surface() {
134        if ( ! self::renders_admin_chrome() ) {
135            // Calypso's sidebar replays wp-admin/menu.php over REST, where nothing else lists the dashboard.
136            add_action( 'admin_menu', array( static::class, 'register_replayed_admin_menu' ) );
137            return;
138        }
139
140        self::load_dashboard();
141    }
142
143    /**
144     * Load what the dashboard page renders with.
145     *
146     * @return void
147     */
148    private static function load_dashboard() {
149        Dashboard_Support::load();
150        self::load_dashboard_components();
151        self::load_build();
152        self::remove_full_page_interceptor();
153        self::register_admin_page();
154    }
155
156    /**
157     * Whether this request can render an admin screen.
158     *
159     * Core also sets is_admin() on admin-ajax.php and admin-post.php, which render no screen, so neither
160     * parses the build here; the admin shell's guest endpoint loads it later, in load_as_admin_shell_guest().
161     *
162     * @return bool
163     */
164    private static function renders_admin_chrome() {
165        if ( ! is_admin() || wp_doing_ajax() ) {
166            return false;
167        }
168
169        // wp-includes/vars.php sets $pagenow before plugins load.
170        return 'admin-post.php' !== ( $GLOBALS['pagenow'] ?? '' );
171    }
172
173    /**
174     * Initialize the Analytics app on WordPress.com Simple.
175     *
176     * Simple reaches public-api.wordpress.com directly via WPCOM's apiFetch bridge, registering
177     * no local REST surface (no proxy, notices, sync bootstrap, or dashboard routes) — WPCOM handles those.
178     *
179     * @param array $options Optional configuration options.
180     *                       Supported keys:
181     *                       - menu_title (string|\Closure): Admin menu label. Defaults to
182     *                         the package's own translated label. Pass a closure to supply
183     *                         a translated label of your own: it runs on admin_menu, where
184     *                         a textdomain can load, unlike init time.
185     * @return void
186     */
187    public static function init_wpcom_simple( $options = array() ) {
188        self::apply_options( $options );
189        if ( self::$initialized ) {
190            return;
191        }
192        self::$initialized = true;
193
194        self::boot_shared_services();
195        self::load_dashboard_surface();
196    }
197
198    /**
199     * Apply init-time configuration options.
200     *
201     * @param array $options Options passed to the init entry points.
202     * @return void
203     */
204    private static function apply_options( $options ) {
205        if ( ! empty( $options['menu_title'] ) ) {
206            self::$menu_title          = $options['menu_title'];
207            self::$resolved_menu_title = null;
208        }
209        if ( ! empty( $options['replaces_pre_connection_stats_page'] ) ) {
210            self::$replaces_pre_connection_stats_page = true;
211        }
212    }
213
214    /**
215     * Replace stats-admin's pre-connection Stats page with this dashboard when the host asks, or once classic Stats is retired.
216     *
217     * The callback reads the option when stats-admin initializes on `plugins_loaded`, so a host whose
218     * init() call comes after another plugin's still takes effect.
219     *
220     * @return void
221     */
222    private static function register_pre_connection_stats_page_replacement() {
223        add_filter(
224            'jetpack_stats_admin_pre_connection_dashboard',
225            static function ( $register ) {
226                return self::$replaces_pre_connection_stats_page || Classic_Stats::is_retired() ? false : $register;
227            }
228        );
229    }
230
231    /**
232     * Boot the services every platform needs, whether or not the site serves the
233     * dashboard support routes itself.
234     *
235     * @return void
236     */
237    private static function boot_shared_services() {
238        // Must be hooked before admin_menu and rest_api_init check the capability.
239        Capabilities::register();
240
241        // Emit WooCommerce store events into the Woo pipeline (ClickHouse + proxy).
242        WooCommerce_Analytics_Tracker::configure();
243
244        // CSV report export pipeline (WOOA7S-1581): hooks rest_api_init, so it must
245        // register on all requests. Self-gates on WooCommerce + Jetpack connection.
246        Export::configure();
247
248        self::register_script_data();
249
250        // Stats links elsewhere (post list table, admin bar, action bar) open this dashboard.
251        Stats_Links::register();
252
253        // What the dashboard announces on the What's new surface it hosts.
254        Dashboard_Announcements::configure();
255    }
256
257    /**
258     * URL of a dashboard route on this site.
259     *
260     * The SPA path travels in `p`, encoded here since add_query_arg() leaves values alone and a
261     * raw `?` inside it would read as an outer query param.
262     *
263     * @since 0.4.0
264     *
265     * @param string $path Route path, e.g. `/post/123`.
266     * @return string
267     */
268    public static function dashboard_url( $path = '/' ) {
269        return admin_url( 'admin.php?page=' . self::MENU_PAGE_SLUG . '&p=' . rawurlencode( $path ) );
270    }
271
272    /**
273     * Announce to Jetpack's other surfaces that this dashboard is the site's analytics UI,
274     * so they link here instead of the Stats page.
275     *
276     * @return void
277     */
278    private static function register_script_data() {
279        add_filter( 'jetpack_admin_js_script_data', array( static::class, 'add_script_data' ) );
280    }
281
282    /**
283     * Runs on nearly every admin page load, so the payload stays to two strings,
284     * a bool, and one access check.
285     *
286     * `can_view` is whether this user can open a Stats view: every link other surfaces build from it opens one.
287     *
288     * @param array $data The script data.
289     * @return array The script data with the analytics key added.
290     */
291    public static function add_script_data( $data ) {
292        $data['analytics'] = array(
293            'enabled'   => true,
294            'page_slug' => self::MENU_PAGE_SLUG,
295            'can_view'  => Capabilities::current_user_can_open_stats(),
296            'timezone'  => self::site_timezone(),
297        );
298
299        return $data;
300    }
301
302    /**
303     * Prefers `timezone_string` over `gmt_offset`, matching the dashboard's own `siteTimeZone()`:
304     * analytics links point at past dates, so a fixed offset applied to the far side of a
305     * daylight-saving transition shifts the day.
306     *
307     * @return string An IANA timezone name, or a `+HH:MM` UTC offset.
308     */
309    private static function site_timezone() {
310        $timezone_string = get_option( 'timezone_string' );
311
312        if ( is_string( $timezone_string ) && $timezone_string !== '' ) {
313            return $timezone_string;
314        }
315
316        return self::format_gmt_offset( (float) get_option( 'gmt_offset' ) );
317    }
318
319    /**
320     * Format a GMT offset in hours as `+HH:MM`.
321     *
322     * @param float $offset The offset in hours, e.g. 5.5 or -8.
323     * @return string The formatted offset.
324     */
325    private static function format_gmt_offset( $offset ) {
326        $sign     = $offset < 0 ? '-' : '+';
327        $absolute = abs( $offset );
328        $hours    = (int) floor( $absolute );
329        $minutes  = (int) round( ( $absolute - $hours ) * 60 );
330
331        return sprintf( '%s%02d:%02d', $sign, $hours, $minutes );
332    }
333
334    /**
335     * Register the sync services that feed the local data pipeline.
336     *
337     * @return void
338     */
339    private static function register_sync_bootstrap() {
340        // Keep the shared connection available when another connection-owning plugin is deactivated.
341        Connection_Configuration::configure();
342
343        Sync_Status_Tracker::configure();
344    }
345
346    /**
347     * Register the site-served REST API: the WPCOM data proxy, notices and the Stats settings.
348     *
349     * Each self-gates on its own rest_api_init hook.
350     *
351     * @return void
352     */
353    private static function register_local_api() {
354        Api_Proxy_Controller::register();
355        Notices_Controller::register();
356        Stats_Settings::configure();
357    }
358
359    /**
360     * Load the package's own dashboard components, over the API Dashboard_Support::load() provides.
361     *
362     * Admin-only, via load_dashboard_surface(); boot_routes() requires these
363     * again for REST.
364     *
365     * @return void
366     */
367    private static function load_dashboard_components() {
368        // The package's own sections, registered through the section API.
369        require_once __DIR__ . '/default-dashboard-sections.php';
370        configure_dashboard_sections_script_data();
371
372        // Single-report page API, then the package's own pages registered through it.
373        require_once __DIR__ . '/single-report-pages.php';
374        require_once __DIR__ . '/default-single-report-pages.php';
375        configure_single_report_pages_script_data();
376
377        // Default-on CSV export settings and server-side disable filter.
378        require_once __DIR__ . '/csv-exports.php';
379        configure_csv_exports();
380
381        // VideoPress availability for the client's video routes. The widget layer
382        // reads the same signal through widget-type-support.php.
383        require_once __DIR__ . '/videopress-availability.php';
384        configure_videopress_availability();
385
386        // The plan's locked Stats features, for the client's locked states.
387        require_once __DIR__ . '/stats-plan-gates.php';
388        configure_stats_plan_gates();
389
390        // The promo slot other packages register into, for the dashboard, the menu and Settings.
391        require_once __DIR__ . '/promos.php';
392        configure_promos();
393
394        // The purchase a Stats checkout returned with, for the thank-you notice.
395        require_once __DIR__ . '/purchase-success.php';
396        configure_purchase_success();
397
398        // When the site first opened the dashboard, for notices that wait a while before showing.
399        require_once __DIR__ . '/dashboard-first-visit.php';
400        configure_dashboard_first_visit();
401
402        require_once __DIR__ . '/assets-url.php';
403        configure_assets_url();
404
405        // The locale's default date format, for site formats the dashboard cannot shorten.
406        require_once __DIR__ . '/date-format.php';
407        configure_date_format();
408
409        // Temporary: carries a default layout move into layouts readers customized before it.
410        Stored_Layout_Move::register();
411    }
412
413    /**
414     * Serve the dashboard support routes from the site. Simple skips this —
415     * WPCOM calls Dashboard_Support_Routes::register() itself instead.
416     *
417     * @return void
418     */
419    private static function register_dashboard_support_routes() {
420        Dashboard_Support_Routes::register();
421    }
422
423    /**
424     * Load the wp-build output (interceptor, routes, page render); Dashboard_Support::load()
425     * already registered its script modules.
426     *
427     * Admin-only, via load_dashboard_surface(). REST does not need it:
428     * boot_routes() and ensure_widget_registry_ready() load what they use.
429     *
430     * @return void
431     */
432    private static function load_build() {
433        $build_entry = self::build_entry_path();
434        if ( file_exists( $build_entry ) ) {
435            require_once $build_entry;
436        }
437    }
438
439    /**
440     * Path to the wp-build entry point.
441     *
442     * @return string
443     */
444    private static function build_entry_path() {
445        return self::$build_entry ?? __DIR__ . '/../build/build.php';
446    }
447
448    /**
449     * Load the dashboard sections, which the dashboard capability depends on, without the build.
450     *
451     * @return void
452     */
453    private static function load_section_registry() {
454        require_once __DIR__ . '/dashboard-layout.php';
455        require_once __DIR__ . '/default-dashboard-sections.php';
456    }
457
458    /**
459     * Register the wp-build polyfills the dashboard needs on WordPress before 7.0.
460     *
461     * They force-replace core handles (wp-private-apis), so only the dashboard and the admin shell's wp-build pages that load it as a guest call this; never another admin page, such as the block editor.
462     *
463     * @return void
464     */
465    private static function register_polyfills() {
466        WP_Build_Polyfills::register(
467            'jetpack-premium-analytics',
468            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
469        );
470    }
471
472    /**
473     * Unhook wp-build's full-page render interceptor — security-relevant: it renders
474     * `?page=jetpack-premium-analytics` from admin_init with no capability check, and only
475     * renders_admin_chrome() gates the admin-post.php/admin-ajax.php paths that reach admin_init
476     * without Core's own slug check. The admin shell's guest endpoint loads the build on admin-ajax.php
477     * only after admin_init has run, so the interceptor never fires there either.
478     *
479     * Because remove_action() no-ops on a callback name it can't find, a wp-build rename would
480     * silently restore this entry point — hence the _doing_it_wrong() below when that happens.
481     *
482     * @return void
483     */
484    private static function remove_full_page_interceptor() {
485        if ( remove_action( 'admin_init', 'jpa_jetpack_premium_analytics_intercept_render' ) ) {
486            return;
487        }
488
489        if ( function_exists( 'jpa_jetpack_premium_analytics_intercept_render' ) ) {
490            _doing_it_wrong(
491                __METHOD__,
492                'The Premium Analytics full-page interceptor could not be unhooked: wp-build changed the generated callback name or its admin_init priority.',
493                ''
494            );
495        }
496    }
497
498    /**
499     * Absolute path to the generated widget manifest.
500     *
501     * @return string
502     */
503    public static function widget_manifest_path() {
504        /**
505         * Filters the path to the generated widget manifest.
506         *
507         * @param string $path Absolute path to the generated widget manifest.
508         */
509        return apply_filters(
510            'jetpack_premium_analytics_widgets_manifest_path',
511            __DIR__ . '/../build/widgets.php'
512        );
513    }
514
515    /**
516     * Register the admin-only render path: polyfills, menu, and page hooks.
517     *
518     * @return void
519     */
520    private static function register_admin_page() {
521        if ( self::renders_dashboard() ) {
522            self::register_polyfills();
523
524            add_action( 'admin_enqueue_scripts', array( static::class, 'enqueue_i18n_loader' ) );
525            add_action( 'admin_enqueue_scripts', array( static::class, 'enqueue_tracks_transport' ) );
526            add_filter( 'jetpack_admin_js_script_data', array( static::class, 'add_tracks_identity_script_data' ), 20 );
527            require_once __DIR__ . '/error-reporting.php';
528            add_filter( 'jetpack_admin_js_script_data', __NAMESPACE__ . '\\add_error_reporting_script_data', 20 );
529            add_filter( 'wpcom_error_reporting_delegated', __NAMESPACE__ . '\\delegate_wp_admin_error_reporting' );
530            add_action( 'admin_page_access_denied', array( static::class, 'redirect_denied_dashboard_request' ) );
531        }
532
533        add_action( 'admin_menu', array( static::class, 'register_admin_menu' ) );
534    }
535
536    /**
537     * Join the admin shell, which switches between Jetpack dashboards without a page load.
538     *
539     * @return void
540     */
541    private static function register_admin_shell_member() {
542        // An older admin-ui, loaded first by another plugin, can't host a top-level page or its widget modules.
543        if ( ! is_admin() || ! method_exists( Admin_Shell::class, 'requested_guest' ) ) {
544            return;
545        }
546        add_filter( 'jetpack_admin_shell_members', array( static::class, 'add_admin_shell_member' ) );
547        // The standalone plugin reaches admin-ui only through the admin menu, which admin-ajax never builds.
548        Admin_Shell::init();
549    }
550
551    /**
552     * Register the dashboard with the admin shell.
553     *
554     * @since $$next-version$$
555     *
556     * @param array $members Shell members keyed by admin page slug.
557     * @return array
558     */
559    public static function add_admin_shell_member( $members ) {
560        if ( ! file_exists( self::build_entry_path() ) ) {
561            return $members;
562        }
563
564        // The guest endpoint checks the capability before it loads anything.
565        self::load_section_registry();
566
567        $members[ self::MENU_PAGE_SLUG ] = array(
568            'build_prefix' => 'jpa',
569            'build_page'   => 'jetpack-premium-analytics',
570            'init_modules' => array( '@jetpack-premium-analytics/init' ),
571            'title'        => self::menu_title(),
572            'capability'   => Capabilities::dashboard_page_capability(),
573            'handles'      => array( 'jetpack-script-data', 'wp-api-fetch', 'wp-jp-i18n-loader', 'jp-tracks' ),
574            'load'         => array( static::class, 'load_as_admin_shell_guest' ),
575            // The Settings card links to Features through menu_page_url().
576            'admin_menu'   => true,
577        );
578        return $members;
579    }
580
581    /**
582     * Ready the dashboard's routes and page data while another dashboard's page is open.
583     *
584     * @since $$next-version$$
585     *
586     * @return void
587     */
588    public static function load_as_admin_shell_guest() {
589        // The guest endpoint runs on admin-ajax, where load_dashboard_surface() loads nothing.
590        if ( wp_doing_ajax() ) {
591            self::load_dashboard();
592        } else {
593            self::register_polyfills();
594        }
595
596        // The generated registration runs on wp_default_scripts, which may already have fired.
597        if ( function_exists( 'jpa_register_script_modules' ) ) {
598            jpa_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Defined in the generated build/modules.php.
599        }
600    }
601
602    /**
603     * Sends a reader who lost access, for example because the site was disconnected, to the
604     * wp-admin Dashboard instead of the "not allowed" screen.
605     *
606     * @return never
607     */
608    public static function redirect_denied_dashboard_request() {
609        wp_safe_redirect( admin_url() );
610        exit;
611    }
612
613    /**
614     * The admin page slug the dashboard menu registers. Published in script data
615     * so no caller has to hard-code it.
616     */
617    const MENU_PAGE_SLUG = 'jetpack-premium-analytics-wp-admin';
618
619    /**
620     * Where the dashboard sits in the admin menu: under the Dashboard, and on WordPress.com
621     * between My Home (2.01) and Hosting (2.98).
622     *
623     * Not 2, which the Dashboard holds: core gives a second entry there a hashed fraction to
624     * tell the two apart, and the menu's natural sort reads one such as .21518 as past .99.
625     */
626    private const MENU_POSITION = 2.1;
627
628    /**
629     * Whether the current request is rendering the Premium Analytics dashboard.
630     *
631     * Scopes the wp-build polyfill registration (which force-replaces core script handles) to
632     * this dashboard; reads the menu slug directly, not current_screen, to stay safe at plugin-load time.
633     *
634     * @return bool True when serving the dashboard page in wp-admin.
635     */
636    public static function is_dashboard_request() {
637        if ( ! is_admin() ) {
638            return false;
639        }
640
641        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading the menu page slug to scope asset loading; no state is changed.
642        $page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
643
644        return self::MENU_PAGE_SLUG === $page;
645    }
646
647    /**
648     * Whether the current request renders the dashboard: its own page, or the admin shell loading it into another one.
649     *
650     * The shell also loads it on a menu hover, so code that marks a visit or writes anything checks is_dashboard_request() instead.
651     *
652     * @since $$next-version$$
653     *
654     * @return bool
655     */
656    public static function renders_dashboard() {
657        if ( method_exists( Admin_Shell::class, 'requested_guest' ) && self::MENU_PAGE_SLUG === Admin_Shell::requested_guest() ) {
658            return true;
659        }
660        return self::is_dashboard_request();
661    }
662
663    /**
664     * Register the admin menu page.
665     *
666     * Uses wp-build's `-wp-admin` variant so Core applies the menu capability check. Reports the
667     * page and widget artifacts independently since the build loader includes each conditionally.
668     *
669     * Queued through Admin_Menu rather than registered here, so the entry is reachable by the
670     * `jetpack_admin_menu_visibility` filter.
671     *
672     * @return void
673     */
674    public static function register_admin_menu() {
675        $can_render          = function_exists( 'jpa_jetpack_premium_analytics_wp_admin_render_page' );
676        $has_widget_manifest = file_exists( self::widget_manifest_path() );
677
678        $missing = array();
679        if ( ! $can_render ) {
680            // Named by symbol, not by file: build/pages.php is only a loader, and the
681            // callback can also go missing to a renamed page slug or an absent build entry.
682            $missing[] = 'the jpa_jetpack_premium_analytics_wp_admin_render_page() callback, generated under build/pages/';
683        }
684        if ( ! $has_widget_manifest ) {
685            $missing[] = 'build/widgets.php (the widget manifest)';
686        }
687
688        if ( $missing ) {
689            // Surfaced here rather than only on the page itself, so a partial deploy shows up on
690            // the first admin request instead of waiting for someone to open the dashboard.
691            _doing_it_wrong(
692                __METHOD__,
693                // esc_html() only to satisfy WordPress.Security.EscapeOutput, which treats
694                // this argument as output; every entry is a literal from just above.
695                'The Premium Analytics build output is incomplete: ' . esc_html( implode( ', ', $missing ) ) . '. The package build did not run, or ran only partially, for this deploy.',
696                ''
697            );
698        }
699
700        $render_callback = $can_render
701            ? 'jpa_jetpack_premium_analytics_wp_admin_render_page'
702            : array( __CLASS__, 'render_missing_build_notice' );
703
704        self::add_dashboard_menu_entry( $render_callback );
705    }
706
707    /**
708     * List the dashboard in a menu built outside wp-admin, such as the one the admin-menu REST endpoint returns.
709     *
710     * Loads the section registry but not the build: the menu capability depends on the sections.
711     * Do not rename: wpcomsh retires classic Stats on Atomic only while this method exists.
712     *
713     * @since 0.17.0
714     *
715     * @return void
716     */
717    public static function register_replayed_admin_menu() {
718        self::load_section_registry();
719
720        self::add_dashboard_menu_entry( '__return_null' );
721    }
722
723    /**
724     * Add the dashboard's top-level menu entry.
725     *
726     * @param callable $render_callback Renders the page.
727     * @return void
728     */
729    private static function add_dashboard_menu_entry( $render_callback ) {
730        $menu_title = esc_html( self::menu_title() );
731        $capability = Capabilities::dashboard_page_capability();
732
733        // An older admin-ui, loaded first by another plugin, may predate add_top_level_menu().
734        if ( ! method_exists( Admin_Menu::class, 'add_top_level_menu' ) ) {
735            add_menu_page( $menu_title, $menu_title, $capability, self::MENU_PAGE_SLUG, $render_callback, 'dashicons-chart-bar', self::MENU_POSITION );
736            return;
737        }
738
739        // A fixed key rather than the slug, which carries a build-specific suffix. No gate:
740        // the dashboard has no My Jetpack product class and no module to name.
741        Admin_Menu::add_top_level_menu( $menu_title, $menu_title, $capability, self::MENU_PAGE_SLUG, $render_callback, 'dashicons-chart-bar', self::MENU_POSITION, array( 'key' => 'jetpack-premium-analytics' ) );
742    }
743
744    /**
745     * Stand-in for the generated render callback when the build output is absent.
746     *
747     * The PHP classes come from Composer and the build output from pnpm, so a
748     * partial deploy can leave the class loadable with nothing to render.
749     *
750     * @return void
751     */
752    public static function render_missing_build_notice() {
753        printf(
754            '<div class="wrap"><h1>%s</h1><p>%s</p></div>',
755            esc_html( self::menu_title() ),
756            esc_html__( 'The Premium Analytics assets are missing. The package build did not run for this deploy.', 'jetpack-premium-analytics-pkg' )
757        );
758    }
759
760    /**
761     * The caller's menu label override, or the package's own translated label.
762     *
763     * Call only once translations can load — admin_menu or later — and memoize so every call site
764     * agrees. Deliberately not is_callable(): PHP function names are case-insensitive, so a plain
765     * label like "Analytics" could match a stray analytics() function and get called.
766     *
767     * @return string
768     */
769    private static function menu_title() {
770        if ( null !== self::$resolved_menu_title ) {
771            return self::$resolved_menu_title;
772        }
773
774        $title = self::$menu_title instanceof \Closure
775            ? ( self::$menu_title )()
776            : self::$menu_title;
777
778        // A positive check rather than a null coalesce: a closure may return an empty string, or
779        // something that isn't a string at all, and either would reach esc_html() as a broken label.
780        if ( is_string( $title ) && '' !== $title ) {
781            self::$resolved_menu_title = $title;
782        } elseif ( Classic_Stats::is_retired() ) {
783            // No classic Stats menu is left to tell apart from.
784            self::$resolved_menu_title = __( 'Stats', 'jetpack-premium-analytics-pkg' );
785        } else {
786            self::$resolved_menu_title = __( 'Stats v2', 'jetpack-premium-analytics-pkg' );
787        }
788
789        return self::$resolved_menu_title;
790    }
791
792    /**
793     * Enqueue the i18n loader so the wp-build init module can download its JS
794     * translation catalogs. It's registered on every admin page by jetpack-assets
795     * but only enqueued when depended on; the esbuild bundles don't pull it in.
796     *
797     * @return void
798     */
799    public static function enqueue_i18n_loader() {
800        if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
801            wp_enqueue_script( 'wp-jp-i18n-loader' );
802        }
803    }
804
805    /**
806     * Load the Tracks transport for the dashboard.
807     *
808     * `@automattic/jetpack-analytics` only queues events into `window._tkq` — its own w.js
809     * loader is disabled — so without this handle no `jetpack_premium_analytics_*` event
810     * ever flushes. Simple is skipped because stats.php already prints the same script.
811     *
812     * @return void
813     */
814    public static function enqueue_tracks_transport() {
815        if ( ( new Host() )->is_wpcom_simple() ) {
816            return;
817        }
818
819        wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
820    }
821
822    /**
823     * Publish the WPCOM identity the dashboard attributes its Tracks events to.
824     *
825     * Core's script data carries only the local user. Publicize is the one package that fills
826     * `current_user.wpcom` in, and the standalone plugin does not bundle it, so without this
827     * every event would land anonymous there.
828     *
829     * @param array $data The script data.
830     * @return array The script data with the WPCOM identity added.
831     */
832    public static function add_tracks_identity_script_data( $data ) {
833        if ( ( new Host() )->is_wpcom_simple() ) {
834            $wpcom_user = array(
835                'ID'    => get_current_user_id(),
836                'login' => wp_get_current_user()->user_login,
837            );
838        } else {
839            $connected = ( new Connection_Manager() )->get_connected_user_data();
840
841            if ( empty( $connected['ID'] ) || empty( $connected['login'] ) ) {
842                return $data;
843            }
844
845            // Only the two fields `identifyUser` needs: the rest of the connected-user payload
846            // is profile data the dashboard never reads.
847            $wpcom_user = array(
848                'ID'    => $connected['ID'],
849                'login' => $connected['login'],
850            );
851        }
852
853        $data['user']['current_user']['wpcom'] = array_merge(
854            $data['user']['current_user']['wpcom'] ?? array(),
855            $wpcom_user
856        );
857
858        return $data;
859    }
860}