Completed
Push — try/add-jetpack-purchase-token ( dd3973...a226ea )
by
unknown
37:20 queued 21:00
created

Jetpack_React_Page::generate_purchase_token()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
203
		return Jetpack_Options::get_option( 'purchase_token', false );
204
	}
205
206
	/**
207
	 * Generates a purchase token that is used for Jetpack logged out visitor checkout.
208
	 *
209
	 * @since 9.8.0
210
	 * @return string
211
	 */
212
	public function generate_purchase_token() {
213
		return wp_generate_password( 12, false );
214
	}
215
216
	function get_initial_state() {
217
		global $is_safari;
218
219
		// Load API endpoint base classes and endpoints for getting the module list fed into the JS Admin Page
220
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-xmlrpc-consumer-endpoint.php';
221
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-module-endpoints.php';
222
		$moduleListEndpoint = new Jetpack_Core_API_Module_List_Endpoint();
223
		$modules = $moduleListEndpoint->get_modules();
224
225
		// Preparing translated fields for JSON encoding by transforming all HTML entities to
226
		// respective characters.
227
		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...
228
			$modules[ $slug ]['name'] = html_entity_decode( $data['name'] );
229
			$modules[ $slug ]['description'] = html_entity_decode( $data['description'] );
230
			$modules[ $slug ]['short_description'] = html_entity_decode( $data['short_description'] );
231
			$modules[ $slug ]['long_description'] = html_entity_decode( $data['long_description'] );
232
		}
233
234
		// Collecting roles that can view site stats.
235
		$stats_roles = array();
236
		$enabled_roles = function_exists( 'stats_get_option' ) ? stats_get_option( 'roles' ) : array( 'administrator' );
237
238
		if ( ! function_exists( 'get_editable_roles' ) ) {
239
			require_once ABSPATH . 'wp-admin/includes/user.php';
240
		}
241
		foreach ( get_editable_roles() as $slug => $role ) {
242
			$stats_roles[ $slug ] = array(
243
				'name' => translate_user_role( $role['name'] ),
244
				'canView' => is_array( $enabled_roles ) ? in_array( $slug, $enabled_roles, true ) : false,
245
			);
246
		}
247
248
		// Get information about current theme.
249
		$current_theme = wp_get_theme();
250
251
		// Get all themes that Infinite Scroll provides support for natively.
252
		$inf_scr_support_themes = array();
253
		foreach ( Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules/infinite-scroll/themes' ) as $path ) {
254
			if ( is_readable( $path ) ) {
255
				$inf_scr_support_themes[] = basename( $path, '.php' );
256
			}
257
		}
258
259
		// Get last post, to build the link to Customizer in the Related Posts module.
260
		$last_post = get_posts( array( 'posts_per_page' => 1 ) );
261
		$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...
262
			? get_permalink( $last_post[0]->ID )
263
			: get_home_url();
264
265
		$current_user_data = jetpack_current_user_data();
266
267
		/**
268
		 * Adds information to the `connectionStatus` API field that is unique to the Jetpack React dashboard.
269
		 */
270
		$connection_status = array(
271
			'isInIdentityCrisis' => Jetpack::validate_sync_error_idc_option(),
272
			'sandboxDomain'      => JETPACK__SANDBOX_DOMAIN,
273
274
			/**
275
			 * Filter to add connection errors
276
			 * Format: array( array( 'code' => '...', 'message' => '...', 'action' => '...' ), ... )
277
			 *
278
			 * @since 8.7.0
279
			 *
280
			 * @param array $errors Connection errors.
281
			 */
282
			'errors'             => apply_filters( 'react_connection_errors_initial_state', array() ),
283
		);
284
285
		$connection_status = array_merge( REST_Connector::connection_status( false ), $connection_status );
286
287
		return array(
288
			'WP_API_root'                 => esc_url_raw( rest_url() ),
289
			'WP_API_nonce'                => wp_create_nonce( 'wp_rest' ),
290
			'purchaseToken'               => $this->get_purchase_token(),
291
			'pluginBaseUrl'               => plugins_url( '', JETPACK__PLUGIN_FILE ),
292
			'connectionStatus'            => $connection_status,
293
			'connectUrl'                  => false == $current_user_data['isConnected'] // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
294
				? Jetpack::init()->build_connect_url( true, false, false )
295
				: '',
296
			'dismissedNotices'            => $this->get_dismissed_jetpack_notices(),
297
			'isDevVersion'                => Jetpack::is_development_version(),
298
			'currentVersion'              => JETPACK__VERSION,
299
			'is_gutenberg_available'      => true,
300
			'getModules'                  => $modules,
301
			'rawUrl'                      => ( new Status() )->get_site_suffix(),
302
			'adminUrl'                    => esc_url( admin_url() ),
303
			'siteTitle'                   => (string) htmlspecialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
304
			'stats'                       => array(
305
				// data is populated asynchronously on page load.
306
				'data'  => array(
307
					'general' => false,
308
					'day'     => false,
309
					'week'    => false,
310
					'month'   => false,
311
				),
312
				'roles' => $stats_roles,
313
			),
314
			'aff'                         => Partner::init()->get_partner_code( Partner::AFFILIATE_CODE ),
315
			'partnerSubsidiaryId'         => Partner::init()->get_partner_code( Partner::SUBSIDIARY_CODE ),
316
			'settings'                    => $this->get_flattened_settings( $modules ),
0 ignored issues
show
Bug introduced by
It seems like $modules defined by $moduleListEndpoint->get_modules() on line 223 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...
317
			'userData'                    => array(
318
				'currentUser' => $current_user_data,
319
			),
320
			'siteData'                    => array(
321
				'icon'                       => has_site_icon()
322
					? 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...
323
					: '',
324
				'siteVisibleToSearchEngines' => '1' == get_option( 'blog_public' ), // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison
325
				/**
326
				 * Whether promotions are visible or not.
327
				 *
328
				 * @since 4.8.0
329
				 *
330
				 * @param bool $are_promotions_active Status of promotions visibility. True by default.
331
				 */
332
				'showPromotions'             => apply_filters( 'jetpack_show_promotions', true ),
333
				'isAtomicSite'               => jetpack_is_atomic_site(),
334
				'plan'                       => Jetpack_Plan::get(),
335
				'showBackups'                => Jetpack::show_backups_ui(),
336
				'showRecommendations'        => Jetpack_Recommendations::is_enabled(),
337
				'isMultisite'                => is_multisite(),
338
				'dateFormat'                 => get_option( 'date_format' ),
339
			),
340
			'themeData'                   => array(
341
				'name'      => $current_theme->get( 'Name' ),
342
				'hasUpdate' => (bool) get_theme_update_available( $current_theme ),
343
				'support'   => array(
344
					'infinite-scroll' => current_theme_supports( 'infinite-scroll' ) || in_array( $current_theme->get_stylesheet(), $inf_scr_support_themes, true ),
345
				),
346
			),
347
			'jetpackStateNotices'         => array(
348
				'messageCode'      => Jetpack::state( 'message' ),
349
				'errorCode'        => Jetpack::state( 'error' ),
350
				'errorDescription' => Jetpack::state( 'error_description' ),
351
				'messageContent'   => Jetpack::state( 'display_update_modal' ) ? $this->get_update_modal_data() : null,
352
			),
353
			'tracksUserData'              => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
354
			'currentIp'                   => function_exists( 'jetpack_protect_get_ip' ) ? jetpack_protect_get_ip() : false,
355
			'lastPostUrl'                 => esc_url( $last_post ),
356
			'externalServicesConnectUrls' => $this->get_external_services_connect_urls(),
357
			'calypsoEnv'                  => Jetpack::get_calypso_env(),
358
			'products'                    => Jetpack::get_products_for_purchase(),
359
			'recommendationsStep'         => Jetpack_Core_Json_Api_Endpoints::get_recommendations_step()['step'],
360
			'isSafari'                    => $is_safari || User_Agent_Info::is_opera_desktop(), // @todo Rename isSafari everywhere.
361
			'doNotUseConnectionIframe'    => Constants::is_true( 'JETPACK_SHOULD_NOT_USE_CONNECTION_IFRAME' ),
362
			'licensing'                   => array(
363
				'error'           => Licensing::instance()->last_error(),
364
				'showLicensingUi' => Licensing::instance()->is_licensing_input_enabled(),
365
			),
366
		);
367
	}
368
369
	function get_external_services_connect_urls() {
370
		$connect_urls = array();
371
		jetpack_require_lib( 'class.jetpack-keyring-service-helper' );
372
		foreach ( Jetpack_Keyring_Service_Helper::$SERVICES as $service_name => $service_info ) {
373
			$connect_urls[ $service_name ] = Jetpack_Keyring_Service_Helper::connect_url( $service_name, $service_info[ 'for' ] );
374
		}
375
		return $connect_urls;
376
	}
377
378
	/**
379
	 * Returns an array of modules and settings both as first class members of the object.
380
	 *
381
	 * @param array $modules the result of an API request to get all modules.
382
	 *
383
	 * @return array flattened settings with modules.
384
	 */
385
	function get_flattened_settings( $modules ) {
386
		$core_api_endpoint = new Jetpack_Core_API_Data();
387
		$settings = $core_api_endpoint->get_all_options();
388
		return $settings->data;
389
	}
390
391
	/**
392
	 * Returns the release post content and image data as an associative array.
393
	 * This data is used to create the update modal.
394
	 */
395
	public function get_update_modal_data() {
396
		$post_data = $this->get_release_post_data();
397
398
		if ( ! isset( $post_data['posts'][0] ) ) {
399
			return;
400
		}
401
402
		$post = $post_data['posts'][0];
403
404
		if ( empty( $post['content'] ) ) {
405
			return;
406
		}
407
408
		// This allows us to embed videopress videos into the release post.
409
		add_filter( 'wp_kses_allowed_html', array( $this, 'allow_post_embed_iframe' ), 10, 2 );
410
		$content = wp_kses_post( $post['content'] );
411
		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...
412
413
		$post_title = isset( $post['title'] ) ? $post['title'] : null;
414
		$title      = wp_kses( $post_title, array() );
415
416
		$post_thumbnail = isset( $post['post_thumbnail'] ) ? $post['post_thumbnail'] : null;
417
		if ( ! empty( $post_thumbnail ) ) {
418
			jetpack_require_lib( 'class.jetpack-photon-image' );
419
			$photon_image = new Jetpack_Photon_Image(
420
				array(
421
					'file'   => jetpack_photon_url( $post_thumbnail['URL'] ),
422
					'width'  => $post_thumbnail['width'],
423
					'height' => $post_thumbnail['height'],
424
				),
425
				$post_thumbnail['mime_type']
426
			);
427
			$photon_image->resize(
428
				array(
429
					'width'  => 600,
430
					'height' => null,
431
					'crop'   => false,
432
				)
433
			);
434
			$post_thumbnail_url = $photon_image->get_raw_filename();
435
		} else {
436
			$post_thumbnail_url = null;
437
		}
438
439
		$post_array = array(
440
			'release_post_content'        => $content,
441
			'release_post_featured_image' => $post_thumbnail_url,
442
			'release_post_title'          => $title,
443
		);
444
445
		return $post_array;
446
	}
447
448
	/**
449
	 * Temporarily allow post content to contain iframes, e.g. for videopress.
450
	 *
451
	 * @param string $tags    The tags.
452
	 * @param string $context The context.
453
	 */
454
	public function allow_post_embed_iframe( $tags, $context ) {
455
		if ( 'post' === $context ) {
456
			$tags['iframe'] = array(
457
				'src'             => true,
458
				'height'          => true,
459
				'width'           => true,
460
				'frameborder'     => true,
461
				'allowfullscreen' => true,
462
			);
463
		}
464
465
		return $tags;
466
	}
467
468
	/**
469
	 * Obtains the release post from the Jetpack release post blog. A release post will be displayed in the
470
	 * update modal when a post has a tag equal to the Jetpack version number.
471
	 *
472
	 * The response parameters for the post array can be found here:
473
	 * https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/posts/%24post_ID/#apidoc-response
474
	 *
475
	 * @return array|null Returns an associative array containing the release post data at index ['posts'][0].
476
	 *                    Returns null if the release post data is not available.
477
	 */
478
	private function get_release_post_data() {
479
		if ( Constants::is_defined( 'TESTING_IN_JETPACK' ) && Constants::get_constant( 'TESTING_IN_JETPACK' ) ) {
480
			return null;
481
		}
482
483
		$release_post_src = add_query_arg(
484
			array(
485
				'order_by' => 'date',
486
				'tag'      => JETPACK__VERSION,
487
				'number'   => '1',
488
			),
489
			'https://public-api.wordpress.com/rest/v1/sites/' . JETPACK__RELEASE_POST_BLOG_SLUG . '/posts'
490
		);
491
492
		$response = wp_remote_get( $release_post_src );
493
494
		if ( ! is_array( $response ) ) {
495
			return null;
496
		}
497
498
		return json_decode( wp_remote_retrieve_body( $response ), true );
499
	}
500
}
501
502
/**
503
 * Gather data about the current user.
504
 *
505
 * @since 4.1.0
506
 *
507
 * @return array
508
 */
509
function jetpack_current_user_data() {
510
	$jetpack_connection = new Connection_Manager( 'jetpack' );
511
512
	$current_user   = wp_get_current_user();
513
	$is_master_user = $current_user->ID == Jetpack_Options::get_option( 'master_user' );
514
	$dotcom_data    = $jetpack_connection->get_connected_user_data();
515
516
	// Add connected user gravatar to the returned dotcom_data.
517
	$dotcom_data['avatar'] = ( ! empty( $dotcom_data['email'] ) ?
518
		get_avatar_url(
519
			$dotcom_data['email'],
520
			array(
521
				'size'    => 64,
522
				'default' => 'mysteryman',
523
			)
524
		)
525
		: false );
526
527
	$current_user_data = array(
528
		'isConnected' => $jetpack_connection->is_user_connected( $current_user->ID ),
529
		'isMaster'    => $is_master_user,
530
		'username'    => $current_user->user_login,
531
		'id'          => $current_user->ID,
532
		'wpcomUser'   => $dotcom_data,
533
		'gravatar'    => get_avatar_url( $current_user->ID, 64, 'mm', '', array( 'force_display' => true ) ),
534
		'permissions' => array(
535
			'admin_page'         => current_user_can( 'jetpack_admin_page' ),
536
			'connect'            => current_user_can( 'jetpack_connect' ),
537
			'connect_user'       => current_user_can( 'jetpack_connect_user' ),
538
			'disconnect'         => current_user_can( 'jetpack_disconnect' ),
539
			'manage_modules'     => current_user_can( 'jetpack_manage_modules' ),
540
			'network_admin'      => current_user_can( 'jetpack_network_admin_page' ),
541
			'network_sites_page' => current_user_can( 'jetpack_network_sites_page' ),
542
			'edit_posts'         => current_user_can( 'edit_posts' ),
543
			'publish_posts'      => current_user_can( 'publish_posts' ),
544
			'manage_options'     => current_user_can( 'manage_options' ),
545
			'view_stats'         => current_user_can( 'view_stats' ),
546
			'manage_plugins'     => current_user_can( 'install_plugins' )
547
									&& current_user_can( 'activate_plugins' )
548
									&& current_user_can( 'update_plugins' )
549
									&& current_user_can( 'delete_plugins' ),
550
		),
551
	);
552
553
	return $current_user_data;
554
}
555