Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.13% covered (success)
98.13%
210 / 214
96.67% covered (success)
96.67%
29 / 30
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Email_Design_Editor
99.53% covered (success)
99.53%
210 / 211
96.67% covered (success)
96.67%
29 / 30
73
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
6 / 6
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
 default_for_this_platform
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 maybe_mark_block_theme
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
4
 filter_flag_for_atomic
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
 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%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 record_screen_view
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 screen_view_properties
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 read_source
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 site_type
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 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%
34 / 34
100.00% covered (success)
100.00%
1 / 1
2
 get_layout_css
100.00% covered (success)
100.00%
7 / 7
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%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_tracks_transport
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 can_send_tracks
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_tracks_data
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
 tracks_identity
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 tracks_blog_id
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 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\Connection\Manager as Connection_Manager;
9use Automattic\Jetpack\Constants;
10use Automattic\Jetpack\Feature_Flags\Feature_Flags;
11use Automattic\Jetpack\Status;
12use Automattic\Jetpack\Status\Host;
13use Automattic\Jetpack\Terms_Of_Service;
14use Automattic\Jetpack\Tracking;
15
16if ( ! defined( 'ABSPATH' ) ) {
17    exit( 0 );
18}
19
20/**
21 * Registers an Appearance page that mounts the WooCommerce email editor against the
22 * newsletter template, so a creator sets their email design once for the whole site.
23 *
24 * The design itself lives on the WordPress.com shadow blog: the browser fetches it from
25 * `/wpcom/v2/email-editor-bootstrap` and this page supplies only what describes *this*
26 * installation. See NL-839.
27 */
28class Jetpack_Email_Design_Editor {
29
30    /**
31     * The `page` query arg the screen answers to.
32     */
33    const PAGE_SLUG = 'jetpack-email-design';
34
35    /**
36     * The feature flag gating the screen. Registered on for a self-hosted site and off on both
37     * WordPress.com platforms, and on WoA answered by the filter below rather than by
38     * `wp companion feature-flag enable jetpack-email-design`.
39     */
40    const FEATURE_FLAG = 'jetpack-email-design';
41
42    /**
43     * The WordPress.com blog sticker that turns the screen on. See NL-1040.
44     */
45    const STICKER = 'email-design-editor';
46
47    /**
48     * The site option that keeps a WoA site in once it has run a block theme. wpcom reads it through sync.
49     */
50    const BLOCK_THEME_OPTION = 'jetpack_email_design_enabled';
51
52    /**
53     * The script handle, and the id of the element the editor mounts into.
54     */
55    const HANDLE = 'jetpack-email-design-editor';
56
57    /**
58     * Flags for JSON handed to a `<script>` tag.
59     */
60    const JSON_FLAGS = JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP;
61
62    /**
63     * The event the screen's arrival is recorded under, which reaches Tracks as
64     * `jetpack_newsletter_email_design_view` -- `record_user_event()` adds the prefix itself.
65     */
66    const VIEW_EVENT = 'newsletter_email_design_view';
67
68    /**
69     * The hook suffix `add_theme_page()` returned, or null when the page is not registered.
70     *
71     * @var string|null
72     */
73    private static $hook_suffix = null;
74
75    /**
76     * Wire the screen up.
77     */
78    public static function init() {
79        // Registered here rather than on `admin_menu` so the flag exists under WP-CLI, REST
80        // and cron too — `wp companion feature-flag list` reads it from one of those.
81        self::register_feature_flags();
82
83        // Last, so that on Atomic the sticker cannot be overridden by a filter added later --
84        // a flag that outlives the sticker is not a kill switch.
85        add_filter( 'jetpack_feature_flag_enabled_' . self::FEATURE_FLAG, array( __CLASS__, 'filter_flag_for_atomic' ), PHP_INT_MAX );
86
87        // Before `add_admin_page()`, so a site already on a block theme gets the screen on this request.
88        add_action( 'switch_theme', array( __CLASS__, 'maybe_mark_block_theme' ) );
89        add_action( 'admin_menu', array( __CLASS__, 'maybe_mark_block_theme' ), 9 );
90
91        add_action( 'admin_menu', array( __CLASS__, 'add_admin_page' ) );
92
93        // Priority 20, because `Newsletter\Settings::add_script_data()` replaces the whole
94        // `newsletter` key at the default priority on the page this link appears on.
95        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_script_data' ), 20 );
96    }
97
98    /**
99     * Tell the admin where this screen is, or that there is none.
100     *
101     * The bare URL: each surface that links here adds its own `return` arg, because each one is
102     * somewhere different to go back to. {@see self::exit_url()} reads and validates it.
103     *
104     * @param array $data The script data so far.
105     * @return array The script data, with `newsletter.emailDesignUrl` null when there is no screen.
106     */
107    public static function add_script_data( $data ) {
108        $url = self::get_url();
109
110        $data['newsletter']['emailDesignUrl'] = '' === $url ? null : $url;
111
112        return $data;
113    }
114
115    /**
116     * The screen's own URL, or an empty string when this request has no such screen.
117     *
118     * Read back from the registration, not built from the slug, so a link cannot outlive the page:
119     * `add_theme_page()` registers nothing without `edit_theme_options`, which `manage_options` --
120     * all the Newsletter settings page asks for -- does not imply.
121     *
122     * @return string
123     */
124    public static function get_url() {
125        return function_exists( 'menu_page_url' ) ? (string) menu_page_url( self::PAGE_SLUG, false ) : '';
126    }
127
128    /**
129     * Declare the screen's feature flag.
130     */
131    public static function register_feature_flags() {
132        Feature_Flags::register(
133            self::FEATURE_FLAG,
134            array(
135                'default'     => self::default_for_this_platform(),
136                'description' => 'Edit the newsletter email design in wp-admin, under Appearance.',
137                'owner'       => 'jetpack-newsletter',
138            )
139        );
140    }
141
142    /**
143     * Whether this platform gets the screen without anyone turning it on: self-hosted only (NL-1120).
144     *
145     * WordPress.com keeps its sticker switch, since a default would outlive the sticker rollback.
146     * WoA only, not the whole Atomic platform: wpcom's rule counts WP Cloud partner sites as self-hosted.
147     *
148     * @return bool
149     */
150    private static function default_for_this_platform() {
151        $host = new Host();
152
153        return ! $host->is_wpcom_simple() && ! $host->is_woa_site();
154    }
155
156    /**
157     * Keep a WoA site in once it runs a block theme: nothing clears the option, so a later classic theme does not.
158     *
159     * WoA only, which leaves Flex out: its WP Cloud client does not load wpcomsh.
160     */
161    public static function maybe_mark_block_theme() {
162        if ( get_option( self::BLOCK_THEME_OPTION ) || ! ( new Host() )->is_woa_site() || ! wp_is_block_theme() ) {
163            return;
164        }
165
166        update_option( self::BLOCK_THEME_OPTION, 1 );
167    }
168
169    /**
170     * Answer the flag from the Atomic sticker, the a8c proxy, or a block theme the site has run.
171     *
172     * The incoming value is dropped rather than widened, so removing the sticker closes the
173     * screen even where the flag was forced on -- unless the proxy or the option keeps it open.
174     *
175     * The proxy clause is the a12 rollout (NL-41), and gates dogfooding rather than access:
176     * wpcom's `/wpcom/v2/email-editor-bootstrap` still decides whether the blog is in, so on a
177     * customer's site the screen errors rather than exposing or saving anything.
178     *
179     * Off Atomic wpcomsh's reader answers false for every sticker, because its
180     * `Atomic_Persistent_Data` is a blank stand-in there -- hence the platform check, or the
181     * flag would be pinned off on a site whose only way in is the flag. The reader is checked
182     * as well: a host can define `IS_ATOMIC` without loading wpcomsh, and calling it then is
183     * a fatal.
184     *
185     * @param bool $enabled Whether the flag is enabled so far.
186     * @return bool
187     */
188    public static function filter_flag_for_atomic( $enabled ) {
189        if ( ! Constants::is_true( 'IS_ATOMIC' ) || ! function_exists( 'wpcomsh_is_site_sticker_active' ) ) {
190            return (bool) $enabled;
191        }
192
193        // Read through `Constants` rather than `defined()`, as the rest of the monorepo's
194        // `AT_PROXIED_REQUEST` call sites do, so this branch is reachable from tests at all.
195        return (bool) wpcomsh_is_site_sticker_active( self::STICKER )
196            || Constants::is_true( 'AT_PROXIED_REQUEST' )
197            || (bool) get_option( self::BLOCK_THEME_OPTION );
198    }
199
200    /**
201     * Whether the screen should exist on this site.
202     *
203     * On WoA the `email-design-editor` sticker, the a8c proxy and the block-theme option decide,
204     * through the filter above; on Simple wpcom's mu-plugin turns the flag on alongside the sticker. Any other
205     * site cannot read its own blog's stickers, so the registered default is the gate there --
206     * wpcom's rollout rule still gates the bootstrap, and so the emails.
207     *
208     * @return bool
209     */
210    public static function is_enabled() {
211        return Feature_Flags::is_enabled( self::FEATURE_FLAG );
212    }
213
214    /**
215     * Add the screen under Appearance.
216     */
217    public static function add_admin_page() {
218        if ( ! self::is_enabled() ) {
219            return;
220        }
221
222        self::$hook_suffix = add_theme_page(
223            __( 'Email Design', 'jetpack' ),
224            __( 'Email Design', 'jetpack' ),
225            'edit_theme_options',
226            self::PAGE_SLUG,
227            array( __CLASS__, 'render' )
228        );
229
230        if ( self::$hook_suffix ) {
231            add_action( 'load-' . self::$hook_suffix, array( __CLASS__, 'on_load' ) );
232        }
233    }
234
235    /**
236     * Scope everything else to this one screen.
237     */
238    public static function on_load() {
239        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
240        add_filter( 'admin_body_class', array( __CLASS__, 'add_fullscreen_body_class' ) );
241
242        // On `shutdown` rather than here: the Tracks pixel is a blocking request with a one-second
243        // timeout, so recorded now it would sit in front of the screen's first paint.
244        add_action( 'shutdown', array( __CLASS__, 'record_screen_view' ) );
245    }
246
247    /**
248     * Record the arrival, with the route that brought the creator here.
249     *
250     * Server-side so the three routes are counted the same way: entered from the Appearance menu
251     * there is no click to record, and recorded here it also counts a creator whose editor never
252     * loaded, which the bundle's own events cannot. See NL-1088.
253     */
254    public static function record_screen_view() {
255        // Jetpack's recorder refuses on Simple: it asks the terms of service and the user's
256        // connection, and a Simple site has neither to answer with. WordPress.com records its own
257        // events there instead, and does not prefix the name, so this passes the whole one.
258        if ( ( new Host() )->is_wpcom_simple() ) {
259            if ( function_exists( 'wpcom_record_tracks_event' ) ) {
260                wpcom_record_tracks_event( 'jetpack_' . self::VIEW_EVENT, self::screen_view_properties() );
261            }
262
263            return;
264        }
265
266        $connection = new Connection_Manager( 'jetpack' );
267
268        ( new Tracking( 'jetpack', $connection ) )->record_user_event(
269            self::VIEW_EVENT,
270            self::screen_view_properties()
271        );
272    }
273
274    /**
275     * What the arrival event carries.
276     *
277     * Separate from the call above because that one cannot be asserted: Tracks refuses to record
278     * for a test user, before the event is built, so these are the only part of the contract with
279     * whoever reads the funnel that a test can see.
280     *
281     * @return array
282     */
283    private static function screen_view_properties() {
284        return array(
285            'source'    => self::read_source(),
286            'site_type' => self::site_type(),
287        );
288    }
289
290    /**
291     * Which surface sent the creator here.
292     *
293     * An explicit arg rather than a guess at the others: the previewer's link carries neither
294     * `post_id` nor `return` when the post is unsaved and has no id, which is indistinguishable
295     * from the Appearance menu. Allowlisted because the arg is as hand-editable as any other.
296     *
297     * @return string
298     */
299    private static function read_source() {
300        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read as an attribution label only, and allowlisted below.
301        $source = isset( $_GET['source'] ) ? sanitize_key( wp_unslash( $_GET['source'] ) ) : '';
302
303        if ( '' === $source ) {
304            return 'admin_menu';
305        }
306
307        return in_array( $source, array( 'newsletter_settings', 'preview_modal' ), true )
308            ? $source
309            : 'unknown';
310    }
311
312    /**
313     * The platform, spelled the way `getSiteType()` spells it for the screen's other events.
314     *
315     * @return string
316     */
317    private static function site_type() {
318        $host = new Host();
319
320        if ( $host->is_wpcom_simple() ) {
321            return 'simple';
322        }
323
324        return $host->is_woa_site() ? 'woa' : 'jetpack';
325    }
326
327    /**
328     * Put the screen in fullscreen mode before the bundle has loaded.
329     *
330     * `wp-editor` hides the admin menu on this class, and the editor sets it from a React
331     * component — so it cannot apply until the bundle has loaded and the bootstrap has answered,
332     * and the page visibly reflows a few seconds in. Setting it here makes fullscreen the layout
333     * from first paint. The admin bar is untouched, which keeps a way out if the editor fails.
334     *
335     * @param string $classes Space-separated admin body classes.
336     * @return string
337     */
338    public static function add_fullscreen_body_class( $classes ) {
339        return trim( $classes . ' is-fullscreen-mode' );
340    }
341
342    /**
343     * Enqueue the editor bundle and the block-editor assets it expects to find.
344     */
345    public static function enqueue_assets() {
346        $asset_path = JETPACK__PLUGIN_DIR . '_inc/build/email-design-editor.asset.php';
347
348        if ( ! file_exists( $asset_path ) ) {
349            return;
350        }
351
352        $asset = include $asset_path;
353
354        self::enqueue_block_editor_assets();
355        self::enqueue_tracks_transport();
356
357        // `@woocommerce/email-editor` opts into core's private APIs as `@wordpress/edit-site`,
358        // resolved against the site's `wp-private-apis`. Re-check on a package bump. NL-839 (j).
359        wp_enqueue_script(
360            self::HANDLE,
361            plugins_url( '_inc/build/email-design-editor.js', JETPACK__PLUGIN_FILE ),
362            $asset['dependencies'],
363            $asset['version'],
364            true
365        );
366        wp_set_script_translations( self::HANDLE, 'jetpack' );
367
368        // `wp-editor`, `wp-block-editor` and `wp-preferences` are what lay the editor's frame
369        // out; without them every region stacks into one narrow column. Keep the list to
370        // handles WordPress registers — an unregistered one drops this stylesheet silently,
371        // which is `wp-interface`'s trap.
372        wp_enqueue_style(
373            self::HANDLE,
374            plugins_url( '_inc/build/email-design-editor.css', JETPACK__PLUGIN_FILE ),
375            array(
376                'wp-components',
377                'wp-block-editor',
378                'wp-editor',
379                'wp-edit-blocks',
380                'wp-preferences',
381                'wp-format-library',
382            ),
383            $asset['version']
384        );
385        wp_style_add_data( self::HANDLE, 'rtl', 'replace' );
386        wp_add_inline_style( self::HANDLE, self::get_layout_css() );
387
388        wp_add_inline_script(
389            self::HANDLE,
390            'window.JetpackEmailDesignEditor = ' . wp_json_encode( self::get_screen_data(), self::JSON_FLAGS ) . ';',
391            'before'
392        );
393    }
394
395    /**
396     * Fill the screen with the editor.
397     *
398     * The editor's frame expects a viewport, not the flow of an admin page: inside the usual
399     * wp-admin content column it collapses to a fraction of the height and scrolls its own
400     * regions. Woo avoids this by running on `post.php`, which is already fullscreen.
401     *
402     * @return string
403     */
404    private static function get_layout_css() {
405        return '
406            #wpcontent { padding-inline-start: 0; }
407            #wpfooter { display: none; }
408            #' . self::HANDLE . ' {
409                position: fixed;
410                /* Below #wpadminbar (99999) so the editor\'s own popovers and snackbars, which ask
411                   for 100000, cannot cover it — this caps everything inside. The admin menu is
412                   hidden on this screen, so there is nothing else left to clear. */
413                z-index: 99990;
414                inset-block: var(--wp-admin--admin-bar--height, 32px) 0;
415                inset-inline: 0;
416            }
417            /* wp-edit-post pins this and the screen does not load it, so without this the
418               snackbar renders in flow beside the header instead of over the canvas. */
419            #' . self::HANDLE . ' .components-editor-notices__snackbar {
420                position: absolute;
421                inset-block-end: 20px;
422                inset-inline-start: 20px;
423            }
424            /* Above the editor\'s own popovers and snackbars, which ask for 100000 inside this
425               container, so nothing the editor renders shows through the reset. */
426            #' . self::HANDLE . ' .jetpack-email-design-reset-overlay {
427                position: absolute;
428                inset: 0;
429                z-index: 100001;
430                display: flex;
431                align-items: center;
432                justify-content: center;
433                background-color: rgba(255, 255, 255, 0.82);
434            }
435            /* The screen is styles-only: the root block editing mode is `disabled`, so nothing is
436               insertable and core filters disabled blocks out of List View. Drop when blocks land. NL-1086. */
437            #' . self::HANDLE . ' .editor-document-tools__inserter-toggle,
438            #' . self::HANDLE . ' .editor-document-tools__document-overview-toggle {
439                display: none;
440            }
441        ';
442    }
443
444    /**
445     * Reproduce what the package's `Assets_Manager` does on WooCommerce's own screen.
446     *
447     * None of this happens automatically on a custom admin page: without it the editor
448     * mounts against no block library, no block categories and no server-side block
449     * definitions. See NL-839 (a).
450     *
451     * @todo Firing `enqueue_block_editor_assets` wholesale is the leading suspect for the
452     *       second Styles button — it pulls in core's site-editing global styles UI. NL-839 (e).
453     */
454    private static function enqueue_block_editor_assets() {
455        // Named rather than built from a post: there is no post here, and `get_block_categories()`
456        // hands whatever it gets to filters that type-hint the context.
457        $context = new WP_Block_Editor_Context( array( 'name' => 'jetpack/email-design' ) );
458
459        wp_enqueue_media();
460
461        do_action( 'enqueue_block_assets' );
462        do_action( 'enqueue_block_editor_assets' );
463
464        wp_enqueue_style( 'wp-edit-blocks' );
465        wp_enqueue_style( 'wp-format-library' );
466
467        wp_add_inline_script(
468            'wp-blocks',
469            sprintf( 'wp.blocks.setCategories( %s );', wp_json_encode( get_block_categories( $context ), self::JSON_FLAGS ) ),
470            'after'
471        );
472        wp_add_inline_script(
473            'wp-blocks',
474            sprintf(
475                'wp.blocks.unstable__bootstrapServerSideBlockDefinitions( %s );',
476                wp_json_encode( get_block_editor_server_block_settings(), self::JSON_FLAGS )
477            ),
478            'after'
479        );
480    }
481
482    /**
483     * What the page hands the bundle, as `window.JetpackEmailDesignEditor`.
484     *
485     * Every WordPress.com id — the template's, the global-styles record's — comes from the
486     * bootstrap response instead, because they are namespaced to the shadow blog's theme and
487     * a locally computed one is right on Simple and wrong everywhere else. See NL-839 (c).
488     *
489     * @return array
490     */
491    private static function get_screen_data() {
492        $exit_url = self::exit_url();
493
494        return array(
495            'elementId'      => self::HANDLE,
496            'editorSettings' => self::get_iframe_asset_settings(),
497
498            // The editor assigns these to `window.location.href` from its header buttons. Both
499            // leave the editor, and there is one design rather than a list, so both go to the
500            // same place.
501            'urls'           => array(
502                'back'     => $exit_url,
503                'listings' => $exit_url,
504            ),
505            'userEmail'      => wp_get_current_user()->user_email,
506
507            // The post the canvas should preview, where the previewer sent one. The design itself
508            // stays site-wide. {@see self::preview_post_id()}
509            'postId'         => self::preview_post_id(),
510
511            // What the bundle needs to record its own events. {@see self::get_tracks_data()}
512            'tracks'         => self::get_tracks_data(),
513        );
514    }
515
516    /**
517     * Enqueue the Tracks sender, where this site may send at all.
518     *
519     * `Jetpack_Gutenberg` enqueues `jp-tracks` for the block editor and then dequeues it whenever
520     * `wp_should_load_block_editor_scripts_and_styles()` is false, which this screen is -- it is an
521     * Appearance page, so `is_block_editor()` answers no. Without this the queue the analytics
522     * package pushes onto is never drained and every event is silently lost.
523     *
524     * Simple already has it: `w.js` arrives with the masterbar there.
525     */
526    private static function enqueue_tracks_transport() {
527        if ( ! self::can_send_tracks() || ( new Host() )->is_wpcom_simple() ) {
528            return;
529        }
530
531        wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
532    }
533
534    /**
535     * Whether this site and this creator may be recorded.
536     *
537     * @return bool
538     */
539    private static function can_send_tracks() {
540        // The gate below asks about the terms of service and the user's connection, which are both
541        // things a Simple site has none of, so it answers no there for a site that records
542        // everything else it does. WordPress.com loads the sender and identifies the user itself.
543        if ( ( new Host() )->is_wpcom_simple() ) {
544            return true;
545        }
546
547        $tracking = new Tracking( 'jetpack', new Connection_Manager( 'jetpack' ) );
548
549        return $tracking->should_enable_tracking( new Terms_Of_Service(), new Status() );
550    }
551
552    /**
553     * The identity the bundle records against, or the refusal.
554     *
555     * Narrowed to the two fields the analytics package takes, so the email address and locale that
556     * `get_connected_user_tracks_identity()` also returns stay out of the page's HTML. A site can
557     * be allowed to send with no connected user, which records anonymously, so `canSend` is asked
558     * separately rather than inferred from having an identity.
559     *
560     * @return array
561     */
562    private static function get_tracks_data() {
563        if ( ! self::can_send_tracks() ) {
564            return array(
565                'canSend'  => false,
566                'userData' => null,
567                'blogId'   => null,
568            );
569        }
570
571        return array(
572            'canSend'  => true,
573            'userData' => self::tracks_identity(),
574            'blogId'   => self::tracks_blog_id(),
575        );
576    }
577
578    /**
579     * Who the bundle records against, or nobody.
580     *
581     * Narrowed to the two fields the analytics package takes, so the email address and locale that
582     * `get_connected_user_tracks_identity()` also returns stay out of the page's HTML.
583     *
584     * Nobody on Simple: WordPress.com has already identified the logged-in user to the sender it
585     * loaded, and ours would replace that with an identity derived from a connection Simple does
586     * not have. Elsewhere a site can still record with no connected user, anonymously, which is
587     * why `canSend` is asked separately from this.
588     *
589     * @return array|null
590     */
591    private static function tracks_identity() {
592        if ( ( new Host() )->is_wpcom_simple() ) {
593            return null;
594        }
595
596        $identity = Jetpack_Tracks_Client::get_connected_user_tracks_identity();
597
598        if ( ! $identity ) {
599            return null;
600        }
601
602        return array(
603            'userid'   => $identity['userid'],
604            'username' => $identity['username'],
605        );
606    }
607
608    /**
609     * The WordPress.com blog the events name.
610     *
611     * Read the way the connected user's identity reads it, so both name one blog -- except on
612     * Simple, where the blog is a WordPress.com blog already and the Jetpack option that names it
613     * everywhere else is not what identifies it.
614     *
615     * @return int
616     */
617    private static function tracks_blog_id() {
618        if ( ( new Host() )->is_wpcom_simple() ) {
619            return get_current_blog_id();
620        }
621
622        return (int) Jetpack_Options::get_option( 'id', 0 );
623    }
624
625    /**
626     * The post the canvas should preview, or null to leave the default.
627     *
628     * The previewer's link carries the post the reader was looking at, so changing the design does
629     * not replace it with the sample post. See NL-1051.
630     *
631     * Capability-checked here as well as on WordPress.com, so a hand-edited URL cannot name a post
632     * this user may not read. `absint()` is as forgiving as `exit_url()`'s validation -- `12abc`
633     * arrives as 12 -- which only ever yields an id shape `edit_post` then has the final word on.
634     *
635     * @return int|null
636     */
637    private static function preview_post_id() {
638        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read as a preview target only, and capability-checked below.
639        $post_id = isset( $_GET['post_id'] ) ? absint( wp_unslash( $_GET['post_id'] ) ) : 0;
640
641        if ( $post_id > 0 && current_user_can( 'edit_post', $post_id ) ) {
642            return $post_id;
643        }
644
645        return null;
646    }
647
648    /**
649     * Where the editor's header buttons leave to.
650     *
651     * The `return` arg, where the surface that linked here sent one, so the editor goes back the
652     * way the reader came. Validated like core's Customizer validates its own
653     * (`wp-admin/customize.php`), and narrowed to wp-admin so the button cannot be aimed off it.
654     *
655     * Without a usable one -- Appearance, a bookmark, a reload, or the previewer's new tab, which
656     * sends none on purpose -- the dashboard, as the site editor does from the same menu
657     * (`__experimentalDashboardLink`).
658     *
659     * @return string
660     */
661    private static function exit_url() {
662        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read as a navigation target only, and validated below.
663        $return = isset( $_GET['return'] ) ? wp_validate_redirect( esc_url_raw( wp_unslash( $_GET['return'] ) ), '' ) : '';
664
665        if ( '' !== $return && 0 === strpos( $return, admin_url() ) ) {
666            return $return;
667        }
668
669        return admin_url( '/' );
670    }
671
672    /**
673     * The two editor settings that describe this installation rather than the design.
674     *
675     * WordPress.com strips both from the bootstrap bundle, because there they would name
676     * WordPress.com's own asset URLs and push them into the site's canvas.
677     *
678     * @return array
679     */
680    private static function get_iframe_asset_settings() {
681        // Absent before WP 6.3, and private, but it is what core's own block editors call to
682        // resolve the assets an iframed canvas needs.
683        if ( ! function_exists( '_wp_get_iframed_editor_assets' ) ) {
684            return array();
685        }
686
687        $handles = self::get_allowed_iframe_style_handles();
688
689        return array(
690            '__unstableResolvedAssets'  => self::get_resolved_assets( $handles ),
691            'allowedIframeStyleHandles' => $handles,
692        );
693    }
694
695    /**
696     * The stylesheet handles the canvas is allowed to keep.
697     *
698     * Mirrors the package's `Settings_Controller::get_allowed_iframe_style_handles()`. An empty
699     * list is not a no-op: the client strips every stylesheet not named here, so omitting this
700     * leaves the canvas painted in the site's own styles rather than the email's.
701     *
702     * @return string[]
703     */
704    private static function get_allowed_iframe_style_handles() {
705        $handles = array(
706            'wp-components-css',
707            'wp-reset-editor-styles-css',
708            'wp-block-library-css',
709            'wp-block-editor-content-css',
710            'wp-edit-blocks-css',
711        );
712
713        // Registration args reach the block type verbatim — `WP_Block_Type::set_props()` normalizes
714        // only `attributes`, and `register_block_type_args` can rewrite the rest — so a block
715        // declaring a bare string here would otherwise fatal the screen inside `array_merge()`.
716        foreach ( WP_Block_Type_Registry::get_instance()->get_all_registered() as $block ) {
717            if ( ! is_array( $block->supports ) || empty( $block->supports['email'] ) ) {
718                continue;
719            }
720
721            foreach ( array_merge( (array) $block->style_handles, (array) $block->editor_style_handles ) as $handle ) {
722                if ( is_string( $handle ) ) {
723                    $handles[] = $handle . '-css';
724                }
725            }
726        }
727
728        return $handles;
729    }
730
731    /**
732     * The iframe assets, trimmed to the allowed handles.
733     *
734     * @param string[] $allowed Handles to keep.
735     * @return array The `_wp_get_iframed_editor_assets()` shape, with `styles` filtered.
736     */
737    private static function get_resolved_assets( array $allowed ) {
738        // Core collects the canvas's assets by buffering `wp_print_footer_scripts()`, one of the two
739        // actions `wp_auth_check_load()` puts its "Session expired" dialog on. Core's own editor is
740        // built before `admin_enqueue_scripts` registers that; this screen is not. NL-957.
741        $had_auth_check = remove_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
742
743        $assets = _wp_get_iframed_editor_assets();
744
745        if ( $had_auth_check ) {
746            add_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
747        }
748
749        $kept = array();
750
751        foreach ( explode( "\n", (string) $assets['styles'] ) as $asset ) {
752            foreach ( $allowed as $handle ) {
753                if ( str_contains( $asset, $handle ) ) {
754                    $kept[] = $asset;
755                    break;
756                }
757            }
758        }
759
760        $assets['styles'] = implode( "\n", $kept );
761
762        return $assets;
763    }
764
765    /**
766     * Render the container the editor mounts into.
767     */
768    public static function render() {
769        printf( '<div id="%s" class="jetpack-email-design-editor"></div>', esc_attr( self::HANDLE ) );
770    }
771}
772
773Jetpack_Email_Design_Editor::init();