Completed
Push — add/testing-info ( be1095...03b7e9 )
by
unknown
09:20
created

Jetpack_React_Page::add_noscript_head_meta()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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