Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.26% covered (success)
97.26%
142 / 146
94.74% covered (success)
94.74%
18 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Email_Design_Editor
99.30% covered (success)
99.30%
142 / 143
94.74% covered (success)
94.74%
18 / 19
43
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%
11 / 11
100.00% covered (success)
100.00%
1 / 1
1
 preview_post_id
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 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            // The post the canvas should preview, where the previewer sent one. The design itself
348            // stays site-wide. {@see self::preview_post_id()}
349            'postId'         => self::preview_post_id(),
350        );
351    }
352
353    /**
354     * The post the canvas should preview, or null to leave the default.
355     *
356     * The previewer's link carries the post the reader was looking at, so changing the design does
357     * not replace it with the sample post. See NL-1051.
358     *
359     * Capability-checked here as well as on WordPress.com, so a hand-edited URL cannot name a post
360     * this user may not read. `absint()` is as forgiving as `exit_url()`'s validation -- `12abc`
361     * arrives as 12 -- which only ever yields an id shape `edit_post` then has the final word on.
362     *
363     * @return int|null
364     */
365    private static function preview_post_id() {
366        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read as a preview target only, and capability-checked below.
367        $post_id = isset( $_GET['post_id'] ) ? absint( wp_unslash( $_GET['post_id'] ) ) : 0;
368
369        if ( $post_id > 0 && current_user_can( 'edit_post', $post_id ) ) {
370            return $post_id;
371        }
372
373        return null;
374    }
375
376    /**
377     * Where the editor's header buttons leave to.
378     *
379     * The `return` arg, where the surface that linked here sent one, so the editor goes back the
380     * way the reader came. Validated like core's Customizer validates its own
381     * (`wp-admin/customize.php`), and narrowed to wp-admin so the button cannot be aimed off it.
382     *
383     * Without a usable one -- Appearance, a bookmark, a reload, or the previewer's new tab, which
384     * sends none on purpose -- the dashboard, as the site editor does from the same menu
385     * (`__experimentalDashboardLink`).
386     *
387     * @return string
388     */
389    private static function exit_url() {
390        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read as a navigation target only, and validated below.
391        $return = isset( $_GET['return'] ) ? wp_validate_redirect( esc_url_raw( wp_unslash( $_GET['return'] ) ), '' ) : '';
392
393        if ( '' !== $return && 0 === strpos( $return, admin_url() ) ) {
394            return $return;
395        }
396
397        return admin_url( '/' );
398    }
399
400    /**
401     * The two editor settings that describe this installation rather than the design.
402     *
403     * WordPress.com strips both from the bootstrap bundle, because there they would name
404     * WordPress.com's own asset URLs and push them into the site's canvas.
405     *
406     * @return array
407     */
408    private static function get_iframe_asset_settings() {
409        // Absent before WP 6.3, and private, but it is what core's own block editors call to
410        // resolve the assets an iframed canvas needs.
411        if ( ! function_exists( '_wp_get_iframed_editor_assets' ) ) {
412            return array();
413        }
414
415        $handles = self::get_allowed_iframe_style_handles();
416
417        return array(
418            '__unstableResolvedAssets'  => self::get_resolved_assets( $handles ),
419            'allowedIframeStyleHandles' => $handles,
420        );
421    }
422
423    /**
424     * The stylesheet handles the canvas is allowed to keep.
425     *
426     * Mirrors the package's `Settings_Controller::get_allowed_iframe_style_handles()`. An empty
427     * list is not a no-op: the client strips every stylesheet not named here, so omitting this
428     * leaves the canvas painted in the site's own styles rather than the email's.
429     *
430     * @return string[]
431     */
432    private static function get_allowed_iframe_style_handles() {
433        $handles = array(
434            'wp-components-css',
435            'wp-reset-editor-styles-css',
436            'wp-block-library-css',
437            'wp-block-editor-content-css',
438            'wp-edit-blocks-css',
439        );
440
441        // Registration args reach the block type verbatim — `WP_Block_Type::set_props()` normalizes
442        // only `attributes`, and `register_block_type_args` can rewrite the rest — so a block
443        // declaring a bare string here would otherwise fatal the screen inside `array_merge()`.
444        foreach ( WP_Block_Type_Registry::get_instance()->get_all_registered() as $block ) {
445            if ( ! is_array( $block->supports ) || empty( $block->supports['email'] ) ) {
446                continue;
447            }
448
449            foreach ( array_merge( (array) $block->style_handles, (array) $block->editor_style_handles ) as $handle ) {
450                if ( is_string( $handle ) ) {
451                    $handles[] = $handle . '-css';
452                }
453            }
454        }
455
456        return $handles;
457    }
458
459    /**
460     * The iframe assets, trimmed to the allowed handles.
461     *
462     * @param string[] $allowed Handles to keep.
463     * @return array The `_wp_get_iframed_editor_assets()` shape, with `styles` filtered.
464     */
465    private static function get_resolved_assets( array $allowed ) {
466        // Core collects the canvas's assets by buffering `wp_print_footer_scripts()`, one of the two
467        // actions `wp_auth_check_load()` puts its "Session expired" dialog on. Core's own editor is
468        // built before `admin_enqueue_scripts` registers that; this screen is not. NL-957.
469        $had_auth_check = remove_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
470
471        $assets = _wp_get_iframed_editor_assets();
472
473        if ( $had_auth_check ) {
474            add_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
475        }
476
477        $kept = array();
478
479        foreach ( explode( "\n", (string) $assets['styles'] ) as $asset ) {
480            foreach ( $allowed as $handle ) {
481                if ( str_contains( $asset, $handle ) ) {
482                    $kept[] = $asset;
483                    break;
484                }
485            }
486        }
487
488        $assets['styles'] = implode( "\n", $kept );
489
490        return $assets;
491    }
492
493    /**
494     * Render the container the editor mounts into.
495     */
496    public static function render() {
497        printf( '<div id="%s" class="jetpack-email-design-editor"></div>', esc_attr( self::HANDLE ) );
498    }
499}
500
501Jetpack_Email_Design_Editor::init();