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