Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.73% covered (success)
98.73%
78 / 79
83.33% covered (warning)
83.33%
5 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
Initial_State
98.73% covered (success)
98.73%
78 / 79
83.33% covered (warning)
83.33%
5 / 6
21
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%
18 / 18
100.00% covered (success)
100.00%
1 / 1
6
 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 $$next-version$$
107     *
108     * @param Status $status Status instance.
109     * @return array|null Null outside Safe Mode.
110     */
111    private static function get_identity_crisis_data( Status $status ) {
112        // Guarded: another plugin can still load the older Identity_Crisis from the abandoned jetpack-identity-crisis package.
113        if ( ! $status->in_safe_mode() || ! method_exists( Identity_Crisis::class, 'is_new_screen_enabled' ) ) {
114            return null;
115        }
116
117        $can_resolve = current_user_can( 'jetpack_disconnect' );
118        $data        = array(
119            'useNewScreen'        => Identity_Crisis::is_new_screen_enabled(),
120            'canResolve'          => $can_resolve,
121            'isSafeModeConfirmed' => (bool) Identity_Crisis::safe_mode_is_confirmed(),
122        );
123
124        // This state is printed for any logged-in user who loads connection scripts.
125        if ( ! $can_resolve ) {
126            return $data;
127        }
128
129        $idc_urls = self::get_mismatched_urls();
130
131        return $data + array(
132            'wpcomHomeUrl'                   => $idc_urls ? $idc_urls['wpcom_url'] : '',
133            'currentUrl'                     => $idc_urls ? $idc_urls['current_url'] : ( Identity_Crisis::get_sync_error_idc_option()['home'] ?? '' ),
134            'isDevelopmentSite'              => (bool) Status::is_development_site(),
135            'possibleDynamicSiteUrlDetected' => (bool) Identity_Crisis::detect_possible_dynamic_site_url(),
136            'logoUrl'                        => Jetpack_Connector::get_connector_logo_url(),
137        );
138    }
139
140    /**
141     * Get the mismatched URLs, including once Safe Mode is confirmed.
142     *
143     * @since $$next-version$$
144     *
145     * @return array{wpcom_url: string, current_url: string}|false
146     */
147    private static function get_mismatched_urls() {
148        $idc_urls = Identity_Crisis::get_stored_mismatched_urls();
149        if ( ! $idc_urls ) {
150            return false;
151        }
152
153        // The WordPress.com URLs are stored reversed, and only the filter Identity_Crisis::init() adds turns them back.
154        if ( false === has_filter( 'jetpack_options', array( Identity_Crisis::class, 'reverse_wpcom_urls_for_idc' ) ) ) {
155            $error = \Jetpack_Options::get_option( 'sync_error_idc' );
156            if ( is_array( $error ) && ! empty( $error['reversed_url'] ) ) {
157                $idc_urls['wpcom_url'] = strrev( $idc_urls['wpcom_url'] );
158            }
159        }
160
161        return $idc_urls;
162    }
163
164    /**
165     * Set the connection script data.
166     *
167     * @param array $data The script data.
168     */
169    public static function set_connection_script_data( $data ) {
170
171        $data['connection'] = self::get_data();
172
173        if ( empty( $data['site']['wpcom']['blog_id'] ) ) {
174            $data['site']['wpcom']['blog_id'] = absint( \Jetpack_Options::get_option( 'id', 0 ) );
175        }
176
177        return $data;
178    }
179
180    /**
181     * Render the initial state into a JavaScript variable.
182     *
183     * @return string
184     */
185    public static function render() {
186        /*
187         * `window.jpTracksContext` is an intentionally minimal, Tracks-specific global used by the
188         * @automattic/jetpack-analytics package to read `blog_id` at event-fire time. It exists
189         * separately from `window.JetpackScriptData` because the analytics package is consumed in
190         * contexts (e.g. Boost frontend) where `JetpackScriptData` is not reliably available, and
191         * coupling the analytics package to that schema would widen its surface unnecessarily.
192         * When both are present, `JetpackScriptData.site.wpcom.blog_id` is populated via
193         * `set_connection_script_data()` above for other consumers.
194         * Jetpack_Connector::enqueue_script_module() prints the same line on the Connectors screen.
195         */
196        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 ) . ');'
197            . sprintf( 'window.jpTracksContext = window.jpTracksContext || {}; window.jpTracksContext.blog_id = %s;', absint( \Jetpack_Options::get_option( 'id', 0 ) ) );
198    }
199
200    /**
201     * Render the initial state using an inline script.
202     *
203     * @param string $handle The JS script handle.
204     *
205     * @return void
206     */
207    public static function render_script( $handle ) {
208        wp_add_inline_script( $handle, static::render(), 'before' );
209    }
210}