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