Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
34.40% covered (danger)
34.40%
97 / 282
20.83% covered (danger)
20.83%
5 / 24
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_WPCOM_Block_Editor
34.52% covered (danger)
34.52%
97 / 281
20.83% covered (danger)
20.83%
5 / 24
2212.07
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
2
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 init_actions
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 is_iframed_block_editor
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
 disable_send_frame_options_header
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
12
 add_iframed_body_class
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 check_iframe_cookie_setting
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
42
 allow_block_editor_login
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
56
 add_login_message
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 add_login_html
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 do_redirect
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 framing_allowed
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
 verify_frame_nonce
86.36% covered (warning)
86.36%
19 / 22
0.00% covered (danger)
0.00%
0 / 1
9.21
 filter_salt
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 enqueue_block_editor_assets
66.67% covered (warning)
66.67%
60 / 90
0.00% covered (danger)
0.00%
0 / 1
15.48
 enqueue_block_assets
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 add_justify_class
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 has_justified_block
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 add_tinymce_plugins
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 enable_cross_site_auth_cookies
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 maybe_send_cookies
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 get_samesite_attr_for_auth_cookies
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 set_samesite_auth_cookies
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
20
 set_samesite_logged_in_cookies
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2/**
3 * WordPress.com Block Editor
4 * Allow new block editor posts to be composed on WordPress.com.
5 *
6 * @package automattic/jetpack-mu-wpcom
7 */
8
9namespace Automattic\Jetpack\Jetpack_Mu_Wpcom\WPCOM_Block_Editor;
10
11use Automattic\Jetpack\Connection\Manager as Connection_Manager;
12use Automattic\Jetpack\Connection\Tokens;
13use Automattic\Jetpack\Modules;
14use Automattic\Jetpack\Status\Host;
15use WP_Error;
16use WP_Post;
17
18/**
19 * WordPress.com Block editor
20 */
21class Jetpack_WPCOM_Block_Editor {
22    /**
23     * ID of the user who signed the nonce.
24     *
25     * @var int
26     */
27    private $nonce_user_id;
28
29    /**
30     * An array to store auth cookies until we can determine if they should be sent
31     *
32     * @var array
33     */
34    private $set_cookie_args;
35
36    /**
37     * Singleton
38     */
39    public static function init() {
40        static $instance = false;
41
42        if ( ! $instance ) {
43            $instance = new Jetpack_WPCOM_Block_Editor();
44        }
45
46        return $instance;
47    }
48
49    /**
50     * Jetpack_WPCOM_Block_Editor constructor.
51     */
52    private function __construct() {
53        $this->set_cookie_args = array();
54        add_action( 'init', array( $this, 'init_actions' ) );
55    }
56
57    /**
58     * Add in all hooks.
59     */
60    public function init_actions() {
61        // Bail early if Jetpack's block editor extensions are disabled on the site.
62        /* This filter is documented in projects/plugins/jetpack/class.jetpack-gutenberg.php */
63        if ( ! apply_filters( 'jetpack_gutenberg', true ) ) {
64            return;
65        }
66
67        if ( ! ( new Host() )->is_wpcom_simple() && $this->is_iframed_block_editor() ) {
68            add_action( 'admin_init', array( $this, 'disable_send_frame_options_header' ), 9 );
69            add_filter( 'admin_body_class', array( $this, 'add_iframed_body_class' ) );
70        }
71
72        add_action( 'edit_form_top', 'Automattic\Jetpack\Jetpack_Mu_Wpcom\WPCOM_Block_Editor\EditorType\remember_classic_editor' );
73        add_action( 'login_init', array( $this, 'allow_block_editor_login' ), 1 );
74        add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_block_editor_assets' ), 9 );
75        add_action( 'enqueue_block_assets', array( $this, 'enqueue_block_assets' ) );
76        add_filter( 'render_block_core/paragraph', array( $this, 'add_justify_class' ), 10, 2 );
77        add_filter( 'mce_external_plugins', array( $this, 'add_tinymce_plugins' ) );
78        add_filter( 'block_editor_settings_all', 'Automattic\Jetpack\Jetpack_Mu_Wpcom\WPCOM_Block_Editor\EditorType\remember_block_editor', 10, 2 );
79
80        $this->enable_cross_site_auth_cookies();
81    }
82
83    /**
84     * Checks if we are embedding the block editor in an iframe in WordPress.com.
85     *
86     * @return bool Whether the current request is from the iframed block editor.
87     */
88    public function is_iframed_block_editor() {
89        global $pagenow;
90
91        // phpcs:ignore WordPress.Security.NonceVerification
92        return ( 'post.php' === $pagenow || 'post-new.php' === $pagenow ) && ! empty( $_GET['frame-nonce'] );
93    }
94
95    /**
96     * Prevents frame options header from firing if this is a allowed iframe request.
97     */
98    public function disable_send_frame_options_header() {
99        // phpcs:ignore WordPress.Security.NonceVerification, WordPress.Security.ValidatedSanitizedInput
100        if ( isset( $_GET['frame-nonce'] ) && $this->framing_allowed( $_GET['frame-nonce'] ) ) {
101            remove_action( 'admin_init', 'send_frame_options_header' );
102        }
103    }
104
105    /**
106     * Adds custom admin body class if this is a allowed iframe request.
107     *
108     * @param string $classes Admin body classes.
109     * @return string
110     */
111    public function add_iframed_body_class( $classes ) {
112        // phpcs:ignore WordPress.Security.NonceVerification, WordPress.Security.ValidatedSanitizedInput
113        if ( isset( $_GET['frame-nonce'] ) && $this->framing_allowed( $_GET['frame-nonce'] ) ) {
114            $classes .= ' is-iframed ';
115        }
116
117        return $classes;
118    }
119
120    /**
121     * Checks to see if cookie can be set in current context. If 3rd party cookie blocking
122     * is enabled the editor can't load in iFrame, so emiting X-Frame-Options: DENY will
123     * force the editor to break out of the iFrame.
124     */
125    private function check_iframe_cookie_setting() {
126        if ( ! isset( $_SERVER['QUERY_STRING'] ) || ! strpos( filter_var( wp_unslash( $_SERVER['QUERY_STRING'] ) ), 'calypsoify%3D1%26block-editor' ) || isset( $_COOKIE['wordpress_test_cookie'] ) ) {
127            return;
128        }
129
130        if ( isset( $_SERVER['REQUEST_URI'] ) && empty( $_GET['calypsoify_cookie_check'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
131            header( 'Location: ' . esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) . '&calypsoify_cookie_check=true' ) );
132            exit( 0 );
133        }
134
135        header( 'X-Frame-Options: DENY' );
136        exit( 0 );
137    }
138
139    /**
140     * Allows to iframe the login page if a user is logged out
141     * while trying to access the block editor from wordpress.com.
142     */
143    public function allow_block_editor_login() {
144        // phpcs:ignore WordPress.Security.NonceVerification
145        if ( ( new Host() )->is_wpcom_simple() || empty( $_REQUEST['redirect_to'] ) ) {
146            return;
147        }
148        // phpcs:ignore WordPress.Security.NonceVerification
149        $redirect_to = esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) );
150
151        $this->check_iframe_cookie_setting();
152
153        $query = wp_parse_url( urldecode( $redirect_to ), PHP_URL_QUERY );
154        $args  = wp_parse_args( $query );
155
156        // Check nonce and make sure this is a Gutenframe request.
157        if ( ! empty( $args['frame-nonce'] ) && $this->framing_allowed( $args['frame-nonce'] ) ) {
158
159            // If SSO is active, we'll let WordPress.com handle authentication...
160            if ( ( new Modules() )->is_active( 'sso' ) ) {
161                // ...but only if it's not an Atomic site. They already do that.
162                if ( ! ( new Host() )->is_woa_site() ) {
163                    add_filter( 'jetpack_sso_bypass_login_forward_wpcom', '__return_true' );
164                }
165            } else {
166                $_REQUEST['interim-login'] = true;
167                add_action( 'wp_login', array( $this, 'do_redirect' ) );
168                add_action( 'login_form', array( $this, 'add_login_html' ) );
169                add_filter( 'wp_login_errors', array( $this, 'add_login_message' ) );
170                remove_action( 'login_init', 'send_frame_options_header' );
171                wp_add_inline_style( 'login', '.interim-login #login{padding-top:8%}' );
172            }
173        }
174    }
175
176    /**
177     * Adds a login message.
178     *
179     * Intended to soften the expectation mismatch of ending up with a login screen rather than the editor.
180     *
181     * @param WP_Error $errors WP Error object.
182     * @return \WP_Error
183     */
184    public function add_login_message( $errors ) {
185        $errors->remove( 'expired' );
186        $errors->add( 'info', __( 'Before we continue, please log in to your Jetpack site.', 'jetpack-mu-wpcom' ), 'message' );
187
188        return $errors;
189    }
190
191    /**
192     * Maintains the `redirect_to` parameter in login form links.
193     * Adds visual feedback of login in progress.
194     */
195    public function add_login_html() {
196        ?>
197        <input type="hidden" name="redirect_to" value="<?php echo isset( $_REQUEST['redirect_to'] ) ? esc_url( wp_unslash( $_REQUEST['redirect_to'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized ?>" />
198        <script type="application/javascript">
199            document.getElementById( 'loginform' ).addEventListener( 'submit' , function() {
200                document.getElementById( 'wp-submit' ).setAttribute( 'disabled', 'disabled' );
201                document.getElementById( 'wp-submit' ).value = <?php echo wp_json_encode( __( 'Logging In...', 'jetpack-mu-wpcom' ), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?>;
202            } );
203        </script>
204        <?php
205    }
206
207    /**
208     * Does the redirect to the block editor.
209     *
210     * @return never
211     */
212    public function do_redirect() {
213        wp_safe_redirect( $GLOBALS['redirect_to'] );
214        exit( 0 );
215    }
216
217    /**
218     * Checks whether this is an allowed iframe request.
219     *
220     * @param string $nonce Nonce to verify.
221     * @return bool
222     */
223    public function framing_allowed( $nonce ) {
224        $blog_id = Connection_Manager::get_site_id();
225        if ( is_wp_error( $blog_id ) ) {
226            return false;
227        }
228
229        $verified = $this->verify_frame_nonce( $nonce, 'frame-' . $blog_id );
230
231        if ( is_wp_error( $verified ) ) {
232            wp_die( $verified ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
233        }
234
235        if ( $verified && ! defined( 'IFRAME_REQUEST' ) ) {
236            define( 'IFRAME_REQUEST', true );
237        }
238
239        return (bool) $verified;
240    }
241
242    /**
243     * Verify that correct nonce was used with time limit.
244     *
245     * The user is given an amount of time to use the token, so therefore, since the
246     * UID and $action remain the same, the independent variable is the time.
247     *
248     * @param string $nonce Nonce that was used in the form to verify.
249     * @param string $action Should give context to what is taking place and be the same when nonce was created.
250     * @return boolean|WP_Error Whether the nonce is valid.
251     */
252    public function verify_frame_nonce( $nonce, $action ) {
253        if ( empty( $nonce ) ) {
254            return false;
255        }
256
257        $parts = explode( ':', $nonce, 3 );
258        if ( count( $parts ) !== 3 ) {
259            return false;
260        }
261        list( $expiration, $user_id, $hash ) = $parts;
262
263        $this->nonce_user_id = (int) $user_id;
264        if ( ! $this->nonce_user_id ) {
265            return false;
266        }
267
268        $token = ( new Tokens() )->get_access_token( $this->nonce_user_id );
269        if ( ! $token ) {
270            return false;
271        }
272
273        /*
274         * Failures must return `false` (blocking the iframe) prior to the
275         * signature verification.
276         */
277
278        add_filter( 'salt', array( $this, 'filter_salt' ), 10, 2 );
279        $expected_hash = wp_hash( "$expiration|$action|{$this->nonce_user_id}", 'jetpack_frame_nonce' );
280        remove_filter( 'salt', array( $this, 'filter_salt' ) );
281
282        if ( ! hash_equals( $hash, $expected_hash ) ) {
283            return false;
284        }
285
286        /*
287         * Failures may return `WP_Error` (showing an error in the iframe) after the
288         * signature verification passes.
289         */
290
291        if ( time() > $expiration ) {
292            return new WP_Error( 'nonce_invalid_expired', 'Expired nonce.', array( 'status' => 401 ) );
293        }
294
295        // Check if it matches the current user, unless they're trying to log in.
296        if ( get_current_user_id() !== $this->nonce_user_id && ! doing_action( 'login_init' ) ) {
297            return new WP_Error( 'nonce_invalid_user_mismatch', 'User ID mismatch.', array( 'status' => 401 ) );
298        }
299
300        return true;
301    }
302
303    /**
304     * Filters the WordPress salt.
305     *
306     * @param string $salt Salt for the given scheme.
307     * @param string $scheme Authentication scheme.
308     * @return string
309     */
310    public function filter_salt( $salt, $scheme ) {
311        if ( 'jetpack_frame_nonce' === $scheme ) {
312            $token = ( new Tokens() )->get_access_token( $this->nonce_user_id );
313
314            if ( $token ) {
315                $salt = $token->secret;
316            }
317        }
318
319        return $salt;
320    }
321
322    /**
323     * Enqueues the WordPress.com block editor integration assets for the editor.
324     */
325    public function enqueue_block_editor_assets() {
326        global $pagenow;
327
328        // Bail if we're not in the post editor, but on the widget settings screen.
329        if ( is_customize_preview() || 'widgets.php' === $pagenow ) {
330            return;
331        }
332
333        $debug   = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG;
334        $version = gmdate( 'Ymd' );
335
336        // Keep these dependencies in sync with the generated asset metadata from
337        // the Calypso wpcom-block-editor app.
338        wp_enqueue_script(
339            'wpcom-block-editor-default-editor-script',
340            $debug
341                ? '//widgets.wp.com/wpcom-block-editor/default.editor.js?minify=false'
342                : '//widgets.wp.com/wpcom-block-editor/default.editor.min.js',
343            array(
344                'react',
345                'wp-block-editor',
346                'wp-blocks',
347                'wp-compose',
348                'wp-data',
349                'wp-rich-text',
350            ),
351            $version,
352            true
353        );
354
355        if ( ! ( new Host() )->is_wpcom_simple() ) { // Same object is already used in gutenberg-wpcom plugin.
356            wp_localize_script(
357                'wpcom-block-editor-default-editor-script',
358                'wpcomGutenberg',
359                array(
360                    'richTextToolbar' => array(
361                        'justify'   => __( 'Justify', 'jetpack-mu-wpcom' ),
362                        'underline' => __( 'Underline', 'jetpack-mu-wpcom' ),
363                    ),
364                )
365            );
366        }
367
368        wp_enqueue_script(
369            'wpcom-block-editor-wpcom-editor-script',
370            $debug
371                ? '//widgets.wp.com/wpcom-block-editor/wpcom.editor.js?minify=false'
372                : '//widgets.wp.com/wpcom-block-editor/wpcom.editor.min.js',
373            array(
374                'lodash',
375                'react',
376                'wp-block-editor',
377                'wp-blocks',
378                'wp-components',
379                'wp-compose',
380                'wp-data',
381                'wp-dom-ready',
382                'wp-element',
383                'wp-hooks',
384                'wp-i18n',
385                'wp-plugins',
386                'wp-primitives',
387                'wp-url',
388            ),
389            $version,
390            true
391        );
392        wp_enqueue_style(
393            'wpcom-block-editor-wpcom-editor-styles',
394            $debug
395                ? '//widgets.wp.com/wpcom-block-editor/wpcom.editor.css?minify=false'
396                : '//widgets.wp.com/wpcom-block-editor/wpcom.editor.min.css',
397            array(),
398            $version
399        );
400
401        if ( $this->is_iframed_block_editor() ) {
402            wp_enqueue_script(
403                'wpcom-block-editor-calypso-editor-script',
404                $debug
405                    ? '//widgets.wp.com/wpcom-block-editor/calypso.editor.js?minify=false'
406                    : '//widgets.wp.com/wpcom-block-editor/calypso.editor.min.js',
407                array(
408                    'jquery',
409                    'lodash',
410                    'react',
411                    'wp-blocks',
412                    'wp-data',
413                    'wp-hooks',
414                    'wp-tinymce',
415                    'wp-url',
416                ),
417                $version,
418                true
419            );
420
421            wp_enqueue_style(
422                'wpcom-block-editor-calypso-editor-styles',
423                $debug
424                    ? '//widgets.wp.com/wpcom-block-editor/calypso.editor.css?minify=false'
425                    : '//widgets.wp.com/wpcom-block-editor/calypso.editor.min.css',
426                array(),
427                $version
428            );
429        }
430    }
431
432    /**
433     * Enqueues the WordPress.com block editor integration assets for both editor and front-end.
434     */
435    public function enqueue_block_assets() {
436        // These styles are manually copied from //widgets.wp.com/wpcom-block-editor/default.view.css in order to
437        // improve the performance by avoiding an extra network request to download the CSS file on every page.
438        wp_add_inline_style( 'wp-block-library', '.has-text-align-justify{text-align:justify;}' );
439    }
440
441    /**
442     * Adds the has-text-align-justify class to paragraphs saved with a justify text alignment.
443     *
444     * Core's text-align support serializes no class for justify, so the saved markup loses it.
445     * https://github.com/WordPress/gutenberg/pull/80264 fixes new saves only; posts saved before it still need this.
446     *
447     * @param string $block_content The block content.
448     * @param array  $block         The parsed block.
449     * @return string The block content.
450     */
451    public function add_justify_class( $block_content, $block ) {
452        if ( ! is_string( $block_content ) || 'justify' !== ( $block['attrs']['style']['typography']['textAlign'] ?? null ) ) {
453            return $block_content;
454        }
455
456        $tags = new \WP_HTML_Tag_Processor( $block_content );
457        if ( $tags->next_tag( 'p' ) ) {
458            $tags->add_class( 'has-text-align-justify' );
459        }
460
461        return $tags->get_updated_html();
462    }
463
464    /**
465     * Determines if the current $post contains a justified paragraph block.
466     *
467     * @return boolean true if justified paragraph is found, false otherwise.
468     */
469    public function has_justified_block() {
470        global $post;
471        if ( ! $post instanceof WP_Post ) {
472            return false;
473        }
474
475        if ( ! has_blocks( $post ) ) {
476            return false;
477        }
478
479        return str_contains( $post->post_content, '<!-- wp:paragraph {"align":"justify"' );
480    }
481
482    /**
483     * Register the Tiny MCE plugins for the WordPress.com block editor integration.
484     *
485     * @param array $plugin_array An array of external Tiny MCE plugins.
486     * @return array External TinyMCE plugins.
487     */
488    public function add_tinymce_plugins( $plugin_array ) {
489        if ( $this->is_iframed_block_editor() ) {
490            $debug = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG;
491
492            $plugin_array['gutenberg-wpcom-iframe-media-modal'] = add_query_arg(
493                'v',
494                gmdate( 'YW' ),
495                $debug
496                    ? '//widgets.wp.com/wpcom-block-editor/calypso.tinymce.js?minify=false'
497                    : '//widgets.wp.com/wpcom-block-editor/calypso.tinymce.min.js'
498            );
499        }
500
501        return $plugin_array;
502    }
503
504    /**
505     * Ensures the authentication cookies are designated for cross-site access.
506     */
507    private function enable_cross_site_auth_cookies() {
508        /**
509         * Allow plugins to disable the cross-site auth cookies.
510         *
511         * @since jetpack-8.1.1
512         *
513         * @param false bool Whether auth cookies should be disabled for cross-site access. False by default.
514         */
515        if ( apply_filters( 'jetpack_disable_cross_site_auth_cookies', false ) ) {
516            return;
517        }
518
519        add_action( 'set_auth_cookie', array( $this, 'set_samesite_auth_cookies' ), 10, 5 );
520        add_action( 'set_logged_in_cookie', array( $this, 'set_samesite_logged_in_cookies' ), 10, 4 );
521        add_filter( 'send_auth_cookies', array( $this, 'maybe_send_cookies' ), 9999 );
522    }
523
524    /**
525     * Checks if we've stored any cookies to send and then sends them
526     * if the send_auth_cookies value is true.
527     *
528     * @param bool $send_cookies The filtered value that determines whether to send auth cookies.
529     */
530    public function maybe_send_cookies( $send_cookies ) {
531
532        if ( ! empty( $this->set_cookie_args ) && $send_cookies ) {
533            array_walk(
534                $this->set_cookie_args,
535                function ( $cookie ) {
536                    call_user_func_array( 'setcookie', $cookie );
537                }
538            );
539            $this->set_cookie_args = array();
540            return false;
541        }
542
543        return $send_cookies;
544    }
545
546    /**
547     * Gets the SameSite attribute to use in auth cookies.
548     *
549     * @param  bool $secure Whether the connection is secure.
550     * @return string SameSite attribute to use on auth cookies.
551     */
552    public function get_samesite_attr_for_auth_cookies( $secure ) {
553        $samesite = $secure ? 'None' : 'Lax';
554        /**
555         * Filters the SameSite attribute to use in auth cookies.
556         *
557         * @param string $samesite SameSite attribute to use in auth cookies.
558         *
559         * @since jetpack-8.1.1
560         */
561        $samesite = apply_filters( 'jetpack_auth_cookie_samesite', $samesite );
562
563        return $samesite;
564    }
565
566    /**
567     * Generates cross-site auth cookies so they can be accessed by WordPress.com.
568     *
569     * @param string $auth_cookie Authentication cookie value.
570     * @param int    $expire      The time the login grace period expires as a UNIX timestamp.
571     *                            Default is 12 hours past the cookie's expiration time.
572     * @param int    $expiration  The time when the authentication cookie expires as a UNIX timestamp.
573     *                            Default is 14 days from now.
574     * @param int    $user_id     User ID.
575     * @param string $scheme      Authentication scheme. Values include 'auth' or 'secure_auth'.
576     */
577    public function set_samesite_auth_cookies( $auth_cookie, $expire, $expiration, $user_id, $scheme ) {
578        if ( $scheme && is_scalar( $scheme ) && str_starts_with( (string) $scheme, 'secure_' ) ) {
579            $secure           = true;
580            $auth_cookie_name = SECURE_AUTH_COOKIE;
581        } else {
582            $secure           = false;
583            $auth_cookie_name = AUTH_COOKIE;
584        }
585        $samesite = $this->get_samesite_attr_for_auth_cookies( $secure );
586
587        $this->set_cookie_args[] = array(
588            $auth_cookie_name,
589            $auth_cookie,
590            array(
591                'expires'  => $expire,
592                'path'     => PLUGINS_COOKIE_PATH,
593                'domain'   => COOKIE_DOMAIN,
594                'secure'   => $secure,
595                'httponly' => true,
596                'samesite' => $samesite,
597            ),
598        );
599
600        $this->set_cookie_args[] = array(
601            $auth_cookie_name,
602            $auth_cookie,
603            array(
604                'expires'  => $expire,
605                'path'     => ADMIN_COOKIE_PATH,
606                'domain'   => COOKIE_DOMAIN,
607                'secure'   => $secure,
608                'httponly' => true,
609                'samesite' => $samesite,
610            ),
611        );
612    }
613
614    /**
615     * Generates cross-site logged in cookies so they can be accessed by WordPress.com.
616     *
617     * @param string $logged_in_cookie The logged-in cookie value.
618     * @param int    $expire           The time the login grace period expires as a UNIX timestamp.
619     *                                 Default is 12 hours past the cookie's expiration time.
620     * @param int    $expiration       The time when the logged-in cookie expires as a UNIX timestamp.
621     *                                 Default is 14 days from now.
622     * @param int    $user_id          User ID.
623     */
624    public function set_samesite_logged_in_cookies( $logged_in_cookie, $expire, $expiration, $user_id ) {
625        $secure = is_ssl();
626
627        // Front-end cookie is secure when the auth cookie is secure and the site's home URL is forced HTTPS.
628        $secure_logged_in_cookie = $secure && 'https' === wp_parse_url( get_option( 'home' ), PHP_URL_SCHEME );
629
630        /** This filter is documented in core/src/wp-includes/pluggable.php */
631        $secure = apply_filters( 'secure_auth_cookie', $secure, $user_id );
632
633        /** This filter is documented in core/src/wp-includes/pluggable.php */
634        $secure_logged_in_cookie = apply_filters( 'secure_logged_in_cookie', $secure_logged_in_cookie, $user_id, $secure );
635
636        $samesite = $this->get_samesite_attr_for_auth_cookies( $secure_logged_in_cookie );
637
638        $this->set_cookie_args[] = array(
639            LOGGED_IN_COOKIE,
640            $logged_in_cookie,
641            array(
642                'expires'  => $expire,
643                'path'     => COOKIEPATH,
644                'domain'   => COOKIE_DOMAIN,
645                'secure'   => $secure_logged_in_cookie,
646                'httponly' => true,
647                'samesite' => $samesite,
648            ),
649        );
650
651        if ( COOKIEPATH !== SITECOOKIEPATH ) {
652            $this->set_cookie_args[] = array(
653                LOGGED_IN_COOKIE,
654                $logged_in_cookie,
655                array(
656                    'expires'  => $expire,
657                    'path'     => SITECOOKIEPATH,
658                    'domain'   => COOKIE_DOMAIN,
659                    'secure'   => $secure_logged_in_cookie,
660                    'httponly' => true,
661                    'samesite' => $samesite,
662                ),
663            );
664        }
665    }
666}
667
668Jetpack_WPCOM_Block_Editor::init();