Completed
Push — renovate/node-12.x ( 02b777...439792 )
by
unknown
45:19 queued 36:16
created

Jetpack_React_Page   C

Complexity

Total Complexity 56

Size/Duplication

Total Lines 449
Duplicated Lines 1.56 %

Coupling/Cohesion

Components 1
Dependencies 16

Importance

Changes 0
Metric Value
dl 7
loc 449
rs 5.5199
c 0
b 0
f 0
wmc 56
lcom 1
cbo 16

17 Methods

Rating   Name   Duplication   Size   Complexity  
A get_page_hook() 0 4 1
B add_page_actions() 0 25 6
A jetpack_add_dashboard_sub_nav_item() 4 6 3
A jetpack_add_settings_sub_nav_item() 3 5 4
A add_fallback_head_meta() 0 3 1
A add_noscript_head_meta() 0 5 1
A jetpack_menu_order() 0 5 1
A page_render() 0 20 2
A get_dismissed_jetpack_notices() 0 12 1
A additional_styles() 0 3 1
A page_admin_scripts() 0 37 5
F get_initial_state() 0 149 15
A get_external_services_connect_urls() 0 8 2
A get_flattened_settings() 0 5 1
B get_update_modal_data() 0 52 6
A allow_post_embed_iframe() 0 13 2
A get_release_post_data() 0 22 4

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Jetpack_React_Page often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Jetpack_React_Page, and based on these observations, apply Extract Interface, too.

1
<?php
2
use Automattic\Jetpack\Constants;
3
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
4
use Automattic\Jetpack\Connection\REST_Connector;
5
use Automattic\Jetpack\Licensing;
6
use Automattic\Jetpack\Partner;
7
use Automattic\Jetpack\Status;
8
9
include_once( 'class.jetpack-admin-page.php' );
10
11
// Builds the landing page and its menu
12
class Jetpack_React_Page extends Jetpack_Admin_Page {
13
14
	protected $dont_show_if_not_active = false;
15
16
	protected $is_redirecting = false;
17
18
	function get_page_hook() {
19
		// Add the main admin Jetpack menu
20
		return add_menu_page( 'Jetpack', 'Jetpack', 'jetpack_admin_page', 'jetpack', array( $this, 'render' ), 'div', 3 );
21
	}
22
23
	function add_page_actions( $hook ) {
24
		/** This action is documented in class.jetpack.php */
25
		do_action( 'jetpack_admin_menu', $hook );
26
27
		if ( ! isset( $_GET['page'] ) || 'jetpack' !== $_GET['page'] ) {
28
			return; // No need to handle the fallback redirection if we are not on the Jetpack page
29
		}
30
31
		// Adding a redirect meta tag if the REST API is disabled
32
		if ( ! $this->is_rest_api_enabled() ) {
33
			$this->is_redirecting = true;
34
			add_action( 'admin_head', array( $this, 'add_fallback_head_meta' ) );
35
		}
36
37
		// Adding a redirect meta tag wrapped in noscript tags for all browsers in case they have JavaScript disabled
38
		add_action( 'admin_head', array( $this, 'add_noscript_head_meta' ) );
39
40
		// If this is the first time the user is viewing the admin, don't show JITMs.
41
		// This filter is added just in time because this function is called on admin_menu
42
		// and JITMs are initialized on admin_init
43
		if ( Jetpack::is_active() && ! Jetpack_Options::get_option( 'first_admin_view', false ) ) {
44
			Jetpack_Options::update_option( 'first_admin_view', true );
45
			add_filter( 'jetpack_just_in_time_msgs', '__return_false' );
46
		}
47
	}
48
49
	/**
50
	 * Add Jetpack Dashboard sub-link and point it to AAG if the user can view stats, manage modules or if Protect is active.
51
	 *
52
	 * Works in Dev Mode or when user is connected.
53
	 *
54
	 * @since 4.3.0
55
	 */
56
	function jetpack_add_dashboard_sub_nav_item() {
57 View Code Duplication
		if ( ( new Status() )->is_offline_mode() || Jetpack::is_active() ) {
58
			add_submenu_page( 'jetpack', __( 'Dashboard', 'jetpack' ), __( 'Dashboard', 'jetpack' ), 'jetpack_admin_page', 'jetpack#/dashboard', '__return_null' );
59
			remove_submenu_page( 'jetpack', 'jetpack' );
60
		}
61
	}
62
63
	/**
64
	 * If user is allowed to see the Jetpack Admin, add Settings sub-link.
65
	 *
66
	 * @since 4.3.0
67
	 */
68
	function jetpack_add_settings_sub_nav_item() {
69 View Code Duplication
		if ( ( ( new Status() )->is_offline_mode() || Jetpack::is_active() ) && current_user_can( 'edit_posts' ) ) {
70
			add_submenu_page( 'jetpack', __( 'Settings', 'jetpack' ), __( 'Settings', 'jetpack' ), 'jetpack_admin_page', 'jetpack#/settings', '__return_null' );
71
		}
72
	}
73
74
	function add_fallback_head_meta() {
75
		echo '<meta http-equiv="refresh" content="0; url=?page=jetpack_modules">';
76
	}
77
78
	function add_noscript_head_meta() {
79
		echo '<noscript>';
80
		$this->add_fallback_head_meta();
81
		echo '</noscript>';
82
	}
83
84
	/**
85
	 * Custom menu order.
86
	 *
87
	 * @deprecated since 9.2.0
88
	 * @param array $menu_order Menu order.
89
	 * @return array
90
	 */
91
	function jetpack_menu_order( $menu_order ) {
92
		_deprecated_function( __METHOD__, 'jetpack-9.2' );
93
94
		return $menu_order;
95
	}
96
97
	function page_render() {
98
		/** This action is already documented in views/admin/admin-page.php */
99
		do_action( 'jetpack_notices' );
100
101
		// Try fetching by patch
102
		$static_html = @file_get_contents( JETPACK__PLUGIN_DIR . '_inc/build/static.html' );
103
104
		if ( false === $static_html ) {
105
106
			// If we still have nothing, display an error
107
			echo '<p>';
108
			esc_html_e( 'Error fetching static.html. Try running: ', 'jetpack' );
109
			echo '<code>yarn distclean && yarn build</code>';
110
			echo '</p>';
111
		} else {
112
113
			// We got the static.html so let's display it
114
			echo $static_html;
115
		}
116
	}
117
118
	/**
119
	 * Gets array of any Jetpack notices that have been dismissed.
120
	 *
121
	 * @since 4.0.1
122
	 * @return mixed|void
123
	 */
124
	function get_dismissed_jetpack_notices() {
125
		$jetpack_dismissed_notices = get_option( 'jetpack_dismissed_notices', array() );
126
		/**
127
		 * Array of notices that have been dismissed.
128
		 *
129
		 * @since 4.0.1
130
		 *
131
		 * @param array $jetpack_dismissed_notices If empty, will not show any Jetpack notices.
132
		 */
133
		$dismissed_notices = apply_filters( 'jetpack_dismissed_notices', $jetpack_dismissed_notices );
134
		return $dismissed_notices;
135
	}
136
137
	function additional_styles() {
138
		Jetpack_Admin_Page::load_wrapper_styles();
139
	}
140
141
	function page_admin_scripts() {
142
		if ( $this->is_redirecting ) {
143
			return; // No need for scripts on a fallback page
144
		}
145
146
		$status              = new Status();
147
		$is_offline_mode     = $status->is_offline_mode();
148
		$site_suffix         = $status->get_site_suffix();
149
		$script_deps_path    = JETPACK__PLUGIN_DIR . '_inc/build/admin.asset.php';
150
		$script_dependencies = array( 'wp-polyfill' );
151
		if ( file_exists( $script_deps_path ) ) {
152
			$asset_manifest      = include $script_deps_path;
153
			$script_dependencies = $asset_manifest['dependencies'];
154
		}
155
156
		wp_enqueue_script(
157
			'react-plugin',
158
			plugins_url( '_inc/build/admin.js', JETPACK__PLUGIN_FILE ),
159
			$script_dependencies,
160
			JETPACK__VERSION,
161
			true
162
		);
163
164
		if ( ! $is_offline_mode && Jetpack::is_active() ) {
165
			// Required for Analytics.
166
			wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
167
		}
168
169
		wp_set_script_translations( 'react-plugin', 'jetpack' );
170
171
		// Add objects to be passed to the initial state of the app.
172
		// Use wp_add_inline_script instead of wp_localize_script, see https://core.trac.wordpress.org/ticket/25280.
173
		wp_add_inline_script( 'react-plugin', 'var Initial_State=JSON.parse(decodeURIComponent("' . rawurlencode( wp_json_encode( $this->get_initial_state() ) ) . '"));', 'before' );
174
175
		// This will set the default URL of the jp_redirects lib.
176
		wp_add_inline_script( 'react-plugin', 'var jetpack_redirects = { currentSiteRawUrl: "' . $site_suffix . '" };', 'before' );
177
	}
178
179
	function get_initial_state() {
180
		global $is_safari;
181
		// Load API endpoint base classes and endpoints for getting the module list fed into the JS Admin Page
182
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-xmlrpc-consumer-endpoint.php';
183
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-module-endpoints.php';
184
		$moduleListEndpoint = new Jetpack_Core_API_Module_List_Endpoint();
185
		$modules = $moduleListEndpoint->get_modules();
186
187
		// Preparing translated fields for JSON encoding by transforming all HTML entities to
188
		// respective characters.
189
		foreach( $modules as $slug => $data ) {
0 ignored issues
show
Bug introduced by
The expression $modules of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
190
			$modules[ $slug ]['name'] = html_entity_decode( $data['name'] );
191
			$modules[ $slug ]['description'] = html_entity_decode( $data['description'] );
192
			$modules[ $slug ]['short_description'] = html_entity_decode( $data['short_description'] );
193
			$modules[ $slug ]['long_description'] = html_entity_decode( $data['long_description'] );
194
		}
195
196
		// Collecting roles that can view site stats.
197
		$stats_roles = array();
198
		$enabled_roles = function_exists( 'stats_get_option' ) ? stats_get_option( 'roles' ) : array( 'administrator' );
199
200
		if ( ! function_exists( 'get_editable_roles' ) ) {
201
			require_once ABSPATH . 'wp-admin/includes/user.php';
202
		}
203
		foreach ( get_editable_roles() as $slug => $role ) {
204
			$stats_roles[ $slug ] = array(
205
				'name' => translate_user_role( $role['name'] ),
206
				'canView' => is_array( $enabled_roles ) ? in_array( $slug, $enabled_roles, true ) : false,
207
			);
208
		}
209
210
		// Get information about current theme.
211
		$current_theme = wp_get_theme();
212
213
		// Get all themes that Infinite Scroll provides support for natively.
214
		$inf_scr_support_themes = array();
215
		foreach ( Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules/infinite-scroll/themes' ) as $path ) {
216
			if ( is_readable( $path ) ) {
217
				$inf_scr_support_themes[] = basename( $path, '.php' );
218
			}
219
		}
220
221
		// Get last post, to build the link to Customizer in the Related Posts module.
222
		$last_post = get_posts( array( 'posts_per_page' => 1 ) );
223
		$last_post = isset( $last_post[0] ) && $last_post[0] instanceof WP_Post
0 ignored issues
show
Bug introduced by
The class WP_Post does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
224
			? get_permalink( $last_post[0]->ID )
225
			: get_home_url();
226
227
		$current_user_data = jetpack_current_user_data();
228
229
		/**
230
		 * Adds information to the `connectionStatus` API field that is unique to the Jetpack React dashboard.
231
		 */
232
		$connection_status = array(
233
			'isInIdentityCrisis' => Jetpack::validate_sync_error_idc_option(),
234
			'sandboxDomain'      => JETPACK__SANDBOX_DOMAIN,
235
236
			/**
237
			 * Filter to add connection errors
238
			 * Format: array( array( 'code' => '...', 'message' => '...', 'action' => '...' ), ... )
239
			 *
240
			 * @since 8.7.0
241
			 *
242
			 * @param array $errors Connection errors.
243
			 */
244
			'errors'             => apply_filters( 'react_connection_errors_initial_state', array() ),
245
		);
246
247
		$connection_status = array_merge( REST_Connector::connection_status( false ), $connection_status );
248
249
		return array(
250
			'WP_API_root'                 => esc_url_raw( rest_url() ),
251
			'WP_API_nonce'                => wp_create_nonce( 'wp_rest' ),
252
			'pluginBaseUrl'               => plugins_url( '', JETPACK__PLUGIN_FILE ),
253
			'connectionStatus'            => $connection_status,
254
			'connectUrl'                  => false == $current_user_data['isConnected'] // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
255
				? Jetpack::init()->build_connect_url( true, false, false )
256
				: '',
257
			'dismissedNotices'            => $this->get_dismissed_jetpack_notices(),
258
			'isDevVersion'                => Jetpack::is_development_version(),
259
			'currentVersion'              => JETPACK__VERSION,
260
			'is_gutenberg_available'      => true,
261
			'getModules'                  => $modules,
262
			'rawUrl'                      => ( new Status() )->get_site_suffix(),
263
			'adminUrl'                    => esc_url( admin_url() ),
264
			'siteTitle'                   => (string) htmlspecialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
265
			'stats'                       => array(
266
				// data is populated asynchronously on page load.
267
				'data'  => array(
268
					'general' => false,
269
					'day'     => false,
270
					'week'    => false,
271
					'month'   => false,
272
				),
273
				'roles' => $stats_roles,
274
			),
275
			'aff'                         => Partner::init()->get_partner_code( Partner::AFFILIATE_CODE ),
276
			'partnerSubsidiaryId'         => Partner::init()->get_partner_code( Partner::SUBSIDIARY_CODE ),
277
			'settings'                    => $this->get_flattened_settings( $modules ),
0 ignored issues
show
Bug introduced by
It seems like $modules defined by $moduleListEndpoint->get_modules() on line 185 can also be of type string; however, Jetpack_React_Page::get_flattened_settings() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
278
			'userData'                    => array(
279
				'currentUser' => $current_user_data,
280
			),
281
			'siteData'                    => array(
282
				'icon'                       => has_site_icon()
283
					? apply_filters( 'jetpack_photon_url', get_site_icon_url(), array( 'w' => 64 ) )
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with array('w' => 64).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
284
					: '',
285
				'siteVisibleToSearchEngines' => '1' == get_option( 'blog_public' ), // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
286
				/**
287
				 * Whether promotions are visible or not.
288
				 *
289
				 * @since 4.8.0
290
				 *
291
				 * @param bool $are_promotions_active Status of promotions visibility. True by default.
292
				 */
293
				'showPromotions'             => apply_filters( 'jetpack_show_promotions', true ),
294
				'isAtomicSite'               => jetpack_is_atomic_site(),
295
				'plan'                       => Jetpack_Plan::get(),
296
				'showBackups'                => Jetpack::show_backups_ui(),
297
				'showRecommendations'        => Jetpack_Recommendations::is_enabled(),
298
				'isMultisite'                => is_multisite(),
299
				'dateFormat'                 => get_option( 'date_format' ),
300
			),
301
			'themeData'                   => array(
302
				'name'      => $current_theme->get( 'Name' ),
303
				'hasUpdate' => (bool) get_theme_update_available( $current_theme ),
304
				'support'   => array(
305
					'infinite-scroll' => current_theme_supports( 'infinite-scroll' ) || in_array( $current_theme->get_stylesheet(), $inf_scr_support_themes, true ),
306
				),
307
			),
308
			'jetpackStateNotices'         => array(
309
				'messageCode'      => Jetpack::state( 'message' ),
310
				'errorCode'        => Jetpack::state( 'error' ),
311
				'errorDescription' => Jetpack::state( 'error_description' ),
312
				'messageContent'   => Jetpack::state( 'display_update_modal' ) ? $this->get_update_modal_data() : null,
313
			),
314
			'tracksUserData'              => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
315
			'currentIp'                   => function_exists( 'jetpack_protect_get_ip' ) ? jetpack_protect_get_ip() : false,
316
			'lastPostUrl'                 => esc_url( $last_post ),
317
			'externalServicesConnectUrls' => $this->get_external_services_connect_urls(),
318
			'calypsoEnv'                  => Jetpack::get_calypso_env(),
319
			'products'                    => Jetpack::get_products_for_purchase(),
320
			'recommendationsStep'         => Jetpack_Core_Json_Api_Endpoints::get_recommendations_step()['step'],
321
			'isSafari'                    => $is_safari,
322
			'doNotUseConnectionIframe'    => Constants::is_true( 'JETPACK_SHOULD_NOT_USE_CONNECTION_IFRAME' ),
323
			'licensing'                   => array(
324
				'error' => Licensing::instance()->last_error(),
325
			),
326
		);
327
	}
328
329
	function get_external_services_connect_urls() {
330
		$connect_urls = array();
331
		jetpack_require_lib( 'class.jetpack-keyring-service-helper' );
332
		foreach ( Jetpack_Keyring_Service_Helper::$SERVICES as $service_name => $service_info ) {
333
			$connect_urls[ $service_name ] = Jetpack_Keyring_Service_Helper::connect_url( $service_name, $service_info[ 'for' ] );
334
		}
335
		return $connect_urls;
336
	}
337
338
	/**
339
	 * Returns an array of modules and settings both as first class members of the object.
340
	 *
341
	 * @param array $modules the result of an API request to get all modules.
342
	 *
343
	 * @return array flattened settings with modules.
344
	 */
345
	function get_flattened_settings( $modules ) {
346
		$core_api_endpoint = new Jetpack_Core_API_Data();
347
		$settings = $core_api_endpoint->get_all_options();
348
		return $settings->data;
349
	}
350
351
	/**
352
	 * Returns the release post content and image data as an associative array.
353
	 * This data is used to create the update modal.
354
	 */
355
	public function get_update_modal_data() {
356
		$post_data = $this->get_release_post_data();
357
358
		if ( ! isset( $post_data['posts'][0] ) ) {
359
			return;
360
		}
361
362
		$post = $post_data['posts'][0];
363
364
		if ( empty( $post['content'] ) ) {
365
			return;
366
		}
367
368
		// This allows us to embed videopress videos into the release post.
369
		add_filter( 'wp_kses_allowed_html', array( $this, 'allow_post_embed_iframe' ), 10, 2 );
370
		$content = wp_kses_post( $post['content'] );
371
		remove_filter( 'wp_kses_allowed_html', array( $this, 'allow_post_embed_iframe' ), 10, 2 );
0 ignored issues
show
Unused Code introduced by
The call to remove_filter() has too many arguments starting with 2.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
372
373
		$post_title = isset( $post['title'] ) ? $post['title'] : null;
374
		$title      = wp_kses( $post_title, array() );
375
376
		$post_thumbnail = isset( $post['post_thumbnail'] ) ? $post['post_thumbnail'] : null;
377
		if ( ! empty( $post_thumbnail ) ) {
378
			jetpack_require_lib( 'class.jetpack-photon-image' );
379
			$photon_image = new Jetpack_Photon_Image(
380
				array(
381
					'file'   => jetpack_photon_url( $post_thumbnail['URL'] ),
382
					'width'  => $post_thumbnail['width'],
383
					'height' => $post_thumbnail['height'],
384
				),
385
				$post_thumbnail['mime_type']
386
			);
387
			$photon_image->resize(
388
				array(
389
					'width'  => 600,
390
					'height' => null,
391
					'crop'   => false,
392
				)
393
			);
394
			$post_thumbnail_url = $photon_image->get_raw_filename();
395
		} else {
396
			$post_thumbnail_url = null;
397
		}
398
399
		$post_array = array(
400
			'release_post_content'        => $content,
401
			'release_post_featured_image' => $post_thumbnail_url,
402
			'release_post_title'          => $title,
403
		);
404
405
		return $post_array;
406
	}
407
408
	/**
409
	 * Temporarily allow post content to contain iframes, e.g. for videopress.
410
	 *
411
	 * @param string $tags    The tags.
412
	 * @param string $context The context.
413
	 */
414
	public function allow_post_embed_iframe( $tags, $context ) {
415
		if ( 'post' === $context ) {
416
			$tags['iframe'] = array(
417
				'src'             => true,
418
				'height'          => true,
419
				'width'           => true,
420
				'frameborder'     => true,
421
				'allowfullscreen' => true,
422
			);
423
		}
424
425
		return $tags;
426
	}
427
428
	/**
429
	 * Obtains the release post from the Jetpack release post blog. A release post will be displayed in the
430
	 * update modal when a post has a tag equal to the Jetpack version number.
431
	 *
432
	 * The response parameters for the post array can be found here:
433
	 * https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/posts/%24post_ID/#apidoc-response
434
	 *
435
	 * @return array|null Returns an associative array containing the release post data at index ['posts'][0].
436
	 *                    Returns null if the release post data is not available.
437
	 */
438
	private function get_release_post_data() {
439
		if ( Constants::is_defined( 'TESTING_IN_JETPACK' ) && Constants::get_constant( 'TESTING_IN_JETPACK' ) ) {
440
			return null;
441
		}
442
443
		$release_post_src = add_query_arg(
444
			array(
445
				'order_by' => 'date',
446
				'tag'      => JETPACK__VERSION,
447
				'number'   => '1',
448
			),
449
			'https://public-api.wordpress.com/rest/v1/sites/' . JETPACK__RELEASE_POST_BLOG_SLUG . '/posts'
450
		);
451
452
		$response = wp_remote_get( $release_post_src );
453
454
		if ( ! is_array( $response ) ) {
455
			return null;
456
		}
457
458
		return json_decode( wp_remote_retrieve_body( $response ), true );
459
	}
460
}
461
462
/**
463
 * Gather data about the current user.
464
 *
465
 * @since 4.1.0
466
 *
467
 * @return array
468
 */
469
function jetpack_current_user_data() {
470
	$jetpack_connection = new Connection_Manager( 'jetpack' );
471
472
	$current_user   = wp_get_current_user();
473
	$is_master_user = $current_user->ID == Jetpack_Options::get_option( 'master_user' );
474
	$dotcom_data    = $jetpack_connection->get_connected_user_data();
475
476
	// Add connected user gravatar to the returned dotcom_data.
477
	$dotcom_data['avatar'] = ( ! empty( $dotcom_data['email'] ) ?
478
		get_avatar_url(
479
			$dotcom_data['email'],
480
			array(
481
				'size'    => 64,
482
				'default' => 'mysteryman',
483
			)
484
		)
485
		: false );
486
487
	$current_user_data = array(
488
		'isConnected' => $jetpack_connection->is_user_connected( $current_user->ID ),
489
		'isMaster'    => $is_master_user,
490
		'username'    => $current_user->user_login,
491
		'id'          => $current_user->ID,
492
		'wpcomUser'   => $dotcom_data,
493
		'gravatar'    => get_avatar_url( $current_user->ID, 64, 'mm', '', array( 'force_display' => true ) ),
494
		'permissions' => array(
495
			'admin_page'         => current_user_can( 'jetpack_admin_page' ),
496
			'connect'            => current_user_can( 'jetpack_connect' ),
497
			'connect_user'       => current_user_can( 'jetpack_connect_user' ),
498
			'disconnect'         => current_user_can( 'jetpack_disconnect' ),
499
			'manage_modules'     => current_user_can( 'jetpack_manage_modules' ),
500
			'network_admin'      => current_user_can( 'jetpack_network_admin_page' ),
501
			'network_sites_page' => current_user_can( 'jetpack_network_sites_page' ),
502
			'edit_posts'         => current_user_can( 'edit_posts' ),
503
			'publish_posts'      => current_user_can( 'publish_posts' ),
504
			'manage_options'     => current_user_can( 'manage_options' ),
505
			'view_stats'         => current_user_can( 'view_stats' ),
506
			'manage_plugins'     => current_user_can( 'install_plugins' )
507
									&& current_user_can( 'activate_plugins' )
508
									&& current_user_can( 'update_plugins' )
509
									&& current_user_can( 'delete_plugins' ),
510
		),
511
	);
512
513
	return $current_user_data;
514
}
515