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