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