Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
75.12% covered (warning)
75.12%
160 / 213
60.00% covered (warning)
60.00%
6 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
jetpack_current_user_data
0.00% covered (danger)
0.00%
0 / 44
0.00% covered (danger)
0.00%
0 / 1
72
Jetpack_Redux_State_Helper
94.67% covered (success)
94.67%
160 / 169
66.67% covered (warning)
66.67%
6 / 9
32.15
0.00% covered (danger)
0.00%
0 / 1
 get_minimal_state
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_plugins_page_state
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 get_initial_state
97.81% covered (success)
97.81%
134 / 137
0.00% covered (danger)
0.00%
0 / 1
17
 get_dismissed_jetpack_notices
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 get_flattened_settings
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 get_update_modal_data
n/a
0 / 0
n/a
0 / 0
1
 allow_post_embed_iframe
n/a
0 / 0
n/a
0 / 0
2
 get_release_post_data
n/a
0 / 0
n/a
0 / 0
1
 get_external_services_connect_urls
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_purchase_token
28.57% covered (danger)
28.57%
2 / 7
0.00% covered (danger)
0.00%
0 / 1
6.28
 generate_purchase_token
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_site_image
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * A utility class that generates the initial state for Redux in wp-admin.
4 * Modularized from `class.jetpack-react-page.php`.
5 *
6 * @package automattic/jetpack
7 */
8
9use Automattic\Jetpack\Blaze;
10use Automattic\Jetpack\Connection\Manager as Connection_Manager;
11use Automattic\Jetpack\Connection\Plugin_Storage as Connection_Plugin_Storage;
12use Automattic\Jetpack\Connection\REST_Connector;
13use Automattic\Jetpack\Constants;
14use Automattic\Jetpack\Current_Plan as Jetpack_Plan;
15use Automattic\Jetpack\Device_Detection\User_Agent_Info;
16use Automattic\Jetpack\Identity_Crisis;
17use Automattic\Jetpack\IP\Utils as IP_Utils;
18use Automattic\Jetpack\Licensing;
19use Automattic\Jetpack\Licensing\Endpoints as Licensing_Endpoints;
20use Automattic\Jetpack\My_Jetpack\Initializer as My_Jetpack_Initializer;
21use Automattic\Jetpack\Partner;
22use Automattic\Jetpack\Publicize\Keyring_Helper;
23use Automattic\Jetpack\Stats\Options as Stats_Options;
24use Automattic\Jetpack\Status;
25use Automattic\Jetpack\Status\Host;
26
27/**
28 * Responsible for populating the initial Redux state.
29 */
30class Jetpack_Redux_State_Helper {
31    /**
32     * Generate minimal state for React to fetch its own data asynchronously after load
33     * This can improve user experience, reducing time spent on server requests before serving the page
34     * e.g. used by React Disconnect Dialog on plugins page where the full initial state is not needed
35     */
36    public static function get_minimal_state() {
37        return array(
38            'WP_API_root'  => esc_url_raw( rest_url() ),
39            'WP_API_nonce' => wp_create_nonce( 'wp_rest' ),
40        );
41    }
42
43    /**
44     * Generate the state for the plugins page: the minimal state plus what the deactivation survey needs.
45     *
46     * @since $$next-version$$
47     *
48     * @return array
49     */
50    public static function get_plugins_page_state() {
51        $state = self::get_minimal_state();
52
53        $connection = new Connection_Manager();
54
55        $state['pluginDeactivation'] = array(
56            'siteId'                 => (int) Jetpack_Options::get_option( 'id' ),
57            'hasConnectedUser'       => $connection->has_connected_user(),
58            'isCurrentUserConnected' => $connection->is_user_connected(),
59        );
60
61        return $state;
62    }
63
64    /**
65     * Generate the initial state array to be used by the Redux store.
66     */
67    public static function get_initial_state() {
68        global $is_safari;
69
70        // Load API endpoint base classes and endpoints for getting the module list fed into the JS Admin Page.
71        require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-xmlrpc-consumer-endpoint.php';
72        require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-module-endpoints.php';
73        require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-site-endpoints.php';
74
75        $module_list_endpoint = new Jetpack_Core_API_Module_List_Endpoint();
76        $modules              = $module_list_endpoint->get_modules();
77
78        // Preparing translated fields for JSON encoding by transforming all HTML entities to
79        // respective characters.
80        foreach ( $modules as $slug => $data ) {
81            $modules[ $slug ]['name']              = html_entity_decode( $data['name'], ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 );
82            $modules[ $slug ]['description']       = html_entity_decode( $data['description'], ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 );
83            $modules[ $slug ]['short_description'] = html_entity_decode( $data['short_description'], ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 );
84            $modules[ $slug ]['long_description']  = html_entity_decode( $data['long_description'], ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 );
85        }
86
87        // "mock" a block module in order to get it searchable in the settings.
88        $modules['blocks']['module']                    = 'blocks';
89        $modules['blocks']['additional_search_queries'] = esc_html_x( 'blocks, block, gutenberg', 'Search terms', 'jetpack' );
90
91        // "mock" an Earn module in order to get it searchable in the settings.
92        $modules['earn']['module']                    = 'earn';
93        $modules['earn']['additional_search_queries'] = esc_html_x( 'earn, paypal, stripe, payments, pay', 'Search terms', 'jetpack' );
94
95        // Collecting roles that can view site stats.
96        $stats_roles   = array();
97        $enabled_roles = Stats_Options::get_option( 'roles' );
98
99        if ( ! function_exists( 'get_editable_roles' ) ) {
100            require_once ABSPATH . 'wp-admin/includes/user.php';
101        }
102        foreach ( get_editable_roles() as $slug => $role ) {
103            $stats_roles[ $slug ] = array(
104                'name'    => translate_user_role( $role['name'] ),
105                'canView' => is_array( $enabled_roles ) ? in_array( $slug, $enabled_roles, true ) : false,
106            );
107        }
108
109        // Get information about current theme.
110        $current_theme = wp_get_theme();
111
112        // Get all themes that Infinite Scroll provides support for natively.
113        $inf_scr_support_themes = array();
114        foreach ( Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules/infinite-scroll/themes' ) as $path ) {
115            if ( is_readable( $path ) ) {
116                $inf_scr_support_themes[] = basename( $path, '.php' );
117            }
118        }
119
120        // Get last post, to build the link to Customizer in the Related Posts module.
121        $last_post = get_posts( array( 'posts_per_page' => 1 ) );
122        $last_post = isset( $last_post[0] ) && $last_post[0] instanceof WP_Post
123            ? get_permalink( $last_post[0]->ID )
124            : get_home_url();
125
126        $current_user_data = jetpack_current_user_data();
127
128        /**
129         * Adds information to the `connectionStatus` API field that is unique to the Jetpack React dashboard.
130         */
131        $connection_status = array(
132            'isInIdentityCrisis' => Identity_Crisis::validate_sync_error_idc_option(),
133            'sandboxDomain'      => JETPACK__SANDBOX_DOMAIN,
134
135            /**
136             * Filter to add connection errors
137             * Format: array( array( 'code' => '...', 'message' => '...', 'action' => '...' ), ... )
138             *
139             * @since 8.7.0
140             *
141             * @param array $errors Connection errors.
142             */
143            'errors'             => apply_filters( 'react_connection_errors_initial_state', array() ),
144        );
145
146        $connection_status = array_merge( REST_Connector::connection_status( false ), $connection_status );
147
148        $block_availability = Jetpack_Gutenberg::get_cached_availability();
149
150        return array(
151            'WP_API_root'                          => esc_url_raw( rest_url() ),
152            'WP_API_nonce'                         => wp_create_nonce( 'wp_rest' ),
153            'registrationNonce'                    => '', // Not used, keeping it for compatibility reasons, see https://github.com/Automattic/jetpack/pull/42076
154            'purchaseToken'                        => self::get_purchase_token(),
155            'pluginBaseUrl'                        => plugins_url( '', JETPACK__PLUGIN_FILE ),
156            'connectionStatus'                     => $connection_status,
157            'connectedPlugins'                     => Connection_Plugin_Storage::get_all(),
158            'connectUrl'                           => false == $current_user_data['isConnected'] // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
159                ? Jetpack::init()->build_connect_url( true, false, false )
160                : '',
161            'dismissedNotices'                     => self::get_dismissed_jetpack_notices(),
162            'isDevVersion'                         => Jetpack::is_development_version(),
163            'currentVersion'                       => JETPACK__VERSION,
164            'is_gutenberg_available'               => true,
165            'getModules'                           => $modules,
166            'rawUrl'                               => ( new Status() )->get_site_suffix(),
167            'adminUrl'                             => esc_url( admin_url() ),
168            'siteTitle'                            => htmlspecialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
169            'stats'                                => array(
170                // data is populated asynchronously on page load.
171                'data'  => array(
172                    'general' => false,
173                    'day'     => false,
174                    'week'    => false,
175                    'month'   => false,
176                ),
177                'roles' => $stats_roles,
178            ),
179            'aff'                                  => Partner::init()->get_partner_code( Partner::AFFILIATE_CODE ),
180            'partnerSubsidiaryId'                  => Partner::init()->get_partner_code( Partner::SUBSIDIARY_CODE ),
181            'settings'                             => self::get_flattened_settings(),
182            'userData'                             => array(
183                'currentUser' => $current_user_data,
184            ),
185            'siteData'                             => array(
186                'blog_id'                    => Jetpack_Options::get_option( 'id', 0 ),
187                'icon'                       => has_site_icon()
188                    ? apply_filters( 'jetpack_photon_url', get_site_icon_url(), array( 'w' => 64 ) )
189                    : '',
190                'representativeImage'        => self::get_site_image(),
191                'siteVisibleToSearchEngines' => '1' == get_option( 'blog_public' ), // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
192                /**
193                 * Whether promotions are visible or not.
194                 *
195                 * @since 4.8.0
196                 *
197                 * @param bool $are_promotions_active Status of promotions visibility. True by default.
198                 */
199                'showPromotions'             => apply_filters( 'jetpack_show_promotions', true ),
200                'plan'                       => Jetpack_Plan::get(),
201                'showBackups'                => Jetpack::show_backups_ui(),
202                'showScan'                   => Jetpack::show_scan_ui(),
203                /** This filter is documented in my-jetpack/src/class-initializer.php */
204                'showMyJetpack'              => My_Jetpack_Initializer::should_initialize(),
205                'isMultisite'                => is_multisite(),
206                'dateFormat'                 => get_option( 'date_format' ),
207                'isSharingBlockAvailable'    => isset( $block_availability['sharing-buttons'] )
208                    && $block_availability['sharing-buttons']['available'],
209                'isLikeBlockAvailable'       => isset( $block_availability['like'] )
210                    && $block_availability['like']['available'],
211            ),
212            'themeData'                            => array(
213                'name'         => $current_theme->get( 'Name' ),
214                'stylesheet'   => $current_theme->get_stylesheet(),
215                'hasUpdate'    => (bool) get_theme_update_available( $current_theme ),
216                'isBlockTheme' => (bool) $current_theme->is_block_theme(),
217                'support'      => array(
218                    'infinite-scroll' => current_theme_supports( 'infinite-scroll' ) || in_array( $current_theme->get_stylesheet(), $inf_scr_support_themes, true ),
219                    'widgets'         => current_theme_supports( 'widgets' ),
220                    'webfonts'        => wp_theme_has_theme_json()
221                        && ( function_exists( 'wp_register_webfont_provider' ) || function_exists( 'wp_register_webfonts' ) ),
222                ),
223            ),
224            'jetpackStateNotices'                  => array(
225                'messageCode'      => Jetpack::state( 'message' ),
226                'errorCode'        => Jetpack::state( 'error' ),
227                'errorDescription' => Jetpack::state( 'error_description' ),
228            ),
229            'tracksUserData'                       => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
230            'currentIp'                            => IP_Utils::get_ip(),
231            'lastPostUrl'                          => esc_url( $last_post ),
232            'externalServicesConnectUrls'          => self::get_external_services_connect_urls(),
233            'calypsoEnv'                           => ( new Host() )->get_calypso_env(),
234            'isSafari'                             => $is_safari || User_Agent_Info::is_opera_desktop(), // @todo Rename isSafari everywhere.
235            'doNotUseConnectionIframe'             => Constants::is_true( 'JETPACK_SHOULD_NOT_USE_CONNECTION_IFRAME' ),
236            'licensing'                            => array(
237                'error'                   => Licensing::instance()->last_error(),
238                'showLicensingUi'         => Licensing::instance()->is_licensing_input_enabled(),
239                'userCounts'              => Licensing_Endpoints::get_user_license_counts(),
240                'activationNoticeDismiss' => Licensing::instance()->get_license_activation_notice_dismiss(),
241            ),
242            'useMyJetpackLicensingUI'              => My_Jetpack_Initializer::is_licensing_ui_enabled(),
243            'isOdysseyStatsEnabled'                => Stats_Options::get_option( 'enable_odyssey_stats' ),
244            'shouldInitializeBlaze'                => Blaze::should_initialize(),
245            'isBlazeDashboardEnabled'              => Blaze::is_dashboard_enabled(),
246            // The composed AI gate chain (host, and the master where its rollout
247            // is active) â€” what the editor enforces, for settings UI that must
248            // not contradict it.
249            'isAiEnabled'                          => Jetpack_AI_Settings::is_ai_enabled(),
250            // The AI SEO feature, gates folded in: controls that drive only its
251            // automatic half must follow it too.
252            'isAiSeoEnabled'                       => Jetpack_AI_Settings::is_ai_seo_enabled(),
253            'isSubscriptionSiteEnabled'            => apply_filters( 'jetpack_subscription_site_enabled', false ),
254            'newsletterDateExample'                => gmdate( get_option( 'date_format' ), time() ),
255            'subscriptionSiteEditSupported'        => $current_theme->is_block_theme(),
256
257            /*
258             * This filter is already documented in jetpack/modules/subscriptions.php.
259             * Defaults on for every site; hosts can opt out with the filter.
260             */
261            'isWpAdminSubscriberManagementEnabled' => apply_filters(
262                'jetpack_wp_admin_subscriber_management_enabled',
263                true
264            ),
265        );
266    }
267
268    /**
269     * Gets array of any Jetpack notices that have been dismissed.
270     *
271     * @return mixed|void
272     */
273    public static function get_dismissed_jetpack_notices() {
274        $jetpack_dismissed_notices = get_option( 'jetpack_dismissed_notices', array() );
275        /**
276         * Array of notices that have been dismissed.
277         *
278         * @param array $jetpack_dismissed_notices If empty, will not show any Jetpack notices.
279         */
280        $dismissed_notices = apply_filters( 'jetpack_dismissed_notices', $jetpack_dismissed_notices );
281        return $dismissed_notices;
282    }
283
284    /**
285     * Returns an array of modules and settings both as first class members of the object.
286     *
287     * @return array flattened settings with modules.
288     */
289    public static function get_flattened_settings() {
290        $core_api_endpoint = new Jetpack_Core_API_Data();
291        $settings          = $core_api_endpoint->get_all_options();
292        return $settings->data;
293    }
294
295    /**
296     * Returns the release post content and image data as an associative array.
297     *
298     * The update modal that consumed this data has been removed, so there is nothing to return.
299     *
300     * @deprecated 16.2
301     *
302     * @return null
303     */
304    public static function get_update_modal_data() {
305        _deprecated_function( __METHOD__, 'jetpack-16.2' );
306        return null;
307    }
308
309    /**
310     * Temporarily allow post content to contain iframes, e.g. for videopress.
311     *
312     * Only ever used while sanitizing the release post for the removed update modal.
313     *
314     * @deprecated 16.2
315     *
316     * @param string $tags    The tags.
317     * @param string $context The context.
318     */
319    public static function allow_post_embed_iframe( $tags, $context ) {
320        _deprecated_function( __METHOD__, 'jetpack-16.2' );
321
322        if ( 'post' === $context ) {
323            $tags['iframe'] = array(
324                'src'             => true,
325                'height'          => true,
326                'width'           => true,
327                'frameborder'     => true,
328                'allowfullscreen' => true,
329            );
330        }
331
332        return $tags;
333    }
334
335    /**
336     * Obtains the release post from the Jetpack release post blog.
337     *
338     * The release post blog has had no post tagged for a current Jetpack version since 2023, and the
339     * update modal that consumed this has been removed, so this no longer makes a remote request.
340     *
341     * @deprecated 16.2
342     *
343     * @return null
344     */
345    public static function get_release_post_data() {
346        _deprecated_function( __METHOD__, 'jetpack-16.2' );
347        return null;
348    }
349
350    /**
351     * Get external services connect URLs.
352     */
353    public static function get_external_services_connect_urls() {
354        $connect_urls = array();
355        foreach ( Keyring_Helper::SERVICES as $service_name => $service_info ) {
356            $connect_urls[ $service_name ] = Keyring_Helper::connect_url( $service_name, $service_info['for'] );
357        }
358        return $connect_urls;
359    }
360
361    /**
362     * Gets a purchase token that is used for Jetpack logged out visitor checkout.
363     * The purchase token should be appended to all CTA url's that lead to checkout.
364     *
365     * @since 9.8.0
366     * @return string|boolean
367     */
368    public static function get_purchase_token() {
369        if ( ! Jetpack::current_user_can_purchase() ) {
370            return false;
371        }
372
373        $purchase_token = Jetpack_Options::get_option( 'purchase_token', false );
374
375        if ( $purchase_token ) {
376            return $purchase_token;
377        }
378        // If the purchase token is not saved in the options table yet, then add it.
379        Jetpack_Options::update_option( 'purchase_token', self::generate_purchase_token(), true );
380        return Jetpack_Options::get_option( 'purchase_token', false );
381    }
382
383    /**
384     * Generates a purchase token that is used for Jetpack logged out visitor checkout.
385     *
386     * @since 9.8.0
387     * @return string
388     */
389    public static function generate_purchase_token() {
390        return wp_generate_password( 12, false );
391    }
392
393    /**
394     * Get a representative image for the site.
395     *
396     * @since 15.0
397     *
398     * @return string
399     */
400    public static function get_site_image(): string {
401        // Get the dynamic image generated for the Open Graph Meta tags.
402        require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
403        return jetpack_og_get_fallback_social_image( 200, 200 )['src'];
404    }
405}
406
407// phpcs:disable Universal.Files.SeparateFunctionsFromOO.Mixed -- TODO: Move these functions to some other file.
408
409/**
410 * Gather data about the current user.
411 *
412 * @since 4.1.0
413 *
414 * @return array
415 */
416function jetpack_current_user_data() {
417    $jetpack_connection = new Connection_Manager( 'jetpack' );
418
419    $current_user      = wp_get_current_user();
420    $is_user_connected = $jetpack_connection->is_user_connected( $current_user->ID );
421    $is_master_user    = $is_user_connected && (int) $current_user->ID && (int) Jetpack_Options::get_option( 'master_user' ) === (int) $current_user->ID;
422    $dotcom_data       = $jetpack_connection->get_connected_user_data();
423
424    // Add connected user gravatar to the returned dotcom_data.
425    // Probably we shouldn't do this when $dotcom_data is false, but we have been since 2016 so
426    // clients probably expect that by now.
427    if ( false === $dotcom_data ) {
428        $dotcom_data = array();
429    }
430    $dotcom_data['avatar'] = ( ! empty( $dotcom_data['email'] ) ?
431        get_avatar_url(
432            $dotcom_data['email'],
433            array(
434                'size'    => 64,
435                'default' => 'mysteryman',
436            )
437        )
438        : false );
439
440    $current_user_data = array(
441        'isConnected' => $is_user_connected,
442        'isMaster'    => $is_master_user,
443        'username'    => $current_user->user_login,
444        'displayName' => $current_user->display_name,
445        'email'       => $current_user->user_email,
446        'id'          => $current_user->ID,
447        'wpcomUser'   => $dotcom_data,
448        'gravatar'    => get_avatar_url( $current_user->ID ),
449        'permissions' => array(
450            'admin_page'         => current_user_can( 'jetpack_admin_page' ),
451            'connect'            => current_user_can( 'jetpack_connect' ),
452            'connect_user'       => current_user_can( 'jetpack_connect_user' ),
453            'disconnect'         => current_user_can( 'jetpack_disconnect' ),
454            'manage_modules'     => current_user_can( 'jetpack_manage_modules' ),
455            'network_admin'      => current_user_can( 'jetpack_network_admin_page' ),
456            'network_sites_page' => current_user_can( 'jetpack_network_sites_page' ),
457            'edit_posts'         => current_user_can( 'edit_posts' ),
458            'publish_posts'      => current_user_can( 'publish_posts' ),
459            'manage_options'     => current_user_can( 'manage_options' ),
460            'view_stats'         => current_user_can( 'view_stats' ),
461            'manage_plugins'     => current_user_can( 'install_plugins' )
462                                    && current_user_can( 'activate_plugins' )
463                                    && current_user_can( 'update_plugins' )
464                                    && current_user_can( 'delete_plugins' ),
465        ),
466    );
467
468    return $current_user_data;
469}