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