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