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