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