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