Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
59.43% covered (warning)
59.43%
145 / 244
47.83% covered (danger)
47.83%
11 / 23
CRAP
0.00% covered (danger)
0.00%
0 / 1
Settings
59.43% covered (warning)
59.43%
145 / 244
47.83% covered (danger)
47.83%
11 / 23
376.85
0.00% covered (danger)
0.00%
0 / 1
 register_feature_flags
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 init
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 is_subscriptions_active
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 should_show_menu_item
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 init_hooks
54.17% covered (warning)
54.17%
13 / 24
0.00% covered (danger)
0.00%
0 / 1
5.54
 redirect_retired_subscribers_page
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
4.13
 maybe_load_wp_build
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
4.05
 add_wp_admin_menu
97.14% covered (success)
97.14%
34 / 35
0.00% covered (danger)
0.00%
0 / 1
10
 add_wp_admin_submenu
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
56
 admin_init
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 add_script_data
100.00% covered (success)
100.00%
28 / 28
100.00% covered (success)
100.00%
1 / 1
5
 load_admin_scripts
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
4
 get_subscriber_management_url
16.67% covered (danger)
16.67%
2 / 12
0.00% covered (danger)
0.00%
0 / 1
19.47
 render
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 add_reading_page_notice
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 render_reading_page_notice
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
2
 load_wp_build
27.27% covered (danger)
27.27%
3 / 11
0.00% covered (danger)
0.00%
0 / 1
3.54
 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
 maybe_opt_out_of_jitms
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 hide_jitms_on_wp_build_dashboard
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 is_modernized
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_newsletter_admin_request
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * A class that adds a newsletter settings screen to wp-admin.
4 *
5 * @package automattic/jetpack-newsletter
6 */
7
8namespace Automattic\Jetpack\Newsletter;
9
10use Automattic\Jetpack\Admin_UI\Admin_Menu;
11use Automattic\Jetpack\Assets;
12use Automattic\Jetpack\Connection\Manager as Connection_Manager;
13use Automattic\Jetpack\Feature_Flags\Feature_Flags;
14use Automattic\Jetpack\Modules;
15use Automattic\Jetpack\Redirect;
16use Automattic\Jetpack\Status;
17use Automattic\Jetpack\Status\Host;
18use Jetpack_Tracks_Client;
19
20/**
21 * A class responsible for adding a newsletter settings screen to wp-admin.
22 */
23class Settings {
24
25    const PACKAGE_VERSION = '0.15.0';
26
27    const ADMIN_PAGE_SLUG = 'jetpack-newsletter';
28
29    /**
30     * Slug of the retired Subscribers page, kept only to redirect stale bookmarks.
31     */
32    const RETIRED_SUBSCRIBERS_PAGE_SLUG = 'jetpack-subscribers';
33
34    /**
35     * Filter name that gates the wp-build–based dashboard.
36     *
37     * When this filter returns true, "Jetpack > Newsletter" renders the new
38     * wp-build dashboard instead of the legacy Newsletter Settings React app.
39     */
40    const MODERNIZATION_FILTER = 'rsm_jetpack_ui_modernization_newsletter';
41
42    /**
43     * Feature flag for the Newsletter Overview tab.
44     */
45    const OVERVIEW_FEATURE_FLAG = 'newsletter-overview';
46
47    /**
48     * Whether the class has been initialized
49     *
50     * @var boolean
51     */
52    private static $initialized = false;
53
54    /**
55     * The screen ID alias_screen_id_for_wp_build() replaced, until it is restored.
56     *
57     * @var string|null
58     */
59    private static $wp_build_original_screen_id = null;
60
61    /**
62     * The dashboard screen hide_jitms_on_wp_build_dashboard() opts out of JITMs.
63     *
64     * @var string|null
65     */
66    private static $jitm_opt_out_screen_id = null;
67
68    /**
69     * Register Newsletter feature flags.
70     *
71     * @return void
72     */
73    public static function register_feature_flags() {
74        Feature_Flags::register(
75            self::OVERVIEW_FEATURE_FLAG,
76            array(
77                'default'     => false,
78                'description' => 'Enable the Newsletter Overview tab.',
79                'owner'       => 'jetpack-newsletter',
80            )
81        );
82    }
83
84    /**
85     * Init Newsletter Settings if it wasn't already.
86     */
87    public static function init() {
88        self::register_feature_flags();
89
90        if ( ! self::$initialized ) {
91            self::$initialized = true;
92            ( new self() )->init_hooks();
93        }
94    }
95
96    /**
97     * Check if the subscriptions module is active.
98     *
99     * @return bool
100     */
101    private function is_subscriptions_active() {
102        return ( new Modules() )->is_active( 'subscriptions' );
103    }
104
105    /**
106     * Determine whether to show the Newsletter menu item.
107     * When true, shown regardless of subscriptions module state.
108     *
109     * @return bool
110     */
111    private function should_show_menu_item() {
112        /**
113         * Filter to control Newsletter menu item visibility.
114         * Defaults to true.
115         *
116         * @since 0.6.0
117         * @param bool $show Whether to show the menu item.
118         */
119        return apply_filters(
120            'jetpack_show_newsletter_menu_item',
121            true
122        );
123    }
124
125    /**
126     * Subscribe to necessary hooks.
127     */
128    public function init_hooks() {
129        // Priority 1 so this runs before the menu is built and the request is denied.
130        add_action( 'admin_menu', array( __CLASS__, 'redirect_retired_subscribers_page' ), 1 );
131
132        // Add the Reading settings notice as long as subscriptions are active.
133        if ( $this->is_subscriptions_active() ) {
134            add_action( 'admin_init', array( $this, 'add_reading_page_notice' ) );
135        }
136
137        // Hijack the config URLs to point to our settings page.
138        // Priority 20 to override the default URL set in subscriptions.php.
139        add_filter(
140            'jetpack_module_configuration_url_subscriptions',
141            function () {
142                return Urls::get_newsletter_settings_url();
143            },
144            20
145        );
146
147        // Defer wp-build loading to admin_menu (priority 1) on every host. The
148        // modernization filter â€” which third parties typically register from a
149        // plugins_loaded callback â€” needs to have been applied before we read it,
150        // and the wp-build render function needs to be defined before any menu
151        // callback runs (priority 999 on standalone Jetpack, priority 999999 on
152        // wpcom Simple via wpcom-admin-menu.php's call to add_wp_admin_submenu).
153        // Settings::init() runs synchronously from load-jetpack.php at
154        // plugin-file-include time â€” before any plugins_loaded callback fires â€”
155        // so an inline check here would always see the unfiltered default.
156        add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
157
158        $host = new Host();
159
160        // Admin-ajax rather than `/wp/v2/users/me`: WordPress.com's public API drops user meta it hasn't allowlisted.
161        if ( $host->is_wpcom_platform() ) {
162            add_action(
163                'wp_ajax_jetpack_newsletter_dismiss_subscriber_count_notice',
164                static function () {
165                    check_ajax_referer( 'jetpack_newsletter_dismiss_subscriber_count_notice' );
166                    update_user_meta( get_current_user_id(), 'jetpack_newsletter_subscriber_count_notice_dismissed', 1 );
167                    wp_send_json_success( null, 200, JSON_UNESCAPED_SLASHES );
168                }
169            );
170        }
171
172        // On wpcom Simple, the Jetpack menu is created at priority 999999 by wpcom-admin-menu.php,
173        // which will call add_wp_admin_submenu() directly. Skip adding the menu here to avoid
174        // trying to add a submenu before the parent menu exists.
175        if ( $host->is_wpcom_simple() ) {
176            return;
177        }
178
179        // Add admin menu item.
180        // Use priority 999 to ensure menu items are queued BEFORE Admin_Menu::admin_menu_hook_callback
181        // runs at priority 1000 to process all queued items.
182        add_action( 'admin_menu', array( $this, 'add_wp_admin_menu' ), 999 );
183    }
184
185    /**
186     * Send the retired Subscribers page to Newsletter, which absorbed it.
187     *
188     * The slug was live for about three months, so it is still in browser histories,
189     * where it would otherwise hit WordPress's generic "not allowed to access this
190     * page" and read as a permissions error rather than a move.
191     *
192     * @return void
193     */
194    public static function redirect_retired_subscribers_page() {
195        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
196        $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
197
198        if ( self::RETIRED_SUBSCRIBERS_PAGE_SLUG !== $page || ! current_user_can( 'manage_options' ) ) {
199            return;
200        }
201
202        wp_safe_redirect( admin_url( 'admin.php?page=' . self::ADMIN_PAGE_SLUG ) );
203        exit( 0 );
204    }
205
206    /**
207     * Load wp-build for the Newsletter admin page when modernization is enabled.
208     *
209     * Hooked to `admin_menu` priority 1 so the modernization filter has been
210     * registered by any opt-in code (mu-plugins, snippets, themes) before we
211     * read it, and so the wp-build render function and enqueue hook are in
212     * place before `add_wp_admin_menu` runs at priority 999.
213     *
214     * @return void
215     */
216    public static function maybe_load_wp_build() {
217        if ( ! self::is_modernized() || ! self::is_newsletter_admin_request() ) {
218            return;
219        }
220
221        // Hooked either side of load_wp_build(), so the alias holds only for the generated
222        // enqueue check it registers at the same priority.
223        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
224        self::load_wp_build();
225        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id_after_wp_build' ) );
226
227        // wp-build registers standalone modules (e.g. the init module) on
228        // wp_default_scripts, which has already fired by admin_menu. Register them
229        // directly so the init module makes it into the import map.
230        if ( function_exists( 'jetpack_newsletter_register_script_modules' ) ) {
231            jetpack_newsletter_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists(); defined in the generated build/modules.php, which Phan excludes.
232        }
233    }
234
235    /**
236     * Add the newsletter settings submenu to the Jetpack menu.
237     *
238     * Note: This method is NOT called on wpcom Simple sites. Simple sites use
239     * add_wp_admin_submenu() called from wpcom-admin-menu.php instead.
240     */
241    public function add_wp_admin_menu() {
242        // On sites using Jetpack, only show the menu if the site is connected.
243        if ( ! ( new Connection_Manager() )->is_connected() ) {
244            return;
245        }
246
247        // On the modernized dashboard, the Newsletter screen is only useful when the
248        // subscriptions module is active, so skip registering the menu entirely when it
249        // is off. Gated on the modernization flag to leave legacy behavior unchanged.
250        if ( self::is_modernized() && ! $this->is_subscriptions_active() ) {
251            return;
252        }
253
254        $host = new Host();
255
256        // should_show_menu_item() controls visibility of the menu item.
257        $show_menu   = $this->should_show_menu_item();
258        $parent_slug = $show_menu ? 'jetpack' : '';
259
260        // On Atomic, use add_submenu_page. On standalone Jetpack, use Admin_Menu when showing in menu.
261        $use_jetpack_menu = ! $host->is_woa_site() && $show_menu;
262
263        $callback = self::is_modernized() && function_exists( 'jetpack_newsletter_jetpack_newsletter_dashboard_wp_admin_render_page' )
264            ? 'jetpack_newsletter_jetpack_newsletter_dashboard_wp_admin_render_page'
265            : array( $this, 'render' );
266
267        // Register menu item.
268        if ( $use_jetpack_menu ) {
269            $page_suffix = Admin_Menu::add_menu(
270                /** "Newsletter" is a product name, do not translate. */
271                'Newsletter',
272                'Newsletter',
273                'manage_options',
274                'jetpack-newsletter',
275                $callback,
276                null,
277                array(
278                    'product' => 'newsletter',
279                    'key'     => 'jetpack-newsletter',
280                )
281            );
282        } else {
283            $page_suffix = add_submenu_page(
284                $parent_slug,
285                /** "Newsletter" is a product name, do not translate. */
286                'Newsletter',
287                'Newsletter',
288                'manage_options',
289                'jetpack-newsletter',
290                $callback
291            );
292        }
293
294        if ( $page_suffix ) {
295            add_action( 'load-' . $page_suffix, array( $this, 'admin_init' ) );
296            self::maybe_opt_out_of_jitms( $page_suffix );
297        }
298    }
299
300    /**
301     * Add the newsletter settings submenu directly under the Jetpack menu.
302     *
303     * This method is called from wpcom-admin-menu.php on Simple sites at late priority
304     * (999999) when the Jetpack menu already exists.
305     */
306    public function add_wp_admin_submenu() {
307        // On the modernized dashboard, the Newsletter screen is only useful when the
308        // subscriptions module is active, so skip registering the menu entirely when it
309        // is off. Gated on the modernization flag to leave legacy behavior unchanged.
310        if ( self::is_modernized() && ! $this->is_subscriptions_active() ) {
311            return;
312        }
313
314        $parent_slug = $this->should_show_menu_item() ? 'jetpack' : '';
315        $callback    = self::is_modernized() && function_exists( 'jetpack_newsletter_jetpack_newsletter_dashboard_wp_admin_render_page' )
316            ? 'jetpack_newsletter_jetpack_newsletter_dashboard_wp_admin_render_page'
317            : array( $this, 'render' );
318        $page_suffix = add_submenu_page(
319            $parent_slug,
320            /** "Newsletter" is a product name, do not translate. */
321            'Newsletter',
322            'Newsletter',
323            'manage_options',
324            'jetpack-newsletter',
325            $callback
326        );
327
328        if ( $page_suffix ) {
329            add_action( 'load-' . $page_suffix, array( $this, 'admin_init' ) );
330            self::maybe_opt_out_of_jitms( $page_suffix );
331        }
332    }
333
334    /**
335     * Admin init actions.
336     */
337    public function admin_init() {
338        add_filter( 'jetpack_admin_js_script_data', array( $this, 'add_script_data' ) );
339        add_action( 'admin_enqueue_scripts', array( $this, 'load_admin_scripts' ) );
340    }
341
342    /**
343     * Add newsletter-specific data to the global JetpackScriptData object.
344     *
345     * @param array $data The existing script data.
346     * @return array The modified script data.
347     */
348    public function add_script_data( $data ) {
349        $current_user = wp_get_current_user();
350        $theme        = wp_get_theme();
351
352        $host                   = new Host();
353        $status                 = new Status();
354        $site_suffix            = $status->get_site_suffix();
355        $blog_id                = (int) $host->get_wpcom_site_id();
356        $is_wpcom               = $host->is_wpcom_platform();
357        $is_block_theme         = wp_is_block_theme();
358        $setup_payment_plan_url = ( $is_wpcom ? 'https://wordpress.com/earn/payments/' : 'https://cloud.jetpack.com/monetize/payments/' ) . $site_suffix;
359
360        $wp_admin_subscriber_management_enabled = apply_filters( 'jetpack_wp_admin_subscriber_management_enabled', true );
361
362        // Populate blog_id which is needed for API calls on Simple sites.
363        $data['site']['wpcom']['blog_id'] = $blog_id;
364
365        // Add newsletter-specific data.
366        // Note: Common data like admin_url, rest_nonce, rest_root, title, is_wpcom_platform,
367        // and user.current_user.display_name are already provided by Script_Data.
368        $data['newsletter'] = array(
369            'isBlockTheme'                    => $is_block_theme,
370            'themeStylesheet'                 => $theme->get_stylesheet(),
371            'email'                           => $current_user->user_email,
372            'gravatar'                        => get_avatar_url( $current_user->ID ),
373            'dateExample'                     => gmdate( get_option( 'date_format' ), time() ),
374            'subscriberManagementUrl'         => $this->get_subscriber_management_url( $wp_admin_subscriber_management_enabled, $is_wpcom, $site_suffix, $blog_id ),
375            'subscriberManagementEnabled'     => (bool) $wp_admin_subscriber_management_enabled,
376            'overviewEnabled'                 => Feature_Flags::is_enabled( self::OVERVIEW_FEATURE_FLAG ),
377            'isSubscriptionSiteEditSupported' => $is_block_theme,
378            'setupPaymentPlansUrl'            => $setup_payment_plan_url,
379            'isSitePublic'                    => ! $status->is_private_site() && ! $status->is_coming_soon(),
380            'tracksUserData'                  => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
381            'showSubscriberCountNotice'       => $is_wpcom && ! get_user_meta( $current_user->ID, 'jetpack_newsletter_subscriber_count_notice_dismissed', true ),
382            'subscriberCountNoticeNonce'      => $is_wpcom ? wp_create_nonce( 'jetpack_newsletter_dismiss_subscriber_count_notice' ) : '',
383        );
384
385        return $data;
386    }
387
388    /**
389     * Load the admin scripts.
390     */
391    public function load_admin_scripts() {
392        // This callback is registered via `admin_enqueue_scripts` from `admin_init`,
393        // which itself fires on `load-{$page_suffix}` in `add_wp_admin_menu()` â€” so it
394        // only fires on the Newsletter admin page; no need to re-check the page here.
395        // The Tracks transport is required on both surfaces â€” `analytics.initialize`
396        // only queues events into `window._tkq`; without `jp-tracks` loaded, no
397        // pixel.gif requests fire and the queue grows forever.
398        wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
399
400        if ( self::is_modernized() ) {
401            // The i18n loader is registered on every admin page by jetpack-assets but
402            // only enqueued when depended on; the esbuild bundles don't pull it in.
403            // Enqueue it so the wp-build dashboard's init module can download its JS
404            // translation catalogs.
405            if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
406                wp_enqueue_script( 'wp-jp-i18n-loader' );
407            }
408
409            // wp-build manages the rest of its enqueue pipeline. The legacy
410            // newsletter script and JetpackScriptData are intentionally skipped
411            // for the wp-build dashboard.
412            return;
413        }
414
415        // The legacy bundle imports `@wordpress/ui`, which reaches
416        // `@wordpress/theme` and so lists `wp-theme` in its generated asset file.
417        // Core does not register that handle, and `load_wp_build()` â€” the only
418        // other caller â€” runs on the modernized path alone. Without this,
419        // WordPress silently drops the script over the unregistered dependency
420        // and the page renders blank. Request only the handles this bundle needs:
421        // `wp-theme` (Core never registers it), `wp-private-apis` (so the polyfill
422        // can replace Core's incomplete allowlist on older WP) and `wp-rich-text`
423        // (`@wordpress/ui` also reaches `@wordpress/dataviews`, whose dataform
424        // controls unlock rich-text's `privateApis` at module scope; WP 6.9 exports
425        // none, which throws "Cannot unlock an undefined object"). We leave out
426        // `wp-notices` so the polyfill's force-replacement never touches it.
427        if ( class_exists( \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills::class ) ) {
428            \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills::register(
429                'jetpack-newsletter',
430                array( 'wp-theme', 'wp-private-apis', 'wp-rich-text' )
431            );
432        }
433
434        Assets::register_script(
435            'jetpack-newsletter',
436            '../build/newsletter.js',
437            __FILE__,
438            array(
439                'in_footer'    => true,
440                'textdomain'   => 'jetpack-newsletter',
441                'enqueue'      => true,
442                'dependencies' => array( 'jetpack-script-data' ),
443            )
444        );
445    }
446
447    /**
448     * Get the subscriber management URL based on site type and filter settings.
449     *
450     * - If jetpack_wp_admin_subscriber_management_enabled filter is true: wp-admin subscribers page
451     * - If filter is false AND wpcom site: wordpress.com/subscribers/$domain
452     * - If filter is false AND Jetpack site: jetpack.com redirect URL
453     *
454     * @param bool   $wp_admin_enabled Whether wp-admin subscriber management is enabled.
455     * @param bool   $is_wpcom         Whether this is a WordPress.com site.
456     * @param string $site_suffix      The Calypso site suffix (home host, slashes as `::`).
457     * @param int    $blog_id          The blog ID.
458     * @return string The subscriber management URL.
459     */
460    private function get_subscriber_management_url( $wp_admin_enabled, $is_wpcom, $site_suffix, $blog_id ) {
461        // If wp-admin subscriber management is enabled, use the wp-admin page.
462        if ( $wp_admin_enabled ) {
463            return admin_url( 'admin.php?page=subscribers' );
464        }
465
466        // For wpcom sites, use the wordpress.com URL.
467        if ( $is_wpcom ) {
468            return 'https://wordpress.com/subscribers/' . $site_suffix;
469        }
470
471        // For Jetpack sites, use the jetpack.com redirect URL.
472        $site_id = $blog_id ? (int) $blog_id : Connection_Manager::get_site_id( true );
473        $args    = ( ! empty( $site_id ) )
474            ? array( 'site' => $site_id )
475            : array();
476
477        return Redirect::get_url(
478            'jetpack-settings-jetpack-manage-subscribers',
479            $args
480        );
481    }
482
483    /**
484     * Render the newsletter settings page.
485     */
486    public function render() {
487        ?>
488        <div id="newsletter-settings-root"></div>
489        <?php
490    }
491
492    /**
493     * Register a notice on the Reading settings page to clarify that the RSS
494     * excerpt setting does not control newsletter emails.
495     *
496     * @since 0.5.1
497     */
498    public function add_reading_page_notice() {
499        add_settings_field(
500            'jetpack_newsletter_reading_notice',
501            '',
502            array( $this, 'render_reading_page_notice' ),
503            'reading',
504            'default'
505        );
506    }
507
508    /**
509     * Render the clarifying notice on the Reading settings page.
510     *
511     * Uses JavaScript to relocate the notice next to the "For each post in a feed"
512     * (rss_use_excerpt) setting.
513     *
514     * @since 0.5.1
515     */
516    public function render_reading_page_notice() {
517        $newsletter_url = Urls::get_newsletter_settings_url();
518
519        printf(
520            '<p class="description" id="jetpack-newsletter-reading-notice">%s</p>',
521            sprintf(
522                wp_kses(
523                    /* translators: %s is a link to the Newsletter settings page. */
524                    __( 'To control what’s included in newsletter emails, visit your <a href="%s">Newsletter settings</a>.', 'jetpack-newsletter' ),
525                    array(
526                        'a' => array(
527                            'href' => array(),
528                        ),
529                    )
530                ),
531                esc_url( $newsletter_url )
532            )
533        );
534        ?>
535        <script type="text/javascript">
536            document.addEventListener( 'DOMContentLoaded', function() {
537                var notice = document.getElementById( 'jetpack-newsletter-reading-notice' );
538                var excerptInput = document.querySelector( 'input[name="rss_use_excerpt"]' );
539                var excerptRow = excerptInput ? excerptInput.closest( 'tr' ) : null;
540
541                if ( ! notice || ! excerptRow ) {
542                    return;
543                }
544
545                // Remember the original parent before moving the notice.
546                var originalTable = notice.closest( 'table' );
547                var excerptTable = excerptRow.closest( 'table' );
548
549                // Move the notice into the rss_use_excerpt row's fieldset.
550                excerptRow.querySelector( 'td' ).appendChild( notice );
551
552                // Remove the now-empty original table (if it's different from the excerpt's table).
553                if ( originalTable && originalTable !== excerptTable ) {
554                    originalTable.remove();
555                }
556            } );
557        </script>
558        <?php
559    }
560
561    /**
562     * Load the wp-build entry file and register its polyfills.
563     *
564     * Only called on `?page=jetpack-newsletter` admin requests when the
565     * modernization filter is enabled. Keeps wp-build off every other request.
566     *
567     * @return void
568     */
569    private static function load_wp_build() {
570        $build_index = dirname( __DIR__ ) . '/build/build.php';
571
572        if ( ! file_exists( $build_index ) ) {
573            return;
574        }
575
576        require_once $build_index;
577
578        \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills::register(
579            'jetpack-newsletter',
580            array_merge(
581                \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills::SCRIPT_HANDLES,
582                \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills::MODULE_IDS
583            )
584        );
585    }
586
587    /**
588     * Alias the current screen ID to satisfy wp-build's auto-generated enqueue check.
589     *
590     * Wp-build's `<page>-wp-admin` enqueue callback enqueues only when the screen ID
591     * matches the wp-build page slug (`jetpack-newsletter-dashboard`). Our wp-admin
592     * menu slug stays `jetpack-newsletter`, so we mutate the screen object in place
593     * to make the check pass without changing the user-facing URL.
594     *
595     * Hooked only when modernization is on AND we're on the Newsletter admin page,
596     * so this never affects any other request.
597     *
598     * @since $$next-version$$ Takes no argument; hooked on `admin_enqueue_scripts`.
599     *
600     * @return void
601     */
602    public static function alias_screen_id_for_wp_build() {
603        $screen = get_current_screen();
604        if ( ! $screen ) {
605            return;
606        }
607
608        self::$wp_build_original_screen_id = $screen->id;
609        $screen->id                        = 'jetpack-newsletter-dashboard';
610    }
611
612    /**
613     * Undo alias_screen_id_for_wp_build(), so code after the generated check sees the real screen ID.
614     *
615     * @since $$next-version$$
616     *
617     * @return void
618     */
619    public static function restore_screen_id_after_wp_build() {
620        $screen = get_current_screen();
621        if ( ! $screen || null === self::$wp_build_original_screen_id ) {
622            return;
623        }
624
625        $screen->id                        = self::$wp_build_original_screen_id;
626        self::$wp_build_original_screen_id = null;
627    }
628
629    /**
630     * Opt the dashboard's screen out of JITMs while the wp-build dashboard serves it.
631     *
632     * @param string $screen_id The hook suffix the page was registered under, which is its screen ID.
633     * @return void
634     */
635    private static function maybe_opt_out_of_jitms( $screen_id ) {
636        // The legacy dashboard renders `#jp-admin-notices`, so it keeps its JITMs.
637        if ( ! self::is_modernized() ) {
638            return;
639        }
640
641        self::$jitm_opt_out_screen_id = $screen_id;
642        add_filter( 'jetpack_display_jitms_on_screen', array( __CLASS__, 'hide_jitms_on_wp_build_dashboard' ), 10, 2 );
643    }
644
645    /**
646     * Keep JITMs off the wp-build dashboard, which has no `#jp-admin-notices` to show them in.
647     *
648     * Fetching a JITM records a view, so one the page hides would still be counted.
649     *
650     * @since $$next-version$$
651     *
652     * @param bool   $show      Whether to show JITMs on the screen.
653     * @param string $screen_id The screen ID.
654     * @return bool
655     */
656    public static function hide_jitms_on_wp_build_dashboard( $show, $screen_id ) {
657        if ( null !== self::$jitm_opt_out_screen_id && self::$jitm_opt_out_screen_id === $screen_id ) {
658            return false;
659        }
660
661        return $show;
662    }
663
664    /**
665     * Returns true when the wp-build modernization filter is enabled.
666     *
667     * The modernized Newsletter dashboard, wp-admin subscriber management, and the
668     * retired Calypso Subscribers submenu now default on for every site. Hosts (and
669     * a11ns who want the legacy view back) can still force the legacy experience with
670     * `add_filter( self::MODERNIZATION_FILTER, '__return_false' );`.
671     *
672     * @return bool
673     */
674    private static function is_modernized() {
675        return (bool) apply_filters( self::MODERNIZATION_FILTER, true );
676    }
677
678    /**
679     * Returns true when the current request targets the Newsletter admin page.
680     *
681     * Used to scope wp-build loading to the one page that needs it. The
682     * `$_GET['page']` value is populated by wp-admin/admin.php before any of
683     * our hooks fire, so this check is reliable from `init_hooks()` onwards.
684     *
685     * @return bool
686     */
687    private static function is_newsletter_admin_request() {
688        if ( ! is_admin() || ! isset( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
689            return false;
690        }
691
692        return sanitize_text_field( wp_unslash( $_GET['page'] ) ) === self::ADMIN_PAGE_SLUG; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
693    }
694}