Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
69.34% covered (warning)
69.34%
95 / 137
41.18% covered (danger)
41.18%
7 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
Admin_Page
69.34% covered (warning)
69.34%
95 / 137
41.18% covered (danger)
41.18%
7 / 17
125.94
0.00% covered (danger)
0.00%
0 / 1
 init
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 add_wp_admin_submenu
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
4
 admin_init
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_i18n_loader
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 enqueue_tracks_transport
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 maybe_load_wp_build
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 inject_podcast_script_data
83.33% covered (warning)
83.33%
25 / 30
0.00% covered (danger)
0.00%
0 / 1
11.56
 get_tracks_user_data
44.44% covered (danger)
44.44%
4 / 9
0.00% covered (danger)
0.00%
0 / 1
9.29
 get_selected_category
30.00% covered (danger)
30.00%
3 / 10
0.00% covered (danger)
0.00%
0 / 1
6.09
 load_wp_build
30.00% covered (danger)
30.00%
3 / 10
0.00% covered (danger)
0.00%
0 / 1
6.09
 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
 render
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 is_podcast_admin_request
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
1<?php
2/**
3 * Registers the Jetpack Podcast wp-admin page and loads the wp-build dashboard.
4 *
5 * @package automattic/jetpack-podcast
6 */
7
8namespace Automattic\Jetpack\Podcast;
9
10use Automattic\Jetpack\Admin_UI\Admin_Menu;
11use Automattic\Jetpack\Connection\Manager as Connection_Manager;
12use Automattic\Jetpack\My_Jetpack\Products as My_Jetpack_Products;
13use Automattic\Jetpack\Status\Host;
14use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
15use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id;
16
17/**
18 * Adds the "Jetpack > Podcast" wp-admin screen.
19 */
20class Admin_Page {
21
22    const ADMIN_PAGE_SLUG = 'jetpack-podcast';
23
24    /**
25     * Where the Podcast item used to sit in the Jetpack submenu on self-hosted.
26     *
27     * Unread since Podcast registers without a position; kept so consumers do not fatal.
28     *
29     * @deprecated 2.1.1
30     */
31    const MENU_POSITION = 11;
32
33    /**
34     * Slug emitted by `@wordpress/build`. wp-build's auto-generated enqueue
35     * callback only fires when `$screen->id` matches this value, so we alias
36     * the screen id around that check without changing the user-facing URL.
37     */
38    const WP_BUILD_SLUG = 'jetpack-podcast-dashboard';
39
40    /**
41     * Whether `init()` has already wired its hooks.
42     *
43     * @var bool
44     */
45    private static $initialized = false;
46
47    /**
48     * The screen ID alias_screen_id_for_wp_build() replaced, until it is restored.
49     *
50     * @var string|null
51     */
52    private static $wp_build_original_screen_id = null;
53
54    /**
55     * The dashboard screen hide_jitms_on_wp_build_dashboard() opts out of JITMs.
56     *
57     * @var string|null
58     */
59    private static $jitm_opt_out_screen_id = null;
60
61    /**
62     * Wire admin hooks. Idempotent.
63     */
64    public static function init() {
65        if ( self::$initialized ) {
66            return;
67        }
68        self::$initialized = true;
69
70        add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
71
72        // On Simple/Atomic, wpcom-admin-menu.php builds the Jetpack menu at
73        // priority 999999 and calls add_wp_admin_submenu() itself. Self-hosted
74        // has no such file, so we register our own. Priority 999 queues the item
75        // before Admin_Menu's priority-1000 callback.
76        if ( ! ( new Host() )->is_wpcom_platform() ) {
77            add_action( 'admin_menu', array( __CLASS__, 'add_wp_admin_submenu' ), 999 );
78        }
79    }
80
81    /**
82     * Register the Podcast submenu under the Jetpack menu.
83     */
84    public static function add_wp_admin_submenu() {
85        // Prefer the wp-build render function once it's defined (by
86        // maybe_load_wp_build() at admin_menu priority 1); fall back otherwise.
87        $wp_build_render = 'jetpack_podcast_jetpack_podcast_dashboard_wp_admin_render_page';
88        $callback        = function_exists( $wp_build_render ) ? $wp_build_render : array( __CLASS__, 'render' );
89
90        if ( ( new Host() )->is_wpcom_platform() ) {
91            $page_suffix = add_submenu_page(
92                'jetpack',
93                /** "Podcast" is a product name, do not translate. */
94                'Podcast',
95                'Podcast',
96                'manage_options',
97                self::ADMIN_PAGE_SLUG,
98                $callback
99            );
100        } else {
101            $page_suffix = Admin_Menu::add_menu(
102                /** "Podcast" is a product name, do not translate. */
103                'Podcast',
104                'Podcast',
105                'manage_options',
106                self::ADMIN_PAGE_SLUG,
107                $callback,
108                null,
109                // Podcast has no My Jetpack product class, so the module is the only gate available.
110                array(
111                    'module' => 'podcast',
112                    'key'    => 'jetpack-podcast',
113                )
114            );
115        }
116
117        if ( $page_suffix ) {
118            add_action( 'load-' . $page_suffix, array( __CLASS__, 'admin_init' ) );
119            self::opt_out_of_jitms( $page_suffix );
120        }
121    }
122
123    /**
124     * Wire admin-init actions once we know the Podcast page is loading.
125     */
126    public static function admin_init() {
127        // MediaUpload (cover-image-control) reads wp.media.view — only defined after this runs.
128        add_action( 'admin_enqueue_scripts', 'wp_enqueue_media' );
129        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_tracks_transport' ) );
130        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_i18n_loader' ) );
131    }
132
133    /**
134     * Enqueue the JS translation loader so the dashboard's init module can download its catalogs.
135     *
136     * The loader is registered on every admin page by jetpack-assets but only enqueued when
137     * something depends on it; the esbuild bundles don't pull it in.
138     */
139    public static function enqueue_i18n_loader() {
140        if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
141            wp_enqueue_script( 'wp-jp-i18n-loader' );
142        }
143    }
144
145    /**
146     * Load the Tracks transport for the dashboard's client-side events.
147     *
148     * `jetpackAnalytics.tracks.recordEvent()` only pushes onto `window._tkq`,
149     * which stays an inert array until `w.js` loads and drains it. Nothing
150     * supplies that on Atomic or self-hosted, so without this the queue grows
151     * for the life of the page. Simple is skipped because stats.php already
152     * prints the same script on `admin_footer`, and loading it twice would
153     * re-drain a queue that has already been flushed.
154     */
155    public static function enqueue_tracks_transport() {
156        if ( ( new Host() )->is_wpcom_simple() ) {
157            return;
158        }
159
160        wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
161    }
162
163    /**
164     * Hooked at admin_menu priority 1 so polyfills register before
165     * `wp_default_scripts` fires and the wp-build render function is defined
166     * before `add_wp_admin_submenu()` runs (priority 999 on self-hosted, 999999
167     * on Simple/Atomic).
168     */
169    public static function maybe_load_wp_build() {
170        if ( ! self::is_podcast_admin_request() ) {
171            return;
172        }
173
174        self::load_wp_build_with_screen_alias();
175        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'inject_podcast_script_data' ) );
176    }
177
178    /**
179     * Add the podcast gate boolean to `window.JetpackScriptData`.
180     *
181     * Hooked from `maybe_load_wp_build()` so it only runs when the request is
182     * for the podcast admin page.
183     *
184     * @param array $data Script data being injected.
185     * @return array
186     */
187    public static function inject_podcast_script_data( $data ) {
188        if ( ! is_array( $data ) ) {
189            $data = array();
190        }
191
192        $is_wpcom = ( new Host() )->is_wpcom_platform();
193
194        if ( ! $is_wpcom && empty( $data['site']['wpcom']['blog_id'] ) ) {
195            $blog_id = (int) Connection_Manager::get_site_id( true );
196            if ( $blog_id > 0 ) {
197                $data['site']['wpcom']['blog_id'] = $blog_id;
198            }
199        }
200
201        $upgrade = array(
202            'product_slug' => $is_wpcom ? 'premium' : 'jetpack_growth_yearly',
203            'plan_name'    => $is_wpcom ? 'Premium' : 'Growth',
204        );
205        if ( ! $is_wpcom && method_exists( My_Jetpack_Products::class, 'get_bundle_offer' ) ) {
206            $offer = My_Jetpack_Products::get_bundle_offer( 'growth' );
207            if ( 'growth' !== ( $offer['slug'] ?? '' ) ) {
208                $upgrade = array(
209                    'product_slug' => $offer['wpcom_product_slug'] ?? '',
210                    'plan_name'    => $offer['title'] ?? '',
211                );
212            }
213        }
214        $data['podcast'] = array(
215            'has_product_access'  => Podcast_Gate::has_product_access(),
216            'is_connected'        => $is_wpcom || ( new Connection_Manager( 'jetpack' ) )->is_connected(),
217            'show_url_hosts'      => Settings::SHOW_URL_HOSTS,
218            'show_url_max_length' => Settings::SHOW_URL_MAX_LENGTH,
219            'feed_limit_max'      => Settings::feed_limit_max(),
220            'preload'             => rest_preload_api_request( array(), '/wpcom/v2/podcast/settings' ),
221            'selected_category'   => self::get_selected_category(),
222            'tracks_user_data'    => self::get_tracks_user_data(),
223            'upgrade'             => $upgrade,
224        );
225
226        return $data;
227    }
228
229    /**
230     * Connected-user identity for Tracks, so client events aren't anonymous on
231     * Atomic and self-hosted. Null on Simple, where stats.php already pushes
232     * `identifyUser` before our bundle runs.
233     *
234     * Deliberately narrower than `get_connected_user_tracks_identity()`, which
235     * also returns email, blogid and locale — none of which Tracks needs here.
236     *
237     * @return array{userid:mixed, username:mixed}|null
238     */
239    private static function get_tracks_user_data() {
240        if ( ! class_exists( 'Jetpack_Tracks_Client' ) ) {
241            return null;
242        }
243
244        $identity = \Jetpack_Tracks_Client::get_connected_user_tracks_identity();
245        if ( ! is_array( $identity ) || ! isset( $identity['userid'] ) || ! isset( $identity['username'] ) ) {
246            return null;
247        }
248
249        return array(
250            'userid'   => $identity['userid'],
251            'username' => $identity['username'],
252        );
253    }
254
255    /**
256     * The currently designated podcast category, injected so the settings
257     * picker can label its selected option on first paint instead of waiting on
258     * the client-side taxonomy→terms fetch. The full list still loads lazily.
259     *
260     * @return array{id:int, name:string}|null Null when no category is set.
261     */
262    public static function get_selected_category() {
263        $category_id = (int) get_option( 'podcasting_category_id', 0 );
264        if ( $category_id <= 0 ) {
265            return null;
266        }
267
268        $term = get_term( $category_id, 'category' );
269        if ( ! $term instanceof \WP_Term ) {
270            return null;
271        }
272
273        return array(
274            'id'   => (int) $term->term_id,
275            'name' => $term->name,
276        );
277    }
278
279    /**
280     * The build artifact may be absent on a fresh checkout before
281     * `pnpm build` has run; in that case `add_wp_admin_submenu()` falls back
282     * to `render()` so the page still loads (just without the React app).
283     */
284    private static function load_wp_build() {
285        $build_index = dirname( __DIR__ ) . '/build/build.php';
286
287        if ( ! file_exists( $build_index ) ) {
288            return;
289        }
290
291        require_once $build_index;
292
293        // wp-build hooks module registration to wp_default_scripts, which has
294        // already fired by admin_menu — call it directly or the init module
295        // never reaches the import map.
296        if ( function_exists( 'jetpack_podcast_register_script_modules' ) ) {
297            jetpack_podcast_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists(); defined in the generated build/modules.php, which Phan excludes.
298        }
299
300        WP_Build_Polyfills::register(
301            'jetpack-podcast',
302            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
303        );
304    }
305
306    /**
307     * Load wp-build with the screen ID aliased across its generated enqueue check.
308     *
309     * @see WP_Build_Screen_Id::load_with_alias()
310     * @return void
311     */
312    private static function load_wp_build_with_screen_alias() {
313        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
314        if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
315            WP_Build_Screen_Id::load_with_alias(
316                array( __CLASS__, 'alias_screen_id_for_wp_build' ),
317                array( __CLASS__, 'restore_screen_id_after_wp_build' ),
318                function () {
319                    self::load_wp_build();
320                }
321            );
322            return;
323        }
324
325        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
326        self::load_wp_build();
327        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id_after_wp_build' ) );
328    }
329
330    /**
331     * Alias the current screen id to wp-build's expected slug.
332     *
333     * @since 2.1.3 Takes no argument; hooked on `admin_enqueue_scripts`.
334     */
335    public static function alias_screen_id_for_wp_build() {
336        $screen = get_current_screen();
337        if ( ! $screen ) {
338            return;
339        }
340
341        self::$wp_build_original_screen_id = $screen->id;
342        $screen->id                        = self::WP_BUILD_SLUG;
343    }
344
345    /**
346     * Undo alias_screen_id_for_wp_build(), so code after the generated check sees the real screen ID.
347     *
348     * @since 2.1.3
349     */
350    public static function restore_screen_id_after_wp_build() {
351        $screen = get_current_screen();
352        if ( ! $screen || null === self::$wp_build_original_screen_id ) {
353            return;
354        }
355
356        $screen->id                        = self::$wp_build_original_screen_id;
357        self::$wp_build_original_screen_id = null;
358    }
359
360    /**
361     * Opt the dashboard's screen out of JITMs.
362     *
363     * @param string $screen_id The hook suffix the page was registered under, which is its screen ID.
364     */
365    private static function opt_out_of_jitms( $screen_id ) {
366        self::$jitm_opt_out_screen_id = $screen_id;
367        add_filter( 'jetpack_display_jitms_on_screen', array( __CLASS__, 'hide_jitms_on_wp_build_dashboard' ), 10, 2 );
368    }
369
370    /**
371     * Keep JITMs off the wp-build dashboard, which has no `#jp-admin-notices` to show them in.
372     *
373     * Fetching a JITM records a view, so one the page hides would still be counted.
374     *
375     * @since 2.1.3
376     *
377     * @param bool   $show      Whether to show JITMs on the screen.
378     * @param string $screen_id The screen ID.
379     * @return bool
380     */
381    public static function hide_jitms_on_wp_build_dashboard( $show, $screen_id ) {
382        if ( null !== self::$jitm_opt_out_screen_id && self::$jitm_opt_out_screen_id === $screen_id ) {
383            return false;
384        }
385
386        return $show;
387    }
388
389    /**
390     * Fallback render used when the wp-build artifact is missing.
391     */
392    public static function render() {
393        ?>
394        <div class="wrap">
395            <h1>Podcast</h1>
396        </div>
397        <?php
398    }
399
400    /**
401     * Whether the current request targets the Podcast admin page.
402     */
403    private static function is_podcast_admin_request() {
404        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
405        if ( ! is_admin() || ! isset( $_GET['page'] ) ) {
406            return false;
407        }
408
409        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
410        return self::ADMIN_PAGE_SLUG === sanitize_text_field( wp_unslash( $_GET['page'] ) );
411    }
412}