Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.75% covered (success)
98.75%
79 / 80
83.33% covered (warning)
83.33%
5 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
Initial_State
98.75% covered (success)
98.75%
79 / 80
83.33% covered (warning)
83.33%
5 / 6
22
0.00% covered (danger)
0.00%
0 / 1
 get_data
100.00% covered (success)
100.00%
46 / 46
100.00% covered (success)
100.00%
1 / 1
6
 get_identity_crisis_data
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
7
 get_mismatched_urls
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
 set_connection_script_data
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 render
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 render_script
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * The React initial state.
4 *
5 * @package automattic/jetpack-connection
6 */
7
8namespace Automattic\Jetpack\Connection;
9
10use Automattic\Jetpack\Identity_Crisis;
11use Automattic\Jetpack\Status;
12
13/**
14 * The React initial state.
15 */
16class Initial_State {
17
18    /**
19     * Get the initial state data.
20     *
21     * @return array
22     */
23    private static function get_data() {
24        global $wp_version;
25
26        $status                = new Status();
27        $manager               = new Manager();
28        $can_manage_connection = current_user_can( 'jetpack_connect' );
29
30        // Only expose the owner's identity to users who can act on connection issues:
31        // this state is printed for any logged-in user loading connection scripts
32        // (e.g. contributors in the editor). The owner is derived from the master_user
33        // option rather than the token-dependent Manager::get_connection_owner(): that
34        // method returns false exactly when the owner's token is broken, which is the
35        // scenario connection-error UIs need this data for (and it re-reports
36        // invalid_connection_owner as a side effect). Unlike
37        // userConnectionData.connectionOwner (the *connected* owner), this field
38        // identifies who holds ownership regardless of token health.
39        $connection_owner = null;
40        if ( $can_manage_connection ) {
41            $owner_id = (int) \Jetpack_Options::get_option( 'master_user' );
42            $owner    = $owner_id > 0 ? get_userdata( $owner_id ) : false;
43
44            if ( $owner instanceof \WP_User ) {
45                $connection_owner = array(
46                    'id'          => $owner_id,
47                    'displayName' => $owner->display_name,
48                    'avatar'      => get_avatar_url(
49                        $owner_id,
50                        array(
51                            'size'    => 48,
52                            'default' => 'mysteryman',
53                        )
54                    ),
55                );
56            }
57        }
58
59        // Behind the same gate: on an anchored site, resolving the owner can cost a WordPress.com lookup.
60        $has_protected_owner            = null;
61        $requires_protected_owner       = null;
62        $use_default_protected_owner_ui = null;
63        if ( $can_manage_connection ) {
64            $has_protected_owner      = $manager->has_protected_owner();
65            $requires_protected_owner = $manager->requires_protected_owner();
66
67            /**
68             * Filters whether the connection package renders its default protected owner UI.
69             *
70             * Return `false` from a consumer that renders its own confirmation flow.
71             *
72             * @since 9.7.0
73             *
74             * @param bool $use_default_ui Whether to render the default UI. Default true.
75             */
76            $use_default_protected_owner_ui = (bool) apply_filters( 'jetpack_connection_protected_owner_default_ui', true );
77        }
78
79        return array(
80            'apiRoot'                    => esc_url_raw( rest_url() ),
81            'apiNonce'                   => wp_create_nonce( 'wp_rest' ),
82            'registrationNonce'          => wp_create_nonce( 'jetpack-registration-nonce' ),
83            'connectionStatus'           => REST_Connector::connection_status( false ),
84            'userConnectionData'         => REST_Connector::get_user_connection_data( false ),
85            'connectedPlugins'           => REST_Connector::get_connection_plugins( false ),
86            'wpVersion'                  => $wp_version,
87            'siteSuffix'                 => $status->get_site_suffix(),
88            'connectionErrors'           => Error_Handler::get_instance()->get_displayable_errors(),
89            'isOfflineMode'              => $status->is_offline_mode(),
90            'calypsoEnv'                 => ( new Status\Host() )->get_calypso_env(),
91            // @deprecated 9.18.0 Nothing reads it any more; kept for third-party readers. Remove in a later release.
92            'isOwnershipTransferable'    => $manager->is_ownership_transferable(),
93            // Null on a partial update with a Manager that predates the method; JS then falls back to the trunk rule.
94            'canTakeOwnerSlot'           => method_exists( $manager, 'can_take_owner_slot' ) ? $manager->can_take_owner_slot() : null,
95            'connectionOwner'            => $connection_owner,
96            'hasProtectedOwner'          => $has_protected_owner,
97            'requiresProtectedOwner'     => $requires_protected_owner,
98            'useDefaultProtectedOwnerUi' => $use_default_protected_owner_ui,
99            'identityCrisis'             => self::get_identity_crisis_data( $status ),
100        );
101    }
102
103    /**
104     * Get the Safe Mode state the shared Safe Mode screen reads.
105     *
106     * @since 9.18.3
107     * @since $$next-version$$ Adds `pluginLogos`.
108     *
109     * @param Status $status Status instance.
110     * @return array|null Null outside Safe Mode.
111     */
112    private static function get_identity_crisis_data( Status $status ) {
113        // Guarded: another plugin can still load the older Identity_Crisis from the abandoned jetpack-identity-crisis package.
114        if ( ! $status->in_safe_mode() || ! method_exists( Identity_Crisis::class, 'is_new_screen_enabled' ) ) {
115            return null;
116        }
117
118        $can_resolve = current_user_can( 'jetpack_disconnect' );
119        $data        = array(
120            'useNewScreen'        => Identity_Crisis::is_new_screen_enabled(),
121            'canResolve'          => $can_resolve,
122            'isSafeModeConfirmed' => (bool) Identity_Crisis::safe_mode_is_confirmed(),
123        );
124
125        // This state is printed for any logged-in user who loads connection scripts.
126        if ( ! $can_resolve ) {
127            return $data;
128        }
129
130        $idc_urls = self::get_mismatched_urls();
131
132        return $data + array(
133            'wpcomHomeUrl'                   => $idc_urls ? $idc_urls['wpcom_url'] : '',
134            'currentUrl'                     => $idc_urls ? $idc_urls['current_url'] : ( Identity_Crisis::get_sync_error_idc_option()['home'] ?? '' ),
135            'isDevelopmentSite'              => (bool) Status::is_development_site(),
136            'possibleDynamicSiteUrlDetected' => (bool) Identity_Crisis::detect_possible_dynamic_site_url(),
137            'logoUrl'                        => Jetpack_Connector::get_connector_logo_url(),
138            // Guarded: an older Jetpack_Connector may already be loaded.
139            'pluginLogos'                    => method_exists( Jetpack_Connector::class, 'get_connected_plugin_logos' ) ? Jetpack_Connector::get_connected_plugin_logos() : array(),
140        );
141    }
142
143    /**
144     * Get the mismatched URLs, including once Safe Mode is confirmed.
145     *
146     * @since 9.18.3
147     *
148     * @return array{wpcom_url: string, current_url: string}|false
149     */
150    private static function get_mismatched_urls() {
151        $idc_urls = Identity_Crisis::get_stored_mismatched_urls();
152        if ( ! $idc_urls ) {
153            return false;
154        }
155
156        // The WordPress.com URLs are stored reversed, and only the filter Identity_Crisis::init() adds turns them back.
157        if ( false === has_filter( 'jetpack_options', array( Identity_Crisis::class, 'reverse_wpcom_urls_for_idc' ) ) ) {
158            $error = \Jetpack_Options::get_option( 'sync_error_idc' );
159            if ( is_array( $error ) && ! empty( $error['reversed_url'] ) ) {
160                $idc_urls['wpcom_url'] = strrev( $idc_urls['wpcom_url'] );
161            }
162        }
163
164        return $idc_urls;
165    }
166
167    /**
168     * Set the connection script data.
169     *
170     * @param array $data The script data.
171     */
172    public static function set_connection_script_data( $data ) {
173
174        $data['connection'] = self::get_data();
175
176        if ( empty( $data['site']['wpcom']['blog_id'] ) ) {
177            $data['site']['wpcom']['blog_id'] = absint( \Jetpack_Options::get_option( 'id', 0 ) );
178        }
179
180        return $data;
181    }
182
183    /**
184     * Render the initial state into a JavaScript variable.
185     *
186     * @return string
187     */
188    public static function render() {
189        /*
190         * `window.jpTracksContext` is an intentionally minimal, Tracks-specific global used by the
191         * @automattic/jetpack-analytics package to read `blog_id` at event-fire time. It exists
192         * separately from `window.JetpackScriptData` because the analytics package is consumed in
193         * contexts (e.g. Boost frontend) where `JetpackScriptData` is not reliably available, and
194         * coupling the analytics package to that schema would widen its surface unnecessarily.
195         * When both are present, `JetpackScriptData.site.wpcom.blog_id` is populated via
196         * `set_connection_script_data()` above for other consumers.
197         * Jetpack_Connector::enqueue_script_module() prints the same line on the Connectors screen.
198         */
199        return 'var JP_CONNECTION_INITIAL_STATE; typeof JP_CONNECTION_INITIAL_STATE === "object" || (JP_CONNECTION_INITIAL_STATE = ' . wp_json_encode( self::get_data(), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ) . ');'
200            . sprintf( 'window.jpTracksContext = window.jpTracksContext || {}; window.jpTracksContext.blog_id = %s;', absint( \Jetpack_Options::get_option( 'id', 0 ) ) );
201    }
202
203    /**
204     * Render the initial state using an inline script.
205     *
206     * @param string $handle The JS script handle.
207     *
208     * @return void
209     */
210    public static function render_script( $handle ) {
211        wp_add_inline_script( $handle, static::render(), 'before' );
212    }
213}