PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 16.3-a.3
Jetpack – WP Security, Backup, Speed, & Growth v16.3-a.3
16.3-a.5 16.3-a.7 16.3-a.3 16.3-a.1 16.2 16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 All 506 releases
jetpack / _inc / lib / admin-pages / class-jetpack-redux-state-helper.php

class-jetpack-redux-state-helper.php in Jetpack – WP Security, Backup, Speed, & Growth 16.3-a.3, at _inc/lib/admin-pages/class-jetpack-redux-state-helper.php

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