Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.04% covered (success)
98.04%
50 / 51
75.00% covered (warning)
75.00%
3 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
Initial_State
98.04% covered (success)
98.04%
50 / 51
75.00% covered (warning)
75.00%
3 / 4
9
0.00% covered (danger)
0.00%
0 / 1
 get_data
100.00% covered (success)
100.00%
44 / 44
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\Status;
11
12/**
13 * The React initial state.
14 */
15class Initial_State {
16
17    /**
18     * Get the initial state data.
19     *
20     * @return array
21     */
22    private static function get_data() {
23        global $wp_version;
24
25        $status                = new Status();
26        $manager               = new Manager();
27        $can_manage_connection = current_user_can( 'jetpack_connect' );
28
29        // Only expose the owner's identity to users who can act on connection issues:
30        // this state is printed for any logged-in user loading connection scripts
31        // (e.g. contributors in the editor). The owner is derived from the master_user
32        // option rather than the token-dependent Manager::get_connection_owner(): that
33        // method returns false exactly when the owner's token is broken, which is the
34        // scenario connection-error UIs need this data for (and it re-reports
35        // invalid_connection_owner as a side effect). Unlike
36        // userConnectionData.connectionOwner (the *connected* owner), this field
37        // identifies who holds ownership regardless of token health.
38        $connection_owner = null;
39        if ( $can_manage_connection ) {
40            $owner_id = (int) \Jetpack_Options::get_option( 'master_user' );
41            $owner    = $owner_id > 0 ? get_userdata( $owner_id ) : false;
42
43            if ( $owner instanceof \WP_User ) {
44                $connection_owner = array(
45                    'id'          => $owner_id,
46                    'displayName' => $owner->display_name,
47                    'avatar'      => get_avatar_url(
48                        $owner_id,
49                        array(
50                            'size'    => 48,
51                            'default' => 'mysteryman',
52                        )
53                    ),
54                );
55            }
56        }
57
58        // Behind the same gate: on an anchored site, resolving the owner can cost a WordPress.com lookup.
59        $has_protected_owner            = null;
60        $requires_protected_owner       = null;
61        $use_default_protected_owner_ui = null;
62        if ( $can_manage_connection ) {
63            $has_protected_owner      = $manager->has_protected_owner();
64            $requires_protected_owner = $manager->requires_protected_owner();
65
66            /**
67             * Filters whether the connection package renders its default protected owner UI.
68             *
69             * Return `false` from a consumer that renders its own confirmation flow.
70             *
71             * @since 9.7.0
72             *
73             * @param bool $use_default_ui Whether to render the default UI. Default true.
74             */
75            $use_default_protected_owner_ui = (bool) apply_filters( 'jetpack_connection_protected_owner_default_ui', true );
76        }
77
78        return array(
79            'apiRoot'                    => esc_url_raw( rest_url() ),
80            'apiNonce'                   => wp_create_nonce( 'wp_rest' ),
81            'registrationNonce'          => wp_create_nonce( 'jetpack-registration-nonce' ),
82            'connectionStatus'           => REST_Connector::connection_status( false ),
83            'userConnectionData'         => REST_Connector::get_user_connection_data( false ),
84            'connectedPlugins'           => REST_Connector::get_connection_plugins( false ),
85            'wpVersion'                  => $wp_version,
86            'siteSuffix'                 => $status->get_site_suffix(),
87            'connectionErrors'           => Error_Handler::get_instance()->get_displayable_errors(),
88            'isOfflineMode'              => $status->is_offline_mode(),
89            'calypsoEnv'                 => ( new Status\Host() )->get_calypso_env(),
90            'isOwnershipTransferable'    => $manager->is_ownership_transferable(),
91            'connectionOwner'            => $connection_owner,
92            'hasProtectedOwner'          => $has_protected_owner,
93            'requiresProtectedOwner'     => $requires_protected_owner,
94            'useDefaultProtectedOwnerUi' => $use_default_protected_owner_ui,
95        );
96    }
97
98    /**
99     * Set the connection script data.
100     *
101     * @param array $data The script data.
102     */
103    public static function set_connection_script_data( $data ) {
104
105        $data['connection'] = self::get_data();
106
107        if ( empty( $data['site']['wpcom']['blog_id'] ) ) {
108            $data['site']['wpcom']['blog_id'] = absint( \Jetpack_Options::get_option( 'id', 0 ) );
109        }
110
111        return $data;
112    }
113
114    /**
115     * Render the initial state into a JavaScript variable.
116     *
117     * @return string
118     */
119    public static function render() {
120        /*
121         * `window.jpTracksContext` is an intentionally minimal, Tracks-specific global used by the
122         * @automattic/jetpack-analytics package to read `blog_id` at event-fire time. It exists
123         * separately from `window.JetpackScriptData` because the analytics package is consumed in
124         * contexts (e.g. Boost frontend) where `JetpackScriptData` is not reliably available, and
125         * coupling the analytics package to that schema would widen its surface unnecessarily.
126         * When both are present, `JetpackScriptData.site.wpcom.blog_id` is populated via
127         * `set_connection_script_data()` above for other consumers.
128         */
129        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 ) . ');'
130            . sprintf( 'window.jpTracksContext = window.jpTracksContext || {}; window.jpTracksContext.blog_id = %s;', absint( \Jetpack_Options::get_option( 'id', 0 ) ) );
131    }
132
133    /**
134     * Render the initial state using an inline script.
135     *
136     * @param string $handle The JS script handle.
137     *
138     * @return void
139     */
140    public static function render_script( $handle ) {
141        wp_add_inline_script( $handle, static::render(), 'before' );
142    }
143}