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