Completed
Push — add/sync-partial-sync-checksum... ( 93f4e2...c9ed3f )
by
unknown
253:26 queued 243:12
created

Jetpack_React_Page::page_admin_scripts()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 5
nop 0
dl 0
loc 36
rs 9.0328
c 0
b 0
f 0
1
<?php
2
use Automattic\Jetpack\Constants;
3
use Automattic\Jetpack\Connection\REST_Connector;
4
use Automattic\Jetpack\Licensing;
5
use Automattic\Jetpack\Status;
6
use Automattic\Jetpack\Partner;
7
8
include_once( 'class.jetpack-admin-page.php' );
9
10
// Builds the landing page and its menu
11
class Jetpack_React_Page extends Jetpack_Admin_Page {
12
13
	protected $dont_show_if_not_active = false;
14
15
	protected $is_redirecting = false;
16
17
	function get_page_hook() {
18
		// Add the main admin Jetpack menu
19
		return add_menu_page( 'Jetpack', 'Jetpack', 'jetpack_admin_page', 'jetpack', array( $this, 'render' ), 'div' );
20
	}
21
22
	function add_page_actions( $hook ) {
23
		/** This action is documented in class.jetpack.php */
24
		do_action( 'jetpack_admin_menu', $hook );
25
26
		// Place the Jetpack menu item on top and others in the order they appear
27
		add_filter( 'custom_menu_order',         '__return_true' );
28
		add_filter( 'menu_order',                array( $this, 'jetpack_menu_order' ) );
29
30
		if ( ! isset( $_GET['page'] ) || 'jetpack' !== $_GET['page'] ) {
31
			return; // No need to handle the fallback redirection if we are not on the Jetpack page
32
		}
33
34
		// Adding a redirect meta tag if the REST API is disabled
35
		if ( ! $this->is_rest_api_enabled() ) {
36
			$this->is_redirecting = true;
37
			add_action( 'admin_head', array( $this, 'add_fallback_head_meta' ) );
38
		}
39
40
		// Adding a redirect meta tag wrapped in noscript tags for all browsers in case they have JavaScript disabled
41
		add_action( 'admin_head', array( $this, 'add_noscript_head_meta' ) );
42
43
		// If this is the first time the user is viewing the admin, don't show JITMs.
44
		// This filter is added just in time because this function is called on admin_menu
45
		// and JITMs are initialized on admin_init
46
		if ( Jetpack::is_active() && ! Jetpack_Options::get_option( 'first_admin_view', false ) ) {
47
			Jetpack_Options::update_option( 'first_admin_view', true );
48
			add_filter( 'jetpack_just_in_time_msgs', '__return_false' );
49
		}
50
	}
51
52
	/**
53
	 * Add Jetpack Setup sub-link for eligible users
54
	 */
55
	function jetpack_add_set_up_sub_nav_item() {
56
		if ( $this->show_setup_wizard() ) {
57
			global $submenu;
58
			$submenu['jetpack'][] = array( __( 'Set up', 'jetpack' ), 'jetpack_admin_page', 'admin.php?page=jetpack#/setup' );
59
		}
60
	}
61
62
	/**
63
	 * Add Jetpack Dashboard sub-link and point it to AAG if the user can view stats, manage modules or if Protect is active.
64
	 *
65
	 * Works in Dev Mode or when user is connected.
66
	 *
67
	 * @since 4.3.0
68
	 */
69
	function jetpack_add_dashboard_sub_nav_item() {
70 View Code Duplication
		if ( ( new Status() )->is_offline_mode() || Jetpack::is_active() ) {
71
			global $submenu;
72
			if ( current_user_can( 'jetpack_admin_page' ) ) {
73
				$submenu['jetpack'][] = array( __( 'Dashboard', 'jetpack' ), 'jetpack_admin_page', 'admin.php?page=jetpack#/dashboard' );
74
			}
75
		}
76
	}
77
78
	/**
79
	 * If user is allowed to see the Jetpack Admin, add Settings sub-link.
80
	 *
81
	 * @since 4.3.0
82
	 */
83
	function jetpack_add_settings_sub_nav_item() {
84 View Code Duplication
		if ( ( ( new Status() )->is_offline_mode() || Jetpack::is_active() ) && current_user_can( 'jetpack_admin_page' ) && current_user_can( 'edit_posts' ) ) {
85
			global $submenu;
86
			$submenu['jetpack'][] = array( __( 'Settings', 'jetpack' ), 'jetpack_admin_page', 'admin.php?page=jetpack#/settings' );
87
		}
88
	}
89
90
	function add_fallback_head_meta() {
91
		echo '<meta http-equiv="refresh" content="0; url=?page=jetpack_modules">';
92
	}
93
94
	function add_noscript_head_meta() {
95
		echo '<noscript>';
96
		$this->add_fallback_head_meta();
97
		echo '</noscript>';
98
	}
99
100 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
101
		$jp_menu_order = array();
102
103
		foreach ( $menu_order as $index => $item ) {
104
			if ( $item != 'jetpack' )
105
				$jp_menu_order[] = $item;
106
107
			if ( $index == 0 )
108
				$jp_menu_order[] = 'jetpack';
109
		}
110
111
		return $jp_menu_order;
112
	}
113
114
	function page_render() {
115
		/** This action is already documented in views/admin/admin-page.php */
116
		do_action( 'jetpack_notices' );
117
118
		// Try fetching by patch
119
		$static_html = @file_get_contents( JETPACK__PLUGIN_DIR . '_inc/build/static.html' );
120
121
		if ( false === $static_html ) {
122
123
			// If we still have nothing, display an error
124
			echo '<p>';
125
			esc_html_e( 'Error fetching static.html. Try running: ', 'jetpack' );
126
			echo '<code>yarn distclean && yarn build</code>';
127
			echo '</p>';
128
		} else {
129
130
			// We got the static.html so let's display it
131
			echo $static_html;
132
		}
133
	}
134
135
	/**
136
	 * Gets array of any Jetpack notices that have been dismissed.
137
	 *
138
	 * @since 4.0.1
139
	 * @return mixed|void
140
	 */
141
	function get_dismissed_jetpack_notices() {
142
		$jetpack_dismissed_notices = get_option( 'jetpack_dismissed_notices', array() );
143
		/**
144
		 * Array of notices that have been dismissed.
145
		 *
146
		 * @since 4.0.1
147
		 *
148
		 * @param array $jetpack_dismissed_notices If empty, will not show any Jetpack notices.
149
		 */
150
		$dismissed_notices = apply_filters( 'jetpack_dismissed_notices', $jetpack_dismissed_notices );
151
		return $dismissed_notices;
152
	}
153
154
	function additional_styles() {
155
		Jetpack_Admin_Page::load_wrapper_styles();
156
	}
157
158
	function page_admin_scripts() {
159
		if ( $this->is_redirecting ) {
160
			return; // No need for scripts on a fallback page
161
		}
162
163
164
		$is_offline_mode     = ( new Status() )->is_offline_mode();
165
		$script_deps_path    = JETPACK__PLUGIN_DIR . '_inc/build/admin.asset.php';
166
		$script_dependencies = array( 'wp-polyfill' );
167
		if ( file_exists( $script_deps_path ) ) {
168
			$asset_manifest      = include $script_deps_path;
169
			$script_dependencies = $asset_manifest['dependencies'];
170
		}
171
172
		wp_enqueue_script(
173
			'react-plugin',
174
			plugins_url( '_inc/build/admin.js', JETPACK__PLUGIN_FILE ),
175
			$script_dependencies,
176
			JETPACK__VERSION,
177
			true
178
		);
179
180
		if ( ! $is_offline_mode && Jetpack::is_active() ) {
181
			// Required for Analytics.
182
			wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
183
		}
184
185
		wp_set_script_translations( 'react-plugin', 'jetpack' );
186
187
		// Add objects to be passed to the initial state of the app.
188
		// Use wp_add_inline_script instead of wp_localize_script, see https://core.trac.wordpress.org/ticket/25280.
189
		wp_add_inline_script( 'react-plugin', 'var Initial_State=JSON.parse(decodeURIComponent("' . rawurlencode( wp_json_encode( $this->get_initial_state() ) ) . '"));', 'before' );
190
191
		// This will set the default URL of the jp_redirects lib.
192
		wp_add_inline_script( 'react-plugin', 'var jetpack_redirects = { currentSiteRawUrl: "' . Jetpack::build_raw_urls( get_home_url() ) . '" };', 'before' );
193
	}
194
195
	function get_initial_state() {
196
		global $is_safari;
197
		// Load API endpoint base classes and endpoints for getting the module list fed into the JS Admin Page
198
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-xmlrpc-consumer-endpoint.php';
199
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-module-endpoints.php';
200
		$moduleListEndpoint = new Jetpack_Core_API_Module_List_Endpoint();
201
		$modules = $moduleListEndpoint->get_modules();
202
203
		// Preparing translated fields for JSON encoding by transforming all HTML entities to
204
		// respective characters.
205
		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...
206
			$modules[ $slug ]['name'] = html_entity_decode( $data['name'] );
207
			$modules[ $slug ]['description'] = html_entity_decode( $data['description'] );
208
			$modules[ $slug ]['short_description'] = html_entity_decode( $data['short_description'] );
209
			$modules[ $slug ]['long_description'] = html_entity_decode( $data['long_description'] );
210
		}
211
212
		// Collecting roles that can view site stats.
213
		$stats_roles = array();
214
		$enabled_roles = function_exists( 'stats_get_option' ) ? stats_get_option( 'roles' ) : array( 'administrator' );
215
216
		if ( ! function_exists( 'get_editable_roles' ) ) {
217
			require_once ABSPATH . 'wp-admin/includes/user.php';
218
		}
219
		foreach ( get_editable_roles() as $slug => $role ) {
220
			$stats_roles[ $slug ] = array(
221
				'name' => translate_user_role( $role['name'] ),
222
				'canView' => is_array( $enabled_roles ) ? in_array( $slug, $enabled_roles, true ) : false,
223
			);
224
		}
225
226
		// Get information about current theme.
227
		$current_theme = wp_get_theme();
228
229
		// Get all themes that Infinite Scroll provides support for natively.
230
		$inf_scr_support_themes = array();
231
		foreach ( Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules/infinite-scroll/themes' ) as $path ) {
232
			if ( is_readable( $path ) ) {
233
				$inf_scr_support_themes[] = basename( $path, '.php' );
234
			}
235
		}
236
237
		// Get last post, to build the link to Customizer in the Related Posts module.
238
		$last_post = get_posts( array( 'posts_per_page' => 1 ) );
239
		$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...
240
			? get_permalink( $last_post[0]->ID )
241
			: get_home_url();
242
243
		$current_user_data = jetpack_current_user_data();
244
245
		/**
246
		 * Adds information to the `connectionStatus` API field that is unique to the Jetpack React dashboard.
247
		 */
248
		$connection_status = array(
249
			'isInIdentityCrisis' => Jetpack::validate_sync_error_idc_option(),
250
			'sandboxDomain'      => JETPACK__SANDBOX_DOMAIN,
251
252
			/**
253
			 * Filter to add connection errors
254
			 * Format: array( array( 'code' => '...', 'message' => '...', 'action' => '...' ), ... )
255
			 *
256
			 * @since 8.7.0
257
			 *
258
			 * @param array $errors Connection errors.
259
			 */
260
			'errors'             => apply_filters( 'react_connection_errors_initial_state', array() ),
261
		);
262
263
		$connection_status = array_merge( REST_Connector::connection_status( false ), $connection_status );
264
265
		return array(
266
			'WP_API_root'                 => esc_url_raw( rest_url() ),
267
			'WP_API_nonce'                => wp_create_nonce( 'wp_rest' ),
268
			'pluginBaseUrl'               => plugins_url( '', JETPACK__PLUGIN_FILE ),
269
			'connectionStatus'            => $connection_status,
270
			'connectUrl'                  => false == $current_user_data['isConnected'] // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
271
				? Jetpack::init()->build_connect_url( true, false, false )
272
				: '',
273
			'dismissedNotices'            => $this->get_dismissed_jetpack_notices(),
274
			'isDevVersion'                => Jetpack::is_development_version(),
275
			'currentVersion'              => JETPACK__VERSION,
276
			'is_gutenberg_available'      => true,
277
			'getModules'                  => $modules,
278
			'rawUrl'                      => Jetpack::build_raw_urls( get_home_url() ),
279
			'adminUrl'                    => esc_url( admin_url() ),
280
			'siteTitle'                   => (string) htmlspecialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
281
			'stats'                       => array(
282
				// data is populated asynchronously on page load.
283
				'data'  => array(
284
					'general' => false,
285
					'day'     => false,
286
					'week'    => false,
287
					'month'   => false,
288
				),
289
				'roles' => $stats_roles,
290
			),
291
			'aff'                         => Partner::init()->get_partner_code( Partner::AFFILIATE_CODE ),
292
			'partnerSubsidiaryId'         => Partner::init()->get_partner_code( Partner::SUBSIDIARY_CODE ),
293
			'settings'                    => $this->get_flattened_settings( $modules ),
0 ignored issues
show
Bug introduced by
It seems like $modules defined by $moduleListEndpoint->get_modules() on line 201 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...
294
			'userData'                    => array(
295
				'currentUser' => $current_user_data,
296
			),
297
			'siteData'                    => array(
298
				'icon'                       => has_site_icon()
299
					? 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...
300
					: '',
301
				'siteVisibleToSearchEngines' => '1' == get_option( 'blog_public' ), // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
302
				/**
303
				 * Whether promotions are visible or not.
304
				 *
305
				 * @since 4.8.0
306
				 *
307
				 * @param bool $are_promotions_active Status of promotions visibility. True by default.
308
				 */
309
				'showPromotions'             => apply_filters( 'jetpack_show_promotions', true ),
310
				'isAtomicSite'               => jetpack_is_atomic_site(),
311
				'plan'                       => Jetpack_Plan::get(),
312
				'showBackups'                => Jetpack::show_backups_ui(),
313
				'showSetupWizard'            => $this->show_setup_wizard(),
314
				'isMultisite'                => is_multisite(),
315
				'dateFormat'                 => get_option( 'date_format' ),
316
			),
317
			'themeData'                   => array(
318
				'name'      => $current_theme->get( 'Name' ),
319
				'hasUpdate' => (bool) get_theme_update_available( $current_theme ),
320
				'support'   => array(
321
					'infinite-scroll' => current_theme_supports( 'infinite-scroll' ) || in_array( $current_theme->get_stylesheet(), $inf_scr_support_themes, true ),
322
				),
323
			),
324
			'jetpackStateNotices'         => array(
325
				'messageCode'      => Jetpack::state( 'message' ),
326
				'errorCode'        => Jetpack::state( 'error' ),
327
				'errorDescription' => Jetpack::state( 'error_description' ),
328
				'messageContent'   => Jetpack::state( 'display_update_modal' ) ? $this->get_update_modal_data() : null,
329
			),
330
			'tracksUserData'              => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
331
			'currentIp'                   => function_exists( 'jetpack_protect_get_ip' ) ? jetpack_protect_get_ip() : false,
332
			'lastPostUrl'                 => esc_url( $last_post ),
333
			'externalServicesConnectUrls' => $this->get_external_services_connect_urls(),
334
			'calypsoEnv'                  => Jetpack::get_calypso_env(),
335
			'products'                    => Jetpack::get_products_for_purchase(),
336
			'setupWizardStatus'           => Jetpack_Options::get_option( 'setup_wizard_status', 'not-started' ),
337
			'isSafari'                    => $is_safari,
338
			'doNotUseConnectionIframe'    => Constants::is_true( 'JETPACK_SHOULD_NOT_USE_CONNECTION_IFRAME' ),
339
			'licensing'                   => array(
340
				'error' => Licensing::instance()->last_error(),
341
			),
342
		);
343
	}
344
345
	function get_external_services_connect_urls() {
346
		$connect_urls = array();
347
		jetpack_require_lib( 'class.jetpack-keyring-service-helper' );
348
		foreach ( Jetpack_Keyring_Service_Helper::$SERVICES as $service_name => $service_info ) {
349
			$connect_urls[ $service_name ] = Jetpack_Keyring_Service_Helper::connect_url( $service_name, $service_info[ 'for' ] );
350
		}
351
		return $connect_urls;
352
	}
353
354
	/**
355
	 * Returns an array of modules and settings both as first class members of the object.
356
	 *
357
	 * @param array $modules the result of an API request to get all modules.
358
	 *
359
	 * @return array flattened settings with modules.
360
	 */
361
	function get_flattened_settings( $modules ) {
362
		$core_api_endpoint = new Jetpack_Core_API_Data();
363
		$settings = $core_api_endpoint->get_all_options();
364
		return $settings->data;
365
	}
366
367
368
	/**
369
	 * Returns a boolean for whether the Setup Wizard should be displayed or not.
370
	 *
371
	 * @return bool True if the Setup Wizard should be displayed, false otherwise.
372
	 */
373
	public function show_setup_wizard() {
374
		return Jetpack_Wizard::can_be_displayed();
375
	}
376
377
	/**
378
	 * Returns the release post content and image data as an associative array.
379
	 * This data is used to create the update modal.
380
	 */
381
	public function get_update_modal_data() {
382
		$post_data = $this->get_release_post_data();
383
384
		if ( ! isset( $post_data['posts'][0] ) ) {
385
			return;
386
		}
387
388
		$post = $post_data['posts'][0];
389
390
		if ( empty( $post['content'] ) ) {
391
			return;
392
		}
393
394
		// This allows us to embed videopress videos into the release post.
395
		add_filter( 'wp_kses_allowed_html', array( $this, 'allow_post_embed_iframe' ), 10, 2 );
396
		$content = wp_kses_post( $post['content'] );
397
		remove_filter( 'wp_kses_allowed_html', array( $this, 'allow_post_embed_iframe' ), 10, 2 );
398
399
		$post_title = isset( $post['title'] ) ? $post['title'] : null;
400
		$title      = wp_kses( $post_title, array() );
401
402
		$post_thumbnail = isset( $post['post_thumbnail'] ) ? $post['post_thumbnail'] : null;
403
		if ( ! empty( $post_thumbnail ) ) {
404
			jetpack_require_lib( 'class.jetpack-photon-image' );
405
			$photon_image = new Jetpack_Photon_Image(
406
				array(
407
					'file'   => jetpack_photon_url( $post_thumbnail['URL'] ),
408
					'width'  => $post_thumbnail['width'],
409
					'height' => $post_thumbnail['height'],
410
				),
411
				$post_thumbnail['mime_type']
412
			);
413
			$photon_image->resize(
414
				array(
415
					'width'  => 600,
416
					'height' => null,
417
					'crop'   => false,
418
				)
419
			);
420
			$post_thumbnail_url = $photon_image->get_raw_filename();
421
		} else {
422
			$post_thumbnail_url = null;
423
		}
424
425
		$post_array = array(
426
			'release_post_content'        => $content,
427
			'release_post_featured_image' => $post_thumbnail_url,
428
			'release_post_title'          => $title,
429
		);
430
431
		return $post_array;
432
	}
433
434
	/**
435
	 * Temporarily allow post content to contain iframes, e.g. for videopress.
436
	 *
437
	 * @param string $tags    The tags.
438
	 * @param string $context The context.
439
	 */
440
	public function allow_post_embed_iframe( $tags, $context ) {
441
		if ( 'post' === $context ) {
442
			$tags['iframe'] = array(
443
				'src'             => true,
444
				'height'          => true,
445
				'width'           => true,
446
				'frameborder'     => true,
447
				'allowfullscreen' => true,
448
			);
449
		}
450
451
		return $tags;
452
	}
453
454
	/**
455
	 * Obtains the release post from the Jetpack release post blog. A release post will be displayed in the
456
	 * update modal when a post has a tag equal to the Jetpack version number.
457
	 *
458
	 * The response parameters for the post array can be found here:
459
	 * https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/posts/%24post_ID/#apidoc-response
460
	 *
461
	 * @return array|null Returns an associative array containing the release post data at index ['posts'][0].
462
	 *                    Returns null if the release post data is not available.
463
	 */
464
	private function get_release_post_data() {
465
		if ( Constants::is_defined( 'TESTING_IN_JETPACK' ) && Constants::get_constant( 'TESTING_IN_JETPACK' ) ) {
466
			return null;
467
		}
468
469
		$release_post_src = add_query_arg(
470
			array(
471
				'order_by' => 'date',
472
				'tag'      => JETPACK__VERSION,
473
				'number'   => '1',
474
			),
475
			'https://public-api.wordpress.com/rest/v1/sites/' . JETPACK__RELEASE_POST_BLOG_SLUG . '/posts'
476
		);
477
478
		$response = wp_remote_get( $release_post_src );
479
480
		if ( ! is_array( $response ) ) {
481
			return null;
482
		}
483
484
		return json_decode( wp_remote_retrieve_body( $response ), true );
485
	}
486
}
487
488
/**
489
 * Gather data about the current user.
490
 *
491
 * @since 4.1.0
492
 *
493
 * @return array
494
 */
495
function jetpack_current_user_data() {
496
	$current_user   = wp_get_current_user();
497
	$is_master_user = $current_user->ID == Jetpack_Options::get_option( 'master_user' );
498
	$dotcom_data    = Jetpack::get_connected_user_data();
499
500
	// Add connected user gravatar to the returned dotcom_data.
501
	$dotcom_data['avatar'] = ( ! empty( $dotcom_data['email'] ) ?
502
		get_avatar_url(
503
			$dotcom_data['email'],
504
			array(
505
				'size'    => 64,
506
				'default' => 'mysteryman',
507
			)
508
		)
509
		: false );
510
511
	$current_user_data = array(
512
		'isConnected' => Jetpack::is_user_connected( $current_user->ID ),
513
		'isMaster'    => $is_master_user,
514
		'username'    => $current_user->user_login,
515
		'id'          => $current_user->ID,
516
		'wpcomUser'   => $dotcom_data,
517
		'gravatar'    => get_avatar_url( $current_user->ID, 64, 'mm', '', array( 'force_display' => true ) ),
518
		'permissions' => array(
519
			'admin_page'         => current_user_can( 'jetpack_admin_page' ),
520
			'connect'            => current_user_can( 'jetpack_connect' ),
521
			'disconnect'         => current_user_can( 'jetpack_disconnect' ),
522
			'manage_modules'     => current_user_can( 'jetpack_manage_modules' ),
523
			'network_admin'      => current_user_can( 'jetpack_network_admin_page' ),
524
			'network_sites_page' => current_user_can( 'jetpack_network_sites_page' ),
525
			'edit_posts'         => current_user_can( 'edit_posts' ),
526
			'publish_posts'      => current_user_can( 'publish_posts' ),
527
			'manage_options'     => current_user_can( 'manage_options' ),
528
			'view_stats'		 => current_user_can( 'view_stats' ),
529
			'manage_plugins'	 => current_user_can( 'install_plugins' )
530
									&& current_user_can( 'activate_plugins' )
531
									&& current_user_can( 'update_plugins' )
532
									&& current_user_can( 'delete_plugins' ),
533
		),
534
	);
535
536
	return $current_user_data;
537
}
538