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