Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.16% covered (success)
97.16%
137 / 141
94.44% covered (success)
94.44%
17 / 18
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Email_Design_Editor
99.28% covered (success)
99.28%
137 / 138
94.44% covered (success)
94.44%
17 / 18
39
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 add_script_data
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 register_feature_flags
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 filter_flag_from_sticker
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
4
 is_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 add_admin_page
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 on_load
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 add_fullscreen_body_class
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_assets
100.00% covered (success)
100.00%
33 / 33
100.00% covered (success)
100.00%
1 / 1
2
 get_layout_css
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_block_editor_assets
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
1
 get_screen_data
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 exit_url
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 get_iframe_asset_settings
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
2.01
 get_allowed_iframe_style_handles
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
6
 get_resolved_assets
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
5
 render
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * The newsletter email design screen.
4 *
5 * @package automattic/jetpack
6 */
7
8use Automattic\Jetpack\Feature_Flags\Feature_Flags;
9
10if ( ! defined( 'ABSPATH' ) ) {
11    exit( 0 );
12}
13
14/**
15 * Registers an Appearance page that mounts the WooCommerce email editor against the
16 * newsletter template, so a creator sets their email design once for the whole site.
17 *
18 * The design itself lives on the WordPress.com shadow blog: the browser fetches it from
19 * `/wpcom/v2/email-editor-bootstrap` and this page supplies only what describes *this*
20 * installation. See NL-839.
21 */
22class Jetpack_Email_Design_Editor {
23
24    /**
25     * The `page` query arg the screen answers to.
26     */
27    const PAGE_SLUG = 'jetpack-email-design';
28
29    /**
30     * The feature flag gating the screen. Registered off, and on Atomic answered by the
31     * sticker below rather than by `wp companion feature-flag enable jetpack-email-design`.
32     */
33    const FEATURE_FLAG = 'jetpack-email-design';
34
35    /**
36     * The WordPress.com blog sticker that turns the screen on. See NL-1040.
37     */
38    const STICKER = 'email-design-editor';
39
40    /**
41     * The script handle, and the id of the element the editor mounts into.
42     */
43    const HANDLE = 'jetpack-email-design-editor';
44
45    /**
46     * Flags for JSON handed to a `<script>` tag.
47     */
48    const JSON_FLAGS = JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP;
49
50    /**
51     * The hook suffix `add_theme_page()` returned, or null when the page is not registered.
52     *
53     * @var string|null
54     */
55    private static $hook_suffix = null;
56
57    /**
58     * Wire the screen up.
59     */
60    public static function init() {
61        // Registered here rather than on `admin_menu` so the flag exists under WP-CLI, REST
62        // and cron too — `wp companion feature-flag list` reads it from one of those.
63        self::register_feature_flags();
64
65        // Last, so that on Atomic the sticker cannot be overridden by a filter added later --
66        // a flag that outlives the sticker is not a kill switch.
67        add_filter( 'jetpack_feature_flag_enabled_' . self::FEATURE_FLAG, array( __CLASS__, 'filter_flag_from_sticker' ), PHP_INT_MAX );
68
69        add_action( 'admin_menu', array( __CLASS__, 'add_admin_page' ) );
70
71        // Priority 20, because `Newsletter\Settings::add_script_data()` replaces the whole
72        // `newsletter` key at the default priority on the page this link appears on.
73        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_script_data' ), 20 );
74    }
75
76    /**
77     * Tell the admin where this screen is, or that there is none.
78     *
79     * The bare URL: each surface that links here adds its own `return` arg, because each one is
80     * somewhere different to go back to. {@see self::exit_url()} reads and validates it.
81     *
82     * @param array $data The script data so far.
83     * @return array The script data, with `newsletter.emailDesignUrl` null when there is no screen.
84     */
85    public static function add_script_data( $data ) {
86        $url = self::get_url();
87
88        $data['newsletter']['emailDesignUrl'] = '' === $url ? null : $url;
89
90        return $data;
91    }
92
93    /**
94     * The screen's own URL, or an empty string when this request has no such screen.
95     *
96     * Read back from the registration, not built from the slug, so a link cannot outlive the page:
97     * `add_theme_page()` registers nothing without `edit_theme_options`, which `manage_options` --
98     * all the Newsletter settings page asks for -- does not imply.
99     *
100     * @return string
101     */
102    public static function get_url() {
103        return function_exists( 'menu_page_url' ) ? (string) menu_page_url( self::PAGE_SLUG, false ) : '';
104    }
105
106    /**
107     * Declare the screen's feature flag.
108     */
109    public static function register_feature_flags() {
110        Feature_Flags::register(
111            self::FEATURE_FLAG,
112            array(
113                'default'     => false,
114                'description' => 'Edit the newsletter email design in wp-admin, under Appearance.',
115                'owner'       => 'jetpack-newsletter',
116            )
117        );
118    }
119
120    /**
121     * Answer the flag from the Atomic sticker, where there is one to read.
122     *
123     * The incoming value is dropped rather than widened: on Atomic the sticker is the whole
124     * switch, so removing it has to close the screen even where the flag was forced on.
125     *
126     * Off Atomic wpcomsh's reader answers false for every sticker, because its
127     * `Atomic_Persistent_Data` is a blank stand-in there -- hence the platform check, or the
128     * flag would be pinned off on a site whose only way in is the flag. The reader is checked
129     * as well: a host can define `IS_ATOMIC` without loading wpcomsh, and calling it then is
130     * a fatal.
131     *
132     * @param bool $enabled Whether the flag is enabled so far.
133     * @return bool
134     */
135    public static function filter_flag_from_sticker( $enabled ) {
136        if ( ! defined( 'IS_ATOMIC' ) || ! IS_ATOMIC || ! function_exists( 'wpcomsh_is_site_sticker_active' ) ) {
137            return (bool) $enabled;
138        }
139
140        return (bool) wpcomsh_is_site_sticker_active( self::STICKER );
141    }
142
143    /**
144     * Whether the screen should exist on this site.
145     *
146     * On Atomic the `email-design-editor` sticker decides, through the filter above; on Simple
147     * wpcom's mu-plugin turns the flag on alongside it. A self-hosted site cannot read its own
148     * blog's stickers, so the flag is the gate there -- the sticker still gates the bootstrap.
149     *
150     * @return bool
151     */
152    public static function is_enabled() {
153        return Feature_Flags::is_enabled( self::FEATURE_FLAG );
154    }
155
156    /**
157     * Add the screen under Appearance.
158     */
159    public static function add_admin_page() {
160        if ( ! self::is_enabled() ) {
161            return;
162        }
163
164        self::$hook_suffix = add_theme_page(
165            __( 'Email Design', 'jetpack' ),
166            __( 'Email Design', 'jetpack' ),
167            'edit_theme_options',
168            self::PAGE_SLUG,
169            array( __CLASS__, 'render' )
170        );
171
172        if ( self::$hook_suffix ) {
173            add_action( 'load-' . self::$hook_suffix, array( __CLASS__, 'on_load' ) );
174        }
175    }
176
177    /**
178     * Scope everything else to this one screen.
179     */
180    public static function on_load() {
181        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
182        add_filter( 'admin_body_class', array( __CLASS__, 'add_fullscreen_body_class' ) );
183    }
184
185    /**
186     * Put the screen in fullscreen mode before the bundle has loaded.
187     *
188     * `wp-editor` hides the admin menu on this class, and the editor sets it from a React
189     * component — so it cannot apply until the bundle has loaded and the bootstrap has answered,
190     * and the page visibly reflows a few seconds in. Setting it here makes fullscreen the layout
191     * from first paint. The admin bar is untouched, which keeps a way out if the editor fails.
192     *
193     * @param string $classes Space-separated admin body classes.
194     * @return string
195     */
196    public static function add_fullscreen_body_class( $classes ) {
197        return trim( $classes . ' is-fullscreen-mode' );
198    }
199
200    /**
201     * Enqueue the editor bundle and the block-editor assets it expects to find.
202     */
203    public static function enqueue_assets() {
204        $asset_path = JETPACK__PLUGIN_DIR . '_inc/build/email-design-editor.asset.php';
205
206        if ( ! file_exists( $asset_path ) ) {
207            return;
208        }
209
210        $asset = include $asset_path;
211
212        self::enqueue_block_editor_assets();
213
214        // `@woocommerce/email-editor` opts into core's private APIs as `@wordpress/edit-site`,
215        // resolved against the site's `wp-private-apis`. Re-check on a package bump. NL-839 (j).
216        wp_enqueue_script(
217            self::HANDLE,
218            plugins_url( '_inc/build/email-design-editor.js', JETPACK__PLUGIN_FILE ),
219            $asset['dependencies'],
220            $asset['version'],
221            true
222        );
223        wp_set_script_translations( self::HANDLE, 'jetpack' );
224
225        // `wp-editor`, `wp-block-editor` and `wp-preferences` are what lay the editor's frame
226        // out; without them every region stacks into one narrow column. Keep the list to
227        // handles WordPress registers — an unregistered one drops this stylesheet silently,
228        // which is `wp-interface`'s trap.
229        wp_enqueue_style(
230            self::HANDLE,
231            plugins_url( '_inc/build/email-design-editor.css', JETPACK__PLUGIN_FILE ),
232            array(
233                'wp-components',
234                'wp-block-editor',
235                'wp-editor',
236                'wp-edit-blocks',
237                'wp-preferences',
238                'wp-format-library',
239            ),
240            $asset['version']
241        );
242        wp_style_add_data( self::HANDLE, 'rtl', 'replace' );
243        wp_add_inline_style( self::HANDLE, self::get_layout_css() );
244
245        wp_add_inline_script(
246            self::HANDLE,
247            'window.JetpackEmailDesignEditor = ' . wp_json_encode( self::get_screen_data(), self::JSON_FLAGS ) . ';',
248            'before'
249        );
250    }
251
252    /**
253     * Fill the screen with the editor.
254     *
255     * The editor's frame expects a viewport, not the flow of an admin page: inside the usual
256     * wp-admin content column it collapses to a fraction of the height and scrolls its own
257     * regions. Woo avoids this by running on `post.php`, which is already fullscreen.
258     *
259     * @return string
260     */
261    private static function get_layout_css() {
262        return '
263            #wpcontent { padding-inline-start: 0; }
264            #wpfooter { display: none; }
265            #' . self::HANDLE . ' {
266                position: fixed;
267                /* Below #wpadminbar (99999) so the editor\'s own popovers and snackbars, which ask
268                   for 100000, cannot cover it — this caps everything inside. The admin menu is
269                   hidden on this screen, so there is nothing else left to clear. */
270                z-index: 99990;
271                inset-block: var(--wp-admin--admin-bar--height, 32px) 0;
272                inset-inline: 0;
273            }
274            /* wp-edit-post pins this and the screen does not load it, so without this the
275               snackbar renders in flow beside the header instead of over the canvas. */
276            #' . self::HANDLE . ' .components-editor-notices__snackbar {
277                position: absolute;
278                inset-block-end: 20px;
279                inset-inline-start: 20px;
280            }
281        ';
282    }
283
284    /**
285     * Reproduce what the package's `Assets_Manager` does on WooCommerce's own screen.
286     *
287     * None of this happens automatically on a custom admin page: without it the editor
288     * mounts against no block library, no block categories and no server-side block
289     * definitions. See NL-839 (a).
290     *
291     * @todo Firing `enqueue_block_editor_assets` wholesale is the leading suspect for the
292     *       second Styles button — it pulls in core's site-editing global styles UI. NL-839 (e).
293     */
294    private static function enqueue_block_editor_assets() {
295        // Named rather than built from a post: there is no post here, and `get_block_categories()`
296        // hands whatever it gets to filters that type-hint the context.
297        $context = new WP_Block_Editor_Context( array( 'name' => 'jetpack/email-design' ) );
298
299        wp_enqueue_media();
300
301        do_action( 'enqueue_block_assets' );
302        do_action( 'enqueue_block_editor_assets' );
303
304        wp_enqueue_style( 'wp-edit-blocks' );
305        wp_enqueue_style( 'wp-format-library' );
306
307        wp_add_inline_script(
308            'wp-blocks',
309            sprintf( 'wp.blocks.setCategories( %s );', wp_json_encode( get_block_categories( $context ), self::JSON_FLAGS ) ),
310            'after'
311        );
312        wp_add_inline_script(
313            'wp-blocks',
314            sprintf(
315                'wp.blocks.unstable__bootstrapServerSideBlockDefinitions( %s );',
316                wp_json_encode( get_block_editor_server_block_settings(), self::JSON_FLAGS )
317            ),
318            'after'
319        );
320    }
321
322    /**
323     * What the page hands the bundle, as `window.JetpackEmailDesignEditor`.
324     *
325     * Every WordPress.com id — the template's, the global-styles record's — comes from the
326     * bootstrap response instead, because they are namespaced to the shadow blog's theme and
327     * a locally computed one is right on Simple and wrong everywhere else. See NL-839 (c).
328     *
329     * @return array
330     */
331    private static function get_screen_data() {
332        $exit_url = self::exit_url();
333
334        return array(
335            'elementId'      => self::HANDLE,
336            'editorSettings' => self::get_iframe_asset_settings(),
337
338            // The editor assigns these to `window.location.href` from its header buttons. Both
339            // leave the editor, and there is one design rather than a list, so both go to the
340            // same place.
341            'urls'           => array(
342                'back'     => $exit_url,
343                'listings' => $exit_url,
344            ),
345            'userEmail'      => wp_get_current_user()->user_email,
346        );
347    }
348
349    /**
350     * Where the editor's header buttons leave to.
351     *
352     * The `return` arg, where the surface that linked here sent one, so the editor goes back the
353     * way the reader came. Validated like core's Customizer validates its own
354     * (`wp-admin/customize.php`), and narrowed to wp-admin so the button cannot be aimed off it.
355     *
356     * Without a usable one -- Appearance, a bookmark, a reload, or the previewer's new tab, which
357     * sends none on purpose -- the dashboard, as the site editor does from the same menu
358     * (`__experimentalDashboardLink`).
359     *
360     * @return string
361     */
362    private static function exit_url() {
363        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read as a navigation target only, and validated below.
364        $return = isset( $_GET['return'] ) ? wp_validate_redirect( esc_url_raw( wp_unslash( $_GET['return'] ) ), '' ) : '';
365
366        if ( '' !== $return && 0 === strpos( $return, admin_url() ) ) {
367            return $return;
368        }
369
370        return admin_url( '/' );
371    }
372
373    /**
374     * The two editor settings that describe this installation rather than the design.
375     *
376     * WordPress.com strips both from the bootstrap bundle, because there they would name
377     * WordPress.com's own asset URLs and push them into the site's canvas.
378     *
379     * @return array
380     */
381    private static function get_iframe_asset_settings() {
382        // Absent before WP 6.3, and private, but it is what core's own block editors call to
383        // resolve the assets an iframed canvas needs.
384        if ( ! function_exists( '_wp_get_iframed_editor_assets' ) ) {
385            return array();
386        }
387
388        $handles = self::get_allowed_iframe_style_handles();
389
390        return array(
391            '__unstableResolvedAssets'  => self::get_resolved_assets( $handles ),
392            'allowedIframeStyleHandles' => $handles,
393        );
394    }
395
396    /**
397     * The stylesheet handles the canvas is allowed to keep.
398     *
399     * Mirrors the package's `Settings_Controller::get_allowed_iframe_style_handles()`. An empty
400     * list is not a no-op: the client strips every stylesheet not named here, so omitting this
401     * leaves the canvas painted in the site's own styles rather than the email's.
402     *
403     * @return string[]
404     */
405    private static function get_allowed_iframe_style_handles() {
406        $handles = array(
407            'wp-components-css',
408            'wp-reset-editor-styles-css',
409            'wp-block-library-css',
410            'wp-block-editor-content-css',
411            'wp-edit-blocks-css',
412        );
413
414        // Registration args reach the block type verbatim — `WP_Block_Type::set_props()` normalizes
415        // only `attributes`, and `register_block_type_args` can rewrite the rest — so a block
416        // declaring a bare string here would otherwise fatal the screen inside `array_merge()`.
417        foreach ( WP_Block_Type_Registry::get_instance()->get_all_registered() as $block ) {
418            if ( ! is_array( $block->supports ) || empty( $block->supports['email'] ) ) {
419                continue;
420            }
421
422            foreach ( array_merge( (array) $block->style_handles, (array) $block->editor_style_handles ) as $handle ) {
423                if ( is_string( $handle ) ) {
424                    $handles[] = $handle . '-css';
425                }
426            }
427        }
428
429        return $handles;
430    }
431
432    /**
433     * The iframe assets, trimmed to the allowed handles.
434     *
435     * @param string[] $allowed Handles to keep.
436     * @return array The `_wp_get_iframed_editor_assets()` shape, with `styles` filtered.
437     */
438    private static function get_resolved_assets( array $allowed ) {
439        // Core collects the canvas's assets by buffering `wp_print_footer_scripts()`, one of the two
440        // actions `wp_auth_check_load()` puts its "Session expired" dialog on. Core's own editor is
441        // built before `admin_enqueue_scripts` registers that; this screen is not. NL-957.
442        $had_auth_check = remove_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
443
444        $assets = _wp_get_iframed_editor_assets();
445
446        if ( $had_auth_check ) {
447            add_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
448        }
449
450        $kept = array();
451
452        foreach ( explode( "\n", (string) $assets['styles'] ) as $asset ) {
453            foreach ( $allowed as $handle ) {
454                if ( str_contains( $asset, $handle ) ) {
455                    $kept[] = $asset;
456                    break;
457                }
458            }
459        }
460
461        $assets['styles'] = implode( "\n", $kept );
462
463        return $assets;
464    }
465
466    /**
467     * Render the container the editor mounts into.
468     */
469    public static function render() {
470        printf( '<div id="%s" class="jetpack-email-design-editor"></div>', esc_attr( self::HANDLE ) );
471    }
472}
473
474Jetpack_Email_Design_Editor::init();