Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
70.34% covered (warning)
70.34%
83 / 118
52.63% covered (warning)
52.63%
10 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Activity_Log
70.69% covered (warning)
70.69%
82 / 116
52.63% covered (warning)
52.63%
10 / 19
109.46
0.00% covered (danger)
0.00%
0 / 1
 initialize
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
 is_module_active
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 register_module
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 add_standalone_module
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 activate_standalone_default
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
4.07
 add_wp_admin_submenu
89.29% covered (warning)
89.29%
25 / 28
0.00% covered (danger)
0.00%
0 / 1
6.04
 is_available
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
4.37
 admin_init
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 load_wp_build
23.08% covered (danger)
23.08%
3 / 13
0.00% covered (danger)
0.00%
0 / 1
7.10
 load_wp_build_with_screen_alias
75.00% covered (warning)
75.00%
9 / 12
0.00% covered (danger)
0.00%
0 / 1
2.06
 alias_screen_id_for_wp_build
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 restore_screen_id_after_wp_build
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 opt_out_of_jitms
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 hide_jitms_on_wp_build_dashboard
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 enqueue_initial_state
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 is_wpcom_simple
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 render_fallback
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 is_activity_log_admin_request
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 register_rest_routes
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * Primary class for the Jetpack Activity Log package.
4 *
5 * @package automattic/jetpack-activity-log
6 */
7
8namespace Automattic\Jetpack\Activity_Log;
9
10if ( ! defined( 'ABSPATH' ) ) {
11    exit( 0 );
12}
13
14use Automattic\Jetpack\Activity_Log\Initial_State as Activity_Log_Initial_State;
15use Automattic\Jetpack\Admin_UI\Admin_Menu;
16use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
17use Automattic\Jetpack\Connection\Manager as Connection_Manager;
18use Automattic\Jetpack\Modules;
19use Automattic\Jetpack\Status\Host;
20use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
21use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id;
22use Jetpack_Options;
23use function add_action;
24use function add_filter;
25use function add_submenu_page;
26use function class_exists;
27use function current_user_can;
28use function did_action;
29use function do_action;
30use function get_current_screen;
31use function is_admin;
32use function is_multisite;
33use function sanitize_text_field;
34use function wp_add_inline_script;
35use function wp_enqueue_script;
36use function wp_register_script;
37use function wp_unslash;
38use function wp_verify_nonce;
39
40/**
41 * Class Jetpack_Activity_Log
42 *
43 * Registers the Activity Log admin page and its REST routes inside the
44 * main Jetpack plugin.
45 */
46class Jetpack_Activity_Log {
47
48    /**
49     * Admin page slug.
50     *
51     * @var string
52     */
53    const PAGE_SLUG = 'jetpack-activity-log';
54
55    /**
56     * Slug of the Jetpack module that turns the Activity Log on and off.
57     *
58     * @var string
59     */
60    const MODULE_SLUG = 'activity-log';
61
62    /**
63     * Jetpack_Options key recording that the module was switched on for a site
64     * with no Jetpack plugin. See `activate_standalone_default()`.
65     *
66     * @var string
67     */
68    const DEFAULT_ACTIVATED_OPTION = 'activity_log_default_activated';
69
70    /**
71     * Page slug for the wp-build dashboard. Distinct from the wp-admin menu
72     * slug (`PAGE_SLUG`) so the user-facing URL stays `admin.php?page=jetpack-activity-log`;
73     * we alias the current screen id to this value so wp-build's
74     * screen-match enqueue callback fires. Must match the `page` in
75     * `routes/dashboard/package.json` and the `wpPlugin.pages` entry.
76     *
77     * @var string
78     */
79    const WP_BUILD_PAGE_SLUG = 'jetpack-activity-log-dashboard';
80
81    /**
82     * Handle for the classic script that carries the React initial state.
83     * The dashboard is a wp-build script module, so there is no classic
84     * bundle handle to attach inline data to — this empty handle exists
85     * purely to print `JPACTIVITYLOG_INITIAL_STATE` and the Connection
86     * initial state before boot runs.
87     *
88     * @var string
89     */
90    const DATA_SCRIPT_HANDLE = 'jetpack-activity-log-data';
91
92    /**
93     * Nonce action for refreshing the access flag after a checkout
94     * return. Used by `admin_init()` below and exposed to the client via
95     * Initial_State so the upsell CTA can embed a valid nonce in its
96     * `redirect_to`. Same shape as `Social_Admin_Page::REFRESH_PLAN_NONCE_ACTION`.
97     *
98     * @var string
99     */
100    const REFRESH_ACCESS_NONCE_ACTION = 'jetpack_activity_log_refresh_access';
101
102    /**
103     * The screen ID alias_screen_id_for_wp_build() replaced, until it is restored.
104     *
105     * @var string|null
106     */
107    private static $wp_build_original_screen_id = null;
108
109    /**
110     * The dashboard screen hide_jitms_on_wp_build_dashboard() opts out of JITMs.
111     *
112     * @var string|null
113     */
114    private static $jitm_opt_out_screen_id = null;
115
116    /**
117     * Entry point. Idempotent: safe to call from multiple bootstraps.
118     *
119     * Bootstraps only while the `activity-log` module is on, so the toggle
120     * means the same thing to the Jetpack plugin and to every standalone
121     * plugin that carries this package.
122     */
123    public static function initialize() {
124        // Simple has no module system, and jetpack-mu-wpcom registers the page itself via add_wp_admin_submenu().
125        if ( self::is_wpcom_simple() ) {
126            return;
127        }
128
129        self::register_module();
130
131        if ( did_action( 'jetpack_activity_log_initialized' ) || ! self::is_module_active() ) {
132            return;
133        }
134
135        add_action( 'admin_menu', array( __CLASS__, 'add_wp_admin_submenu' ) );
136        add_action( 'rest_api_init', array( __CLASS__, 'register_rest_routes' ) );
137        add_filter( 'jetpack_package_versions', array( Package_Version::class, 'send_package_version_to_tracker' ) );
138
139        /**
140         * Fires once the Jetpack Activity Log package has wired its hooks.
141         *
142         * @since 0.1.0
143         */
144        do_action( 'jetpack_activity_log_initialized' );
145    }
146
147    /**
148     * Whether the Activity Log module is switched on.
149     *
150     * @return bool
151     */
152    public static function is_module_active() {
153        return ( new Modules() )->is_active( self::MODULE_SLUG );
154    }
155
156    /**
157     * Make the module controllable, and give a site with no Jetpack plugin the
158     * same default-on state the Jetpack plugin gets from `Auto Activate: Yes`.
159     *
160     * @return void
161     */
162    private static function register_module() {
163        add_filter( 'jetpack_get_available_standalone_modules', array( __CLASS__, 'add_standalone_module' ) );
164
165        // `class_exists( 'Jetpack' )` is only reliable once every plugin file has
166        // loaded: `jetpack-backup/` sorts before `jetpack/` in active_plugins, so
167        // Backup reaches initialize() while the Jetpack class is still undefined.
168        if ( did_action( 'plugins_loaded' ) ) {
169            self::activate_standalone_default();
170        } else {
171            add_action( 'plugins_loaded', array( __CLASS__, 'activate_standalone_default' ) );
172        }
173    }
174
175    /**
176     * Make the module available to the module controller when the Jetpack
177     * plugin is not installed, so `jetpack_active_modules` is not inert there.
178     *
179     * @param array $modules Available standalone module slugs.
180     * @return array
181     */
182    public static function add_standalone_module( $modules ) {
183        $modules[] = self::MODULE_SLUG;
184
185        return array_values( array_unique( $modules ) );
186    }
187
188    /**
189     * Switch the module on once on a site with no Jetpack plugin.
190     *
191     * The Jetpack plugin activates the module for you via `Auto Activate: Yes`;
192     * a standalone install has no equivalent, so without this the page would
193     * disappear from every Backup/Boost/Protect/Search/VideoPress site on
194     * upgrade. Recorded in an option rather than repeated, so a later opt-out
195     * is not undone on the next request.
196     *
197     * @return void
198     */
199    public static function activate_standalone_default() {
200        if ( class_exists( 'Jetpack' ) || Jetpack_Options::get_option( self::DEFAULT_ACTIVATED_OPTION ) ) {
201            return;
202        }
203
204        if ( ! ( new Modules() )->activate( self::MODULE_SLUG, false, false ) ) {
205            return;
206        }
207
208        // Record before re-entering initialize(), which calls back into here.
209        Jetpack_Options::update_option( self::DEFAULT_ACTIVATED_OPTION, true );
210
211        // initialize() ran before this and found the module off, so wire up now
212        // rather than leaving the page missing for the rest of the request.
213        self::initialize();
214    }
215
216    /**
217     * Register the Activity Log submenu under Jetpack.
218     *
219     * Mirrors the gating used by the legacy my-jetpack "Activity Log" menu
220     * item (connected user + non-multisite). On WordPress.com Simple sites,
221     * jetpack-mu-wpcom calls this once it has built the Jetpack menu.
222     *
223     * @since $$next-version$$ Registers the page on WordPress.com Simple sites.
224     *
225     * @return string|null The resulting page's hook suffix, if registered.
226     */
227    public static function add_wp_admin_submenu() {
228        if ( ! self::is_available() ) {
229            return null;
230        }
231
232        // Load wp-build only on the Activity Log request so its generated
233        // render function exists before the menu callback runs, and its
234        // enqueue pipeline/polyfills stay off every other admin page.
235        if ( self::is_activity_log_admin_request() ) {
236            self::load_wp_build_with_screen_alias();
237        }
238
239        // The menu item must appear on every admin page, but the generated
240        // render function is only loaded on the Activity Log request (above).
241        // The callback is only ever invoked while rendering our page — where
242        // the function is loaded — so the fallback is purely defensive.
243        $render_callback = function_exists( 'jetpack_activity_log_jetpack_activity_log_dashboard_wp_admin_render_page' )
244            ? 'jetpack_activity_log_jetpack_activity_log_dashboard_wp_admin_render_page'
245            : array( __CLASS__, 'render_fallback' );
246
247        if ( self::is_wpcom_simple() ) {
248            // jetpack-mu-wpcom calls this after Admin_Menu has already flushed its queue.
249            $page_suffix = add_submenu_page(
250                'jetpack',
251                /** "Activity Log" is a product name, do not translate. */
252                'Activity Log',
253                'Activity Log',
254                'manage_options',
255                self::PAGE_SLUG,
256                $render_callback
257            );
258        } else {
259            $page_suffix = Admin_Menu::add_menu(
260                /** "Activity Log" is a product name, do not translate. */
261                'Activity Log',
262                'Activity Log',
263                'manage_options',
264                self::PAGE_SLUG,
265                $render_callback
266            );
267        }
268
269        if ( ! $page_suffix ) {
270            return null;
271        }
272
273        add_action( 'load-' . $page_suffix, array( __CLASS__, 'admin_init' ) );
274        self::opt_out_of_jitms( $page_suffix );
275
276        return $page_suffix;
277    }
278
279    /**
280     * Whether the Activity Log page should be shown to the current user.
281     *
282     * @return bool
283     */
284    public static function is_available() {
285        if ( ! current_user_can( 'manage_options' ) ) {
286            return false;
287        }
288
289        // Simple sites need no Jetpack connection: their users are WordPress.com users.
290        if ( self::is_wpcom_simple() ) {
291            return true;
292        }
293
294        if ( is_multisite() ) {
295            return false;
296        }
297
298        return ( new Connection_Manager() )->is_user_connected();
299    }
300
301    /**
302     * Fires when the admin page is loaded.
303     *
304     * When the user is returning from a successful checkout, the upsell
305     * CTA appends `?refresh_access=1&_wpnonce=…` to the `redirect_to`
306     * value it hands off to WordPress.com. Detect that here, verify the
307     * nonce, and drop the cached paid-plan signal so
308     * `Initial_State::get_data()` (which runs later in the same request,
309     * when the bundle is enqueued) rehydrates from WPCOM instead of
310     * re-serving the pre-checkout value. Mirrors the pattern in
311     * `Automattic\Jetpack\Publicize\Social_Admin_Page::admin_init()`.
312     */
313    public static function admin_init() {
314        if ( isset( $_GET['refresh_access'] ) && isset( $_GET['_wpnonce'] ) ) {
315            $nonce = sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) );
316            if ( wp_verify_nonce( $nonce, self::REFRESH_ACCESS_NONCE_ACTION ) ) {
317                REST_Controller::clear_access_cache();
318            }
319        }
320
321        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_initial_state' ) );
322    }
323
324    /**
325     * Require the generated wp-build entry and register the script/module
326     * polyfills the boot bundle depends on.
327     *
328     * The boot bundle depends on `@wordpress/*` handles (e.g. `wp-theme`,
329     * pulled in via `@wordpress/ui`) that Core does not register on older
330     * WordPress versions. Without them WP_Scripts silently drops the bundle
331     * and the page renders blank, so register the polyfills here. Scoped to
332     * the Activity Log request by the sole caller, since the register() call
333     * can force-replace Core handles and must not fire on every admin page.
334     *
335     * @return void
336     */
337    private static function load_wp_build() {
338        $build_index = dirname( __DIR__ ) . '/build/build.php';
339
340        if ( ! file_exists( $build_index ) ) {
341            return;
342        }
343
344        require_once $build_index;
345
346        // The generated `modules.php` registers standalone script modules (the
347        // `@jetpack-activity-log/init` i18n bootstrap) on `wp_default_scripts`.
348        // We load wp-build lazily on `admin_menu`, which can run after that
349        // action has already fired — so the hook may be added too late and the
350        // init module never registers, leaving it out of the import map and
351        // breaking boot. Register directly here (mirroring the polyfills call
352        // below); the generated function guards against double-registration.
353        if ( function_exists( 'jetpack_activity_log_register_script_modules' ) ) {
354            jetpack_activity_log_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists(); defined in the generated build/modules.php, which Phan excludes.
355        }
356
357        WP_Build_Polyfills::register(
358            'jetpack-activity-log',
359            array_merge(
360                WP_Build_Polyfills::SCRIPT_HANDLES,
361                WP_Build_Polyfills::MODULE_IDS
362            )
363        );
364    }
365
366    /**
367     * Load wp-build with the screen ID aliased across its generated enqueue check.
368     *
369     * @see WP_Build_Screen_Id::load_with_alias()
370     * @return void
371     */
372    private static function load_wp_build_with_screen_alias() {
373        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
374        if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
375            WP_Build_Screen_Id::load_with_alias(
376                array( __CLASS__, 'alias_screen_id_for_wp_build' ),
377                array( __CLASS__, 'restore_screen_id_after_wp_build' ),
378                function () {
379                    self::load_wp_build();
380                }
381            );
382            return;
383        }
384
385        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
386        self::load_wp_build();
387        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id_after_wp_build' ) );
388    }
389
390    /**
391     * Alias the current screen id to the wp-build page slug.
392     *
393     * The wp-build-generated enqueue callback only fires when the screen id
394     * equals the wp-build page slug. Our menu slug stays `jetpack-activity-log`,
395     * so alias the screen id in place to make the check pass without changing
396     * the user-facing URL. Hooked only for the Activity Log request, so this
397     * never affects any other screen.
398     *
399     * @since 0.4.1 Takes no argument; hooked on `admin_enqueue_scripts`.
400     *
401     * @return void
402     */
403    public static function alias_screen_id_for_wp_build() {
404        $screen = get_current_screen();
405        if ( ! $screen ) {
406            return;
407        }
408
409        self::$wp_build_original_screen_id = $screen->id;
410        $screen->id                        = self::WP_BUILD_PAGE_SLUG;
411    }
412
413    /**
414     * Undo alias_screen_id_for_wp_build(), so code after the generated check sees the real screen ID.
415     *
416     * @since 0.4.1
417     *
418     * @return void
419     */
420    public static function restore_screen_id_after_wp_build() {
421        $screen = get_current_screen();
422        if ( ! $screen || null === self::$wp_build_original_screen_id ) {
423            return;
424        }
425
426        $screen->id                        = self::$wp_build_original_screen_id;
427        self::$wp_build_original_screen_id = null;
428    }
429
430    /**
431     * Opt the dashboard's screen out of JITMs.
432     *
433     * @param string $screen_id The hook suffix the page was registered under, which is its screen ID.
434     * @return void
435     */
436    private static function opt_out_of_jitms( $screen_id ) {
437        self::$jitm_opt_out_screen_id = $screen_id;
438        add_filter( 'jetpack_display_jitms_on_screen', array( __CLASS__, 'hide_jitms_on_wp_build_dashboard' ), 10, 2 );
439    }
440
441    /**
442     * Keep JITMs off the wp-build dashboard, which has no `#jp-admin-notices` to show them in.
443     *
444     * Fetching a JITM records a view, so one the page hides would still be counted.
445     *
446     * @since 0.4.1
447     *
448     * @param bool   $show      Whether to show JITMs on the screen.
449     * @param string $screen_id The screen ID.
450     * @return bool
451     */
452    public static function hide_jitms_on_wp_build_dashboard( $show, $screen_id ) {
453        if ( null !== self::$jitm_opt_out_screen_id && self::$jitm_opt_out_screen_id === $screen_id ) {
454            return false;
455        }
456
457        return $show;
458    }
459
460    /**
461     * Print the React initial state and the Connection initial state, and load
462     * the Tracks transport.
463     *
464     * The initial state is attached to a dedicated empty classic handle because
465     * the dashboard is a wp-build script module — there is no classic bundle
466     * handle to hang the inline data on. Boot defers its own execution to
467     * `DOMContentLoaded`, so this inline data is always set on `window` first.
468     *
469     * `jp-tracks` (stats.wp.com/w.js) is required for analytics: the dashboard's
470     * `@automattic/jetpack-analytics` events only queue into `window._tkq`
471     * (the package's own w.js loader is disabled), so without this handle no
472     * `jetpack_activity_log_*` event ever flushes. Mirrors Newsletter's
473     * `Settings::load_admin_scripts()`.
474     *
475     * @return void
476     */
477    public static function enqueue_initial_state() {
478        wp_register_script( self::DATA_SCRIPT_HANDLE, false, array(), Package_Version::PACKAGE_VERSION, true );
479        wp_enqueue_script( self::DATA_SCRIPT_HANDLE );
480
481        wp_add_inline_script( self::DATA_SCRIPT_HANDLE, ( new Activity_Log_Initial_State() )->render(), 'before' );
482
483        // Simple has no Jetpack connection to describe; the app treats a missing state as no connection errors.
484        if ( ! self::is_wpcom_simple() ) {
485            Connection_Initial_State::render_script( self::DATA_SCRIPT_HANDLE );
486        }
487
488        wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
489
490        // The dashboard is a wp-build script module: it externalizes
491        // `@wordpress/i18n` to the shared `wp.i18n` global but has no
492        // `wp_set_script_translations()` equivalent to load its JS catalog.
493        // Enqueue Jetpack's i18n loader (`wp.jpI18nLoader`, from jetpack-assets,
494        // registered on `wp_default_scripts`) so the `@jetpack-activity-log/init`
495        // boot module can fetch and install the translation catalog before the
496        // app renders. Without this the UI ships in English on non-English sites.
497        if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
498            wp_enqueue_script( 'wp-jp-i18n-loader' );
499        }
500    }
501
502    /**
503     * Whether this is a WordPress.com Simple site.
504     *
505     * @since $$next-version$$
506     *
507     * @return bool
508     */
509    public static function is_wpcom_simple() {
510        return ( new Host() )->is_wpcom_simple();
511    }
512
513    /**
514     * Fallback page body if the generated wp-build render function is
515     * unavailable (e.g. assets not built). Keeps the menu from fataling and
516     * still gives boot its mount container.
517     *
518     * @return void
519     */
520    public static function render_fallback() {
521        echo '<div class="wrap"><div id="jetpack-activity-log-dashboard-wp-admin-app"></div></div>';
522    }
523
524    /**
525     * Whether the current request targets the Activity Log admin page.
526     *
527     * The `$_GET['page']` value is populated by wp-admin/admin.php before any
528     * of our hooks fire, so this check is reliable from `admin_menu` onwards.
529     *
530     * @return bool
531     */
532    private static function is_activity_log_admin_request() {
533        if ( ! is_admin() || ! isset( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
534            return false;
535        }
536
537        return sanitize_text_field( wp_unslash( $_GET['page'] ) ) === self::PAGE_SLUG; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
538    }
539
540    /**
541     * Register the REST routes backing the Activity Log UI.
542     *
543     * Routes are added in Phase 2. This method exists now so that the
544     * `jetpack/v4/activity-log` namespace is reserved and the hook is wired.
545     */
546    public static function register_rest_routes() {
547        REST_Controller::register_rest_routes();
548    }
549}