Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
8.20% covered (danger)
8.20%
10 / 122
16.67% covered (danger)
16.67%
2 / 12
CRAP
0.00% covered (danger)
0.00%
0 / 1
AI_Launchpad
10.00% covered (danger)
10.00%
10 / 100
16.67% covered (danger)
16.67%
2 / 12
876.72
0.00% covered (danger)
0.00%
0 / 1
 init
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 redirect_to_dashboard
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 maybe_redirect_dashboard_to_site_setup
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 should_redirect_dashboard_to_site_setup
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 is_ai_launchpad_request
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
12
 is_eligible
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 is_enabled_for_site
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 register_menu
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 load_wp_build
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
6
 enqueue_jwt_initial_state
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 enqueue_script_translations
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 enqueue_tracks
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
30
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- Feature entry file, named after the feature, also holds the AI_Launchpad bootstrap class.
2/**
3 * AI Launchpad: an AI-tailored onboarding tasklist on a top-level wp-admin page.
4 *
5 * @package automattic/jetpack-mu-wpcom
6 */
7
8namespace Automattic\Jetpack\Jetpack_Mu_Wpcom;
9
10use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
11use Automattic\Jetpack\Connection\Manager as Connection_Manager;
12use Automattic\Jetpack\Status;
13use Automattic\Jetpack\Status\Host;
14use Automattic\Jetpack\Terms_Of_Service;
15use Automattic\Jetpack\Tracking;
16use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
17
18// helpers.php defines the shared option reader the listeners depend on, so it loads first.
19require_once __DIR__ . '/helpers.php';
20require_once __DIR__ . '/../../common/wp-build-script-translations.php';
21require_once __DIR__ . '/../../common/launchpad-no-guidance.php';
22require_once __DIR__ . '/eligibility.php';
23require_once __DIR__ . '/class-ai-launchpad-memberships.php';
24require_once __DIR__ . '/class-ai-launchpad-difm-offer.php';
25require_once __DIR__ . '/class-ai-launchpad-bring-your-ai-tool.php';
26require_once __DIR__ . '/class-ai-launchpad-task-registry.php';
27require_once __DIR__ . '/class-ai-launchpad-rest.php';
28require_once __DIR__ . '/class-ai-launchpad-listeners.php';
29require_once __DIR__ . '/class-ai-launchpad-theme-listener.php';
30require_once __DIR__ . '/class-ai-launchpad-social-listener.php';
31require_once __DIR__ . '/class-ai-launchpad-subscribers-listener.php';
32require_once __DIR__ . '/class-ai-launchpad-subscribe-block-listener.php';
33require_once __DIR__ . '/class-ai-launchpad-about-page-listener.php';
34require_once __DIR__ . '/class-ai-launchpad-gallery-page-listener.php';
35require_once __DIR__ . '/class-ai-launchpad-contact-page-listener.php';
36require_once __DIR__ . '/class-ai-launchpad-events-page-listener.php';
37require_once __DIR__ . '/class-ai-launchpad-video-page-listener.php';
38require_once __DIR__ . '/class-ai-launchpad-portfolio-piece-listener.php';
39require_once __DIR__ . '/class-ai-launchpad-first-post-listener.php';
40require_once __DIR__ . '/class-ai-launchpad-dev-enable.php';
41
42/**
43 * Registers the AI Launchpad admin page and its wp-build assets.
44 */
45class AI_Launchpad {
46
47    /**
48     * Admin page slug. The `-wp-admin` suffix is the wp-build convention for pages that integrate with wp-admin chrome.
49     */
50    const MENU_SLUG = 'site-setup-wp-admin';
51
52    /**
53     * Render callback generated by wp-build in build/pages/site-setup/page-wp-admin.php.
54     */
55    const RENDER_CALLBACK = 'jetpack_mu_wpcom_site_setup_wp_admin_render_page';
56
57    /**
58     * Initialize the feature.
59     */
60    public static function init() {
61        add_action( 'admin_menu', array( __CLASS__, 'register_menu' ) );
62        add_action( 'load-index.php', array( __CLASS__, 'maybe_redirect_dashboard_to_site_setup' ) );
63
64        if ( ! self::is_ai_launchpad_request() ) {
65            return;
66        }
67
68        // WordPress 7.2 answers an unregistered page on wp_admin_page_not_found and never reaches admin_page_access_denied.
69        add_action( 'wp_admin_page_not_found', array( __CLASS__, 'redirect_to_dashboard' ) );
70        add_action( 'admin_page_access_denied', array( __CLASS__, 'redirect_to_dashboard' ) );
71
72        self::load_wp_build();
73        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_jwt_initial_state' ), 20 );
74        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_tracks' ), 20 );
75        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_script_translations' ), 20 );
76    }
77
78    /**
79     * Sends a Site Setup visit the page can't serve (done, dismissed, ineligible, not an admin) to the Dashboard
80     * instead of core's "not allowed" screen, e.g. a refresh right after the last task or an old bookmark.
81     *
82     * @return never
83     */
84    public static function redirect_to_dashboard() {
85        wp_safe_redirect( admin_url( 'index.php' ) );
86        exit;
87    }
88
89    /**
90     * Sends an AI-built site's first Dashboard visit to Site Setup, e.g. from the builder's "Return to WP Admin".
91     *
92     * @return void
93     */
94    public static function maybe_redirect_dashboard_to_site_setup() {
95        if ( ! self::should_redirect_dashboard_to_site_setup() ) {
96            return;
97        }
98
99        wp_safe_redirect( admin_url( 'admin.php?page=' . self::MENU_SLUG ) );
100        exit;
101    }
102
103    /**
104     * Whether this Dashboard visit goes to Site Setup: for an admin of an AI-built site where Site Setup never opened.
105     *
106     * Site Setup's first load records the builder's answers as the wizard option, so the redirect happens only once.
107     *
108     * @return bool
109     */
110    public static function should_redirect_dashboard_to_site_setup() {
111        return ! get_option( \AI_Launchpad_REST::OPTION_WIZARD )
112            // A list without wizard answers never gets them, and a finished one hides Site Setup: both would loop.
113            && ! get_option( \AI_Launchpad_REST::OPTION_AI_OUTPUT )
114            && current_user_can( 'manage_options' )
115            && self::is_eligible()
116            && wpcom_ai_launchpad_is_ai_built();
117    }
118
119    /**
120     * Whether the current request targets the AI Launchpad admin page.
121     *
122     * @return bool
123     */
124    private static function is_ai_launchpad_request() {
125        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
126        return is_admin() && isset( $_GET['page'] ) && self::MENU_SLUG === $_GET['page'];
127    }
128
129    /**
130     * Whether the current site is eligible for the AI Launchpad.
131     *
132     * Gate: enabled for the site (see is_enabled_for_site(), which also excludes a dismissed AI Launchpad).
133     *
134     * @return bool
135     */
136    public static function is_eligible() {
137        static $eligible = null;
138
139        if ( null === $eligible ) {
140            $eligible = self::is_enabled_for_site();
141        }
142
143        return $eligible;
144    }
145
146    /**
147     * Whether the AI Launchpad has been enabled for this site.
148     *
149     * Set at site creation for new onboarding sites, by the ?enable-ai-launchpad=1 dev handler, or manually.
150     *
151     * @return bool
152     */
153    private static function is_enabled_for_site() {
154        return (bool) get_option( 'wpcom_ai_launchpad_enabled' ) && ! wpcom_launchpad_is_no_guidance();
155    }
156
157    /**
158     * Register the top-level admin menu item for eligible users.
159     */
160    public static function register_menu() {
161        if ( ! self::is_eligible() ) {
162            return;
163        }
164
165        // Once every task is done, drop the launchpad from the sidebar. Separate from eligibility on purpose — the
166        // enable option stays set, so re-tailoring or a reset brings it back. Reads the latched flag, no rebuild.
167        if ( get_option( \AI_Launchpad_REST::OPTION_COMPLETED ) ) {
168            return;
169        }
170
171        // The render callback only exists once build/build.php is loaded, which happens on the AI Launchpad page itself.
172        $callback = function_exists( self::RENDER_CALLBACK )
173            ? self::RENDER_CALLBACK
174            : '__return_empty_string';
175
176        // The "border" glyph from @wordpress/icons — the same icon the launchpad list uses for a to-do task.
177        $icon = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="#fff" d="m6.6 15.6-1.2.8c.6.9 1.3 1.6 2.2 2.2l.8-1.2c-.7-.5-1.3-1.1-1.8-1.8zM5.5 12c0-.4 0-.9.1-1.3l-1.5-.3c0 .5-.1 1.1-.1 1.6s.1 1.1.2 1.6l1.5-.3c-.2-.4-.2-.9-.2-1.3zm11.9-3.6 1.2-.8c-.6-.9-1.3-1.6-2.2-2.2l-.8 1.2c.7.5 1.3 1.1 1.8 1.8zM5.3 7.6l1.2.8c.5-.7 1.1-1.3 1.8-1.8l-.7-1.3c-.9.6-1.7 1.4-2.3 2.3zm14.5 2.8-1.5.3c.1.4.1.8.1 1.3s0 .9-.1 1.3l1.5.3c.1-.5.2-1 .2-1.6s-.1-1.1-.2-1.6zM12 18.5c-.4 0-.9 0-1.3-.1l-.3 1.5c.5.1 1 .2 1.6.2s1.1-.1 1.6-.2l-.3-1.5c-.4.1-.9.1-1.3.1zm3.6-1.1.8 1.2c.9-.6 1.6-1.3 2.2-2.2l-1.2-.8c-.5.7-1.1 1.3-1.8 1.8zM10.4 4.2l.3 1.5c.4-.1.8-.1 1.3-.1s.9 0 1.3.1l.3-1.5c-.5-.1-1.1-.2-1.6-.2s-1.1.1-1.6.2z"/></svg>';
178
179        add_menu_page(
180            __( 'Site Setup', 'jetpack-mu-wpcom' ),
181            __( 'Site Setup', 'jetpack-mu-wpcom' ),
182            'manage_options',
183            self::MENU_SLUG,
184            $callback,
185            'data:image/svg+xml;base64,' . base64_encode( $icon ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Encoding an inline SVG for the menu icon data URI.
186            1 // Above Dashboard (position 2): setup is the site's primary surface until it's done.
187        );
188    }
189
190    /**
191     * Load the wp-build generated asset registrations and the boot polyfills.
192     */
193    private static function load_wp_build() {
194        $wp_build_index = dirname( __DIR__, 3 ) . '/build/build.php';
195
196        if ( ! file_exists( $wp_build_index ) ) {
197            return;
198        }
199
200        require_once $wp_build_index;
201
202        // Register polyfills for WP < 7.0 (must run before enqueue).
203        WP_Build_Polyfills::register(
204            'jetpack-mu-wpcom',
205            array_merge(
206                WP_Build_Polyfills::SCRIPT_HANDLES,
207                WP_Build_Polyfills::MODULE_IDS
208            ),
209            null,
210            array(
211                array(
212                    'prefix' => 'jetpack_mu_wpcom',
213                    'slug'   => 'site-setup',
214                ),
215            )
216        );
217    }
218
219    /**
220     * Attach the JWT preconditions to the page's prerequisites script:
221     * `JP_CONNECTION_INITIAL_STATE` (apiNonce + siteSuffix for requestJwt())
222     * and `Jetpack_Editor_Initial_State.wpcomBlogId`.
223     */
224    public static function enqueue_jwt_initial_state() {
225        $handle = self::MENU_SLUG . '-prerequisites';
226
227        if ( ! wp_script_is( $handle, 'registered' ) ) {
228            return;
229        }
230
231        Connection_Initial_State::render_script( $handle );
232
233        wp_localize_script(
234            $handle,
235            'Jetpack_Editor_Initial_State',
236            array(
237                'wpcomBlogId' => get_wpcom_blog_id(),
238            )
239        );
240    }
241
242    /**
243     * Install the JS translation catalogs on the prerequisites script, which runs before the boot
244     * module, so every `__()` in the route bundle evaluates translated.
245     */
246    public static function enqueue_script_translations() {
247        $handle    = self::MENU_SLUG . '-prerequisites';
248        $build_dir = dirname( __DIR__, 3 ) . '/build';
249        $constants = $build_dir . '/constants.php';
250
251        if ( ! wp_script_is( $handle, 'registered' ) || ! file_exists( $constants ) ) {
252            return;
253        }
254
255        // The same URL the generated route registrations use, so core resolves the same catalog names.
256        $build_constants = require $constants;
257        $translations    = wpcom_wp_build_script_translations( $build_dir . '/i18n-manifest.json', $build_constants['build_url'], 'site-setup' );
258
259        if ( null !== $translations ) {
260            wp_add_inline_script( $handle, $translations, 'before' );
261        }
262    }
263
264    /**
265     * Attach the page's Tracks preconditions: the transport itself on Atomic, and the standard
266     * event properties as a global the client recorder reads.
267     *
268     * On Simple, wpcom's stats.php loads the Tracks transport on every admin page and pushes
269     * identifyUser and the blog_id super prop with it. On Atomic nothing does — wpcomsh only
270     * enqueues jp-tracks inside the editor — so `window._tkq` stays an ordinary array, every
271     * push accumulates in it, and the whole client-side funnel is discarded on unload.
272     *
273     * The transport is only enqueued where tracking is actually permitted: "not Simple" also
274     * covers jurassic.ninja / jurassic.tube and self-hosted sites running this package, where
275     * the server recorder already stays silent under a declined ToS or offline mode. Gating
276     * here mirrors `wpcom_enqueue_tracking_scripts()` in `src/common/index.php`. The props/
277     * identity global below stays ungated: it is inert without the transport.
278     */
279    public static function enqueue_tracks() {
280        $handle = self::MENU_SLUG . '-prerequisites';
281
282        if ( ! wp_script_is( $handle, 'registered' ) ) {
283            return;
284        }
285
286        if ( ! ( new Host() )->is_wpcom_simple() ) {
287            $tracking = new Tracking( 'jetpack-mu-wpcom', new Connection_Manager() );
288            if ( $tracking->should_enable_tracking( new Terms_Of_Service(), new Status() ) ) {
289                wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
290            }
291        }
292
293        // JSON rather than wp_localize_script(), which stringifies every value: blog_id would
294        // reach Tracks as a string instead of an int.
295        $bootstrap = wp_json_encode(
296            array(
297                'props'    => wpcom_ai_launchpad_standard_props(),
298                'identity' => wpcom_ai_launchpad_tracks_identity(),
299            ),
300            JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP
301        );
302
303        // WordPress concatenates every `before` inline script queued for this handle into one
304        // <script> tag, so a false here (encode failure) would emit a syntax error that also
305        // takes out the other scripts sharing the handle — including JP_CONNECTION_INITIAL_STATE
306        // and Jetpack_Editor_Initial_State.wpcomBlogId, the JWT and blog id the page needs to
307        // function at all. Fall back to an empty object so this global stays inert instead.
308        if ( false === $bootstrap ) {
309            $bootstrap = '{}';
310        }
311
312        wp_add_inline_script( $handle, 'window.wpcomAiLaunchpadTracks = ' . $bootstrap . ';', 'before' );
313    }
314}