Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.10% covered (success)
98.10%
155 / 158
80.00% covered (warning)
80.00%
12 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
Odyssey_Config_Data
98.10% covered (success)
98.10%
155 / 158
80.00% covered (warning)
80.00%
12 / 15
38
0.00% covered (danger)
0.00%
0 / 1
 get_js_config_data
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_data
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 merge_wpcom_site_record
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_wpcom_site_record
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
8.01
 get_object_field
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
 get_connected_blog_id
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_site_agnostic_data
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
2
 get_initial_state
100.00% covered (success)
100.00%
47 / 47
100.00% covered (success)
100.00%
1 / 1
6
 is_automated_transfer
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 get_gmt_offset
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_admin_path
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
 get_user_locale
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 get_plan_features
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
4.03
 get_plan
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_current_user_capabilities
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Stats Initial State
4 *
5 * @package automattic/jetpack-stats-admin
6 */
7
8namespace Automattic\Jetpack\Stats_Admin;
9
10use Automattic\Jetpack\Blaze;
11use Automattic\Jetpack\Connection\REST_Connector;
12use Automattic\Jetpack\Current_Plan as Jetpack_Plan;
13use Automattic\Jetpack\Modules;
14use Automattic\Jetpack\Status\Host;
15use Jetpack_Options;
16
17/**
18 * Class Odyssey_Config_Data
19 *
20 * @package automattic/jetpack-stats-admin
21 */
22class Odyssey_Config_Data {
23
24    /**
25     * Set configData to window.configData.
26     *
27     * @param string $config_variable_name The config variable name.
28     * @param array  $config_data The config data.
29     */
30    public function get_js_config_data( $config_variable_name = 'configData', $config_data = null ) {
31        return "window.{$config_variable_name} = " . wp_json_encode(
32            $config_data === null ? $this->get_data() : $config_data,
33            JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP
34        ) . ';';
35    }
36
37    /**
38     * Return the config for the app.
39     *
40     * @param bool $with_wpcom_site_record Fold in the WordPress.com site record, which the Stats page
41     *                                     app otherwise fetches before it renders anything.
42     */
43    public function get_data( $with_wpcom_site_record = false ) {
44        $blog_id = $this->get_connected_blog_id();
45        $data    = $this->get_site_agnostic_data( $blog_id );
46
47        /*
48         * A site the app cannot reach has no record to seed its store with. Emitting one anyway
49         * would key every entry on a blog ID of 0 and make each lookup miss, so leave it out and
50         * let the app fall back to the screens it shows without a site.
51         */
52        if ( $blog_id ) {
53            $data['intial_state'] = $this->get_initial_state( $blog_id, $with_wpcom_site_record );
54        }
55
56        return $data;
57    }
58
59    /**
60     * Merge the WordPress.com site record into the seeded one, as the app's `ODYSSEY_SITE_RECEIVE`
61     * reducer would: seeded top-level fields win, while WordPress.com wins inside `options` and
62     * `capabilities`. The app skips its blocking `jetpack/v4/site` request once `options.is_commercial` is set.
63     *
64     * @param array  $site   The seeded site record.
65     * @param object $record The WordPress.com site record.
66     * @return array
67     */
68    protected function merge_wpcom_site_record( array $site, $record ) {
69        $merged                 = array_merge( get_object_vars( $record ), $site );
70        $merged['options']      = array_merge( $site['options'], $this->get_object_field( $record, 'options' ) );
71        $merged['capabilities'] = array_merge( $site['capabilities'], $this->get_object_field( $record, 'capabilities' ) );
72
73        return $merged;
74    }
75
76    /**
77     * The site record `jetpack/v4/site` would serve, read through the connection package's cache.
78     *
79     * Decoded to objects so that an empty object stays `{}` when it is printed again.
80     *
81     * @return object|null Null when WordPress.com could not supply one, or the route would refuse this user.
82     */
83    protected function get_wpcom_site_record() {
84        // method_exists guard: an older connection package may win the autoloader on another plugin.
85        if ( ! method_exists( REST_Connector::class, 'site_data_response' ) ) {
86            return null;
87        }
88
89        // `view_stats` can be granted to roles the route refuses; those users keep fetching it themselves.
90        if ( true !== REST_Connector::site_data_permission_check() ) {
91            return null;
92        }
93
94        // On a cache miss this runs before any HTML is sent, so give it the render budget `Dashboard::maybe_refresh_plan()` uses.
95        $cap_timeout = static function ( $args, $url ) {
96            if ( false !== strpos( $url, '/sites/' . Jetpack_Options::get_option( 'id' ) . '?force=wpcom' ) ) {
97                $args['timeout'] = min( (int) $args['timeout'], 5 );
98            }
99            return $args;
100        };
101
102        $response = null;
103        add_filter( 'http_request_args', $cap_timeout, 10, 2 );
104        try {
105            $response = REST_Connector::site_data_response();
106        } finally {
107            remove_filter( 'http_request_args', $cap_timeout, 10 );
108        }
109
110        if ( is_wp_error( $response ) ) {
111            return null;
112        }
113
114        $body   = $response->get_data();
115        $record = isset( $body['data'] ) && is_string( $body['data'] ) ? json_decode( $body['data'] ) : null;
116
117        return is_object( $record ) ? $record : null;
118    }
119
120    /**
121     * Read an object-valued field of a decoded record as an array.
122     *
123     * @param object $record The decoded record.
124     * @param string $field  The field name.
125     * @return array Empty when the field is missing or not an object.
126     */
127    private function get_object_field( $record, $field ) {
128        return isset( $record->$field ) && is_object( $record->$field ) ? get_object_vars( $record->$field ) : array();
129    }
130
131    /**
132     * The WordPress.com blog ID the app can talk to, or 0 when there is none.
133     *
134     * A site keeps its blog ID when it disconnects, but every request the app would make with it
135     * has to be signed with a token the site no longer holds. Such a site has no more to offer
136     * the app than one that was never connected.
137     *
138     * @return int
139     */
140    protected function get_connected_blog_id() {
141        $blog_id = (int) Jetpack_Options::get_option( 'id' );
142
143        if ( ! Main::is_site_connected() ) {
144            return 0;
145        }
146
147        // Keep registered sites in the dashboard even when their token is malformed.
148        // The traffic request reports the connection error; an ID of 0 routes to plan selection.
149        return $blog_id;
150    }
151
152    /**
153     * Config the app can rely on with or without a WordPress.com connection.
154     *
155     * @param int $blog_id The WordPress.com blog ID, 0 when the site is not connected.
156     * @return array
157     */
158    protected function get_site_agnostic_data( $blog_id ) {
159        global $wp_version;
160
161        return array(
162            'admin_page_base'                => $this->get_admin_path(),
163            'api_root'                       => esc_url_raw( rest_url() ),
164            'blog_id'                        => $blog_id,
165            'enable_all_sections'            => false,
166            'env_id'                         => 'production',
167            'google_analytics_key'           => 'UA-10673494-15',
168            'google_maps_and_places_api_key' => '',
169            'hostname'                       => wp_parse_url( get_site_url(), PHP_URL_HOST ),
170            'i18n_default_locale_slug'       => 'en',
171            'i18n_locale_slug'               => $this->get_user_locale(),
172            'mc_analytics_enabled'           => false,
173            'meta'                           => array(),
174            'nonce'                          => wp_create_nonce( 'wp_rest' ),
175            'site_name'                      => \get_bloginfo( 'name' ),
176            'sections'                       => array(),
177            // Features are inlined @see https://github.com/Automattic/wp-calypso/pull/70122
178            'features'                       => array(
179                'is_running_in_jetpack_site' => ! ( new Host() )->is_wpcom_simple(),
180            ),
181            // Intended for apps that do not use redux.
182            'gmt_offset'                     => $this->get_gmt_offset(),
183            // Empty for a site set to a fixed UTC offset; `gmt_offset` alone cannot follow daylight saving.
184            'timezone'                       => (string) get_option( 'timezone_string' ),
185            'odyssey_stats_base_url'         => admin_url( 'admin.php?page=stats' ),
186            // Repeated in the site record below, which a site without a connection never gets.
187            'admin_url'                      => admin_url(),
188            'jetpack_version'                => defined( 'JETPACK__VERSION' ) ? JETPACK__VERSION : '',
189            'stats_admin_version'            => Main::VERSION,
190            'software_version'               => $wp_version,
191        );
192    }
193
194    /**
195     * The Redux state the app boots with.
196     *
197     * @param int  $blog_id                The WordPress.com blog ID.
198     * @param bool $with_wpcom_site_record Fold in the WordPress.com site record.
199     * @return array
200     */
201    protected function get_initial_state( $blog_id, $with_wpcom_site_record = false ) {
202        global $wp_version;
203
204        $host         = new Host();
205        $capabilities = $this->get_current_user_capabilities();
206        $can_blaze    = class_exists( 'Automattic\Jetpack\Blaze' ) && Blaze::should_initialize()['can_init'];
207
208        /*
209         * Fetched first, as its `jetpack_site_data_fetched` listeners refresh the plan read below.
210         * Simple sites do not serve `jetpack/v4/site`; the app fetches their record from WordPress.com.
211         */
212        $record = $with_wpcom_site_record && ! $host->is_wpcom_simple() ? $this->get_wpcom_site_record() : null;
213
214        $site = array(
215            'ID'           => $blog_id,
216            'URL'          => site_url(),
217            // Atomic and jetpack sites should return true.
218            'jetpack'      => ! $host->is_wpcom_simple(),
219            'visible'      => true,
220            'capabilities' => $capabilities,
221            'products'     => Jetpack_Plan::get_products(),
222            'plan'         => $this->get_plan(),
223            'options'      => array(
224                'wordads'               => ( new Modules() )->is_active( 'wordads' ),
225                'admin_url'             => admin_url(),
226                'gmt_offset'            => $this->get_gmt_offset(),
227                'is_automated_transfer' => $this->is_automated_transfer( $blog_id ),
228                'is_wpcom_atomic'       => $host->is_woa_site(),
229                'is_wpcom_simple'       => $host->is_wpcom_simple(),
230                'is_vip'                => $host->is_vip_site(),
231                'jetpack_version'       => defined( 'JETPACK__VERSION' ) ? JETPACK__VERSION : '',
232                'stats_admin_version'   => Main::VERSION,
233                'software_version'      => $wp_version,
234                'can_blaze'             => $can_blaze,
235                'has_stats_settings'    => ! $host->is_wpcom_simple(),
236            ),
237        );
238
239        if ( null !== $record ) {
240            $site = $this->merge_wpcom_site_record( $site, $record );
241        }
242
243        return array(
244            'currentUser' => array(
245                'id'           => 1000,
246                'user'         => array(
247                    'ID'       => 1000,
248                    'username' => 'no-user',
249                ),
250                'capabilities' => array(
251                    "$blog_id" => $capabilities,
252                ),
253            ),
254            'sites'       => array(
255                'items'    => array(
256                    "$blog_id" => $site,
257                ),
258                'features' => array( "$blog_id" => array( 'data' => $this->get_plan_features() ) ),
259            ),
260        );
261    }
262
263    /**
264     * Defines a filter to set whether a site is an automated_transfer site or not.
265     *
266     * Default is false. On Atomic, this is set to true by `wpcomsh`.
267     *
268     * @param int $blog_id Blog ID.
269     *
270     * @return bool
271     */
272    public function is_automated_transfer( $blog_id ) {
273        /**
274         * Filter if a site is an automated-transfer site.
275         *
276         * @module json-api
277         *
278         * @since 6.4.0
279         *
280         * @param bool is_automated_transfer( $this->blog_id )
281         * @param int  $blog_id Blog identifier.
282         */
283        return apply_filters(
284            'jetpack_site_automated_transfer',
285            false,
286            $blog_id
287        );
288    }
289
290    /**
291     * Get the current site GMT Offset.
292     *
293     * @return float The current site GMT Offset by hours.
294     */
295    protected function get_gmt_offset() {
296        return (float) get_option( 'gmt_offset' );
297    }
298
299    /**
300     * Page base for the Calypso admin page.
301     */
302    protected function get_admin_path() {
303        if ( ! isset( $_SERVER['PHP_SELF'] ) || ! isset( $_SERVER['QUERY_STRING'] ) ) {
304            $parsed = wp_parse_url( admin_url( 'admin.php?page=stats' ) );
305            return $parsed['path'] . '?' . $parsed['query'];
306        }
307        // We do this because page.js requires the exactly page base to be set otherwise it will not work properly.
308        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
309        return wp_unslash( $_SERVER['PHP_SELF'] ) . '?' . wp_unslash( $_SERVER['QUERY_STRING'] );
310    }
311
312    /**
313     * Get locale acceptable by Calypso.
314     */
315    protected function get_user_locale() {
316        /**
317         * In WP, locales are formatted as LANGUAGE_REGION, for example `en`, `en_US`, `es_AR`,
318         * but Calypso expects language-region, e.g. `en-us`, `en`,  `es-ar`. So we need to convert
319         * them to lower case and replace the underscore with a dash.
320         */
321        $locale = strtolower( get_user_locale() );
322        $locale = str_replace( '_', '-', $locale );
323
324        return $locale;
325    }
326
327    /**
328     * Get the features of the current plan.
329     *
330     * The app cannot refresh what it paywalls on, so a WordPress.com-hosted site is asked
331     * directly; a plan cached before an upgrade gates a feature the site has already paid for.
332     */
333    protected function get_plan_features() {
334        // method_exists guard: an older plans package may win the autoloader on another plugin.
335        if ( method_exists( Jetpack_Plan::class, 'get_wpcom_site_specific_features' ) ) {
336            $features = Jetpack_Plan::get_wpcom_site_specific_features();
337            if ( null !== $features ) {
338                return $features;
339            }
340        }
341
342        $plan = Jetpack_Plan::get();
343        if ( empty( $plan['features'] ) ) {
344            return array();
345        }
346        return $plan['features'];
347    }
348
349    /**
350     * Get the current plan.
351     *
352     * @return array
353     */
354    protected function get_plan() {
355        $plan = Jetpack_Plan::get();
356        unset( $plan['features'] );
357        unset( $plan['supports'] );
358        return $plan;
359    }
360
361    /**
362     * Get the capabilities of the current user.
363     *
364     * @return array An array of capabilities.
365     */
366    protected function get_current_user_capabilities() {
367        return array(
368            'edit_pages'          => current_user_can( 'edit_pages' ),
369            'edit_posts'          => current_user_can( 'edit_posts' ),
370            'edit_others_posts'   => current_user_can( 'edit_others_posts' ),
371            'edit_others_pages'   => current_user_can( 'edit_others_pages' ),
372            'delete_posts'        => current_user_can( 'delete_posts' ),
373            'delete_others_posts' => current_user_can( 'delete_others_posts' ),
374            'edit_theme_options'  => current_user_can( 'edit_theme_options' ),
375            'edit_users'          => current_user_can( 'edit_users' ),
376            'list_users'          => current_user_can( 'list_users' ),
377            'manage_categories'   => current_user_can( 'manage_categories' ),
378            'manage_options'      => current_user_can( 'manage_options' ),
379            'moderate_comments'   => current_user_can( 'moderate_comments' ),
380            'activate_wordads'    => current_user_can( 'manage_options' ),
381            'promote_users'       => current_user_can( 'promote_users' ),
382            'publish_posts'       => current_user_can( 'publish_posts' ),
383            'upload_files'        => current_user_can( 'upload_files' ),
384            'delete_users'        => current_user_can( 'delete_users' ),
385            'remove_users'        => current_user_can( 'remove_users' ),
386            'own_site'            => current_user_can( 'manage_options' ), // Administrators are considered owners on site.
387            'view_stats'          => current_user_can( 'view_stats' ),
388            'activate_plugins'    => current_user_can( 'activate_plugins' ),
389        );
390    }
391}