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