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