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