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