Completed
Push — fix/display-connection-errors ( 3ff3b7...d1d4e1 )
by
unknown
21:03 queued 13:28
created

class.jetpack.php (1 issue)

Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
use Automattic\Jetpack\Assets;
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Config;
5
use Automattic\Jetpack\Connection\Client;
6
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
7
use Automattic\Jetpack\Connection\Utils as Connection_Utils;
8
use Automattic\Jetpack\Constants;
9
use Automattic\Jetpack\Partner;
10
use Automattic\Jetpack\Roles;
11
use Automattic\Jetpack\Status;
12
use Automattic\Jetpack\Sync\Functions;
13
use Automattic\Jetpack\Sync\Sender;
14
use Automattic\Jetpack\Sync\Users;
15
use Automattic\Jetpack\Terms_Of_Service;
16
use Automattic\Jetpack\Tracking;
17
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
18
19
/*
20
Options:
21
jetpack_options (array)
22
	An array of options.
23
	@see Jetpack_Options::get_option_names()
24
25
jetpack_register (string)
26
	Temporary verification secrets.
27
28
jetpack_activated (int)
29
	1: the plugin was activated normally
30
	2: the plugin was activated on this site because of a network-wide activation
31
	3: the plugin was auto-installed
32
	4: the plugin was manually disconnected (but is still installed)
33
34
jetpack_active_modules (array)
35
	Array of active module slugs.
36
37
jetpack_do_activate (bool)
38
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
39
*/
40
41
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
42
43
class Jetpack {
44
	public $xmlrpc_server = null;
45
46
	private $rest_authentication_status = null;
47
48
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
49
50
	/**
51
	 * @var array The handles of styles that are concatenated into jetpack.css.
52
	 *
53
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
54
	 */
55
	public $concatenated_style_handles = array(
56
		'jetpack-carousel',
57
		'grunion.css',
58
		'the-neverending-homepage',
59
		'jetpack_likes',
60
		'jetpack_related-posts',
61
		'sharedaddy',
62
		'jetpack-slideshow',
63
		'presentations',
64
		'quiz',
65
		'jetpack-subscriptions',
66
		'jetpack-responsive-videos-style',
67
		'jetpack-social-menu',
68
		'tiled-gallery',
69
		'jetpack_display_posts_widget',
70
		'gravatar-profile-widget',
71
		'goodreads-widget',
72
		'jetpack_social_media_icons_widget',
73
		'jetpack-top-posts-widget',
74
		'jetpack_image_widget',
75
		'jetpack-my-community-widget',
76
		'jetpack-authors-widget',
77
		'wordads',
78
		'eu-cookie-law-style',
79
		'flickr-widget-style',
80
		'jetpack-search-widget',
81
		'jetpack-simple-payments-widget-style',
82
		'jetpack-widget-social-icons-styles',
83
	);
84
85
	/**
86
	 * The handles of scripts that can be loaded asynchronously.
87
	 *
88
	 * @var array
89
	 */
90
	public $async_script_handles = array(
91
		'woocommerce-analytics',
92
	);
93
94
	/**
95
	 * Contains all assets that have had their URL rewritten to minified versions.
96
	 *
97
	 * @var array
98
	 */
99
	static $min_assets = array();
100
101
	public $plugins_to_deactivate = array(
102
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
103
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
104
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
105
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
106
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
107
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
108
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
109
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
110
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
111
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
112
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
113
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
114
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
115
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
116
	);
117
118
	/**
119
	 * Map of roles we care about, and their corresponding minimum capabilities.
120
	 *
121
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
122
	 *
123
	 * @access public
124
	 * @static
125
	 *
126
	 * @var array
127
	 */
128
	public static $capability_translations = array(
129
		'administrator' => 'manage_options',
130
		'editor'        => 'edit_others_posts',
131
		'author'        => 'publish_posts',
132
		'contributor'   => 'edit_posts',
133
		'subscriber'    => 'read',
134
	);
135
136
	/**
137
	 * Map of modules that have conflicts with plugins and should not be auto-activated
138
	 * if the plugins are active.  Used by filter_default_modules
139
	 *
140
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
141
	 * change `module-slug` and add this to your plugin:
142
	 *
143
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
144
	 * function my_jetpack_get_default_modules( $modules ) {
145
	 *     return array_diff( $modules, array( 'module-slug' ) );
146
	 * }
147
	 *
148
	 * @var array
149
	 */
150
	private $conflicting_plugins = array(
151
		'comments'           => array(
152
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
153
			'Disqus'                         => 'disqus-comment-system/disqus.php',
154
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
155
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
156
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
157
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
158
		),
159
		'comment-likes'      => array(
160
			'Epoch' => 'epoch/plugincore.php',
161
		),
162
		'contact-form'       => array(
163
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
164
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
165
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
166
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
167
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
168
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
169
		),
170
		'minileven'          => array(
171
			'WPtouch' => 'wptouch/wptouch.php',
172
		),
173
		'latex'              => array(
174
			'LaTeX for WordPress'     => 'latex/latex.php',
175
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
176
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
177
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
178
			'Enable Latex'            => 'enable-latex/enable-latex.php',
179
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
180
		),
181
		'protect'            => array(
182
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
183
			'Captcha'                           => 'captcha/captcha.php',
184
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
185
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
186
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
187
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
188
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
189
			'Security-protection'               => 'security-protection/security-protection.php',
190
			'Login Security'                    => 'login-security/login-security.php',
191
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
192
			'Wordfence Security'                => 'wordfence/wordfence.php',
193
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
194
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
195
		),
196
		'random-redirect'    => array(
197
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
198
		),
199
		'related-posts'      => array(
200
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
201
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
202
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
203
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
204
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
205
			'outbrain'                    => 'outbrain/outbrain.php',
206
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
207
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
208
		),
209
		'sharedaddy'         => array(
210
			'AddThis'     => 'addthis/addthis_social_widget.php',
211
			'Add To Any'  => 'add-to-any/add-to-any.php',
212
			'ShareThis'   => 'share-this/sharethis.php',
213
			'Shareaholic' => 'shareaholic/shareaholic.php',
214
		),
215
		'seo-tools'          => array(
216
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
217
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
218
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
219
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
220
			'The SEO Framework'              => 'autodescription/autodescription.php',
221
		),
222
		'verification-tools' => array(
223
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
224
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
225
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
226
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
227
			'The SEO Framework'              => 'autodescription/autodescription.php',
228
		),
229
		'widget-visibility'  => array(
230
			'Widget Logic'    => 'widget-logic/widget_logic.php',
231
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
232
		),
233
		'sitemaps'           => array(
234
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
235
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
236
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
237
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
238
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
239
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
240
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
241
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
242
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
243
			'The SEO Framework'                    => 'autodescription/autodescription.php',
244
			'Sitemap'                              => 'sitemap/sitemap.php',
245
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
246
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
247
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
248
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
249
		),
250
		'lazy-images'        => array(
251
			'Lazy Load'              => 'lazy-load/lazy-load.php',
252
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
253
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
254
		),
255
	);
256
257
	/**
258
	 * Plugins for which we turn off our Facebook OG Tags implementation.
259
	 *
260
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
261
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
262
	 *
263
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
264
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
265
	 */
266
	private $open_graph_conflicting_plugins = array(
267
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
268
		// 2 Click Social Media Buttons
269
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
270
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
271
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
272
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
273
		// Open Graph Meta Tags by Heateor
274
		'facebook/facebook.php',                                 // Facebook (official plugin)
275
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
276
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
277
		// Facebook Featured Image & OG Meta Tags
278
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
279
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
280
		// Facebook Open Graph Meta Tags for WordPress
281
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
282
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
283
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
284
		// Fedmich's Facebook Open Graph Meta
285
		'network-publisher/networkpub.php',                      // Network Publisher
286
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
287
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
288
		// NextScripts SNAP
289
		'og-tags/og-tags.php',                                   // OG Tags
290
		'opengraph/opengraph.php',                               // Open Graph
291
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
292
		// Open Graph Protocol Framework
293
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
294
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
295
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
296
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
297
		'sharepress/sharepress.php',                             // SharePress
298
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
299
		'social-discussions/social-discussions.php',             // Social Discussions
300
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
301
		'socialize/socialize.php',                               // Socialize
302
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
303
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
304
		// Tweet, Like, Google +1 and Share
305
		'wordbooker/wordbooker.php',                             // Wordbooker
306
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
307
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
308
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
309
		// WP Facebook Like Send & Open Graph Meta
310
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
311
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
312
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
313
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
314
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
315
	);
316
317
	/**
318
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
319
	 */
320
	private $twitter_cards_conflicting_plugins = array(
321
		// 'twitter/twitter.php',                       // The official one handles this on its own.
322
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
323
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
324
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
325
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
326
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
327
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
328
		'twitter-cards/twitter-cards.php',           // Twitter Cards
329
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
330
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
331
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
332
	);
333
334
	/**
335
	 * Message to display in admin_notice
336
	 *
337
	 * @var string
338
	 */
339
	public $message = '';
340
341
	/**
342
	 * Error to display in admin_notice
343
	 *
344
	 * @var string
345
	 */
346
	public $error = '';
347
348
	/**
349
	 * Modules that need more privacy description.
350
	 *
351
	 * @var string
352
	 */
353
	public $privacy_checks = '';
354
355
	/**
356
	 * Stats to record once the page loads
357
	 *
358
	 * @var array
359
	 */
360
	public $stats = array();
361
362
	/**
363
	 * Jetpack_Sync object
364
	 */
365
	public $sync;
366
367
	/**
368
	 * Verified data for JSON authorization request
369
	 */
370
	public $json_api_authorization_request = array();
371
372
	/**
373
	 * @var Automattic\Jetpack\Connection\Manager
374
	 */
375
	protected $connection_manager;
376
377
	/**
378
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
379
	 */
380
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
381
382
	/**
383
	 * Holds the singleton instance of this class
384
	 *
385
	 * @since 2.3.3
386
	 * @var Jetpack
387
	 */
388
	static $instance = false;
389
390
	/**
391
	 * Singleton
392
	 *
393
	 * @static
394
	 */
395
	public static function init() {
396
		if ( ! self::$instance ) {
397
			self::$instance = new Jetpack();
398
399
			self::$instance->plugin_upgrade();
400
		}
401
402
		return self::$instance;
403
	}
404
405
	/**
406
	 * Must never be called statically
407
	 */
408
	function plugin_upgrade() {
409
		if ( self::is_active() ) {
410
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
411
			if ( JETPACK__VERSION != $version ) {
412
				// Prevent multiple upgrades at once - only a single process should trigger
413
				// an upgrade to avoid stampedes
414
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
415
					return;
416
				}
417
418
				// Set a short lock to prevent multiple instances of the upgrade
419
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
420
421
				// check which active modules actually exist and remove others from active_modules list
422
				$unfiltered_modules = self::get_active_modules();
423
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
424
				if ( array_diff( $unfiltered_modules, $modules ) ) {
425
					self::update_active_modules( $modules );
426
				}
427
428
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
429
430
				// Upgrade to 4.3.0
431
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
432
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
433
				}
434
435
				// Make sure Markdown for posts gets turned back on
436
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
437
					update_option( 'wpcom_publish_posts_with_markdown', true );
438
				}
439
440
				if ( did_action( 'wp_loaded' ) ) {
441
					self::upgrade_on_load();
442
				} else {
443
					add_action(
444
						'wp_loaded',
445
						array( __CLASS__, 'upgrade_on_load' )
446
					);
447
				}
448
			}
449
		}
450
	}
451
452
	/**
453
	 * Runs upgrade routines that need to have modules loaded.
454
	 */
455
	static function upgrade_on_load() {
456
457
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
458
		// This can happen in case Jetpack has been just upgraded and is
459
		// being initialized late during the page load. In this case we wait
460
		// until the next proper admin page load with Jetpack active.
461
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
462
			delete_transient( self::$plugin_upgrade_lock_key );
463
464
			return;
465
		}
466
467
		self::maybe_set_version_option();
468
469
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
470
			Jetpack_Widget_Conditions::migrate_post_type_rules();
471
		}
472
473
		if (
474
			class_exists( 'Jetpack_Sitemap_Manager' )
475
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
476
		) {
477
			do_action( 'jetpack_sitemaps_purge_data' );
478
		}
479
480
		// Delete old stats cache
481
		delete_option( 'jetpack_restapi_stats_cache' );
482
483
		delete_transient( self::$plugin_upgrade_lock_key );
484
	}
485
486
	/**
487
	 * Saves all the currently active modules to options.
488
	 * Also fires Action hooks for each newly activated and deactivated module.
489
	 *
490
	 * @param $modules Array Array of active modules to be saved in options.
491
	 *
492
	 * @return $success bool true for success, false for failure.
493
	 */
494
	static function update_active_modules( $modules ) {
495
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
496
		$active_modules       = self::get_active_modules();
497
		$new_active_modules   = array_diff( $modules, $current_modules );
498
		$new_inactive_modules = array_diff( $active_modules, $modules );
499
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
500
		$reindexed_modules    = array_values( $new_current_modules );
501
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
502
503
		foreach ( $new_active_modules as $module ) {
504
			/**
505
			 * Fires when a specific module is activated.
506
			 *
507
			 * @since 1.9.0
508
			 *
509
			 * @param string $module Module slug.
510
			 * @param boolean $success whether the module was activated. @since 4.2
511
			 */
512
			do_action( 'jetpack_activate_module', $module, $success );
513
			/**
514
			 * Fires when a module is activated.
515
			 * The dynamic part of the filter, $module, is the module slug.
516
			 *
517
			 * @since 1.9.0
518
			 *
519
			 * @param string $module Module slug.
520
			 */
521
			do_action( "jetpack_activate_module_$module", $module );
522
		}
523
524
		foreach ( $new_inactive_modules as $module ) {
525
			/**
526
			 * Fired after a module has been deactivated.
527
			 *
528
			 * @since 4.2.0
529
			 *
530
			 * @param string $module Module slug.
531
			 * @param boolean $success whether the module was deactivated.
532
			 */
533
			do_action( 'jetpack_deactivate_module', $module, $success );
534
			/**
535
			 * Fires when a module is deactivated.
536
			 * The dynamic part of the filter, $module, is the module slug.
537
			 *
538
			 * @since 1.9.0
539
			 *
540
			 * @param string $module Module slug.
541
			 */
542
			do_action( "jetpack_deactivate_module_$module", $module );
543
		}
544
545
		return $success;
546
	}
547
548
	static function delete_active_modules() {
549
		self::update_active_modules( array() );
550
	}
551
552
	/**
553
	 * Constructor.  Initializes WordPress hooks
554
	 */
555
	private function __construct() {
556
		/*
557
		 * Check for and alert any deprecated hooks
558
		 */
559
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
560
561
		add_action( 'plugins_loaded', array( $this, 'configure' ), 1 );
562
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
563
564
		add_filter(
565
			'jetpack_connection_secret_generator',
566
			function( $callable ) {
567
				return function() {
568
					return wp_generate_password( 32, false );
569
				};
570
			}
571
		);
572
573
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
574
575
		$this->connection_manager = new Connection_Manager();
576
		$this->connection_manager->init();
577
578
		/*
579
		 * Load things that should only be in Network Admin.
580
		 *
581
		 * For now blow away everything else until a more full
582
		 * understanding of what is needed at the network level is
583
		 * available
584
		 */
585
		if ( is_multisite() ) {
586
			$network = Jetpack_Network::init();
587
			$network->set_connection( $this->connection_manager );
588
		}
589
590
		add_filter(
591
			'jetpack_signature_check_token',
592
			array( __CLASS__, 'verify_onboarding_token' ),
593
			10,
594
			3
595
		);
596
597
		/**
598
		 * Prepare Gutenberg Editor functionality
599
		 */
600
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
601
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
602
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
603
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
604
605
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
606
607
		// Unlink user before deleting the user from WP.com.
608
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
609
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
610
611
		if ( self::is_active() ) {
612
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
613
614
			Jetpack_Heartbeat::init();
615
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
616
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
617
				Jetpack_Search_Performance_Logger::init();
618
			}
619
		}
620
621
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
622
623
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
624
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
625
626
		add_action( 'admin_init', array( $this, 'admin_init' ) );
627
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
628
629
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
630
631
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
632
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
633
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
634
635
		// returns HTTPS support status
636
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
637
638
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
639
640
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
641
642
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
643
644
		/**
645
		 * These actions run checks to load additional files.
646
		 * They check for external files or plugins, so they need to run as late as possible.
647
		 */
648
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
649
		add_action( 'amp_story_head', array( $this, 'check_open_graph' ), 1 );
650
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
651
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
652
653
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
654
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
655
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
656
657
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
658
659
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
660
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
661
662
		// A filter to control all just in time messages
663
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
664
665
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
666
667
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
668
		// We should make sure to only do this for front end links.
669
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
670
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
671
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
672
673
			// we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
674
			// so they point moderation links on emails to Calypso
675
			jetpack_require_lib( 'functions.wp-notify' );
676
		}
677
678
		// Hide edit post link if mobile app.
679
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
680
			add_filter( 'edit_post_link', '__return_empty_string' );
681
		}
682
683
		// Update the Jetpack plan from API on heartbeats
684
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
685
686
		/**
687
		 * This is the hack to concatenate all css files into one.
688
		 * For description and reasoning see the implode_frontend_css method
689
		 *
690
		 * Super late priority so we catch all the registered styles
691
		 */
692
		if ( ! is_admin() ) {
693
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
694
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
695
		}
696
697
		/**
698
		 * These are sync actions that we need to keep track of for jitms
699
		 */
700
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
701
702
		// Actually push the stats on shutdown.
703
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
704
			add_action( 'shutdown', array( $this, 'push_stats' ) );
705
		}
706
707
		/*
708
		 * Load some scripts asynchronously.
709
		 */
710
		add_action( 'script_loader_tag', array( $this, 'script_add_async' ), 10, 3 );
711
712
		// Actions for Manager::authorize().
713
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
714
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
715
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
716
717
		// Filters for the Manager::get_token() urls and request body.
718
		add_filter( 'jetpack_token_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
719
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
720
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
721
	}
722
723
	/**
724
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
725
	 * Config object.
726
	 */
727
	public function configure() {
728
		$config = new Config();
729
730
		foreach (
731
			array(
732
				'sync',
733
				'tracking',
734
				'tos',
735
			)
736
			as $feature
737
		) {
738
			$config->ensure( $feature );
739
		}
740
741
		// Initialize remote file upload request handlers.
742
		$this->add_remote_request_handlers();
743
744
		/*
745
		 * Enable enhanced handling of previewing sites in Calypso
746
		 */
747
		if ( self::is_active() ) {
748
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
749
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
750
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
751
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
752
		}
753
754
	}
755
756
	/**
757
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
758
	 * initialization code.
759
	 *
760
	 * @action plugins_loaded
761
	 */
762
	public function late_initialization() {
763
		self::plugin_textdomain();
764
		self::load_modules();
765
766
		Partner::init();
767
768
		/**
769
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
770
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
771
		 *
772
		 * @since 8.1.0
773
		 *
774
		 * @param Jetpack $jetpack the main plugin class object.
775
		 */
776
		do_action( 'jetpack_loaded', $this );
777
778
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
779
	}
780
781
	/**
782
	 * Sets up the XMLRPC request handlers.
783
	 *
784
	 * @deprecated since 7.7.0
785
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
786
	 *
787
	 * @param Array                 $request_params Incoming request parameters.
788
	 * @param Boolean               $is_active      Whether the connection is currently active.
789
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
790
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
791
	 */
792
	public function setup_xmlrpc_handlers(
793
		$request_params,
794
		$is_active,
795
		$is_signed,
796
		Jetpack_XMLRPC_Server $xmlrpc_server = null
797
	) {
798
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
799
		return $this->connection_manager->setup_xmlrpc_handlers(
800
			$request_params,
801
			$is_active,
802
			$is_signed,
803
			$xmlrpc_server
804
		);
805
	}
806
807
	/**
808
	 * Initialize REST API registration connector.
809
	 *
810
	 * @deprecated since 7.7.0
811
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
812
	 */
813
	public function initialize_rest_api_registration_connector() {
814
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
815
		$this->connection_manager->initialize_rest_api_registration_connector();
816
	}
817
818
	/**
819
	 * This is ported over from the manage module, which has been deprecated and baked in here.
820
	 *
821
	 * @param $domains
822
	 */
823
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
824
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
825
	}
826
827
	/**
828
	 * Return $domains, with 'wordpress.com' appended.
829
	 * This is ported over from the manage module, which has been deprecated and baked in here.
830
	 *
831
	 * @param $domains
832
	 * @return array
833
	 */
834
	function allow_wpcom_domain( $domains ) {
835
		if ( empty( $domains ) ) {
836
			$domains = array();
837
		}
838
		$domains[] = 'wordpress.com';
839
		return array_unique( $domains );
840
	}
841
842
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
843
		$post = get_post( $post_id );
844
845
		if ( empty( $post ) ) {
846
			return $default_url;
847
		}
848
849
		$post_type = $post->post_type;
850
851
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
852
		// https://en.support.wordpress.com/custom-post-types/
853
		$allowed_post_types = array(
854
			'post'                => 'post',
855
			'page'                => 'page',
856
			'jetpack-portfolio'   => 'edit/jetpack-portfolio',
857
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
858
		);
859
860
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
861
			return $default_url;
862
		}
863
864
		$path_prefix = $allowed_post_types[ $post_type ];
865
866
		$site_slug = self::build_raw_urls( get_home_url() );
867
868
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
869
	}
870
871
	function point_edit_comment_links_to_calypso( $url ) {
872
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
873
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
874
		return esc_url(
875
			sprintf(
876
				'https://wordpress.com/comment/%s/%d',
877
				self::build_raw_urls( get_home_url() ),
878
				$query_args['amp;c']
879
			)
880
		);
881
	}
882
883
	function jetpack_track_last_sync_callback( $params ) {
884
		/**
885
		 * Filter to turn off jitm caching
886
		 *
887
		 * @since 5.4.0
888
		 *
889
		 * @param bool false Whether to cache just in time messages
890
		 */
891
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
892
			return $params;
893
		}
894
895
		if ( is_array( $params ) && isset( $params[0] ) ) {
896
			$option = $params[0];
897
			if ( 'active_plugins' === $option ) {
898
				// use the cache if we can, but not terribly important if it gets evicted
899
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
900
			}
901
		}
902
903
		return $params;
904
	}
905
906
	function jetpack_connection_banner_callback() {
907
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
908
909
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
910
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
911
			wp_send_json_success();
912
		}
913
914
		wp_die();
915
	}
916
917
	/**
918
	 * Removes all XML-RPC methods that are not `jetpack.*`.
919
	 * Only used in our alternate XML-RPC endpoint, where we want to
920
	 * ensure that Core and other plugins' methods are not exposed.
921
	 *
922
	 * @deprecated since 7.7.0
923
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
924
	 *
925
	 * @param array $methods A list of registered WordPress XMLRPC methods.
926
	 * @return array Filtered $methods
927
	 */
928
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
929
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
930
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
931
	}
932
933
	/**
934
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
935
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
936
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
937
	 * which is accessible via a different URI. Most of the below is copied directly
938
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
939
	 *
940
	 * @deprecated since 7.7.0
941
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
942
	 */
943
	public function alternate_xmlrpc() {
944
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
945
		$this->connection_manager->alternate_xmlrpc();
946
	}
947
948
	/**
949
	 * The callback for the JITM ajax requests.
950
	 *
951
	 * @deprecated since 7.9.0
952
	 */
953
	function jetpack_jitm_ajax_callback() {
954
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
955
	}
956
957
	/**
958
	 * If there are any stats that need to be pushed, but haven't been, push them now.
959
	 */
960
	function push_stats() {
961
		if ( ! empty( $this->stats ) ) {
962
			$this->do_stats( 'server_side' );
963
		}
964
	}
965
966
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
967
		$is_development_mode = ( new Status() )->is_development_mode();
968
		switch ( $cap ) {
969
			case 'jetpack_connect':
970
			case 'jetpack_reconnect':
971
				if ( $is_development_mode ) {
972
					$caps = array( 'do_not_allow' );
973
					break;
974
				}
975
				/**
976
				 * Pass through. If it's not development mode, these should match disconnect.
977
				 * Let users disconnect if it's development mode, just in case things glitch.
978
				 */
979
			case 'jetpack_disconnect':
980
				/**
981
				 * In multisite, can individual site admins manage their own connection?
982
				 *
983
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
984
				 */
985
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
986
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
987
						/**
988
						 * We need to update the option name -- it's terribly unclear which
989
						 * direction the override goes.
990
						 *
991
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
992
						 */
993
						$caps = array( 'do_not_allow' );
994
						break;
995
					}
996
				}
997
998
				$caps = array( 'manage_options' );
999
				break;
1000
			case 'jetpack_manage_modules':
1001
			case 'jetpack_activate_modules':
1002
			case 'jetpack_deactivate_modules':
1003
				$caps = array( 'manage_options' );
1004
				break;
1005
			case 'jetpack_configure_modules':
1006
				$caps = array( 'manage_options' );
1007
				break;
1008
			case 'jetpack_manage_autoupdates':
1009
				$caps = array(
1010
					'manage_options',
1011
					'update_plugins',
1012
				);
1013
				break;
1014
			case 'jetpack_network_admin_page':
1015
			case 'jetpack_network_settings_page':
1016
				$caps = array( 'manage_network_plugins' );
1017
				break;
1018
			case 'jetpack_network_sites_page':
1019
				$caps = array( 'manage_sites' );
1020
				break;
1021
			case 'jetpack_admin_page':
1022
				if ( $is_development_mode ) {
1023
					$caps = array( 'manage_options' );
1024
					break;
1025
				} else {
1026
					$caps = array( 'read' );
1027
				}
1028
				break;
1029
			case 'jetpack_connect_user':
1030
				if ( $is_development_mode ) {
1031
					$caps = array( 'do_not_allow' );
1032
					break;
1033
				}
1034
				$caps = array( 'read' );
1035
				break;
1036
		}
1037
		return $caps;
1038
	}
1039
1040
	/**
1041
	 * Require a Jetpack authentication.
1042
	 *
1043
	 * @deprecated since 7.7.0
1044
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1045
	 */
1046
	public function require_jetpack_authentication() {
1047
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1048
		$this->connection_manager->require_jetpack_authentication();
1049
	}
1050
1051
	/**
1052
	 * Load language files
1053
	 *
1054
	 * @action plugins_loaded
1055
	 */
1056
	public static function plugin_textdomain() {
1057
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1058
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1059
	}
1060
1061
	/**
1062
	 * Register assets for use in various modules and the Jetpack admin page.
1063
	 *
1064
	 * @uses wp_script_is, wp_register_script, plugins_url
1065
	 * @action wp_loaded
1066
	 * @return null
1067
	 */
1068
	public function register_assets() {
1069
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1070
			wp_register_script(
1071
				'spin',
1072
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1073
				false,
1074
				'1.3'
1075
			);
1076
		}
1077
1078 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1079
			wp_register_script(
1080
				'jquery.spin',
1081
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1082
				array( 'jquery', 'spin' ),
1083
				'1.3'
1084
			);
1085
		}
1086
1087 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1088
			wp_register_script(
1089
				'jetpack-gallery-settings',
1090
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1091
				array( 'media-views' ),
1092
				'20121225'
1093
			);
1094
		}
1095
1096 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1097
			wp_register_script(
1098
				'jetpack-twitter-timeline',
1099
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1100
				array( 'jquery' ),
1101
				'4.0.0',
1102
				true
1103
			);
1104
		}
1105
1106
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1107
			wp_register_script(
1108
				'jetpack-facebook-embed',
1109
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1110
				array( 'jquery' ),
1111
				null,
1112
				true
1113
			);
1114
1115
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1116
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1117
			if ( ! is_numeric( $fb_app_id ) ) {
1118
				$fb_app_id = '';
1119
			}
1120
			wp_localize_script(
1121
				'jetpack-facebook-embed',
1122
				'jpfbembed',
1123
				array(
1124
					'appid'  => $fb_app_id,
1125
					'locale' => $this->get_locale(),
1126
				)
1127
			);
1128
		}
1129
1130
		/**
1131
		 * As jetpack_register_genericons is by default fired off a hook,
1132
		 * the hook may have already fired by this point.
1133
		 * So, let's just trigger it manually.
1134
		 */
1135
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1136
		jetpack_register_genericons();
1137
1138
		/**
1139
		 * Register the social logos
1140
		 */
1141
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1142
		jetpack_register_social_logos();
1143
1144 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1145
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1146
		}
1147
	}
1148
1149
	/**
1150
	 * Guess locale from language code.
1151
	 *
1152
	 * @param string $lang Language code.
1153
	 * @return string|bool
1154
	 */
1155 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1156
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1157
			return 'en_US';
1158
		}
1159
1160
		if ( ! class_exists( 'GP_Locales' ) ) {
1161
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1162
				return false;
1163
			}
1164
1165
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1166
		}
1167
1168
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1169
			// WP.com: get_locale() returns 'it'
1170
			$locale = GP_Locales::by_slug( $lang );
1171
		} else {
1172
			// Jetpack: get_locale() returns 'it_IT';
1173
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1174
		}
1175
1176
		if ( ! $locale ) {
1177
			return false;
1178
		}
1179
1180
		if ( empty( $locale->facebook_locale ) ) {
1181
			if ( empty( $locale->wp_locale ) ) {
1182
				return false;
1183
			} else {
1184
				// Facebook SDK is smart enough to fall back to en_US if a
1185
				// locale isn't supported. Since supported Facebook locales
1186
				// can fall out of sync, we'll attempt to use the known
1187
				// wp_locale value and rely on said fallback.
1188
				return $locale->wp_locale;
1189
			}
1190
		}
1191
1192
		return $locale->facebook_locale;
1193
	}
1194
1195
	/**
1196
	 * Get the locale.
1197
	 *
1198
	 * @return string|bool
1199
	 */
1200
	function get_locale() {
1201
		$locale = $this->guess_locale_from_lang( get_locale() );
1202
1203
		if ( ! $locale ) {
1204
			$locale = 'en_US';
1205
		}
1206
1207
		return $locale;
1208
	}
1209
1210
	/**
1211
	 * Return the network_site_url so that .com knows what network this site is a part of.
1212
	 *
1213
	 * @param  bool $option
1214
	 * @return string
1215
	 */
1216
	public function jetpack_main_network_site_option( $option ) {
1217
		return network_site_url();
1218
	}
1219
	/**
1220
	 * Network Name.
1221
	 */
1222
	static function network_name( $option = null ) {
1223
		global $current_site;
1224
		return $current_site->site_name;
1225
	}
1226
	/**
1227
	 * Does the network allow new user and site registrations.
1228
	 *
1229
	 * @return string
1230
	 */
1231
	static function network_allow_new_registrations( $option = null ) {
1232
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1233
	}
1234
	/**
1235
	 * Does the network allow admins to add new users.
1236
	 *
1237
	 * @return boolian
1238
	 */
1239
	static function network_add_new_users( $option = null ) {
1240
		return (bool) get_site_option( 'add_new_users' );
1241
	}
1242
	/**
1243
	 * File upload psace left per site in MB.
1244
	 *  -1 means NO LIMIT.
1245
	 *
1246
	 * @return number
1247
	 */
1248
	static function network_site_upload_space( $option = null ) {
1249
		// value in MB
1250
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1251
	}
1252
1253
	/**
1254
	 * Network allowed file types.
1255
	 *
1256
	 * @return string
1257
	 */
1258
	static function network_upload_file_types( $option = null ) {
1259
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1260
	}
1261
1262
	/**
1263
	 * Maximum file upload size set by the network.
1264
	 *
1265
	 * @return number
1266
	 */
1267
	static function network_max_upload_file_size( $option = null ) {
1268
		// value in KB
1269
		return get_site_option( 'fileupload_maxk', 300 );
1270
	}
1271
1272
	/**
1273
	 * Lets us know if a site allows admins to manage the network.
1274
	 *
1275
	 * @return array
1276
	 */
1277
	static function network_enable_administration_menus( $option = null ) {
1278
		return get_site_option( 'menu_items' );
1279
	}
1280
1281
	/**
1282
	 * If a user has been promoted to or demoted from admin, we need to clear the
1283
	 * jetpack_other_linked_admins transient.
1284
	 *
1285
	 * @since 4.3.2
1286
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1287
	 *
1288
	 * @param int    $user_id   The user ID whose role changed.
1289
	 * @param string $role      The new role.
1290
	 * @param array  $old_roles An array of the user's previous roles.
1291
	 */
1292
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1293
		if ( 'administrator' == $role
1294
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1295
			|| is_null( $old_roles )
1296
		) {
1297
			delete_transient( 'jetpack_other_linked_admins' );
1298
		}
1299
	}
1300
1301
	/**
1302
	 * Checks to see if there are any other users available to become primary
1303
	 * Users must both:
1304
	 * - Be linked to wpcom
1305
	 * - Be an admin
1306
	 *
1307
	 * @return mixed False if no other users are linked, Int if there are.
1308
	 */
1309
	static function get_other_linked_admins() {
1310
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1311
1312
		if ( false === $other_linked_users ) {
1313
			$admins = get_users( array( 'role' => 'administrator' ) );
1314
			if ( count( $admins ) > 1 ) {
1315
				$available = array();
1316
				foreach ( $admins as $admin ) {
1317
					if ( self::is_user_connected( $admin->ID ) ) {
1318
						$available[] = $admin->ID;
1319
					}
1320
				}
1321
1322
				$count_connected_admins = count( $available );
1323
				if ( count( $available ) > 1 ) {
1324
					$other_linked_users = $count_connected_admins;
1325
				} else {
1326
					$other_linked_users = 0;
1327
				}
1328
			} else {
1329
				$other_linked_users = 0;
1330
			}
1331
1332
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1333
		}
1334
1335
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1336
	}
1337
1338
	/**
1339
	 * Return whether we are dealing with a multi network setup or not.
1340
	 * The reason we are type casting this is because we want to avoid the situation where
1341
	 * the result is false since when is_main_network_option return false it cases
1342
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1343
	 * database which could be set to anything as opposed to what this function returns.
1344
	 *
1345
	 * @param  bool $option
1346
	 *
1347
	 * @return boolean
1348
	 */
1349
	public function is_main_network_option( $option ) {
1350
		// return '1' or ''
1351
		return (string) (bool) self::is_multi_network();
1352
	}
1353
1354
	/**
1355
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1356
	 *
1357
	 * @param  string $option
1358
	 * @return boolean
1359
	 */
1360
	public function is_multisite( $option ) {
1361
		return (string) (bool) is_multisite();
1362
	}
1363
1364
	/**
1365
	 * Implemented since there is no core is multi network function
1366
	 * Right now there is no way to tell if we which network is the dominant network on the system
1367
	 *
1368
	 * @since  3.3
1369
	 * @return boolean
1370
	 */
1371 View Code Duplication
	public static function is_multi_network() {
1372
		global  $wpdb;
1373
1374
		// if we don't have a multi site setup no need to do any more
1375
		if ( ! is_multisite() ) {
1376
			return false;
1377
		}
1378
1379
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1380
		if ( $num_sites > 1 ) {
1381
			return true;
1382
		} else {
1383
			return false;
1384
		}
1385
	}
1386
1387
	/**
1388
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1389
	 *
1390
	 * @return null
1391
	 */
1392
	function update_jetpack_main_network_site_option() {
1393
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1394
	}
1395
	/**
1396
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1397
	 */
1398
	function update_jetpack_network_settings() {
1399
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1400
		// Only sync this info for the main network site.
1401
	}
1402
1403
	/**
1404
	 * Get back if the current site is single user site.
1405
	 *
1406
	 * @return bool
1407
	 */
1408 View Code Duplication
	public static function is_single_user_site() {
1409
		global $wpdb;
1410
1411
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1412
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1413
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1414
		}
1415
		return 1 === (int) $some_users;
1416
	}
1417
1418
	/**
1419
	 * Returns true if the site has file write access false otherwise.
1420
	 *
1421
	 * @return string ( '1' | '0' )
1422
	 **/
1423
	public static function file_system_write_access() {
1424
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1425
			require_once ABSPATH . 'wp-admin/includes/file.php';
1426
		}
1427
1428
		require_once ABSPATH . 'wp-admin/includes/template.php';
1429
1430
		$filesystem_method = get_filesystem_method();
1431
		if ( $filesystem_method === 'direct' ) {
1432
			return 1;
1433
		}
1434
1435
		ob_start();
1436
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1437
		ob_end_clean();
1438
		if ( $filesystem_credentials_are_stored ) {
1439
			return 1;
1440
		}
1441
		return 0;
1442
	}
1443
1444
	/**
1445
	 * Finds out if a site is using a version control system.
1446
	 *
1447
	 * @return string ( '1' | '0' )
1448
	 **/
1449
	public static function is_version_controlled() {
1450
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1451
		return (string) (int) Functions::is_version_controlled();
1452
	}
1453
1454
	/**
1455
	 * Determines whether the current theme supports featured images or not.
1456
	 *
1457
	 * @return string ( '1' | '0' )
1458
	 */
1459
	public static function featured_images_enabled() {
1460
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1461
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1462
	}
1463
1464
	/**
1465
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1466
	 *
1467
	 * @deprecated 4.7 use get_avatar_url instead.
1468
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1469
	 * @param int               $size Size of the avatar image
1470
	 * @param string            $default URL to a default image to use if no avatar is available
1471
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1472
	 *
1473
	 * @return array
1474
	 */
1475
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1476
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1477
		return get_avatar_url(
1478
			$id_or_email,
1479
			array(
1480
				'size'          => $size,
1481
				'default'       => $default,
1482
				'force_default' => $force_display,
1483
			)
1484
		);
1485
	}
1486
1487
	/**
1488
	 * jetpack_updates is saved in the following schema:
1489
	 *
1490
	 * array (
1491
	 *      'plugins'                       => (int) Number of plugin updates available.
1492
	 *      'themes'                        => (int) Number of theme updates available.
1493
	 *      'wordpress'                     => (int) Number of WordPress core updates available. // phpcs:ignore WordPress.WP.CapitalPDangit.Misspelled
1494
	 *      'translations'                  => (int) Number of translation updates available.
1495
	 *      'total'                         => (int) Total of all available updates.
1496
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1497
	 * )
1498
	 *
1499
	 * @return array
1500
	 */
1501
	public static function get_updates() {
1502
		$update_data = wp_get_update_data();
1503
1504
		// Stores the individual update counts as well as the total count.
1505
		if ( isset( $update_data['counts'] ) ) {
1506
			$updates = $update_data['counts'];
1507
		}
1508
1509
		// If we need to update WordPress core, let's find the latest version number.
1510 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1511
			$cur = get_preferred_from_update_core();
1512
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1513
				$updates['wp_update_version'] = $cur->current;
1514
			}
1515
		}
1516
		return isset( $updates ) ? $updates : array();
1517
	}
1518
1519
	public static function get_update_details() {
1520
		$update_details = array(
1521
			'update_core'    => get_site_transient( 'update_core' ),
1522
			'update_plugins' => get_site_transient( 'update_plugins' ),
1523
			'update_themes'  => get_site_transient( 'update_themes' ),
1524
		);
1525
		return $update_details;
1526
	}
1527
1528
	public static function refresh_update_data() {
1529
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1530
1531
	}
1532
1533
	public static function refresh_theme_data() {
1534
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1535
	}
1536
1537
	/**
1538
	 * Is Jetpack active?
1539
	 */
1540
	public static function is_active() {
1541
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1542
	}
1543
1544
	/**
1545
	 * Make an API call to WordPress.com for plan status
1546
	 *
1547
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1548
	 *
1549
	 * @return bool True if plan is updated, false if no update
1550
	 */
1551
	public static function refresh_active_plan_from_wpcom() {
1552
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1553
		return Jetpack_Plan::refresh_from_wpcom();
1554
	}
1555
1556
	/**
1557
	 * Get the plan that this Jetpack site is currently using
1558
	 *
1559
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1560
	 * @return array Active Jetpack plan details.
1561
	 */
1562
	public static function get_active_plan() {
1563
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1564
		return Jetpack_Plan::get();
1565
	}
1566
1567
	/**
1568
	 * Determine whether the active plan supports a particular feature
1569
	 *
1570
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1571
	 * @return bool True if plan supports feature, false if not.
1572
	 */
1573
	public static function active_plan_supports( $feature ) {
1574
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1575
		return Jetpack_Plan::supports( $feature );
1576
	}
1577
1578
	/**
1579
	 * Deprecated: Is Jetpack in development (offline) mode?
1580
	 *
1581
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1582
	 * and themes still use it, and we do not want to flood them with notices.
1583
	 *
1584
	 * Please use Automattic\Jetpack\Status()->is_development_mode() instead.
1585
	 *
1586
	 * @deprecated since 8.0.
1587
	 */
1588
	public static function is_development_mode() {
1589
		return ( new Status() )->is_development_mode();
1590
	}
1591
1592
	/**
1593
	 * Whether the site is currently onboarding or not.
1594
	 * A site is considered as being onboarded if it currently has an onboarding token.
1595
	 *
1596
	 * @since 5.8
1597
	 *
1598
	 * @access public
1599
	 * @static
1600
	 *
1601
	 * @return bool True if the site is currently onboarding, false otherwise
1602
	 */
1603
	public static function is_onboarding() {
1604
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1605
	}
1606
1607
	/**
1608
	 * Determines reason for Jetpack development mode.
1609
	 */
1610
	public static function development_mode_trigger_text() {
1611
		if ( ! ( new Status() )->is_development_mode() ) {
1612
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1613
		}
1614
1615
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1616
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1617
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1618
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1619
		} else {
1620
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1621
		}
1622
1623
		return $notice;
1624
1625
	}
1626
	/**
1627
	 * Get Jetpack development mode notice text and notice class.
1628
	 *
1629
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_development_mode
1630
	 */
1631
	public static function show_development_mode_notice() {
1632 View Code Duplication
		if ( ( new Status() )->is_development_mode() ) {
1633
			$notice = sprintf(
1634
				/* translators: %s is a URL */
1635
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1636
				'https://jetpack.com/support/development-mode/'
1637
			);
1638
1639
			$notice .= ' ' . self::development_mode_trigger_text();
1640
1641
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1642
		}
1643
1644
		// Throw up a notice if using a development version and as for feedback.
1645
		if ( self::is_development_version() ) {
1646
			/* translators: %s is a URL */
1647
			$notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), 'https://jetpack.com/contact-support/beta-group/' );
1648
1649
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1650
		}
1651
		// Throw up a notice if using staging mode
1652
		if ( ( new Status() )->is_staging_site() ) {
1653
			/* translators: %s is a URL */
1654
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1655
1656
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1657
		}
1658
	}
1659
1660
	/**
1661
	 * Whether Jetpack's version maps to a public release, or a development version.
1662
	 */
1663
	public static function is_development_version() {
1664
		/**
1665
		 * Allows filtering whether this is a development version of Jetpack.
1666
		 *
1667
		 * This filter is especially useful for tests.
1668
		 *
1669
		 * @since 4.3.0
1670
		 *
1671
		 * @param bool $development_version Is this a develoment version of Jetpack?
1672
		 */
1673
		return (bool) apply_filters(
1674
			'jetpack_development_version',
1675
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1676
		);
1677
	}
1678
1679
	/**
1680
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1681
	 */
1682
	public static function is_user_connected( $user_id = false ) {
1683
		return self::connection()->is_user_connected( $user_id );
1684
	}
1685
1686
	/**
1687
	 * Get the wpcom user data of the current|specified connected user.
1688
	 */
1689 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1690
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1691
		if ( ! $user_id ) {
1692
			$user_id = get_current_user_id();
1693
		}
1694
1695
		$transient_key = "jetpack_connected_user_data_$user_id";
1696
1697
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1698
			return $cached_user_data;
1699
		}
1700
1701
		$xml = new Jetpack_IXR_Client(
1702
			array(
1703
				'user_id' => $user_id,
1704
			)
1705
		);
1706
		$xml->query( 'wpcom.getUser' );
1707
		if ( ! $xml->isError() ) {
1708
			$user_data = $xml->getResponse();
1709
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1710
			return $user_data;
1711
		}
1712
1713
		return false;
1714
	}
1715
1716
	/**
1717
	 * Get the wpcom email of the current|specified connected user.
1718
	 */
1719 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1720
		if ( ! $user_id ) {
1721
			$user_id = get_current_user_id();
1722
		}
1723
1724
		$xml = new Jetpack_IXR_Client(
1725
			array(
1726
				'user_id' => $user_id,
1727
			)
1728
		);
1729
		$xml->query( 'wpcom.getUserEmail' );
1730
		if ( ! $xml->isError() ) {
1731
			return $xml->getResponse();
1732
		}
1733
		return false;
1734
	}
1735
1736
	/**
1737
	 * Get the wpcom email of the master user.
1738
	 */
1739
	public static function get_master_user_email() {
1740
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1741
		if ( $master_user_id ) {
1742
			return self::get_connected_user_email( $master_user_id );
1743
		}
1744
		return '';
1745
	}
1746
1747
	/**
1748
	 * Whether the current user is the connection owner.
1749
	 *
1750
	 * @deprecated since 7.7
1751
	 *
1752
	 * @return bool Whether the current user is the connection owner.
1753
	 */
1754
	public function current_user_is_connection_owner() {
1755
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1756
		return self::connection()->is_connection_owner();
1757
	}
1758
1759
	/**
1760
	 * Gets current user IP address.
1761
	 *
1762
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1763
	 *
1764
	 * @return string                  Current user IP address.
1765
	 */
1766
	public static function current_user_ip( $check_all_headers = false ) {
1767
		if ( $check_all_headers ) {
1768
			foreach ( array(
1769
				'HTTP_CF_CONNECTING_IP',
1770
				'HTTP_CLIENT_IP',
1771
				'HTTP_X_FORWARDED_FOR',
1772
				'HTTP_X_FORWARDED',
1773
				'HTTP_X_CLUSTER_CLIENT_IP',
1774
				'HTTP_FORWARDED_FOR',
1775
				'HTTP_FORWARDED',
1776
				'HTTP_VIA',
1777
			) as $key ) {
1778
				if ( ! empty( $_SERVER[ $key ] ) ) {
1779
					return $_SERVER[ $key ];
1780
				}
1781
			}
1782
		}
1783
1784
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1785
	}
1786
1787
	/**
1788
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1789
	 */
1790
	function extra_oembed_providers() {
1791
		// Cloudup: https://dev.cloudup.com/#oembed
1792
		wp_oembed_add_provider( 'https://cloudup.com/*', 'https://cloudup.com/oembed' );
1793
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1794
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1795
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1796
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1797
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1798
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1799
	}
1800
1801
	/**
1802
	 * Synchronize connected user role changes
1803
	 */
1804
	function user_role_change( $user_id ) {
1805
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1806
		Users::user_role_change( $user_id );
1807
	}
1808
1809
	/**
1810
	 * Loads the currently active modules.
1811
	 */
1812
	public static function load_modules() {
1813
		$is_development_mode = ( new Status() )->is_development_mode();
1814
		if (
1815
			! self::is_active()
1816
			&& ! $is_development_mode
1817
			&& ! self::is_onboarding()
1818
			&& (
1819
				! is_multisite()
1820
				|| ! get_site_option( 'jetpack_protect_active' )
1821
			)
1822
		) {
1823
			return;
1824
		}
1825
1826
		$version = Jetpack_Options::get_option( 'version' );
1827 View Code Duplication
		if ( ! $version ) {
1828
			$version = $old_version = JETPACK__VERSION . ':' . time();
1829
			/** This action is documented in class.jetpack.php */
1830
			do_action( 'updating_jetpack_version', $version, false );
1831
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1832
		}
1833
		list( $version ) = explode( ':', $version );
1834
1835
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1836
1837
		$modules_data = array();
1838
1839
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1840
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1841
			$updated_modules = array();
1842
			foreach ( $modules as $module ) {
1843
				$modules_data[ $module ] = self::get_module( $module );
1844
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1845
					continue;
1846
				}
1847
1848
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1849
					continue;
1850
				}
1851
1852
				$updated_modules[] = $module;
1853
			}
1854
1855
			$modules = array_diff( $modules, $updated_modules );
1856
		}
1857
1858
		foreach ( $modules as $index => $module ) {
1859
			// If we're in dev mode, disable modules requiring a connection
1860
			if ( $is_development_mode ) {
1861
				// Prime the pump if we need to
1862
				if ( empty( $modules_data[ $module ] ) ) {
1863
					$modules_data[ $module ] = self::get_module( $module );
1864
				}
1865
				// If the module requires a connection, but we're in local mode, don't include it.
1866
				if ( $modules_data[ $module ]['requires_connection'] ) {
1867
					continue;
1868
				}
1869
			}
1870
1871
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1872
				continue;
1873
			}
1874
1875
			if ( ! include_once self::get_module_path( $module ) ) {
1876
				unset( $modules[ $index ] );
1877
				self::update_active_modules( array_values( $modules ) );
1878
				continue;
1879
			}
1880
1881
			/**
1882
			 * Fires when a specific module is loaded.
1883
			 * The dynamic part of the hook, $module, is the module slug.
1884
			 *
1885
			 * @since 1.1.0
1886
			 */
1887
			do_action( 'jetpack_module_loaded_' . $module );
1888
		}
1889
1890
		/**
1891
		 * Fires when all the modules are loaded.
1892
		 *
1893
		 * @since 1.1.0
1894
		 */
1895
		do_action( 'jetpack_modules_loaded' );
1896
1897
		// Load module-specific code that is needed even when a module isn't active. Loaded here because code contained therein may need actions such as setup_theme.
1898
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1899
	}
1900
1901
	/**
1902
	 * Check if Jetpack's REST API compat file should be included
1903
	 *
1904
	 * @action plugins_loaded
1905
	 * @return null
1906
	 */
1907
	public function check_rest_api_compat() {
1908
		/**
1909
		 * Filters the list of REST API compat files to be included.
1910
		 *
1911
		 * @since 2.2.5
1912
		 *
1913
		 * @param array $args Array of REST API compat files to include.
1914
		 */
1915
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1916
1917
		if ( function_exists( 'bbpress' ) ) {
1918
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1919
		}
1920
1921
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
1922
			require_once $_jetpack_rest_api_compat_include;
1923
		}
1924
	}
1925
1926
	/**
1927
	 * Gets all plugins currently active in values, regardless of whether they're
1928
	 * traditionally activated or network activated.
1929
	 *
1930
	 * @todo Store the result in core's object cache maybe?
1931
	 */
1932
	public static function get_active_plugins() {
1933
		$active_plugins = (array) get_option( 'active_plugins', array() );
1934
1935
		if ( is_multisite() ) {
1936
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1937
			// whereas active_plugins stores them in the values.
1938
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1939
			if ( $network_plugins ) {
1940
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1941
			}
1942
		}
1943
1944
		sort( $active_plugins );
1945
1946
		return array_unique( $active_plugins );
1947
	}
1948
1949
	/**
1950
	 * Gets and parses additional plugin data to send with the heartbeat data
1951
	 *
1952
	 * @since 3.8.1
1953
	 *
1954
	 * @return array Array of plugin data
1955
	 */
1956
	public static function get_parsed_plugin_data() {
1957
		if ( ! function_exists( 'get_plugins' ) ) {
1958
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
1959
		}
1960
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1961
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1962
		$active_plugins = self::get_active_plugins();
1963
1964
		$plugins = array();
1965
		foreach ( $all_plugins as $path => $plugin_data ) {
1966
			$plugins[ $path ] = array(
1967
				'is_active' => in_array( $path, $active_plugins ),
1968
				'file'      => $path,
1969
				'name'      => $plugin_data['Name'],
1970
				'version'   => $plugin_data['Version'],
1971
				'author'    => $plugin_data['Author'],
1972
			);
1973
		}
1974
1975
		return $plugins;
1976
	}
1977
1978
	/**
1979
	 * Gets and parses theme data to send with the heartbeat data
1980
	 *
1981
	 * @since 3.8.1
1982
	 *
1983
	 * @return array Array of theme data
1984
	 */
1985
	public static function get_parsed_theme_data() {
1986
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
1987
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1988
1989
		$themes = array();
1990
		foreach ( $all_themes as $slug => $theme_data ) {
1991
			$theme_headers = array();
1992
			foreach ( $header_keys as $header_key ) {
1993
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1994
			}
1995
1996
			$themes[ $slug ] = array(
1997
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
1998
				'slug'            => $slug,
1999
				'theme_root'      => $theme_data->get_theme_root_uri(),
2000
				'parent'          => $theme_data->parent(),
2001
				'headers'         => $theme_headers,
2002
			);
2003
		}
2004
2005
		return $themes;
2006
	}
2007
2008
	/**
2009
	 * Checks whether a specific plugin is active.
2010
	 *
2011
	 * We don't want to store these in a static variable, in case
2012
	 * there are switch_to_blog() calls involved.
2013
	 */
2014
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2015
		return in_array( $plugin, self::get_active_plugins() );
2016
	}
2017
2018
	/**
2019
	 * Check if Jetpack's Open Graph tags should be used.
2020
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2021
	 *
2022
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2023
	 * @action plugins_loaded
2024
	 * @return null
2025
	 */
2026
	public function check_open_graph() {
2027
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2028
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2029
		}
2030
2031
		$active_plugins = self::get_active_plugins();
2032
2033
		if ( ! empty( $active_plugins ) ) {
2034
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2035
				if ( in_array( $plugin, $active_plugins ) ) {
2036
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2037
					break;
2038
				}
2039
			}
2040
		}
2041
2042
		/**
2043
		 * Allow the addition of Open Graph Meta Tags to all pages.
2044
		 *
2045
		 * @since 2.0.3
2046
		 *
2047
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2048
		 */
2049
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2050
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2051
		}
2052
	}
2053
2054
	/**
2055
	 * Check if Jetpack's Twitter tags should be used.
2056
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2057
	 *
2058
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2059
	 * @action plugins_loaded
2060
	 * @return null
2061
	 */
2062
	public function check_twitter_tags() {
2063
2064
		$active_plugins = self::get_active_plugins();
2065
2066
		if ( ! empty( $active_plugins ) ) {
2067
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2068
				if ( in_array( $plugin, $active_plugins ) ) {
2069
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2070
					break;
2071
				}
2072
			}
2073
		}
2074
2075
		/**
2076
		 * Allow Twitter Card Meta tags to be disabled.
2077
		 *
2078
		 * @since 2.6.0
2079
		 *
2080
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2081
		 */
2082
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2083
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2084
		}
2085
	}
2086
2087
	/**
2088
	 * Allows plugins to submit security reports.
2089
	 *
2090
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2091
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2092
	 * @param array  $args         See definitions above
2093
	 */
2094
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2095
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2096
	}
2097
2098
	/* Jetpack Options API */
2099
2100
	public static function get_option_names( $type = 'compact' ) {
2101
		return Jetpack_Options::get_option_names( $type );
2102
	}
2103
2104
	/**
2105
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2106
	 *
2107
	 * @param string $name    Option name
2108
	 * @param mixed  $default (optional)
2109
	 */
2110
	public static function get_option( $name, $default = false ) {
2111
		return Jetpack_Options::get_option( $name, $default );
2112
	}
2113
2114
	/**
2115
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2116
	 *
2117
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2118
	 * @param string $name  Option name
2119
	 * @param mixed  $value Option value
2120
	 */
2121
	public static function update_option( $name, $value ) {
2122
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2123
		return Jetpack_Options::update_option( $name, $value );
2124
	}
2125
2126
	/**
2127
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2128
	 *
2129
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2130
	 * @param array $array array( option name => option value, ... )
2131
	 */
2132
	public static function update_options( $array ) {
2133
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2134
		return Jetpack_Options::update_options( $array );
2135
	}
2136
2137
	/**
2138
	 * Deletes the given option.  May be passed multiple option names as an array.
2139
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2140
	 *
2141
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2142
	 * @param string|array $names
2143
	 */
2144
	public static function delete_option( $names ) {
2145
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2146
		return Jetpack_Options::delete_option( $names );
2147
	}
2148
2149
	/**
2150
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2151
	 *
2152
	 * Enters a user token into the user_tokens option
2153
	 *
2154
	 * @param int    $user_id The user id.
2155
	 * @param string $token The user token.
2156
	 * @param bool   $is_master_user Whether the user is the master user.
2157
	 * @return bool
2158
	 */
2159
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2160
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2161
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2162
	}
2163
2164
	/**
2165
	 * Returns an array of all PHP files in the specified absolute path.
2166
	 * Equivalent to glob( "$absolute_path/*.php" ).
2167
	 *
2168
	 * @param string $absolute_path The absolute path of the directory to search.
2169
	 * @return array Array of absolute paths to the PHP files.
2170
	 */
2171
	public static function glob_php( $absolute_path ) {
2172
		if ( function_exists( 'glob' ) ) {
2173
			return glob( "$absolute_path/*.php" );
2174
		}
2175
2176
		$absolute_path = untrailingslashit( $absolute_path );
2177
		$files         = array();
2178
		if ( ! $dir = @opendir( $absolute_path ) ) {
2179
			return $files;
2180
		}
2181
2182
		while ( false !== $file = readdir( $dir ) ) {
2183
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2184
				continue;
2185
			}
2186
2187
			$file = "$absolute_path/$file";
2188
2189
			if ( ! is_file( $file ) ) {
2190
				continue;
2191
			}
2192
2193
			$files[] = $file;
2194
		}
2195
2196
		closedir( $dir );
2197
2198
		return $files;
2199
	}
2200
2201
	public static function activate_new_modules( $redirect = false ) {
2202
		if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
2203
			return;
2204
		}
2205
2206
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2207 View Code Duplication
		if ( ! $jetpack_old_version ) {
2208
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2209
			/** This action is documented in class.jetpack.php */
2210
			do_action( 'updating_jetpack_version', $version, false );
2211
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2212
		}
2213
2214
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2215
2216
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2217
			return;
2218
		}
2219
2220
		$active_modules     = self::get_active_modules();
2221
		$reactivate_modules = array();
2222
		foreach ( $active_modules as $active_module ) {
2223
			$module = self::get_module( $active_module );
2224
			if ( ! isset( $module['changed'] ) ) {
2225
				continue;
2226
			}
2227
2228
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2229
				continue;
2230
			}
2231
2232
			$reactivate_modules[] = $active_module;
2233
			self::deactivate_module( $active_module );
2234
		}
2235
2236
		$new_version = JETPACK__VERSION . ':' . time();
2237
		/** This action is documented in class.jetpack.php */
2238
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2239
		Jetpack_Options::update_options(
2240
			array(
2241
				'version'     => $new_version,
2242
				'old_version' => $jetpack_old_version,
2243
			)
2244
		);
2245
2246
		self::state( 'message', 'modules_activated' );
2247
		self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
2248
2249
		if ( $redirect ) {
2250
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2251
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2252
				$page = $_GET['page'];
2253
			}
2254
2255
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2256
			exit;
2257
		}
2258
	}
2259
2260
	/**
2261
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2262
	 * Make sure to tuck away module "library" files in a sub-directory.
2263
	 */
2264
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2265
		static $modules = null;
2266
2267
		if ( ! isset( $modules ) ) {
2268
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2269
			// Use the cache if we're on the front-end and it's available...
2270
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2271
				$modules = $available_modules_option[ JETPACK__VERSION ];
2272
			} else {
2273
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2274
2275
				$modules = array();
2276
2277
				foreach ( $files as $file ) {
2278
					if ( ! $headers = self::get_module( $file ) ) {
2279
						continue;
2280
					}
2281
2282
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2283
				}
2284
2285
				Jetpack_Options::update_option(
2286
					'available_modules',
2287
					array(
2288
						JETPACK__VERSION => $modules,
2289
					)
2290
				);
2291
			}
2292
		}
2293
2294
		/**
2295
		 * Filters the array of modules available to be activated.
2296
		 *
2297
		 * @since 2.4.0
2298
		 *
2299
		 * @param array $modules Array of available modules.
2300
		 * @param string $min_version Minimum version number required to use modules.
2301
		 * @param string $max_version Maximum version number required to use modules.
2302
		 */
2303
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2304
2305
		if ( ! $min_version && ! $max_version ) {
2306
			return array_keys( $mods );
2307
		}
2308
2309
		$r = array();
2310
		foreach ( $mods as $slug => $introduced ) {
2311
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2312
				continue;
2313
			}
2314
2315
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2316
				continue;
2317
			}
2318
2319
			$r[] = $slug;
2320
		}
2321
2322
		return $r;
2323
	}
2324
2325
	/**
2326
	 * Default modules loaded on activation.
2327
	 */
2328
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2329
		$return = array();
2330
2331
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2332
			$module_data = self::get_module( $module );
2333
2334
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2335
				case 'yes':
2336
					$return[] = $module;
2337
					break;
2338
				case 'public':
2339
					if ( Jetpack_Options::get_option( 'public' ) ) {
2340
						$return[] = $module;
2341
					}
2342
					break;
2343
				case 'no':
2344
				default:
2345
					break;
2346
			}
2347
		}
2348
		/**
2349
		 * Filters the array of default modules.
2350
		 *
2351
		 * @since 2.5.0
2352
		 *
2353
		 * @param array $return Array of default modules.
2354
		 * @param string $min_version Minimum version number required to use modules.
2355
		 * @param string $max_version Maximum version number required to use modules.
2356
		 */
2357
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2358
	}
2359
2360
	/**
2361
	 * Checks activated modules during auto-activation to determine
2362
	 * if any of those modules are being deprecated.  If so, close
2363
	 * them out, and add any replacement modules.
2364
	 *
2365
	 * Runs at priority 99 by default.
2366
	 *
2367
	 * This is run late, so that it can still activate a module if
2368
	 * the new module is a replacement for another that the user
2369
	 * currently has active, even if something at the normal priority
2370
	 * would kibosh everything.
2371
	 *
2372
	 * @since 2.6
2373
	 * @uses jetpack_get_default_modules filter
2374
	 * @param array $modules
2375
	 * @return array
2376
	 */
2377
	function handle_deprecated_modules( $modules ) {
2378
		$deprecated_modules = array(
2379
			'debug'            => null,  // Closed out and moved to the debugger library.
2380
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2381
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2382
		);
2383
2384
		// Don't activate SSO if they never completed activating WPCC.
2385
		if ( self::is_module_active( 'wpcc' ) ) {
2386
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2387
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2388
				$deprecated_modules['wpcc'] = null;
2389
			}
2390
		}
2391
2392
		foreach ( $deprecated_modules as $module => $replacement ) {
2393
			if ( self::is_module_active( $module ) ) {
2394
				self::deactivate_module( $module );
2395
				if ( $replacement ) {
2396
					$modules[] = $replacement;
2397
				}
2398
			}
2399
		}
2400
2401
		return array_unique( $modules );
2402
	}
2403
2404
	/**
2405
	 * Checks activated plugins during auto-activation to determine
2406
	 * if any of those plugins are in the list with a corresponding module
2407
	 * that is not compatible with the plugin. The module will not be allowed
2408
	 * to auto-activate.
2409
	 *
2410
	 * @since 2.6
2411
	 * @uses jetpack_get_default_modules filter
2412
	 * @param array $modules
2413
	 * @return array
2414
	 */
2415
	function filter_default_modules( $modules ) {
2416
2417
		$active_plugins = self::get_active_plugins();
2418
2419
		if ( ! empty( $active_plugins ) ) {
2420
2421
			// For each module we'd like to auto-activate...
2422
			foreach ( $modules as $key => $module ) {
2423
				// If there are potential conflicts for it...
2424
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2425
					// For each potential conflict...
2426
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2427
						// If that conflicting plugin is active...
2428
						if ( in_array( $plugin, $active_plugins ) ) {
2429
							// Remove that item from being auto-activated.
2430
							unset( $modules[ $key ] );
2431
						}
2432
					}
2433
				}
2434
			}
2435
		}
2436
2437
		return $modules;
2438
	}
2439
2440
	/**
2441
	 * Extract a module's slug from its full path.
2442
	 */
2443
	public static function get_module_slug( $file ) {
2444
		return str_replace( '.php', '', basename( $file ) );
2445
	}
2446
2447
	/**
2448
	 * Generate a module's path from its slug.
2449
	 */
2450
	public static function get_module_path( $slug ) {
2451
		/**
2452
		 * Filters the path of a modules.
2453
		 *
2454
		 * @since 7.4.0
2455
		 *
2456
		 * @param array $return The absolute path to a module's root php file
2457
		 * @param string $slug The module slug
2458
		 */
2459
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2460
	}
2461
2462
	/**
2463
	 * Load module data from module file. Headers differ from WordPress
2464
	 * plugin headers to avoid them being identified as standalone
2465
	 * plugins on the WordPress plugins page.
2466
	 */
2467
	public static function get_module( $module ) {
2468
		$headers = array(
2469
			'name'                      => 'Module Name',
2470
			'description'               => 'Module Description',
2471
			'sort'                      => 'Sort Order',
2472
			'recommendation_order'      => 'Recommendation Order',
2473
			'introduced'                => 'First Introduced',
2474
			'changed'                   => 'Major Changes In',
2475
			'deactivate'                => 'Deactivate',
2476
			'free'                      => 'Free',
2477
			'requires_connection'       => 'Requires Connection',
2478
			'auto_activate'             => 'Auto Activate',
2479
			'module_tags'               => 'Module Tags',
2480
			'feature'                   => 'Feature',
2481
			'additional_search_queries' => 'Additional Search Queries',
2482
			'plan_classes'              => 'Plans',
2483
		);
2484
2485
		$file = self::get_module_path( self::get_module_slug( $module ) );
2486
2487
		$mod = self::get_file_data( $file, $headers );
2488
		if ( empty( $mod['name'] ) ) {
2489
			return false;
2490
		}
2491
2492
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2493
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2494
		$mod['deactivate']           = empty( $mod['deactivate'] );
2495
		$mod['free']                 = empty( $mod['free'] );
2496
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2497
2498
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2499
			$mod['auto_activate'] = 'No';
2500
		} else {
2501
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2502
		}
2503
2504
		if ( $mod['module_tags'] ) {
2505
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2506
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2507
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2508
		} else {
2509
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2510
		}
2511
2512 View Code Duplication
		if ( $mod['plan_classes'] ) {
2513
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2514
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2515
		} else {
2516
			$mod['plan_classes'] = array( 'free' );
2517
		}
2518
2519 View Code Duplication
		if ( $mod['feature'] ) {
2520
			$mod['feature'] = explode( ',', $mod['feature'] );
2521
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2522
		} else {
2523
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2524
		}
2525
2526
		/**
2527
		 * Filters the feature array on a module.
2528
		 *
2529
		 * This filter allows you to control where each module is filtered: Recommended,
2530
		 * and the default "Other" listing.
2531
		 *
2532
		 * @since 3.5.0
2533
		 *
2534
		 * @param array   $mod['feature'] The areas to feature this module:
2535
		 *     'Recommended' shows on the main Jetpack admin screen.
2536
		 *     'Other' should be the default if no other value is in the array.
2537
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2538
		 * @param array   $mod All the currently assembled module data.
2539
		 */
2540
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2541
2542
		/**
2543
		 * Filter the returned data about a module.
2544
		 *
2545
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2546
		 * so please be careful.
2547
		 *
2548
		 * @since 3.6.0
2549
		 *
2550
		 * @param array   $mod    The details of the requested module.
2551
		 * @param string  $module The slug of the module, e.g. sharedaddy
2552
		 * @param string  $file   The path to the module source file.
2553
		 */
2554
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2555
	}
2556
2557
	/**
2558
	 * Like core's get_file_data implementation, but caches the result.
2559
	 */
2560
	public static function get_file_data( $file, $headers ) {
2561
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2562
		$file_name = basename( $file );
2563
2564
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2565
2566
		$file_data_option = get_transient( $cache_key );
2567
2568
		if ( ! is_array( $file_data_option ) ) {
2569
			delete_transient( $cache_key );
2570
			$file_data_option = false;
2571
		}
2572
2573
		if ( false === $file_data_option ) {
2574
			$file_data_option = array();
2575
		}
2576
2577
		$key           = md5( $file_name . serialize( $headers ) );
2578
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2579
2580
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2581
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2582
			return $file_data_option[ $key ];
2583
		}
2584
2585
		$data = get_file_data( $file, $headers );
2586
2587
		$file_data_option[ $key ] = $data;
2588
2589
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2590
2591
		return $data;
2592
	}
2593
2594
2595
	/**
2596
	 * Return translated module tag.
2597
	 *
2598
	 * @param string $tag Tag as it appears in each module heading.
2599
	 *
2600
	 * @return mixed
2601
	 */
2602
	public static function translate_module_tag( $tag ) {
2603
		return jetpack_get_module_i18n_tag( $tag );
2604
	}
2605
2606
	/**
2607
	 * Get i18n strings as a JSON-encoded string
2608
	 *
2609
	 * @return string The locale as JSON
2610
	 */
2611
	public static function get_i18n_data_json() {
2612
2613
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2614
		// JSON files with the file they should be included for. This is an md5
2615
		// of '_inc/build/admin.js'.
2616
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2617
2618
		$i18n_json =
2619
				   JETPACK__PLUGIN_DIR
2620
				   . 'languages/json/jetpack-'
2621
				   . get_user_locale()
2622
				   . '-'
2623
				   . $path_md5
2624
				   . '.json';
2625
2626
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2627
			$locale_data = @file_get_contents( $i18n_json );
2628
			if ( $locale_data ) {
2629
				return $locale_data;
2630
			}
2631
		}
2632
2633
		// Return valid empty Jed locale
2634
		return '{ "locale_data": { "messages": { "": {} } } }';
2635
	}
2636
2637
	/**
2638
	 * Add locale data setup to wp-i18n
2639
	 *
2640
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2641
	 *
2642
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2643
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2644
	 *
2645
	 * This method provides a safe way to request the setup multiple times but add the script at
2646
	 * most once.
2647
	 *
2648
	 * @since 6.7.0
2649
	 *
2650
	 * @return void
2651
	 */
2652
	public static function setup_wp_i18n_locale_data() {
2653
		static $script_added = false;
2654
		if ( ! $script_added ) {
2655
			$script_added = true;
2656
			wp_add_inline_script(
2657
				'wp-i18n',
2658
				'wp.i18n.setLocaleData( ' . self::get_i18n_data_json() . ', \'jetpack\' );'
2659
			);
2660
		}
2661
	}
2662
2663
	/**
2664
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2665
	 *
2666
	 * @since 3.9.2
2667
	 *
2668
	 * @param array $modules
2669
	 *
2670
	 * @return string|void
2671
	 */
2672
	public static function get_translated_modules( $modules ) {
2673
		foreach ( $modules as $index => $module ) {
2674
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2675
			if ( isset( $module['name'] ) ) {
2676
				$modules[ $index ]['name'] = $i18n_module['name'];
2677
			}
2678
			if ( isset( $module['description'] ) ) {
2679
				$modules[ $index ]['description']       = $i18n_module['description'];
2680
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2681
			}
2682
		}
2683
		return $modules;
2684
	}
2685
2686
	/**
2687
	 * Get a list of activated modules as an array of module slugs.
2688
	 */
2689
	public static function get_active_modules() {
2690
		$active = Jetpack_Options::get_option( 'active_modules' );
2691
2692
		if ( ! is_array( $active ) ) {
2693
			$active = array();
2694
		}
2695
2696
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2697
			$active[] = 'vaultpress';
2698
		} else {
2699
			$active = array_diff( $active, array( 'vaultpress' ) );
2700
		}
2701
2702
		// If protect is active on the main site of a multisite, it should be active on all sites.
2703
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2704
			$active[] = 'protect';
2705
		}
2706
2707
		/**
2708
		 * Allow filtering of the active modules.
2709
		 *
2710
		 * Gives theme and plugin developers the power to alter the modules that
2711
		 * are activated on the fly.
2712
		 *
2713
		 * @since 5.8.0
2714
		 *
2715
		 * @param array $active Array of active module slugs.
2716
		 */
2717
		$active = apply_filters( 'jetpack_active_modules', $active );
2718
2719
		return array_unique( $active );
2720
	}
2721
2722
	/**
2723
	 * Check whether or not a Jetpack module is active.
2724
	 *
2725
	 * @param string $module The slug of a Jetpack module.
2726
	 * @return bool
2727
	 *
2728
	 * @static
2729
	 */
2730
	public static function is_module_active( $module ) {
2731
		return in_array( $module, self::get_active_modules() );
2732
	}
2733
2734
	public static function is_module( $module ) {
2735
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2736
	}
2737
2738
	/**
2739
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2740
	 *
2741
	 * @param bool $catch True to start catching, False to stop.
2742
	 *
2743
	 * @static
2744
	 */
2745
	public static function catch_errors( $catch ) {
2746
		static $display_errors, $error_reporting;
2747
2748
		if ( $catch ) {
2749
			$display_errors  = @ini_set( 'display_errors', 1 );
2750
			$error_reporting = @error_reporting( E_ALL );
2751
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2752
		} else {
2753
			@ini_set( 'display_errors', $display_errors );
2754
			@error_reporting( $error_reporting );
2755
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2756
		}
2757
	}
2758
2759
	/**
2760
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2761
	 */
2762
	public static function catch_errors_on_shutdown() {
2763
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2764
	}
2765
2766
	/**
2767
	 * Rewrite any string to make paths easier to read.
2768
	 *
2769
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2770
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2771
	 *
2772
	 * @param $string
2773
	 * @return mixed
2774
	 */
2775
	public static function alias_directories( $string ) {
2776
		// ABSPATH has a trailing slash.
2777
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2778
		// WP_CONTENT_DIR does not have a trailing slash.
2779
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2780
2781
		return $string;
2782
	}
2783
2784
	public static function activate_default_modules(
2785
		$min_version = false,
2786
		$max_version = false,
2787
		$other_modules = array(),
2788
		$redirect = null,
2789
		$send_state_messages = null
2790
	) {
2791
		$jetpack = self::init();
2792
2793
		if ( is_null( $redirect ) ) {
2794
			if (
2795
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2796
			||
2797
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2798
			||
2799
				( defined( 'WP_CLI' ) && WP_CLI )
2800
			||
2801
				( defined( 'DOING_CRON' ) && DOING_CRON )
2802
			||
2803
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2804
			) {
2805
				$redirect = false;
2806
			} elseif ( is_admin() ) {
2807
				$redirect = true;
2808
			} else {
2809
				$redirect = false;
2810
			}
2811
		}
2812
2813
		if ( is_null( $send_state_messages ) ) {
2814
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2815
		}
2816
2817
		$modules = self::get_default_modules( $min_version, $max_version );
2818
		$modules = array_merge( $other_modules, $modules );
2819
2820
		// Look for standalone plugins and disable if active.
2821
2822
		$to_deactivate = array();
2823
		foreach ( $modules as $module ) {
2824
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2825
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2826
			}
2827
		}
2828
2829
		$deactivated = array();
2830
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2831
			list( $probable_file, $probable_title ) = $deactivate_me;
2832
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2833
				$deactivated[] = $module;
2834
			}
2835
		}
2836
2837
		if ( $deactivated ) {
2838
			if ( $send_state_messages ) {
2839
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2840
			}
2841
2842
			if ( $redirect ) {
2843
				$url = add_query_arg(
2844
					array(
2845
						'action'   => 'activate_default_modules',
2846
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2847
					),
2848
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2849
				);
2850
				wp_safe_redirect( $url );
2851
				exit;
2852
			}
2853
		}
2854
2855
		/**
2856
		 * Fires before default modules are activated.
2857
		 *
2858
		 * @since 1.9.0
2859
		 *
2860
		 * @param string $min_version Minimum version number required to use modules.
2861
		 * @param string $max_version Maximum version number required to use modules.
2862
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2863
		 */
2864
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2865
2866
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2867
		if ( $send_state_messages ) {
2868
			self::restate();
2869
			self::catch_errors( true );
2870
		}
2871
2872
		$active = self::get_active_modules();
2873
2874
		foreach ( $modules as $module ) {
2875
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2876
				$active[] = $module;
2877
				self::update_active_modules( $active );
2878
				continue;
2879
			}
2880
2881
			if ( $send_state_messages && in_array( $module, $active ) ) {
2882
				$module_info = self::get_module( $module );
2883 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2884
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2885
					if ( $active_state = self::state( $state ) ) {
2886
						$active_state = explode( ',', $active_state );
2887
					} else {
2888
						$active_state = array();
2889
					}
2890
					$active_state[] = $module;
2891
					self::state( $state, implode( ',', $active_state ) );
2892
				}
2893
				continue;
2894
			}
2895
2896
			$file = self::get_module_path( $module );
2897
			if ( ! file_exists( $file ) ) {
2898
				continue;
2899
			}
2900
2901
			// we'll override this later if the plugin can be included without fatal error
2902
			if ( $redirect ) {
2903
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2904
			}
2905
2906
			if ( $send_state_messages ) {
2907
				self::state( 'error', 'module_activation_failed' );
2908
				self::state( 'module', $module );
2909
			}
2910
2911
			ob_start();
2912
			require_once $file;
2913
2914
			$active[] = $module;
2915
2916 View Code Duplication
			if ( $send_state_messages ) {
2917
2918
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2919
				if ( $active_state = self::state( $state ) ) {
2920
					$active_state = explode( ',', $active_state );
2921
				} else {
2922
					$active_state = array();
2923
				}
2924
				$active_state[] = $module;
2925
				self::state( $state, implode( ',', $active_state ) );
2926
			}
2927
2928
			self::update_active_modules( $active );
2929
2930
			ob_end_clean();
2931
		}
2932
2933
		if ( $send_state_messages ) {
2934
			self::state( 'error', false );
2935
			self::state( 'module', false );
2936
		}
2937
2938
		self::catch_errors( false );
2939
		/**
2940
		 * Fires when default modules are activated.
2941
		 *
2942
		 * @since 1.9.0
2943
		 *
2944
		 * @param string $min_version Minimum version number required to use modules.
2945
		 * @param string $max_version Maximum version number required to use modules.
2946
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2947
		 */
2948
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2949
	}
2950
2951
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2952
		/**
2953
		 * Fires before a module is activated.
2954
		 *
2955
		 * @since 2.6.0
2956
		 *
2957
		 * @param string $module Module slug.
2958
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2959
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2960
		 */
2961
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2962
2963
		$jetpack = self::init();
2964
2965
		if ( ! strlen( $module ) ) {
2966
			return false;
2967
		}
2968
2969
		if ( ! self::is_module( $module ) ) {
2970
			return false;
2971
		}
2972
2973
		// If it's already active, then don't do it again
2974
		$active = self::get_active_modules();
2975
		foreach ( $active as $act ) {
2976
			if ( $act == $module ) {
2977
				return true;
2978
			}
2979
		}
2980
2981
		$module_data = self::get_module( $module );
2982
2983
		$is_development_mode = ( new Status() )->is_development_mode();
2984
		if ( ! self::is_active() ) {
2985
			if ( ! $is_development_mode && ! self::is_onboarding() ) {
2986
				return false;
2987
			}
2988
2989
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2990
			if ( $is_development_mode && $module_data['requires_connection'] ) {
2991
				return false;
2992
			}
2993
		}
2994
2995
		// Check and see if the old plugin is active
2996
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2997
			// Deactivate the old plugin
2998
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2999
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3000
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3001
				self::state( 'deactivated_plugins', $module );
3002
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3003
				exit;
3004
			}
3005
		}
3006
3007
		// Protect won't work with mis-configured IPs
3008
		if ( 'protect' === $module ) {
3009
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3010
			if ( ! jetpack_protect_get_ip() ) {
3011
				self::state( 'message', 'protect_misconfigured_ip' );
3012
				return false;
3013
			}
3014
		}
3015
3016
		if ( ! Jetpack_Plan::supports( $module ) ) {
3017
			return false;
3018
		}
3019
3020
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3021
		self::state( 'module', $module );
3022
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3023
3024
		self::catch_errors( true );
3025
		ob_start();
3026
		require self::get_module_path( $module );
3027
		/** This action is documented in class.jetpack.php */
3028
		do_action( 'jetpack_activate_module', $module );
3029
		$active[] = $module;
3030
		self::update_active_modules( $active );
3031
3032
		self::state( 'error', false ); // the override
3033
		ob_end_clean();
3034
		self::catch_errors( false );
3035
3036
		if ( $redirect ) {
3037
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3038
		}
3039
		if ( $exit ) {
3040
			exit;
3041
		}
3042
		return true;
3043
	}
3044
3045
	function activate_module_actions( $module ) {
3046
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3047
	}
3048
3049
	public static function deactivate_module( $module ) {
3050
		/**
3051
		 * Fires when a module is deactivated.
3052
		 *
3053
		 * @since 1.9.0
3054
		 *
3055
		 * @param string $module Module slug.
3056
		 */
3057
		do_action( 'jetpack_pre_deactivate_module', $module );
3058
3059
		$jetpack = self::init();
3060
3061
		$active = self::get_active_modules();
3062
		$new    = array_filter( array_diff( $active, (array) $module ) );
3063
3064
		return self::update_active_modules( $new );
3065
	}
3066
3067
	public static function enable_module_configurable( $module ) {
3068
		$module = self::get_module_slug( $module );
3069
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3070
	}
3071
3072
	/**
3073
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3074
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3075
	 *
3076
	 * @param string $module Module slug
3077
	 * @return string $url module configuration URL
3078
	 */
3079
	public static function module_configuration_url( $module ) {
3080
		$module      = self::get_module_slug( $module );
3081
		$default_url = self::admin_url() . "#/settings?term=$module";
3082
		/**
3083
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3084
		 *
3085
		 * @since 6.9.0
3086
		 *
3087
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3088
		 */
3089
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3090
3091
		return $url;
3092
	}
3093
3094
	/* Installation */
3095
	public static function bail_on_activation( $message, $deactivate = true ) {
3096
		?>
3097
<!doctype html>
3098
<html>
3099
<head>
3100
<meta charset="<?php bloginfo( 'charset' ); ?>">
3101
<style>
3102
* {
3103
	text-align: center;
3104
	margin: 0;
3105
	padding: 0;
3106
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3107
}
3108
p {
3109
	margin-top: 1em;
3110
	font-size: 18px;
3111
}
3112
</style>
3113
<body>
3114
<p><?php echo esc_html( $message ); ?></p>
3115
</body>
3116
</html>
3117
		<?php
3118
		if ( $deactivate ) {
3119
			$plugins = get_option( 'active_plugins' );
3120
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3121
			$update  = false;
3122
			foreach ( $plugins as $i => $plugin ) {
3123
				if ( $plugin === $jetpack ) {
3124
					$plugins[ $i ] = false;
3125
					$update        = true;
3126
				}
3127
			}
3128
3129
			if ( $update ) {
3130
				update_option( 'active_plugins', array_filter( $plugins ) );
3131
			}
3132
		}
3133
		exit;
3134
	}
3135
3136
	/**
3137
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3138
	 *
3139
	 * @static
3140
	 */
3141
	public static function plugin_activation( $network_wide ) {
3142
		Jetpack_Options::update_option( 'activated', 1 );
3143
3144
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3145
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3146
		}
3147
3148
		if ( $network_wide ) {
3149
			self::state( 'network_nag', true );
3150
		}
3151
3152
		// For firing one-off events (notices) immediately after activation
3153
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3154
3155
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3156
3157
		self::plugin_initialize();
3158
	}
3159
3160
	public static function get_activation_source( $referer_url ) {
3161
3162
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3163
			return array( 'wp-cli', null );
3164
		}
3165
3166
		$referer = wp_parse_url( $referer_url );
3167
3168
		$source_type  = 'unknown';
3169
		$source_query = null;
3170
3171
		if ( ! is_array( $referer ) ) {
3172
			return array( $source_type, $source_query );
3173
		}
3174
3175
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3176
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3177
3178
		if ( isset( $referer['query'] ) ) {
3179
			parse_str( $referer['query'], $query_parts );
3180
		} else {
3181
			$query_parts = array();
3182
		}
3183
3184
		if ( $plugins_path === $referer['path'] ) {
3185
			$source_type = 'list';
3186
		} elseif ( $plugins_install_path === $referer['path'] ) {
3187
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3188
			switch ( $tab ) {
3189
				case 'popular':
3190
					$source_type = 'popular';
3191
					break;
3192
				case 'recommended':
3193
					$source_type = 'recommended';
3194
					break;
3195
				case 'favorites':
3196
					$source_type = 'favorites';
3197
					break;
3198
				case 'search':
3199
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3200
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3201
					break;
3202
				default:
3203
					$source_type = 'featured';
3204
			}
3205
		}
3206
3207
		return array( $source_type, $source_query );
3208
	}
3209
3210
	/**
3211
	 * Runs before bumping version numbers up to a new version
3212
	 *
3213
	 * @param  string $version    Version:timestamp
3214
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3215
	 * @return null              [description]
3216
	 */
3217
	public static function do_version_bump( $version, $old_version ) {
3218
		if ( ! $old_version ) { // For new sites
3219
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3220
		}
3221
	}
3222
3223
	/**
3224
	 * Sets the internal version number and activation state.
3225
	 *
3226
	 * @static
3227
	 */
3228
	public static function plugin_initialize() {
3229
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3230
			Jetpack_Options::update_option( 'activated', 2 );
3231
		}
3232
3233 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3234
			$version = $old_version = JETPACK__VERSION . ':' . time();
3235
			/** This action is documented in class.jetpack.php */
3236
			do_action( 'updating_jetpack_version', $version, false );
3237
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3238
		}
3239
3240
		self::load_modules();
3241
3242
		Jetpack_Options::delete_option( 'do_activate' );
3243
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3244
	}
3245
3246
	/**
3247
	 * Removes all connection options
3248
	 *
3249
	 * @static
3250
	 */
3251
	public static function plugin_deactivation() {
3252
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3253
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3254
			Jetpack_Network::init()->deactivate();
3255
		} else {
3256
			self::disconnect( false );
3257
			// Jetpack_Heartbeat::init()->deactivate();
3258
		}
3259
	}
3260
3261
	/**
3262
	 * Disconnects from the Jetpack servers.
3263
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3264
	 *
3265
	 * @static
3266
	 */
3267
	public static function disconnect( $update_activated_state = true ) {
3268
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3269
		$connection = self::connection();
3270
		$connection->clean_nonces( true );
3271
3272
		// If the site is in an IDC because sync is not allowed,
3273
		// let's make sure to not disconnect the production site.
3274
		if ( ! self::validate_sync_error_idc_option() ) {
3275
			$tracking = new Tracking();
3276
			$tracking->record_user_event( 'disconnect_site', array() );
3277
3278
			$connection->disconnect_site_wpcom();
3279
		}
3280
3281
		$connection->delete_all_connection_tokens();
3282
		Jetpack_IDC::clear_all_idc_options();
3283
3284
		if ( $update_activated_state ) {
3285
			Jetpack_Options::update_option( 'activated', 4 );
3286
		}
3287
3288
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3289
			// Check then record unique disconnection if site has never been disconnected previously
3290
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3291
				$jetpack_unique_connection['disconnected'] = 1;
3292
			} else {
3293
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3294
					// track unique disconnect
3295
					$jetpack = self::init();
3296
3297
					$jetpack->stat( 'connections', 'unique-disconnect' );
3298
					$jetpack->do_stats( 'server_side' );
3299
				}
3300
				// increment number of times disconnected
3301
				$jetpack_unique_connection['disconnected'] += 1;
3302
			}
3303
3304
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3305
		}
3306
3307
		// Delete all the sync related data. Since it could be taking up space.
3308
		Sender::get_instance()->uninstall();
3309
3310
		// Disable the Heartbeat cron
3311
		Jetpack_Heartbeat::init()->deactivate();
3312
	}
3313
3314
	/**
3315
	 * Unlinks the current user from the linked WordPress.com user.
3316
	 *
3317
	 * @deprecated since 7.7
3318
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3319
	 *
3320
	 * @param Integer $user_id the user identifier.
3321
	 * @return Boolean Whether the disconnection of the user was successful.
3322
	 */
3323
	public static function unlink_user( $user_id = null ) {
3324
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3325
		return Connection_Manager::disconnect_user( $user_id );
3326
	}
3327
3328
	/**
3329
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3330
	 */
3331
	public static function try_registration() {
3332
		$terms_of_service = new Terms_Of_Service();
3333
		// The user has agreed to the TOS at some point by now.
3334
		$terms_of_service->agree();
3335
3336
		// Let's get some testing in beta versions and such.
3337
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3338
			// Before attempting to connect, let's make sure that the domains are viable.
3339
			$domains_to_check = array_unique(
3340
				array(
3341
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3342
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3343
				)
3344
			);
3345
			foreach ( $domains_to_check as $domain ) {
3346
				$result = self::connection()->is_usable_domain( $domain );
3347
				if ( is_wp_error( $result ) ) {
3348
					return $result;
3349
				}
3350
			}
3351
		}
3352
3353
		$result = self::register();
3354
3355
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3356
		if ( ! $result || is_wp_error( $result ) ) {
3357
			return $result;
3358
		} else {
3359
			return true;
3360
		}
3361
	}
3362
3363
	/**
3364
	 * Tracking an internal event log. Try not to put too much chaff in here.
3365
	 *
3366
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3367
	 */
3368
	public static function log( $code, $data = null ) {
3369
		// only grab the latest 200 entries
3370
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3371
3372
		// Append our event to the log
3373
		$log_entry = array(
3374
			'time'    => time(),
3375
			'user_id' => get_current_user_id(),
3376
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3377
			'code'    => $code,
3378
		);
3379
		// Don't bother storing it unless we've got some.
3380
		if ( ! is_null( $data ) ) {
3381
			$log_entry['data'] = $data;
3382
		}
3383
		$log[] = $log_entry;
3384
3385
		// Try add_option first, to make sure it's not autoloaded.
3386
		// @todo: Add an add_option method to Jetpack_Options
3387
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3388
			Jetpack_Options::update_option( 'log', $log );
3389
		}
3390
3391
		/**
3392
		 * Fires when Jetpack logs an internal event.
3393
		 *
3394
		 * @since 3.0.0
3395
		 *
3396
		 * @param array $log_entry {
3397
		 *  Array of details about the log entry.
3398
		 *
3399
		 *  @param string time Time of the event.
3400
		 *  @param int user_id ID of the user who trigerred the event.
3401
		 *  @param int blog_id Jetpack Blog ID.
3402
		 *  @param string code Unique name for the event.
3403
		 *  @param string data Data about the event.
3404
		 * }
3405
		 */
3406
		do_action( 'jetpack_log_entry', $log_entry );
3407
	}
3408
3409
	/**
3410
	 * Get the internal event log.
3411
	 *
3412
	 * @param $event (string) - only return the specific log events
3413
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3414
	 *
3415
	 * @return array of log events || WP_Error for invalid params
3416
	 */
3417
	public static function get_log( $event = false, $num = false ) {
3418
		if ( $event && ! is_string( $event ) ) {
3419
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3420
		}
3421
3422
		if ( $num && ! is_numeric( $num ) ) {
3423
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3424
		}
3425
3426
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3427
3428
		// If nothing set - act as it did before, otherwise let's start customizing the output
3429
		if ( ! $num && ! $event ) {
3430
			return $entire_log;
3431
		} else {
3432
			$entire_log = array_reverse( $entire_log );
3433
		}
3434
3435
		$custom_log_output = array();
3436
3437
		if ( $event ) {
3438
			foreach ( $entire_log as $log_event ) {
3439
				if ( $event == $log_event['code'] ) {
3440
					$custom_log_output[] = $log_event;
3441
				}
3442
			}
3443
		} else {
3444
			$custom_log_output = $entire_log;
3445
		}
3446
3447
		if ( $num ) {
3448
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3449
		}
3450
3451
		return $custom_log_output;
3452
	}
3453
3454
	/**
3455
	 * Log modification of important settings.
3456
	 */
3457
	public static function log_settings_change( $option, $old_value, $value ) {
3458
		switch ( $option ) {
3459
			case 'jetpack_sync_non_public_post_stati':
3460
				self::log( $option, $value );
3461
				break;
3462
		}
3463
	}
3464
3465
	/**
3466
	 * Return stat data for WPCOM sync
3467
	 */
3468
	public static function get_stat_data( $encode = true, $extended = true ) {
3469
		$data = Jetpack_Heartbeat::generate_stats_array();
3470
3471
		if ( $extended ) {
3472
			$additional_data = self::get_additional_stat_data();
3473
			$data            = array_merge( $data, $additional_data );
3474
		}
3475
3476
		if ( $encode ) {
3477
			return json_encode( $data );
3478
		}
3479
3480
		return $data;
3481
	}
3482
3483
	/**
3484
	 * Get additional stat data to sync to WPCOM
3485
	 */
3486
	public static function get_additional_stat_data( $prefix = '' ) {
3487
		$return[ "{$prefix}themes" ]        = self::get_parsed_theme_data();
3488
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3489
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3490
		$return[ "{$prefix}site-count" ]    = 0;
3491
3492
		if ( function_exists( 'get_blog_count' ) ) {
3493
			$return[ "{$prefix}site-count" ] = get_blog_count();
3494
		}
3495
		return $return;
3496
	}
3497
3498
	private static function get_site_user_count() {
3499
		global $wpdb;
3500
3501
		if ( function_exists( 'wp_is_large_network' ) ) {
3502
			if ( wp_is_large_network( 'users' ) ) {
3503
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3504
			}
3505
		}
3506
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3507
			// It wasn't there, so regenerate the data and save the transient
3508
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3509
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3510
		}
3511
		return $user_count;
3512
	}
3513
3514
	/* Admin Pages */
3515
3516
	function admin_init() {
3517
		// If the plugin is not connected, display a connect message.
3518
		if (
3519
			// the plugin was auto-activated and needs its candy
3520
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3521
		||
3522
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3523
			! Jetpack_Options::get_option( 'activated' )
3524
		) {
3525
			self::plugin_initialize();
3526
		}
3527
3528
		$is_development_mode = ( new Status() )->is_development_mode();
3529
		if ( ! self::is_active() && ! $is_development_mode ) {
3530
			Jetpack_Connection_Banner::init();
3531
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3532
			// Upgrade: 1.1 -> 1.1.1
3533
			// Check and see if host can verify the Jetpack servers' SSL certificate
3534
			$args       = array();
3535
			$connection = self::connection();
3536
			Client::_wp_remote_request(
3537
				Connection_Utils::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3538
				$args,
3539
				true
3540
			);
3541
		}
3542
3543
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3544
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3545
		}
3546
3547
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3548
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3549
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3550
3551
		if ( self::is_active() || $is_development_mode ) {
3552
			// Artificially throw errors in certain whitelisted cases during plugin activation
3553
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3554
		}
3555
3556
		// Add custom column in wp-admin/users.php to show whether user is linked.
3557
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3558
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3559
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3560
	}
3561
3562
	function admin_body_class( $admin_body_class = '' ) {
3563
		$classes = explode( ' ', trim( $admin_body_class ) );
3564
3565
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3566
3567
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3568
		return " $admin_body_class ";
3569
	}
3570
3571
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3572
		return $admin_body_class . ' jetpack-pagestyles ';
3573
	}
3574
3575
	/**
3576
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3577
	 * This function artificially throws errors for such cases (whitelisted).
3578
	 *
3579
	 * @param string $plugin The activated plugin.
3580
	 */
3581
	function throw_error_on_activate_plugin( $plugin ) {
3582
		$active_modules = self::get_active_modules();
3583
3584
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3585
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3586
			$throw = false;
3587
3588
			// Try and make sure it really was the stats plugin
3589
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3590
				if ( 'stats.php' == basename( $plugin ) ) {
3591
					$throw = true;
3592
				}
3593
			} else {
3594
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3595
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3596
					$throw = true;
3597
				}
3598
			}
3599
3600
			if ( $throw ) {
3601
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3602
			}
3603
		}
3604
	}
3605
3606
	function intercept_plugin_error_scrape_init() {
3607
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3608
	}
3609
3610
	function intercept_plugin_error_scrape( $action, $result ) {
3611
		if ( ! $result ) {
3612
			return;
3613
		}
3614
3615
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3616
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3617
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3618
			}
3619
		}
3620
	}
3621
3622
	/**
3623
	 * Register the remote file upload request handlers, if needed.
3624
	 *
3625
	 * @access public
3626
	 */
3627
	public function add_remote_request_handlers() {
3628
		// Remote file uploads are allowed only via AJAX requests.
3629
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3630
			return;
3631
		}
3632
3633
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3634
		$remote_request_actions = array(
3635
			'jetpack_upload_file',
3636
			'jetpack_update_file',
3637
		);
3638
3639
		// phpcs:ignore WordPress.Security.NonceVerification
3640
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3641
			return;
3642
		}
3643
3644
		// Require Jetpack authentication for the remote file upload AJAX requests.
3645
		$this->connection_manager->require_jetpack_authentication();
3646
3647
		// Register the remote file upload AJAX handlers.
3648
		foreach ( $remote_request_actions as $action ) {
3649
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3650
		}
3651
	}
3652
3653
	/**
3654
	 * Handler for Jetpack remote file uploads.
3655
	 *
3656
	 * @access public
3657
	 */
3658
	public function remote_request_handlers() {
3659
		$action = current_filter();
3660
3661
		switch ( current_filter() ) {
3662
			case 'wp_ajax_nopriv_jetpack_upload_file':
3663
				$response = $this->upload_handler();
3664
				break;
3665
3666
			case 'wp_ajax_nopriv_jetpack_update_file':
3667
				$response = $this->upload_handler( true );
3668
				break;
3669
			default:
3670
				$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3671
				break;
3672
		}
3673
3674
		if ( ! $response ) {
3675
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3676
		}
3677
3678
		if ( is_wp_error( $response ) ) {
3679
			$status_code       = $response->get_error_data();
3680
			$error             = $response->get_error_code();
3681
			$error_description = $response->get_error_message();
3682
3683
			if ( ! is_int( $status_code ) ) {
3684
				$status_code = 400;
3685
			}
3686
3687
			status_header( $status_code );
3688
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3689
		}
3690
3691
		status_header( 200 );
3692
		if ( true === $response ) {
3693
			exit;
3694
		}
3695
3696
		die( json_encode( (object) $response ) );
3697
	}
3698
3699
	/**
3700
	 * Uploads a file gotten from the global $_FILES.
3701
	 * If `$update_media_item` is true and `post_id` is defined
3702
	 * the attachment file of the media item (gotten through of the post_id)
3703
	 * will be updated instead of add a new one.
3704
	 *
3705
	 * @param  boolean $update_media_item - update media attachment
3706
	 * @return array - An array describing the uploadind files process
3707
	 */
3708
	function upload_handler( $update_media_item = false ) {
3709
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3710
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3711
		}
3712
3713
		$user = wp_authenticate( '', '' );
3714
		if ( ! $user || is_wp_error( $user ) ) {
3715
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3716
		}
3717
3718
		wp_set_current_user( $user->ID );
3719
3720
		if ( ! current_user_can( 'upload_files' ) ) {
3721
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3722
		}
3723
3724
		if ( empty( $_FILES ) ) {
3725
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3726
		}
3727
3728
		foreach ( array_keys( $_FILES ) as $files_key ) {
3729
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3730
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3731
			}
3732
		}
3733
3734
		$media_keys = array_keys( $_FILES['media'] );
3735
3736
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3737
		if ( ! $token || is_wp_error( $token ) ) {
3738
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3739
		}
3740
3741
		$uploaded_files = array();
3742
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3743
		unset( $GLOBALS['post'] );
3744
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3745
			$file = array();
3746
			foreach ( $media_keys as $media_key ) {
3747
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3748
			}
3749
3750
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3751
3752
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3753
			if ( $hmac_provided !== $hmac_file ) {
3754
				$uploaded_files[ $index ] = (object) array(
3755
					'error'             => 'invalid_hmac',
3756
					'error_description' => 'The corresponding HMAC for this file does not match',
3757
				);
3758
				continue;
3759
			}
3760
3761
			$_FILES['.jetpack.upload.'] = $file;
3762
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3763
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3764
				$post_id = 0;
3765
			}
3766
3767
			if ( $update_media_item ) {
3768
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3769
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3770
				}
3771
3772
				$media_array = $_FILES['media'];
3773
3774
				$file_array['name']     = $media_array['name'][0];
3775
				$file_array['type']     = $media_array['type'][0];
3776
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3777
				$file_array['error']    = $media_array['error'][0];
3778
				$file_array['size']     = $media_array['size'][0];
3779
3780
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3781
3782
				if ( is_wp_error( $edited_media_item ) ) {
3783
					return $edited_media_item;
3784
				}
3785
3786
				$response = (object) array(
3787
					'id'   => (string) $post_id,
3788
					'file' => (string) $edited_media_item->post_title,
3789
					'url'  => (string) wp_get_attachment_url( $post_id ),
3790
					'type' => (string) $edited_media_item->post_mime_type,
3791
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3792
				);
3793
3794
				return (array) array( $response );
3795
			}
3796
3797
			$attachment_id = media_handle_upload(
3798
				'.jetpack.upload.',
3799
				$post_id,
3800
				array(),
3801
				array(
3802
					'action' => 'jetpack_upload_file',
3803
				)
3804
			);
3805
3806
			if ( ! $attachment_id ) {
3807
				$uploaded_files[ $index ] = (object) array(
3808
					'error'             => 'unknown',
3809
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3810
				);
3811
			} elseif ( is_wp_error( $attachment_id ) ) {
3812
				$uploaded_files[ $index ] = (object) array(
3813
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3814
					'error_description' => $attachment_id->get_error_message(),
3815
				);
3816
			} else {
3817
				$attachment               = get_post( $attachment_id );
3818
				$uploaded_files[ $index ] = (object) array(
3819
					'id'   => (string) $attachment_id,
3820
					'file' => $attachment->post_title,
3821
					'url'  => wp_get_attachment_url( $attachment_id ),
3822
					'type' => $attachment->post_mime_type,
3823
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3824
				);
3825
				// Zip files uploads are not supported unless they are done for installation purposed
3826
				// lets delete them in case something goes wrong in this whole process
3827
				if ( 'application/zip' === $attachment->post_mime_type ) {
3828
					// Schedule a cleanup for 2 hours from now in case of failed install.
3829
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3830
				}
3831
			}
3832
		}
3833
		if ( ! is_null( $global_post ) ) {
3834
			$GLOBALS['post'] = $global_post;
3835
		}
3836
3837
		return $uploaded_files;
3838
	}
3839
3840
	/**
3841
	 * Add help to the Jetpack page
3842
	 *
3843
	 * @since Jetpack (1.2.3)
3844
	 * @return false if not the Jetpack page
3845
	 */
3846
	function admin_help() {
3847
		$current_screen = get_current_screen();
3848
3849
		// Overview
3850
		$current_screen->add_help_tab(
3851
			array(
3852
				'id'      => 'home',
3853
				'title'   => __( 'Home', 'jetpack' ),
3854
				'content' =>
3855
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3856
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3857
					'<p>' . __( 'On this page, you are able to view the modules available within Jetpack, learn more about them, and activate or deactivate them as needed.', 'jetpack' ) . '</p>',
3858
			)
3859
		);
3860
3861
		// Screen Content
3862
		if ( current_user_can( 'manage_options' ) ) {
3863
			$current_screen->add_help_tab(
3864
				array(
3865
					'id'      => 'settings',
3866
					'title'   => __( 'Settings', 'jetpack' ),
3867
					'content' =>
3868
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3869
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3870
						'<ol>' .
3871
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3872
							'<li>' . __( 'Using the checkboxes next to each module, you can select multiple modules to toggle via the Bulk Actions menu at the top of the list.', 'jetpack' ) . '</li>' .
3873
						'</ol>' .
3874
						'<p>' . __( 'Using the tools on the right, you can search for specific modules, filter by module categories or which are active, or change the sorting order.', 'jetpack' ) . '</p>',
3875
				)
3876
			);
3877
		}
3878
3879
		// Help Sidebar
3880
		$current_screen->set_help_sidebar(
3881
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3882
			'<p><a href="https://jetpack.com/faq/" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3883
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3884
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3885
		);
3886
	}
3887
3888
	function admin_menu_css() {
3889
		wp_enqueue_style( 'jetpack-icons' );
3890
	}
3891
3892
	function admin_menu_order() {
3893
		return true;
3894
	}
3895
3896 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3897
		$jp_menu_order = array();
3898
3899
		foreach ( $menu_order as $index => $item ) {
3900
			if ( $item != 'jetpack' ) {
3901
				$jp_menu_order[] = $item;
3902
			}
3903
3904
			if ( $index == 0 ) {
3905
				$jp_menu_order[] = 'jetpack';
3906
			}
3907
		}
3908
3909
		return $jp_menu_order;
3910
	}
3911
3912
	function admin_banner_styles() {
3913
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3914
3915 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3916
			wp_register_style(
3917
				'jetpack-dops-style',
3918
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3919
				array(),
3920
				JETPACK__VERSION
3921
			);
3922
		}
3923
3924
		wp_enqueue_style(
3925
			'jetpack',
3926
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3927
			array( 'jetpack-dops-style' ),
3928
			JETPACK__VERSION . '-20121016'
3929
		);
3930
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3931
		wp_style_add_data( 'jetpack', 'suffix', $min );
3932
	}
3933
3934
	function plugin_action_links( $actions ) {
3935
3936
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3937
3938
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_development_mode() ) ) {
3939
			return array_merge(
3940
				$jetpack_home,
3941
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3942
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
3943
				$actions
3944
			);
3945
		}
3946
3947
		return array_merge( $jetpack_home, $actions );
3948
	}
3949
3950
	/*
3951
	 * Registration flow:
3952
	 * 1 - ::admin_page_load() action=register
3953
	 * 2 - ::try_registration()
3954
	 * 3 - ::register()
3955
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3956
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3957
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3958
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3959
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3960
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3961
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3962
	 *       jetpack_id, jetpack_secret, jetpack_public
3963
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3964
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3965
	 * 5 - user logs in with WP.com account
3966
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3967
	 *		- Manager::authorize()
3968
	 *		- Manager::get_token()
3969
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3970
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3971
	 *			- which responds with access_token, token_type, scope
3972
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
3973
	 *		- Jetpack::activate_default_modules()
3974
	 *     		- Deactivates deprecated plugins
3975
	 *     		- Activates all default modules
3976
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3977
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3978
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3979
	 *     Done!
3980
	 */
3981
3982
	/**
3983
	 * Handles the page load events for the Jetpack admin page
3984
	 */
3985
	function admin_page_load() {
3986
		$error = false;
3987
3988
		// Make sure we have the right body class to hook stylings for subpages off of.
3989
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
3990
3991
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3992
			// Should only be used in intermediate redirects to preserve state across redirects
3993
			self::restate();
3994
		}
3995
3996
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3997
			// @todo: Add validation against a known whitelist
3998
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3999
			// User clicked in the iframe to link their accounts
4000
			if ( ! self::is_user_connected() ) {
4001
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4002
4003
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4004
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4005
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4006
4007
				if ( isset( $_GET['notes_iframe'] ) ) {
4008
					$connect_url .= '&notes_iframe';
4009
				}
4010
				wp_redirect( $connect_url );
4011
				exit;
4012
			} else {
4013
				if ( ! isset( $_GET['calypso_env'] ) ) {
4014
					self::state( 'message', 'already_authorized' );
4015
					wp_safe_redirect( self::admin_url() );
4016
					exit;
4017
				} else {
4018
					$connect_url  = $this->build_connect_url( true, false, $from );
4019
					$connect_url .= '&already_authorized=true';
4020
					wp_redirect( $connect_url );
4021
					exit;
4022
				}
4023
			}
4024
		}
4025
4026
		if ( isset( $_GET['action'] ) ) {
4027
			switch ( $_GET['action'] ) {
4028
				case 'authorize':
4029
					if ( self::is_active() && self::is_user_connected() ) {
4030
						self::state( 'message', 'already_authorized' );
4031
						wp_safe_redirect( self::admin_url() );
4032
						exit;
4033
					}
4034
					self::log( 'authorize' );
4035
					$client_server = new Jetpack_Client_Server();
4036
					$client_server->client_authorize();
4037
					exit;
4038
				case 'register':
4039
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4040
						$this->error = 'cheatin';
4041
						break;
4042
					}
4043
					check_admin_referer( 'jetpack-register' );
4044
					self::log( 'register' );
4045
					self::maybe_set_version_option();
4046
					$registered = self::try_registration();
4047
					if ( is_wp_error( $registered ) ) {
4048
						$this->error = $registered->get_error_code();
4049
						self::state( 'error', $this->error );
4050
						self::state( 'error', $registered->get_error_message() );
4051
4052
						/**
4053
						 * Jetpack registration Error.
4054
						 *
4055
						 * @since 7.5.0
4056
						 *
4057
						 * @param string|int $error The error code.
4058
						 * @param \WP_Error $registered The error object.
4059
						 */
4060
						do_action( 'jetpack_connection_register_fail', $this->error, $registered );
4061
						break;
4062
					}
4063
4064
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4065
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4066
4067
					/**
4068
					 * Jetpack registration Success.
4069
					 *
4070
					 * @since 7.5.0
4071
					 *
4072
					 * @param string $from 'from' GET parameter;
4073
					 */
4074
					do_action( 'jetpack_connection_register_success', $from );
4075
4076
					$url = $this->build_connect_url( true, $redirect, $from );
4077
4078
					if ( ! empty( $_GET['onboarding'] ) ) {
4079
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4080
					}
4081
4082
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4083
						$url = add_query_arg( 'auth_approved', 'true', $url );
4084
					}
4085
4086
					wp_redirect( $url );
4087
					exit;
4088
				case 'activate':
4089
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4090
						$this->error = 'cheatin';
4091
						break;
4092
					}
4093
4094
					$module = stripslashes( $_GET['module'] );
4095
					check_admin_referer( "jetpack_activate-$module" );
4096
					self::log( 'activate', $module );
4097
					if ( ! self::activate_module( $module ) ) {
4098
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4099
					}
4100
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4101
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4102
					exit;
4103
				case 'activate_default_modules':
4104
					check_admin_referer( 'activate_default_modules' );
4105
					self::log( 'activate_default_modules' );
4106
					self::restate();
4107
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4108
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4109
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4110
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4111
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4112
					exit;
4113
				case 'disconnect':
4114
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4115
						$this->error = 'cheatin';
4116
						break;
4117
					}
4118
4119
					check_admin_referer( 'jetpack-disconnect' );
4120
					self::log( 'disconnect' );
4121
					self::disconnect();
4122
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4123
					exit;
4124
				case 'reconnect':
4125
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4126
						$this->error = 'cheatin';
4127
						break;
4128
					}
4129
4130
					check_admin_referer( 'jetpack-reconnect' );
4131
					self::log( 'reconnect' );
4132
					$this->disconnect();
4133
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4134
					exit;
4135
				case 'deactivate':
4136
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4137
						$this->error = 'cheatin';
4138
						break;
4139
					}
4140
4141
					$modules = stripslashes( $_GET['module'] );
4142
					check_admin_referer( "jetpack_deactivate-$modules" );
4143
					foreach ( explode( ',', $modules ) as $module ) {
4144
						self::log( 'deactivate', $module );
4145
						self::deactivate_module( $module );
4146
						self::state( 'message', 'module_deactivated' );
4147
					}
4148
					self::state( 'module', $modules );
4149
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4150
					exit;
4151
				case 'unlink':
4152
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4153
					check_admin_referer( 'jetpack-unlink' );
4154
					self::log( 'unlink' );
4155
					Connection_Manager::disconnect_user();
4156
					self::state( 'message', 'unlinked' );
4157
					if ( 'sub-unlink' == $redirect ) {
4158
						wp_safe_redirect( admin_url() );
4159
					} else {
4160
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4161
					}
4162
					exit;
4163
				case 'onboard':
4164
					if ( ! current_user_can( 'manage_options' ) ) {
4165
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4166
					} else {
4167
						self::create_onboarding_token();
4168
						$url = $this->build_connect_url( true );
4169
4170
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4171
							$url = add_query_arg( 'onboarding', $token, $url );
4172
						}
4173
4174
						$calypso_env = $this->get_calypso_env();
4175
						if ( ! empty( $calypso_env ) ) {
4176
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4177
						}
4178
4179
						wp_redirect( $url );
4180
						exit;
4181
					}
4182
					exit;
4183
				default:
4184
					/**
4185
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4186
					 *
4187
					 * @since 2.6.0
4188
					 *
4189
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4190
					 */
4191
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4192
			}
4193
		}
4194
4195
		if ( false == $this->error && empty( self::state( 'error' ) ) ) {
4196
			self::activate_new_modules( true );
4197
		}
4198
4199
		$message_code = self::state( 'message' );
4200
		if ( self::state( 'optin-manage' ) ) {
4201
			$activated_manage = $message_code;
4202
			$message_code     = 'jetpack-manage';
4203
		}
4204
4205
		switch ( $message_code ) {
4206
			case 'jetpack-manage':
4207
				$this->message = '<strong>' . sprintf( __( 'You are all set! Your site can now be managed from <a href="%s" target="_blank">wordpress.com/sites</a>.', 'jetpack' ), 'https://wordpress.com/sites' ) . '</strong>';
4208
				if ( $activated_manage ) {
4209
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4210
				}
4211
				break;
4212
4213
		}
4214
4215
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4216
4217
		if ( ! empty( $deactivated_plugins ) ) {
4218
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4219
			$deactivated_titles  = array();
4220
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4221
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4222
					continue;
4223
				}
4224
4225
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4226
			}
4227
4228
			if ( $deactivated_titles ) {
4229
				if ( $this->message ) {
4230
					$this->message .= "<br /><br />\n";
4231
				}
4232
4233
				$this->message .= wp_sprintf(
4234
					_n(
4235
						'Jetpack contains the most recent version of the old %l plugin.',
4236
						'Jetpack contains the most recent versions of the old %l plugins.',
4237
						count( $deactivated_titles ),
4238
						'jetpack'
4239
					),
4240
					$deactivated_titles
4241
				);
4242
4243
				$this->message .= "<br />\n";
4244
4245
				$this->message .= _n(
4246
					'The old version has been deactivated and can be removed from your site.',
4247
					'The old versions have been deactivated and can be removed from your site.',
4248
					count( $deactivated_titles ),
4249
					'jetpack'
4250
				);
4251
			}
4252
		}
4253
4254
		$this->privacy_checks = self::state( 'privacy_checks' );
4255
4256
		if ( $this->message || $this->error || $this->privacy_checks ) {
4257
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4258
		}
4259
4260
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4261
	}
4262
4263
	/**
4264
     * Converts an error_code into a user friendly string for admin notices
4265
     *
4266
	 * @param $error
4267
	 *
4268
	 * @return string
4269
	 */
4270
	private function pretty_error_codes( $error ) {
4271
4272
	    $message = '';
0 ignored issues
show
$message is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
4273
		switch ( $error ) {
4274
			case 'cheatin':
4275
				$message = __( "Cheatin' uh?", 'jetpack' );
4276
				break;
4277
			case 'access_denied':
4278
				$message = sprintf(
4279
					__( 'Would you mind telling us why you did not complete the Jetpack connection in this ' .
4280
					    ' <a href="%s">2 question survey</a>?</br>' .
4281
                        'A Jetpack connection is required for our free security and traffic features to work.', 'jetpack' ),
4282
					'href="https://jetpack.com/cancelled-connection/" rel="noopener noreferrer" target="_blank"'
4283
				);
4284
		        break;
4285
	        case 'wrong_state':
4286
				$message = __(
4287
					'You need to stay logged in to your WordPress blog while you authorize Jetpack.', 'jetpack'
4288
				);
4289
				break;
4290
			case 'invalid_client':
4291
				$message = __(
4292
					'We had an issue connecting Jetpack; deactivate then reactivate the Jetpack plugin, then connect again.', 'jetpack'
4293
				);
4294
				break;
4295
			case 'invalid_grant':
4296
				$message = __(
4297
					'There was an issue connecting your Jetpack. Please click "Connect to WordPress.com" again.', 'jetpack'
4298
				);
4299
				break;
4300
			case 'site_inaccessible':
4301
			case 'site_requires_authorization':
4302
				$message = __(
4303
					'Your website needs to be publicly accessible to use Jetpack.', 'jetpack'
4304
				);
4305
				break;
4306
			case 'site_blacklisted':
4307
				$message = sprintf(
4308
				        __( 'This site can\'t be connected to WordPress.com because it violates our ' .
4309
                            ' <a href="%s">Terms of Service</a>.', 'jetpack' ),
4310
					'href="https://wordpress.com/tos" rel="noopener noreferrer" target="_blank"'
4311
				);
4312
				break;
4313
			case 'not_public':
4314
				$message = __(
4315
					'<strong>Your Jetpack has a glitch.</strong> Connecting this site with WordPress.com is not possible. ' +
4316
					'This usually means your site is not publicly accessible (localhost).', 'jetpack'
4317
				);
4318
				break;
4319
			case 'wpcom_408':
4320
			case 'wpcom_5??':
4321
			case 'wpcom_bad_response':
4322
			case 'wpcom_outage':
4323
				$message = __(
4324
					'WordPress.com is currently having problems and is unable to fuel up your Jetpack.  Please try again later.', 'jetpack'
4325
				);
4326
				break;
4327
			case 'register_http_request_failed':
4328
			case 'token_http_request_failed':
4329
				$message = __(
4330
					'Jetpack could not contact WordPress.com.  This usually means something is incorrectly configured on your web host.',
4331
					'jetpack'
4332
				);
4333
				break;
4334
			case 'no_role':
4335
			case 'no_cap':
4336
			case 'no_code':
4337
			case 'no_state':
4338
			case 'invalid_state':
4339
			case 'invalid_request':
4340
			case 'invalid_scope':
4341
			case 'unsupported_response_type':
4342
			case 'invalid_token':
4343
			case 'no_token':
4344
			case 'missing_secrets':
4345
			case 'home_missing':
4346
			case 'siteurl_missing':
4347
			case 'gmt_offset_missing':
4348
			case 'site_name_missing':
4349
			case 'secret_1_missing':
4350
			case 'secret_2_missing':
4351
			case 'site_lang_missing':
4352
			case 'home_malformed':
4353
			case 'siteurl_malformed':
4354
			case 'gmt_offset_malformed':
4355
			case 'timezone_string_malformed':
4356
			case 'site_name_malformed':
4357
			case 'secret_1_malformed':
4358
			case 'secret_2_malformed':
4359
			case 'site_lang_malformed':
4360
			case 'secrets_mismatch':
4361
			case 'verify_secret_1_missing':
4362
			case 'verify_secret_1_malformed':
4363
			case 'verify_secrets_missing':
4364
			case 'verify_secrets_mismatch':
4365
				$message = __(
4366
					"<strong>Your Jetpack has a glitch.</strong>  We're sorry for the inconvenience. " +
4367
					'Please try again later, if the issue continues please contact support with this message:',
4368
                    'jetpack'
4369
				);
4370
				$message .= " " . esc_html( $error );
4371
				break;
4372
			default:
4373
				$message =
4374
				$message = sprintf(
4375
                    __(
4376
                        "<strong>Your Jetpack has a glitch.</strong>  We're sorry for the inconvenience. " +
4377
                        'Please try again later, if the issue continues please contact support with this message: %s',
4378
                        'jetpack'
4379
                    ),
4380
				    esc_html( $error )
4381
                );
4382
		}
4383
4384
		return $message;
4385
4386
    }
4387
4388
4389
	function admin_notices() {
4390
		if ( $this->error ) {
4391
			?>
4392
<div id="message" class="jetpack-message jetpack-err">
4393
	<div class="squeezer">
4394
		<h2>
4395
			<?php
4396
			echo wp_kses(
4397
				$this->pretty_error_codes( $this->error ),
4398
				array(
4399
					'a'      => array( 'href' => array(), 'rel' => array(), 'target' => array() ),
4400
					'small'  => true,
4401
					'code'   => true,
4402
					'strong' => true,
4403
					'br'     => true,
4404
					'b'      => true,
4405
				)
4406
			);
4407
			?>
4408
			</h2>
4409
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4410
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4411
<?php	endif; ?>
4412
	</div>
4413
</div>
4414
			<?php
4415
		}
4416
4417
		if ( $this->message ) {
4418
			?>
4419
<div id="message" class="jetpack-message">
4420
	<div class="squeezer">
4421
		<h2>
4422
			<?php
4423
			echo wp_kses(
4424
				$this->message,
4425
				array(
4426
					'strong' => array(),
4427
					'a'      => array( 'href' => true ),
4428
					'br'     => true,
4429
				)
4430
			);
4431
			?>
4432
			</h2>
4433
	</div>
4434
</div>
4435
			<?php
4436
		}
4437
4438
		if ( $this->privacy_checks ) :
4439
			$module_names = $module_slugs = array();
4440
4441
			$privacy_checks = explode( ',', $this->privacy_checks );
4442
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4443
			foreach ( $privacy_checks as $module_slug ) {
4444
				$module = self::get_module( $module_slug );
4445
				if ( ! $module ) {
4446
					continue;
4447
				}
4448
4449
				$module_slugs[] = $module_slug;
4450
				$module_names[] = "<strong>{$module['name']}</strong>";
4451
			}
4452
4453
			$module_slugs = join( ',', $module_slugs );
4454
			?>
4455
<div id="message" class="jetpack-message jetpack-err">
4456
	<div class="squeezer">
4457
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4458
		<p>
4459
			<?php
4460
			echo wp_kses(
4461
				wptexturize(
4462
					wp_sprintf(
4463
						_nx(
4464
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4465
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4466
							count( $privacy_checks ),
4467
							'%l = list of Jetpack module/feature names',
4468
							'jetpack'
4469
						),
4470
						$module_names
4471
					)
4472
				),
4473
				array( 'strong' => true )
4474
			);
4475
4476
			echo "\n<br />\n";
4477
4478
			echo wp_kses(
4479
				sprintf(
4480
					_nx(
4481
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4482
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4483
						count( $privacy_checks ),
4484
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4485
						'jetpack'
4486
					),
4487
					wp_nonce_url(
4488
						self::admin_url(
4489
							array(
4490
								'page'   => 'jetpack',
4491
								'action' => 'deactivate',
4492
								'module' => urlencode( $module_slugs ),
4493
							)
4494
						),
4495
						"jetpack_deactivate-$module_slugs"
4496
					),
4497
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4498
				),
4499
				array(
4500
					'a' => array(
4501
						'href'  => true,
4502
						'title' => true,
4503
					),
4504
				)
4505
			);
4506
			?>
4507
		</p>
4508
	</div>
4509
</div>
4510
			<?php
4511
endif;
4512
	}
4513
4514
	/**
4515
	 * We can't always respond to a signed XML-RPC request with a
4516
	 * helpful error message. In some circumstances, doing so could
4517
	 * leak information.
4518
	 *
4519
	 * Instead, track that the error occurred via a Jetpack_Option,
4520
	 * and send that data back in the heartbeat.
4521
	 * All this does is increment a number, but it's enough to find
4522
	 * trends.
4523
	 *
4524
	 * @param WP_Error $xmlrpc_error The error produced during
4525
	 *                               signature validation.
4526
	 */
4527
	function track_xmlrpc_error( $xmlrpc_error ) {
4528
		$code = is_wp_error( $xmlrpc_error )
4529
			? $xmlrpc_error->get_error_code()
4530
			: 'should-not-happen';
4531
4532
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4533
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4534
			// No need to update the option if we already have
4535
			// this code stored.
4536
			return;
4537
		}
4538
		$xmlrpc_errors[ $code ] = true;
4539
4540
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
4541
	}
4542
4543
	/**
4544
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4545
	 */
4546
	function stat( $group, $detail ) {
4547
		if ( ! isset( $this->stats[ $group ] ) ) {
4548
			$this->stats[ $group ] = array();
4549
		}
4550
		$this->stats[ $group ][] = $detail;
4551
	}
4552
4553
	/**
4554
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4555
	 */
4556
	function do_stats( $method = '' ) {
4557
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4558
			foreach ( $this->stats as $group => $stats ) {
4559
				if ( is_array( $stats ) && count( $stats ) ) {
4560
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4561
					if ( 'server_side' === $method ) {
4562
						self::do_server_side_stat( $args );
4563
					} else {
4564
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4565
					}
4566
				}
4567
				unset( $this->stats[ $group ] );
4568
			}
4569
		}
4570
	}
4571
4572
	/**
4573
	 * Runs stats code for a one-off, server-side.
4574
	 *
4575
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4576
	 *
4577
	 * @return bool If it worked.
4578
	 */
4579
	static function do_server_side_stat( $args ) {
4580
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4581
		if ( is_wp_error( $response ) ) {
4582
			return false;
4583
		}
4584
4585
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4586
			return false;
4587
		}
4588
4589
		return true;
4590
	}
4591
4592
	/**
4593
	 * Builds the stats url.
4594
	 *
4595
	 * @param $args array|string The arguments to append to the URL.
4596
	 *
4597
	 * @return string The URL to be pinged.
4598
	 */
4599
	static function build_stats_url( $args ) {
4600
		$defaults = array(
4601
			'v'    => 'wpcom2',
4602
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4603
		);
4604
		$args     = wp_parse_args( $args, $defaults );
4605
		/**
4606
		 * Filter the URL used as the Stats tracking pixel.
4607
		 *
4608
		 * @since 2.3.2
4609
		 *
4610
		 * @param string $url Base URL used as the Stats tracking pixel.
4611
		 */
4612
		$base_url = apply_filters(
4613
			'jetpack_stats_base_url',
4614
			'https://pixel.wp.com/g.gif'
4615
		);
4616
		$url      = add_query_arg( $args, $base_url );
4617
		return $url;
4618
	}
4619
4620
	/**
4621
	 * Get the role of the current user.
4622
	 *
4623
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4624
	 *
4625
	 * @access public
4626
	 * @static
4627
	 *
4628
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4629
	 */
4630
	public static function translate_current_user_to_role() {
4631
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4632
4633
		$roles = new Roles();
4634
		return $roles->translate_current_user_to_role();
4635
	}
4636
4637
	/**
4638
	 * Get the role of a particular user.
4639
	 *
4640
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4641
	 *
4642
	 * @access public
4643
	 * @static
4644
	 *
4645
	 * @param \WP_User $user User object.
4646
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4647
	 */
4648
	public static function translate_user_to_role( $user ) {
4649
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4650
4651
		$roles = new Roles();
4652
		return $roles->translate_user_to_role( $user );
4653
	}
4654
4655
	/**
4656
	 * Get the minimum capability for a role.
4657
	 *
4658
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4659
	 *
4660
	 * @access public
4661
	 * @static
4662
	 *
4663
	 * @param string $role Role name.
4664
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4665
	 */
4666
	public static function translate_role_to_cap( $role ) {
4667
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4668
4669
		$roles = new Roles();
4670
		return $roles->translate_role_to_cap( $role );
4671
	}
4672
4673
	/**
4674
	 * Sign a user role with the master access token.
4675
	 * If not specified, will default to the current user.
4676
	 *
4677
	 * @deprecated since 7.7
4678
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4679
	 *
4680
	 * @access public
4681
	 * @static
4682
	 *
4683
	 * @param string $role    User role.
4684
	 * @param int    $user_id ID of the user.
4685
	 * @return string Signed user role.
4686
	 */
4687
	public static function sign_role( $role, $user_id = null ) {
4688
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4689
		return self::connection()->sign_role( $role, $user_id );
4690
	}
4691
4692
	/**
4693
	 * Builds a URL to the Jetpack connection auth page
4694
	 *
4695
	 * @since 3.9.5
4696
	 *
4697
	 * @param bool        $raw If true, URL will not be escaped.
4698
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4699
	 *                              If string, will be a custom redirect.
4700
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4701
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4702
	 *
4703
	 * @return string Connect URL
4704
	 */
4705
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4706
		$site_id    = Jetpack_Options::get_option( 'id' );
4707
		$blog_token = Jetpack_Data::get_access_token();
4708
4709
		if ( $register || ! $blog_token || ! $site_id ) {
4710
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4711
4712
			if ( ! empty( $redirect ) ) {
4713
				$url = add_query_arg(
4714
					'redirect',
4715
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4716
					$url
4717
				);
4718
			}
4719
4720
			if ( is_network_admin() ) {
4721
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4722
			}
4723
4724
			$calypso_env = self::get_calypso_env();
4725
4726
			if ( ! empty( $calypso_env ) ) {
4727
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4728
			}
4729
		} else {
4730
4731
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4732
			// because otherwise this logic can get us in to a loop.
4733
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4734
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4735
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4736
4737
				$response = Client::wpcom_json_api_request_as_blog(
4738
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4739
					'1.1'
4740
				);
4741
4742
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4743
4744
					// Generating a register URL instead to refresh the existing token
4745
					return $this->build_connect_url( $raw, $redirect, $from, true );
4746
				}
4747
			}
4748
4749
			$url = $this->build_authorize_url( $redirect );
4750
		}
4751
4752
		if ( $from ) {
4753
			$url = add_query_arg( 'from', $from, $url );
4754
		}
4755
4756
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4757
		/**
4758
		 * Filter the URL used when connecting a user to a WordPress.com account.
4759
		 *
4760
		 * @since 8.1.0
4761
		 *
4762
		 * @param string $url Connection URL.
4763
		 * @param bool   $raw If true, URL will not be escaped.
4764
		 */
4765
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
4766
	}
4767
4768
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4769
4770
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4771
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4772
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4773
4774
		if ( $iframe ) {
4775
			add_filter( 'jetpack_api_url', array( __CLASS__, 'filter_connect_api_iframe_url' ), 10, 2 );
4776
		}
4777
4778
		$c8n = self::connection();
4779
		$url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
4780
4781
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4782
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4783
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4784
4785
		if ( $iframe ) {
4786
			remove_filter( 'jetpack_api_url', array( __CLASS__, 'filter_connect_api_iframe_url' ) );
4787
		}
4788
4789
		return $url;
4790
	}
4791
4792
	/**
4793
	 * Filters the connection URL parameter array.
4794
	 *
4795
	 * @param Array $args default URL parameters used by the package.
4796
	 * @return Array the modified URL arguments array.
4797
	 */
4798
	public static function filter_connect_request_body( $args ) {
4799
		if (
4800
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4801
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4802
		) {
4803
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4804
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4805
				? $gp_locale->slug
4806
				: '';
4807
		}
4808
4809
		$tracking        = new Tracking();
4810
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4811
4812
		$args = array_merge(
4813
			$args,
4814
			array(
4815
				'_ui' => $tracks_identity['_ui'],
4816
				'_ut' => $tracks_identity['_ut'],
4817
			)
4818
		);
4819
4820
		$calypso_env = self::get_calypso_env();
4821
4822
		if ( ! empty( $calypso_env ) ) {
4823
			$args['calypso_env'] = $calypso_env;
4824
		}
4825
4826
		return $args;
4827
	}
4828
4829
	/**
4830
	 * Filters the URL that will process the connection data. It can be different from the URL
4831
	 * that we send the user to after everything is done.
4832
	 *
4833
	 * @param String $processing_url the default redirect URL used by the package.
4834
	 * @return String the modified URL.
4835
	 */
4836
	public static function filter_connect_processing_url( $processing_url ) {
4837
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4838
		return $processing_url;
4839
	}
4840
4841
	/**
4842
	 * Filters the redirection URL that is used for connect requests. The redirect
4843
	 * URL should return the user back to the Jetpack console.
4844
	 *
4845
	 * @param String $redirect the default redirect URL used by the package.
4846
	 * @return String the modified URL.
4847
	 */
4848
	public static function filter_connect_redirect_url( $redirect ) {
4849
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4850
		$redirect           = $redirect
4851
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4852
			: $jetpack_admin_page;
4853
4854
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4855
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4856
		}
4857
4858
		return $redirect;
4859
	}
4860
4861
	/**
4862
	 * Filters the API URL that is used for connect requests. The method
4863
	 * intercepts only the authorize URL and replaces it with another if needed.
4864
	 *
4865
	 * @param String $api_url the default redirect API URL used by the package.
4866
	 * @param String $relative_url the path of the URL that's being used.
4867
	 * @return String the modified URL.
4868
	 */
4869
	public static function filter_connect_api_iframe_url( $api_url, $relative_url ) {
4870
4871
		// Short-circuit on anything that is not related to connect requests.
4872
		if ( 'authorize' !== $relative_url ) {
4873
			return $api_url;
4874
		}
4875
4876
		$c8n = self::connection();
4877
4878
		return $c8n->api_url( 'authorize_iframe' );
4879
	}
4880
4881
	/**
4882
	 * This action fires at the beginning of the Manager::authorize method.
4883
	 */
4884
	public static function authorize_starting() {
4885
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4886
		// Checking if site has been active/connected previously before recording unique connection.
4887
		if ( ! $jetpack_unique_connection ) {
4888
			// jetpack_unique_connection option has never been set.
4889
			$jetpack_unique_connection = array(
4890
				'connected'    => 0,
4891
				'disconnected' => 0,
4892
				'version'      => '3.6.1',
4893
			);
4894
4895
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4896
4897
			// Track unique connection.
4898
			$jetpack = self::init();
4899
4900
			$jetpack->stat( 'connections', 'unique-connection' );
4901
			$jetpack->do_stats( 'server_side' );
4902
		}
4903
4904
		// Increment number of times connected.
4905
		$jetpack_unique_connection['connected'] += 1;
4906
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4907
	}
4908
4909
	/**
4910
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4911
	 * linked.
4912
	 */
4913
	public static function authorize_ending_linked() {
4914
		// Don't activate anything since we are just connecting a user.
4915
		self::state( 'message', 'linked' );
4916
	}
4917
4918
	/**
4919
	 * This action fires at the end of the Manager::authorize method when the master user is
4920
	 * authorized.
4921
	 *
4922
	 * @param array $data The request data.
4923
	 */
4924
	public static function authorize_ending_authorized( $data ) {
4925
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4926
		self::invalidate_onboarding_token();
4927
4928
		// If redirect_uri is SSO, ensure SSO module is enabled.
4929
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4930
4931
		/** This filter is documented in class.jetpack-cli.php */
4932
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4933
4934
		$activate_sso = (
4935
			isset( $redirect_options['action'] ) &&
4936
			'jetpack-sso' === $redirect_options['action'] &&
4937
			$jetpack_start_enable_sso
4938
		);
4939
4940
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4941
4942
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4943
	}
4944
4945
	/**
4946
	 * Get our assumed site creation date.
4947
	 * Calculated based on the earlier date of either:
4948
	 * - Earliest admin user registration date.
4949
	 * - Earliest date of post of any post type.
4950
	 *
4951
	 * @since 7.2.0
4952
	 * @deprecated since 7.8.0
4953
	 *
4954
	 * @return string Assumed site creation date and time.
4955
	 */
4956
	public static function get_assumed_site_creation_date() {
4957
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4958
		return self::connection()->get_assumed_site_creation_date();
4959
	}
4960
4961 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4962
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4963
4964
		if ( $activation_source_name ) {
4965
			$args['_as'] = urlencode( $activation_source_name );
4966
		}
4967
4968
		if ( $activation_source_keyword ) {
4969
			$args['_ak'] = urlencode( $activation_source_keyword );
4970
		}
4971
	}
4972
4973
	function build_reconnect_url( $raw = false ) {
4974
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4975
		return $raw ? $url : esc_url( $url );
4976
	}
4977
4978
	public static function admin_url( $args = null ) {
4979
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4980
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4981
		return $url;
4982
	}
4983
4984
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4985
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4986
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4987
	}
4988
4989
	function dismiss_jetpack_notice() {
4990
4991
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4992
			return;
4993
		}
4994
4995
		switch ( $_GET['jetpack-notice'] ) {
4996
			case 'dismiss':
4997
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4998
4999
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5000
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5001
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5002
				}
5003
				break;
5004
		}
5005
	}
5006
5007
	public static function sort_modules( $a, $b ) {
5008
		if ( $a['sort'] == $b['sort'] ) {
5009
			return 0;
5010
		}
5011
5012
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5013
	}
5014
5015
	function ajax_recheck_ssl() {
5016
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5017
		$result = self::permit_ssl( true );
5018
		wp_send_json(
5019
			array(
5020
				'enabled' => $result,
5021
				'message' => get_transient( 'jetpack_https_test_message' ),
5022
			)
5023
		);
5024
	}
5025
5026
	/* Client API */
5027
5028
	/**
5029
	 * Returns the requested Jetpack API URL
5030
	 *
5031
	 * @deprecated since 7.7
5032
	 * @return string
5033
	 */
5034
	public static function api_url( $relative_url ) {
5035
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5036
		$connection = self::connection();
5037
		return $connection->api_url( $relative_url );
5038
	}
5039
5040
	/**
5041
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
5042
	 *
5043
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
5044
	 */
5045
	public static function fix_url_for_bad_hosts( $url ) {
5046
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
5047
		return Connection_Utils::fix_url_for_bad_hosts( $url );
5048
	}
5049
5050
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5051
		// Default to a blog token.
5052
		$token_type = 'blog';
5053
5054
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5055
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5056
			if ( ! empty( $_GET['onboarding'] ) ) {
5057
				$jpo = $_GET;
5058
			} else {
5059
				$jpo = json_decode( $request_data, true );
5060
			}
5061
5062
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5063
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5064
5065
			if (
5066
				isset( $jpo_user )
5067
				&& isset( $jpo_token )
5068
				&& is_email( $jpo_user )
5069
				&& ctype_alnum( $jpo_token )
5070
				&& isset( $_GET['rest_route'] )
5071
				&& self::validate_onboarding_token_action(
5072
					$jpo_token,
5073
					$_GET['rest_route']
5074
				)
5075
			) {
5076
				$jp_user = get_user_by( 'email', $jpo_user );
5077
				if ( is_a( $jp_user, 'WP_User' ) ) {
5078
					wp_set_current_user( $jp_user->ID );
5079
					$user_can = is_multisite()
5080
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5081
						: current_user_can( 'manage_options' );
5082
					if ( $user_can ) {
5083
						$token_type              = 'user';
5084
						$token->external_user_id = $jp_user->ID;
5085
					}
5086
				}
5087
			}
5088
5089
			$token_data['type']    = $token_type;
5090
			$token_data['user_id'] = $token->external_user_id;
5091
		}
5092
5093
		return $token_data;
5094
	}
5095
5096
	/**
5097
	 * Create a random secret for validating onboarding payload
5098
	 *
5099
	 * @return string Secret token
5100
	 */
5101
	public static function create_onboarding_token() {
5102
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5103
			$token = wp_generate_password( 32, false );
5104
			Jetpack_Options::update_option( 'onboarding', $token );
5105
		}
5106
5107
		return $token;
5108
	}
5109
5110
	/**
5111
	 * Remove the onboarding token
5112
	 *
5113
	 * @return bool True on success, false on failure
5114
	 */
5115
	public static function invalidate_onboarding_token() {
5116
		return Jetpack_Options::delete_option( 'onboarding' );
5117
	}
5118
5119
	/**
5120
	 * Validate an onboarding token for a specific action
5121
	 *
5122
	 * @return boolean True if token/action pair is accepted, false if not
5123
	 */
5124
	public static function validate_onboarding_token_action( $token, $action ) {
5125
		// Compare tokens, bail if tokens do not match
5126
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5127
			return false;
5128
		}
5129
5130
		// List of valid actions we can take
5131
		$valid_actions = array(
5132
			'/jetpack/v4/settings',
5133
		);
5134
5135
		// Whitelist the action
5136
		if ( ! in_array( $action, $valid_actions ) ) {
5137
			return false;
5138
		}
5139
5140
		return true;
5141
	}
5142
5143
	/**
5144
	 * Checks to see if the URL is using SSL to connect with Jetpack
5145
	 *
5146
	 * @since 2.3.3
5147
	 * @return boolean
5148
	 */
5149
	public static function permit_ssl( $force_recheck = false ) {
5150
		// Do some fancy tests to see if ssl is being supported
5151
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5152
			$message = '';
5153
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5154
				$ssl = 0;
5155
			} else {
5156
				switch ( JETPACK_CLIENT__HTTPS ) {
5157
					case 'NEVER':
5158
						$ssl     = 0;
5159
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5160
						break;
5161
					case 'ALWAYS':
5162
					case 'AUTO':
5163
					default:
5164
						$ssl = 1;
5165
						break;
5166
				}
5167
5168
				// If it's not 'NEVER', test to see
5169
				if ( $ssl ) {
5170
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5171
						$ssl     = 0;
5172
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5173
					} else {
5174
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5175
						if ( is_wp_error( $response ) ) {
5176
							$ssl     = 0;
5177
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5178
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5179
							$ssl     = 0;
5180
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5181
						}
5182
					}
5183
				}
5184
			}
5185
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5186
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5187
		}
5188
5189
		return (bool) $ssl;
5190
	}
5191
5192
	/*
5193
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5194
	 */
5195
	public function alert_auto_ssl_fail() {
5196
		if ( ! current_user_can( 'manage_options' ) ) {
5197
			return;
5198
		}
5199
5200
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5201
		?>
5202
5203
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5204
			<div class="jp-banner__content">
5205
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5206
				<p><?php _e( 'Your site could not connect to WordPress.com via HTTPS. This could be due to any number of reasons, including faulty SSL certificates, misconfigured or missing SSL libraries, or network issues.', 'jetpack' ); ?></p>
5207
				<p>
5208
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5209
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5210
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5211
				</p>
5212
				<p>
5213
					<?php
5214
					printf(
5215
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5216
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5217
						esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' )
5218
					);
5219
					?>
5220
				</p>
5221
			</div>
5222
		</div>
5223
		<style>
5224
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5225
		</style>
5226
		<script type="text/javascript">
5227
			jQuery( document ).ready( function( $ ) {
5228
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5229
					var $this = $( this );
5230
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5231
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5232
					e.preventDefault();
5233
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5234
					$.post( ajaxurl, data )
5235
					  .done( function( response ) {
5236
						  if ( response.enabled ) {
5237
							  $( '#jetpack-ssl-warning' ).hide();
5238
						  } else {
5239
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5240
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5241
						  }
5242
					  }.bind( $this ) );
5243
				} );
5244
			} );
5245
		</script>
5246
5247
		<?php
5248
	}
5249
5250
	/**
5251
	 * Returns the Jetpack XML-RPC API
5252
	 *
5253
	 * @deprecated 8.0 Use Connection_Manager instead.
5254
	 * @return string
5255
	 */
5256
	public static function xmlrpc_api_url() {
5257
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5258
		return self::connection()->xmlrpc_api_url();
5259
	}
5260
5261
	/**
5262
	 * Returns the connection manager object.
5263
	 *
5264
	 * @return Automattic\Jetpack\Connection\Manager
5265
	 */
5266
	public static function connection() {
5267
		return self::init()->connection_manager;
5268
	}
5269
5270
	/**
5271
	 * Creates two secret tokens and the end of life timestamp for them.
5272
	 *
5273
	 * Note these tokens are unique per call, NOT static per site for connecting.
5274
	 *
5275
	 * @since 2.6
5276
	 * @param String  $action  The action name.
5277
	 * @param Integer $user_id The user identifier.
5278
	 * @param Integer $exp     Expiration time in seconds.
5279
	 * @return array
5280
	 */
5281
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5282
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5283
	}
5284
5285
	public static function get_secrets( $action, $user_id ) {
5286
		$secrets = self::connection()->get_secrets( $action, $user_id );
5287
5288
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5289
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
5290
		}
5291
5292
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5293
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
5294
		}
5295
5296
		return $secrets;
5297
	}
5298
5299
	/**
5300
	 * @deprecated 7.5 Use Connection_Manager instead.
5301
	 *
5302
	 * @param $action
5303
	 * @param $user_id
5304
	 */
5305
	public static function delete_secrets( $action, $user_id ) {
5306
		return self::connection()->delete_secrets( $action, $user_id );
5307
	}
5308
5309
	/**
5310
	 * Builds the timeout limit for queries talking with the wpcom servers.
5311
	 *
5312
	 * Based on local php max_execution_time in php.ini
5313
	 *
5314
	 * @since 2.6
5315
	 * @return int
5316
	 * @deprecated
5317
	 **/
5318
	public function get_remote_query_timeout_limit() {
5319
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5320
		return self::get_max_execution_time();
5321
	}
5322
5323
	/**
5324
	 * Builds the timeout limit for queries talking with the wpcom servers.
5325
	 *
5326
	 * Based on local php max_execution_time in php.ini
5327
	 *
5328
	 * @since 5.4
5329
	 * @return int
5330
	 **/
5331
	public static function get_max_execution_time() {
5332
		$timeout = (int) ini_get( 'max_execution_time' );
5333
5334
		// Ensure exec time set in php.ini
5335
		if ( ! $timeout ) {
5336
			$timeout = 30;
5337
		}
5338
		return $timeout;
5339
	}
5340
5341
	/**
5342
	 * Sets a minimum request timeout, and returns the current timeout
5343
	 *
5344
	 * @since 5.4
5345
	 **/
5346 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5347
		$timeout = self::get_max_execution_time();
5348
		if ( $timeout < $min_timeout ) {
5349
			$timeout = $min_timeout;
5350
			set_time_limit( $timeout );
5351
		}
5352
		return $timeout;
5353
	}
5354
5355
	/**
5356
	 * Takes the response from the Jetpack register new site endpoint and
5357
	 * verifies it worked properly.
5358
	 *
5359
	 * @since 2.6
5360
	 * @deprecated since 7.7.0
5361
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5362
	 **/
5363
	public function validate_remote_register_response() {
5364
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5365
	}
5366
5367
	/**
5368
	 * @return bool|WP_Error
5369
	 */
5370
	public static function register() {
5371
		$tracking = new Tracking();
5372
		$tracking->record_user_event( 'jpc_register_begin' );
5373
5374
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5375
5376
		$connection   = self::connection();
5377
		$registration = $connection->register();
5378
5379
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5380
5381
		if ( ! $registration || is_wp_error( $registration ) ) {
5382
			return $registration;
5383
		}
5384
5385
		return true;
5386
	}
5387
5388
	/**
5389
	 * Filters the registration request body to include tracking properties.
5390
	 *
5391
	 * @param Array $properties
5392
	 * @return Array amended properties.
5393
	 */
5394 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5395
		$tracking        = new Tracking();
5396
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5397
5398
		return array_merge(
5399
			$properties,
5400
			array(
5401
				'_ui' => $tracks_identity['_ui'],
5402
				'_ut' => $tracks_identity['_ut'],
5403
			)
5404
		);
5405
	}
5406
5407
	/**
5408
	 * Filters the token request body to include tracking properties.
5409
	 *
5410
	 * @param Array $properties
5411
	 * @return Array amended properties.
5412
	 */
5413 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5414
		$tracking        = new Tracking();
5415
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5416
5417
		return array_merge(
5418
			$properties,
5419
			array(
5420
				'_ui' => $tracks_identity['_ui'],
5421
				'_ut' => $tracks_identity['_ut'],
5422
			)
5423
		);
5424
	}
5425
5426
	/**
5427
	 * If the db version is showing something other that what we've got now, bump it to current.
5428
	 *
5429
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5430
	 */
5431
	public static function maybe_set_version_option() {
5432
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5433
		if ( JETPACK__VERSION != $version ) {
5434
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5435
5436
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5437
				/** This action is documented in class.jetpack.php */
5438
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5439
			}
5440
5441
			return true;
5442
		}
5443
		return false;
5444
	}
5445
5446
	/* Client Server API */
5447
5448
	/**
5449
	 * Loads the Jetpack XML-RPC client.
5450
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5451
	 *
5452
	 * @deprecated since 7.7.0
5453
	 */
5454
	public static function load_xml_rpc_client() {
5455
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5456
	}
5457
5458
	/**
5459
	 * Resets the saved authentication state in between testing requests.
5460
	 */
5461
	public function reset_saved_auth_state() {
5462
		$this->rest_authentication_status = null;
5463
		$this->connection_manager->reset_saved_auth_state();
5464
	}
5465
5466
	/**
5467
	 * Verifies the signature of the current request.
5468
	 *
5469
	 * @deprecated since 7.7.0
5470
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5471
	 *
5472
	 * @return false|array
5473
	 */
5474
	public function verify_xml_rpc_signature() {
5475
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5476
		return self::connection()->verify_xml_rpc_signature();
5477
	}
5478
5479
	/**
5480
	 * Verifies the signature of the current request.
5481
	 *
5482
	 * This function has side effects and should not be used. Instead,
5483
	 * use the memoized version `->verify_xml_rpc_signature()`.
5484
	 *
5485
	 * @deprecated since 7.7.0
5486
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5487
	 * @internal
5488
	 */
5489
	private function internal_verify_xml_rpc_signature() {
5490
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5491
	}
5492
5493
	/**
5494
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5495
	 *
5496
	 * @deprecated since 7.7.0
5497
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5498
	 *
5499
	 * @param \WP_User|mixed $user     User object if authenticated.
5500
	 * @param string         $username Username.
5501
	 * @param string         $password Password string.
5502
	 * @return \WP_User|mixed Authenticated user or error.
5503
	 */
5504
	public function authenticate_jetpack( $user, $username, $password ) {
5505
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5506
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5507
	}
5508
5509
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5510
	// Uses the existing XMLRPC request signing implementation.
5511
	function wp_rest_authenticate( $user ) {
5512
		if ( ! empty( $user ) ) {
5513
			// Another authentication method is in effect.
5514
			return $user;
5515
		}
5516
5517
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5518
			// Nothing to do for this authentication method.
5519
			return null;
5520
		}
5521
5522
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5523
			// Nothing to do for this authentication method.
5524
			return null;
5525
		}
5526
5527
		// Ensure that we always have the request body available.  At this
5528
		// point, the WP REST API code to determine the request body has not
5529
		// run yet.  That code may try to read from 'php://input' later, but
5530
		// this can only be done once per request in PHP versions prior to 5.6.
5531
		// So we will go ahead and perform this read now if needed, and save
5532
		// the request body where both the Jetpack signature verification code
5533
		// and the WP REST API code can see it.
5534
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5535
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5536
		}
5537
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5538
5539
		// Only support specific request parameters that have been tested and
5540
		// are known to work with signature verification.  A different method
5541
		// can be passed to the WP REST API via the '?_method=' parameter if
5542
		// needed.
5543
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5544
			$this->rest_authentication_status = new WP_Error(
5545
				'rest_invalid_request',
5546
				__( 'This request method is not supported.', 'jetpack' ),
5547
				array( 'status' => 400 )
5548
			);
5549
			return null;
5550
		}
5551
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5552
			$this->rest_authentication_status = new WP_Error(
5553
				'rest_invalid_request',
5554
				__( 'This request method does not support body parameters.', 'jetpack' ),
5555
				array( 'status' => 400 )
5556
			);
5557
			return null;
5558
		}
5559
5560
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5561
5562
		if (
5563
			$verified &&
5564
			isset( $verified['type'] ) &&
5565
			'user' === $verified['type'] &&
5566
			! empty( $verified['user_id'] )
5567
		) {
5568
			// Authentication successful.
5569
			$this->rest_authentication_status = true;
5570
			return $verified['user_id'];
5571
		}
5572
5573
		// Something else went wrong.  Probably a signature error.
5574
		$this->rest_authentication_status = new WP_Error(
5575
			'rest_invalid_signature',
5576
			__( 'The request is not signed correctly.', 'jetpack' ),
5577
			array( 'status' => 400 )
5578
		);
5579
		return null;
5580
	}
5581
5582
	/**
5583
	 * Report authentication status to the WP REST API.
5584
	 *
5585
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5586
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5587
	 */
5588
	public function wp_rest_authentication_errors( $value ) {
5589
		if ( $value !== null ) {
5590
			return $value;
5591
		}
5592
		return $this->rest_authentication_status;
5593
	}
5594
5595
	/**
5596
	 * Add our nonce to this request.
5597
	 *
5598
	 * @deprecated since 7.7.0
5599
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5600
	 *
5601
	 * @param int    $timestamp Timestamp of the request.
5602
	 * @param string $nonce     Nonce string.
5603
	 */
5604
	public function add_nonce( $timestamp, $nonce ) {
5605
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5606
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5607
	}
5608
5609
	/**
5610
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5611
	 * Capture it here so we can verify the signature later.
5612
	 *
5613
	 * @deprecated since 7.7.0
5614
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5615
	 *
5616
	 * @param array $methods XMLRPC methods.
5617
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5618
	 */
5619
	public function xmlrpc_methods( $methods ) {
5620
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5621
		return $this->connection_manager->xmlrpc_methods( $methods );
5622
	}
5623
5624
	/**
5625
	 * Register additional public XMLRPC methods.
5626
	 *
5627
	 * @deprecated since 7.7.0
5628
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5629
	 *
5630
	 * @param array $methods Public XMLRPC methods.
5631
	 * @return array Public XMLRPC methods, with the getOptions one.
5632
	 */
5633
	public function public_xmlrpc_methods( $methods ) {
5634
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5635
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5636
	}
5637
5638
	/**
5639
	 * Handles a getOptions XMLRPC method call.
5640
	 *
5641
	 * @deprecated since 7.7.0
5642
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5643
	 *
5644
	 * @param array $args method call arguments.
5645
	 * @return array an amended XMLRPC server options array.
5646
	 */
5647
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5648
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5649
		return $this->connection_manager->jetpack_getOptions( $args );
5650
	}
5651
5652
	/**
5653
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5654
	 *
5655
	 * @deprecated since 7.7.0
5656
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5657
	 *
5658
	 * @param array $options Standard Core options.
5659
	 * @return array Amended options.
5660
	 */
5661
	public function xmlrpc_options( $options ) {
5662
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5663
		return $this->connection_manager->xmlrpc_options( $options );
5664
	}
5665
5666
	/**
5667
	 * Cleans nonces that were saved when calling ::add_nonce.
5668
	 *
5669
	 * @deprecated since 7.7.0
5670
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5671
	 *
5672
	 * @param bool $all whether to clean even non-expired nonces.
5673
	 */
5674
	public static function clean_nonces( $all = false ) {
5675
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5676
		return self::connection()->clean_nonces( $all );
5677
	}
5678
5679
	/**
5680
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5681
	 * SET: state( $key, $value );
5682
	 * GET: $value = state( $key );
5683
	 *
5684
	 * @param string $key
5685
	 * @param string $value
5686
	 * @param bool   $restate private
5687
	 */
5688
	public static function state( $key = null, $value = null, $restate = false ) {
5689
		static $state = array();
5690
		static $path, $domain;
5691
		if ( ! isset( $path ) ) {
5692
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5693
			$admin_url = self::admin_url();
5694
			$bits      = wp_parse_url( $admin_url );
5695
5696
			if ( is_array( $bits ) ) {
5697
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5698
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5699
			} else {
5700
				$path = $domain = null;
5701
			}
5702
		}
5703
5704
		// Extract state from cookies and delete cookies
5705
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5706
			$yum = $_COOKIE['jetpackState'];
5707
			unset( $_COOKIE['jetpackState'] );
5708
			foreach ( $yum as $k => $v ) {
5709
				if ( strlen( $v ) ) {
5710
					$state[ $k ] = $v;
5711
				}
5712
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5713
			}
5714
		}
5715
5716
		if ( $restate ) {
5717
			foreach ( $state as $k => $v ) {
5718
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5719
			}
5720
			return;
5721
		}
5722
5723
		// Get a state variable
5724
		if ( isset( $key ) && ! isset( $value ) ) {
5725
			if ( array_key_exists( $key, $state ) ) {
5726
				return $state[ $key ];
5727
			}
5728
			return null;
5729
		}
5730
5731
		// Set a state variable
5732
		if ( isset( $key ) && isset( $value ) ) {
5733
			if ( is_array( $value ) && isset( $value[0] ) ) {
5734
				$value = $value[0];
5735
			}
5736
			$state[ $key ] = $value;
5737
			if ( ! headers_sent() ) {
5738
				setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5739
			}
5740
		}
5741
	}
5742
5743
	public static function restate() {
5744
		self::state( null, null, true );
5745
	}
5746
5747
	public static function check_privacy( $file ) {
5748
		static $is_site_publicly_accessible = null;
5749
5750
		if ( is_null( $is_site_publicly_accessible ) ) {
5751
			$is_site_publicly_accessible = false;
5752
5753
			$rpc = new Jetpack_IXR_Client();
5754
5755
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5756
			if ( $success ) {
5757
				$response = $rpc->getResponse();
5758
				if ( $response ) {
5759
					$is_site_publicly_accessible = true;
5760
				}
5761
			}
5762
5763
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5764
		}
5765
5766
		if ( $is_site_publicly_accessible ) {
5767
			return;
5768
		}
5769
5770
		$module_slug = self::get_module_slug( $file );
5771
5772
		$privacy_checks = self::state( 'privacy_checks' );
5773
		if ( ! $privacy_checks ) {
5774
			$privacy_checks = $module_slug;
5775
		} else {
5776
			$privacy_checks .= ",$module_slug";
5777
		}
5778
5779
		self::state( 'privacy_checks', $privacy_checks );
5780
	}
5781
5782
	/**
5783
	 * Helper method for multicall XMLRPC.
5784
	 *
5785
	 * @param ...$args Args for the async_call.
5786
	 */
5787
	public static function xmlrpc_async_call( ...$args ) {
5788
		global $blog_id;
5789
		static $clients = array();
5790
5791
		$client_blog_id = is_multisite() ? $blog_id : 0;
5792
5793
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5794
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5795
			if ( function_exists( 'ignore_user_abort' ) ) {
5796
				ignore_user_abort( true );
5797
			}
5798
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5799
		}
5800
5801
		if ( ! empty( $args[0] ) ) {
5802
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5803
		} elseif ( is_multisite() ) {
5804
			foreach ( $clients as $client_blog_id => $client ) {
5805
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5806
					continue;
5807
				}
5808
5809
				$switch_success = switch_to_blog( $client_blog_id, true );
5810
				if ( ! $switch_success ) {
5811
					continue;
5812
				}
5813
5814
				flush();
5815
				$client->query();
5816
5817
				restore_current_blog();
5818
			}
5819
		} else {
5820
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5821
				flush();
5822
				$clients[0]->query();
5823
			}
5824
		}
5825
	}
5826
5827
	public static function staticize_subdomain( $url ) {
5828
5829
		// Extract hostname from URL
5830
		$host = wp_parse_url( $url, PHP_URL_HOST );
5831
5832
		// Explode hostname on '.'
5833
		$exploded_host = explode( '.', $host );
5834
5835
		// Retrieve the name and TLD
5836
		if ( count( $exploded_host ) > 1 ) {
5837
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5838
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5839
			// Rebuild domain excluding subdomains
5840
			$domain = $name . '.' . $tld;
5841
		} else {
5842
			$domain = $host;
5843
		}
5844
		// Array of Automattic domains
5845
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5846
5847
		// Return $url if not an Automattic domain
5848
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5849
			return $url;
5850
		}
5851
5852
		if ( is_ssl() ) {
5853
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5854
		}
5855
5856
		srand( crc32( basename( $url ) ) );
5857
		$static_counter = rand( 0, 2 );
5858
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5859
5860
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5861
	}
5862
5863
	/* JSON API Authorization */
5864
5865
	/**
5866
	 * Handles the login action for Authorizing the JSON API
5867
	 */
5868
	function login_form_json_api_authorization() {
5869
		$this->verify_json_api_authorization_request();
5870
5871
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5872
5873
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5874
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5875
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5876
	}
5877
5878
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5879
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5880
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5881
			return $url;
5882
		}
5883
5884
		$parsed_url = wp_parse_url( $url );
5885
		$url        = strtok( $url, '?' );
5886
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5887
		if ( ! empty( $parsed_url['query'] ) ) {
5888
			$url .= "&{$parsed_url['query']}";
5889
		}
5890
5891
		return $url;
5892
	}
5893
5894
	// Make sure the POSTed request is handled by the same action
5895
	function preserve_action_in_login_form_for_json_api_authorization() {
5896
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5897
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5898
	}
5899
5900
	// If someone logs in to approve API access, store the Access Code in usermeta
5901
	function store_json_api_authorization_token( $user_login, $user ) {
5902
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5903
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5904
		$token = wp_generate_password( 32, false );
5905
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5906
	}
5907
5908
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5909
	function allow_wpcom_public_api_domain( $domains ) {
5910
		$domains[] = 'public-api.wordpress.com';
5911
		return $domains;
5912
	}
5913
5914
	static function is_redirect_encoded( $redirect_url ) {
5915
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5916
	}
5917
5918
	// Add all wordpress.com environments to the safe redirect whitelist
5919
	function allow_wpcom_environments( $domains ) {
5920
		$domains[] = 'wordpress.com';
5921
		$domains[] = 'wpcalypso.wordpress.com';
5922
		$domains[] = 'horizon.wordpress.com';
5923
		$domains[] = 'calypso.localhost';
5924
		return $domains;
5925
	}
5926
5927
	// Add the Access Code details to the public-api.wordpress.com redirect
5928
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5929
		return add_query_arg(
5930
			urlencode_deep(
5931
				array(
5932
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5933
					'jetpack-user-id' => (int) $user->ID,
5934
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5935
				)
5936
			),
5937
			$redirect_to
5938
		);
5939
	}
5940
5941
5942
	/**
5943
	 * Verifies the request by checking the signature
5944
	 *
5945
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5946
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5947
	 *
5948
	 * @param null|array $environment
5949
	 */
5950
	function verify_json_api_authorization_request( $environment = null ) {
5951
		$environment = is_null( $environment )
5952
			? $_REQUEST
5953
			: $environment;
5954
5955
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
5956
		$token                                     = Jetpack_Data::get_access_token( $envUserId, $envToken );
5957
		if ( ! $token || empty( $token->secret ) ) {
5958
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5959
		}
5960
5961
		$die_error = __( 'Someone may be trying to trick you into giving them access to your site.  Or it could be you just encountered a bug :).  Either way, please close this window.', 'jetpack' );
5962
5963
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5964
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5965
			/**
5966
			 * Jetpack authorisation request Error.
5967
			 *
5968
			 * @since 7.5.0
5969
			 */
5970
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5971
			$die_error = sprintf(
5972
				/* translators: %s is a URL */
5973
				__( 'Your site is incorrectly double-encoding redirects from http to https. This is preventing Jetpack from authenticating your connection. Please visit our <a href="%s">support page</a> for details about how to resolve this.', 'jetpack' ),
5974
				'https://jetpack.com/support/double-encoding/'
5975
			);
5976
		}
5977
5978
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5979
5980
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5981
			$signature = $jetpack_signature->sign_request(
5982
				$environment['token'],
5983
				$environment['timestamp'],
5984
				$environment['nonce'],
5985
				'',
5986
				'GET',
5987
				$environment['jetpack_json_api_original_query'],
5988
				null,
5989
				true
5990
			);
5991
		} else {
5992
			$signature = $jetpack_signature->sign_current_request(
5993
				array(
5994
					'body'   => null,
5995
					'method' => 'GET',
5996
				)
5997
			);
5998
		}
5999
6000
		if ( ! $signature ) {
6001
			wp_die( $die_error );
6002
		} elseif ( is_wp_error( $signature ) ) {
6003
			wp_die( $die_error );
6004
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6005
			if ( is_ssl() ) {
6006
				// If we signed an HTTP request on the Jetpack Servers, but got redirected to HTTPS by the local blog, check the HTTP signature as well
6007
				$signature = $jetpack_signature->sign_current_request(
6008
					array(
6009
						'scheme' => 'http',
6010
						'body'   => null,
6011
						'method' => 'GET',
6012
					)
6013
				);
6014
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6015
					wp_die( $die_error );
6016
				}
6017
			} else {
6018
				wp_die( $die_error );
6019
			}
6020
		}
6021
6022
		$timestamp = (int) $environment['timestamp'];
6023
		$nonce     = stripslashes( (string) $environment['nonce'] );
6024
6025
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
6026
			// De-nonce the nonce, at least for 5 minutes.
6027
			// We have to reuse this nonce at least once (used the first time when the initial request is made, used a second time when the login form is POSTed)
6028
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6029
			if ( $old_nonce_time < time() - 300 ) {
6030
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6031
			}
6032
		}
6033
6034
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6035
		$data_filters = array(
6036
			'state'        => 'opaque',
6037
			'client_id'    => 'int',
6038
			'client_title' => 'string',
6039
			'client_image' => 'url',
6040
		);
6041
6042
		foreach ( $data_filters as $key => $sanitation ) {
6043
			if ( ! isset( $data->$key ) ) {
6044
				wp_die( $die_error );
6045
			}
6046
6047
			switch ( $sanitation ) {
6048
				case 'int':
6049
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6050
					break;
6051
				case 'opaque':
6052
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6053
					break;
6054
				case 'string':
6055
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6056
					break;
6057
				case 'url':
6058
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6059
					break;
6060
			}
6061
		}
6062
6063
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6064
			wp_die( $die_error );
6065
		}
6066
	}
6067
6068
	function login_message_json_api_authorization( $message ) {
6069
		return '<p class="message">' . sprintf(
6070
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6071
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6072
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6073
	}
6074
6075
	/**
6076
	 * Get $content_width, but with a <s>twist</s> filter.
6077
	 */
6078
	public static function get_content_width() {
6079
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6080
			? $GLOBALS['content_width']
6081
			: false;
6082
		/**
6083
		 * Filter the Content Width value.
6084
		 *
6085
		 * @since 2.2.3
6086
		 *
6087
		 * @param string $content_width Content Width value.
6088
		 */
6089
		return apply_filters( 'jetpack_content_width', $content_width );
6090
	}
6091
6092
	/**
6093
	 * Pings the WordPress.com Mirror Site for the specified options.
6094
	 *
6095
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6096
	 *
6097
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6098
	 */
6099
	public function get_cloud_site_options( $option_names ) {
6100
		$option_names = array_filter( (array) $option_names, 'is_string' );
6101
6102
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
6103
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6104
		if ( $xml->isError() ) {
6105
			return array(
6106
				'error_code' => $xml->getErrorCode(),
6107
				'error_msg'  => $xml->getErrorMessage(),
6108
			);
6109
		}
6110
		$cloud_site_options = $xml->getResponse();
6111
6112
		return $cloud_site_options;
6113
	}
6114
6115
	/**
6116
	 * Checks if the site is currently in an identity crisis.
6117
	 *
6118
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6119
	 */
6120
	public static function check_identity_crisis() {
6121
		if ( ! self::is_active() || ( new Status() )->is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6122
			return false;
6123
		}
6124
6125
		return Jetpack_Options::get_option( 'sync_error_idc' );
6126
	}
6127
6128
	/**
6129
	 * Checks whether the home and siteurl specifically are whitelisted
6130
	 * Written so that we don't have re-check $key and $value params every time
6131
	 * we want to check if this site is whitelisted, for example in footer.php
6132
	 *
6133
	 * @since  3.8.0
6134
	 * @return bool True = already whitelisted False = not whitelisted
6135
	 */
6136
	public static function is_staging_site() {
6137
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6138
		return ( new Status() )->is_staging_site();
6139
	}
6140
6141
	/**
6142
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6143
	 *
6144
	 * @since 4.4.0
6145
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6146
	 *
6147
	 * @return bool
6148
	 */
6149
	public static function validate_sync_error_idc_option() {
6150
		$is_valid = false;
6151
6152
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6153
		if ( false === $idc_allowed ) {
6154
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6155
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6156
				$json               = json_decode( wp_remote_retrieve_body( $response ) );
6157
				$idc_allowed        = isset( $json, $json->result ) && $json->result ? '1' : '0';
6158
				$transient_duration = HOUR_IN_SECONDS;
6159
			} else {
6160
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6161
				$idc_allowed        = '1';
6162
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6163
			}
6164
6165
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6166
		}
6167
6168
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6169
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6170
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6171
			$local_options = self::get_sync_error_idc_option();
6172
			// Ensure all values are set.
6173
			if ( isset( $sync_error['home'] ) && isset ( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6174
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6175
					$is_valid = true;
6176
				}
6177
			}
6178
6179
		}
6180
6181
		/**
6182
		 * Filters whether the sync_error_idc option is valid.
6183
		 *
6184
		 * @since 4.4.0
6185
		 *
6186
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6187
		 */
6188
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6189
6190
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6191
			// Since the option exists, and did not validate, delete it
6192
			Jetpack_Options::delete_option( 'sync_error_idc' );
6193
		}
6194
6195
		return $is_valid;
6196
	}
6197
6198
	/**
6199
	 * Normalizes a url by doing three things:
6200
	 *  - Strips protocol
6201
	 *  - Strips www
6202
	 *  - Adds a trailing slash
6203
	 *
6204
	 * @since 4.4.0
6205
	 * @param string $url
6206
	 * @return WP_Error|string
6207
	 */
6208
	public static function normalize_url_protocol_agnostic( $url ) {
6209
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6210
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6211
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6212
		}
6213
6214
		// Strip www and protocols
6215
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6216
		return $url;
6217
	}
6218
6219
	/**
6220
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6221
	 *
6222
	 * @since 4.4.0
6223
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6224
	 *
6225
	 * @param array $response
6226
	 * @return array Array of the local urls, wpcom urls, and error code
6227
	 */
6228
	public static function get_sync_error_idc_option( $response = array() ) {
6229
		// Since the local options will hit the database directly, store the values
6230
		// in a transient to allow for autoloading and caching on subsequent views.
6231
		$local_options = get_transient( 'jetpack_idc_local' );
6232
		if ( false === $local_options ) {
6233
			$local_options = array(
6234
				'home'    => Functions::home_url(),
6235
				'siteurl' => Functions::site_url(),
6236
			);
6237
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6238
		}
6239
6240
		$options = array_merge( $local_options, $response );
6241
6242
		$returned_values = array();
6243
		foreach ( $options as $key => $option ) {
6244
			if ( 'error_code' === $key ) {
6245
				$returned_values[ $key ] = $option;
6246
				continue;
6247
			}
6248
6249
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6250
				continue;
6251
			}
6252
6253
			$returned_values[ $key ] = $normalized_url;
6254
		}
6255
6256
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6257
6258
		return $returned_values;
6259
	}
6260
6261
	/**
6262
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6263
	 * If set to true, the site will be put into staging mode.
6264
	 *
6265
	 * @since 4.3.2
6266
	 * @return bool
6267
	 */
6268
	public static function sync_idc_optin() {
6269
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6270
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6271
		} else {
6272
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6273
		}
6274
6275
		/**
6276
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6277
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6278
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6279
		 *
6280
		 * @since 4.3.2
6281
		 *
6282
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6283
		 */
6284
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6285
	}
6286
6287
	/**
6288
	 * Maybe Use a .min.css stylesheet, maybe not.
6289
	 *
6290
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6291
	 */
6292
	public static function maybe_min_asset( $url, $path, $plugin ) {
6293
		// Short out on things trying to find actual paths.
6294
		if ( ! $path || empty( $plugin ) ) {
6295
			return $url;
6296
		}
6297
6298
		$path = ltrim( $path, '/' );
6299
6300
		// Strip out the abspath.
6301
		$base = dirname( plugin_basename( $plugin ) );
6302
6303
		// Short out on non-Jetpack assets.
6304
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6305
			return $url;
6306
		}
6307
6308
		// File name parsing.
6309
		$file              = "{$base}/{$path}";
6310
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6311
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6312
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6313
		$extension         = array_shift( $file_name_parts_r );
6314
6315
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6316
			// Already pointing at the minified version.
6317
			if ( 'min' === $file_name_parts_r[0] ) {
6318
				return $url;
6319
			}
6320
6321
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6322
			if ( file_exists( $min_full_path ) ) {
6323
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6324
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6325
				if ( 'css' === $extension ) {
6326
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6327
					self::$min_assets[ $key ] = $path;
6328
				}
6329
			}
6330
		}
6331
6332
		return $url;
6333
	}
6334
6335
	/**
6336
	 * If the asset is minified, let's flag .min as the suffix.
6337
	 *
6338
	 * Attached to `style_loader_src` filter.
6339
	 *
6340
	 * @param string $tag The tag that would link to the external asset.
6341
	 * @param string $handle The registered handle of the script in question.
6342
	 * @param string $href The url of the asset in question.
6343
	 */
6344
	public static function set_suffix_on_min( $src, $handle ) {
6345
		if ( false === strpos( $src, '.min.css' ) ) {
6346
			return $src;
6347
		}
6348
6349
		if ( ! empty( self::$min_assets ) ) {
6350
			foreach ( self::$min_assets as $file => $path ) {
6351
				if ( false !== strpos( $src, $file ) ) {
6352
					wp_style_add_data( $handle, 'suffix', '.min' );
6353
					return $src;
6354
				}
6355
			}
6356
		}
6357
6358
		return $src;
6359
	}
6360
6361
	/**
6362
	 * Maybe inlines a stylesheet.
6363
	 *
6364
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6365
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6366
	 *
6367
	 * Attached to `style_loader_tag` filter.
6368
	 *
6369
	 * @param string $tag The tag that would link to the external asset.
6370
	 * @param string $handle The registered handle of the script in question.
6371
	 *
6372
	 * @return string
6373
	 */
6374
	public static function maybe_inline_style( $tag, $handle ) {
6375
		global $wp_styles;
6376
		$item = $wp_styles->registered[ $handle ];
6377
6378
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6379
			return $tag;
6380
		}
6381
6382
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6383
			$href = $matches[1];
6384
			// Strip off query string
6385
			if ( $pos = strpos( $href, '?' ) ) {
6386
				$href = substr( $href, 0, $pos );
6387
			}
6388
			// Strip off fragment
6389
			if ( $pos = strpos( $href, '#' ) ) {
6390
				$href = substr( $href, 0, $pos );
6391
			}
6392
		} else {
6393
			return $tag;
6394
		}
6395
6396
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6397
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6398
			return $tag;
6399
		}
6400
6401
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6402
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6403
			// And this isn't the pass that actually deals with the RTL version...
6404
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6405
				// Short out, as the RTL version will deal with it in a moment.
6406
				return $tag;
6407
			}
6408
		}
6409
6410
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6411
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6412
		if ( $css ) {
6413
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6414
			if ( empty( $item->extra['after'] ) ) {
6415
				wp_add_inline_style( $handle, $css );
6416
			} else {
6417
				array_unshift( $item->extra['after'], $css );
6418
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6419
			}
6420
		}
6421
6422
		return $tag;
6423
	}
6424
6425
	/**
6426
	 * Loads a view file from the views
6427
	 *
6428
	 * Data passed in with the $data parameter will be available in the
6429
	 * template file as $data['value']
6430
	 *
6431
	 * @param string $template - Template file to load
6432
	 * @param array  $data - Any data to pass along to the template
6433
	 * @return boolean - If template file was found
6434
	 **/
6435
	public function load_view( $template, $data = array() ) {
6436
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6437
6438
		if ( file_exists( $views_dir . $template ) ) {
6439
			require_once $views_dir . $template;
6440
			return true;
6441
		}
6442
6443
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6444
		return false;
6445
	}
6446
6447
	/**
6448
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6449
	 */
6450
	public function deprecated_hooks() {
6451
		global $wp_filter;
6452
6453
		/*
6454
		 * Format:
6455
		 * deprecated_filter_name => replacement_name
6456
		 *
6457
		 * If there is no replacement, use null for replacement_name
6458
		 */
6459
		$deprecated_list = array(
6460
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6461
			'wpl_sharing_2014_1'                           => null,
6462
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6463
			'jetpack_identity_crisis_options_to_check'     => null,
6464
			'update_option_jetpack_single_user_site'       => null,
6465
			'audio_player_default_colors'                  => null,
6466
			'add_option_jetpack_featured_images_enabled'   => null,
6467
			'add_option_jetpack_update_details'            => null,
6468
			'add_option_jetpack_updates'                   => null,
6469
			'add_option_jetpack_network_name'              => null,
6470
			'add_option_jetpack_network_allow_new_registrations' => null,
6471
			'add_option_jetpack_network_add_new_users'     => null,
6472
			'add_option_jetpack_network_site_upload_space' => null,
6473
			'add_option_jetpack_network_upload_file_types' => null,
6474
			'add_option_jetpack_network_enable_administration_menus' => null,
6475
			'add_option_jetpack_is_multi_site'             => null,
6476
			'add_option_jetpack_is_main_network'           => null,
6477
			'add_option_jetpack_main_network_site'         => null,
6478
			'jetpack_sync_all_registered_options'          => null,
6479
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6480
			'jetpack_is_post_mailable'                     => null,
6481
			'jetpack_seo_site_host'                        => null,
6482
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6483
			'jetpack_holiday_snow_option_name'             => null,
6484
			'jetpack_holiday_chance_of_snow'               => null,
6485
			'jetpack_holiday_snow_js_url'                  => null,
6486
			'jetpack_is_holiday_snow_season'               => null,
6487
			'jetpack_holiday_snow_option_updated'          => null,
6488
			'jetpack_holiday_snowing'                      => null,
6489
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6490
			'jetpack_cache_plans'                          => null,
6491
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6492
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6493
			'jetpack_enable_site_verification'             => null,
6494
			'can_display_jetpack_manage_notice'            => null,
6495
			// Removed in Jetpack 7.3.0
6496
			'atd_load_scripts'                             => null,
6497
			'atd_http_post_timeout'                        => null,
6498
			'atd_http_post_error'                          => null,
6499
			'atd_service_domain'                           => null,
6500
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6501
			// Removed in Jetpack 7.9.0
6502
			'jetpack_pwa_manifest'                         => null,
6503
			'jetpack_pwa_background_color'                 => null,
6504
		);
6505
6506
		// This is a silly loop depth. Better way?
6507
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6508
			if ( has_action( $hook ) ) {
6509
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6510
					foreach ( $values as $hooked ) {
6511
						if ( is_callable( $hooked['function'] ) ) {
6512
							$function_name = 'an anonymous function';
6513
						} else {
6514
							$function_name = $hooked['function'];
6515
						}
6516
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6517
					}
6518
				}
6519
			}
6520
		}
6521
	}
6522
6523
	/**
6524
	 * Converts any url in a stylesheet, to the correct absolute url.
6525
	 *
6526
	 * Considerations:
6527
	 *  - Normal, relative URLs     `feh.png`
6528
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6529
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6530
	 *  - Absolute URLs             `http://domain.com/feh.png`
6531
	 *  - Domain root relative URLs `/feh.png`
6532
	 *
6533
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6534
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6535
	 *
6536
	 * @return mixed|string
6537
	 */
6538
	public static function absolutize_css_urls( $css, $css_file_url ) {
6539
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6540
		$css_dir = dirname( $css_file_url );
6541
		$p       = wp_parse_url( $css_dir );
6542
		$domain  = sprintf(
6543
			'%1$s//%2$s%3$s%4$s',
6544
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6545
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6546
			$p['host'],
6547
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6548
		);
6549
6550
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6551
			$find = $replace = array();
6552
			foreach ( $matches as $match ) {
6553
				$url = trim( $match['path'], "'\" \t" );
6554
6555
				// If this is a data url, we don't want to mess with it.
6556
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6557
					continue;
6558
				}
6559
6560
				// If this is an absolute or protocol-agnostic url,
6561
				// we don't want to mess with it.
6562
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6563
					continue;
6564
				}
6565
6566
				switch ( substr( $url, 0, 1 ) ) {
6567
					case '/':
6568
						$absolute = $domain . $url;
6569
						break;
6570
					default:
6571
						$absolute = $css_dir . '/' . $url;
6572
				}
6573
6574
				$find[]    = $match[0];
6575
				$replace[] = sprintf( 'url("%s")', $absolute );
6576
			}
6577
			$css = str_replace( $find, $replace, $css );
6578
		}
6579
6580
		return $css;
6581
	}
6582
6583
	/**
6584
	 * This methods removes all of the registered css files on the front end
6585
	 * from Jetpack in favor of using a single file. In effect "imploding"
6586
	 * all the files into one file.
6587
	 *
6588
	 * Pros:
6589
	 * - Uses only ONE css asset connection instead of 15
6590
	 * - Saves a minimum of 56k
6591
	 * - Reduces server load
6592
	 * - Reduces time to first painted byte
6593
	 *
6594
	 * Cons:
6595
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6596
	 *      should not cause any issues with themes.
6597
	 * - Plugins/themes dequeuing styles no longer do anything. See
6598
	 *      jetpack_implode_frontend_css filter for a workaround
6599
	 *
6600
	 * For some situations developers may wish to disable css imploding and
6601
	 * instead operate in legacy mode where each file loads seperately and
6602
	 * can be edited individually or dequeued. This can be accomplished with
6603
	 * the following line:
6604
	 *
6605
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6606
	 *
6607
	 * @since 3.2
6608
	 **/
6609
	public function implode_frontend_css( $travis_test = false ) {
6610
		$do_implode = true;
6611
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6612
			$do_implode = false;
6613
		}
6614
6615
		// Do not implode CSS when the page loads via the AMP plugin.
6616
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6617
			$do_implode = false;
6618
		}
6619
6620
		/**
6621
		 * Allow CSS to be concatenated into a single jetpack.css file.
6622
		 *
6623
		 * @since 3.2.0
6624
		 *
6625
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6626
		 */
6627
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6628
6629
		// Do not use the imploded file when default behavior was altered through the filter
6630
		if ( ! $do_implode ) {
6631
			return;
6632
		}
6633
6634
		// We do not want to use the imploded file in dev mode, or if not connected
6635
		if ( ( new Status() )->is_development_mode() || ! self::is_active() ) {
6636
			if ( ! $travis_test ) {
6637
				return;
6638
			}
6639
		}
6640
6641
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6642
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6643
			return;
6644
		}
6645
6646
		/*
6647
		 * Now we assume Jetpack is connected and able to serve the single
6648
		 * file.
6649
		 *
6650
		 * In the future there will be a check here to serve the file locally
6651
		 * or potentially from the Jetpack CDN
6652
		 *
6653
		 * For now:
6654
		 * - Enqueue a single imploded css file
6655
		 * - Zero out the style_loader_tag for the bundled ones
6656
		 * - Be happy, drink scotch
6657
		 */
6658
6659
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6660
6661
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6662
6663
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6664
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6665
	}
6666
6667
	function concat_remove_style_loader_tag( $tag, $handle ) {
6668
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6669
			$tag = '';
6670
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6671
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6672
			}
6673
		}
6674
6675
		return $tag;
6676
	}
6677
6678
	/**
6679
	 * Add an async attribute to scripts that can be loaded asynchronously.
6680
	 * https://www.w3schools.com/tags/att_script_async.asp
6681
	 *
6682
	 * @since 7.7.0
6683
	 *
6684
	 * @param string $tag    The <script> tag for the enqueued script.
6685
	 * @param string $handle The script's registered handle.
6686
	 * @param string $src    The script's source URL.
6687
	 */
6688
	public function script_add_async( $tag, $handle, $src ) {
6689
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6690
			return preg_replace( '/^<script /i', '<script async ', $tag );
6691
		}
6692
6693
		return $tag;
6694
	}
6695
6696
	/*
6697
	 * Check the heartbeat data
6698
	 *
6699
	 * Organizes the heartbeat data by severity.  For example, if the site
6700
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6701
	 *
6702
	 * Data will be added to "caution" array, if it either:
6703
	 *  - Out of date Jetpack version
6704
	 *  - Out of date WP version
6705
	 *  - Out of date PHP version
6706
	 *
6707
	 * $return array $filtered_data
6708
	 */
6709
	public static function jetpack_check_heartbeat_data() {
6710
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6711
6712
		$good    = array();
6713
		$caution = array();
6714
		$bad     = array();
6715
6716
		foreach ( $raw_data as $stat => $value ) {
6717
6718
			// Check jetpack version
6719
			if ( 'version' == $stat ) {
6720
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6721
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6722
					continue;
6723
				}
6724
			}
6725
6726
			// Check WP version
6727
			if ( 'wp-version' == $stat ) {
6728
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6729
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6730
					continue;
6731
				}
6732
			}
6733
6734
			// Check PHP version
6735
			if ( 'php-version' == $stat ) {
6736
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6737
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_PHP_VERSION;
6738
					continue;
6739
				}
6740
			}
6741
6742
			// Check ID crisis
6743
			if ( 'identitycrisis' == $stat ) {
6744
				if ( 'yes' == $value ) {
6745
					$bad[ $stat ] = $value;
6746
					continue;
6747
				}
6748
			}
6749
6750
			// The rest are good :)
6751
			$good[ $stat ] = $value;
6752
		}
6753
6754
		$filtered_data = array(
6755
			'good'    => $good,
6756
			'caution' => $caution,
6757
			'bad'     => $bad,
6758
		);
6759
6760
		return $filtered_data;
6761
	}
6762
6763
6764
	/*
6765
	 * This method is used to organize all options that can be reset
6766
	 * without disconnecting Jetpack.
6767
	 *
6768
	 * It is used in class.jetpack-cli.php to reset options
6769
	 *
6770
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6771
	 *
6772
	 * @return array of options to delete.
6773
	 */
6774
	public static function get_jetpack_options_for_reset() {
6775
		return Jetpack_Options::get_options_for_reset();
6776
	}
6777
6778
	/*
6779
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6780
	 * so we can bring them directly to their site in calypso.
6781
	 *
6782
	 * @param string | url
6783
	 * @return string | url without the guff
6784
	 */
6785
	public static function build_raw_urls( $url ) {
6786
		$strip_http = '/.*?:\/\//i';
6787
		$url        = preg_replace( $strip_http, '', $url );
6788
		$url        = str_replace( '/', '::', $url );
6789
		return $url;
6790
	}
6791
6792
	/**
6793
	 * Stores and prints out domains to prefetch for page speed optimization.
6794
	 *
6795
	 * @param mixed $new_urls
6796
	 */
6797
	public static function dns_prefetch( $new_urls = null ) {
6798
		static $prefetch_urls = array();
6799
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6800
			echo "\r\n";
6801
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6802
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6803
			}
6804
		} elseif ( ! empty( $new_urls ) ) {
6805
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6806
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6807
			}
6808
			foreach ( (array) $new_urls as $this_new_url ) {
6809
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6810
			}
6811
			$prefetch_urls = array_unique( $prefetch_urls );
6812
		}
6813
	}
6814
6815
	public function wp_dashboard_setup() {
6816
		if ( self::is_active() ) {
6817
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6818
		}
6819
6820
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6821
			$jetpack_logo = new Jetpack_Logo();
6822
			$widget_title = sprintf(
6823
				wp_kses(
6824
					/* translators: Placeholder is a Jetpack logo. */
6825
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6826
					array( 'span' => array() )
6827
				),
6828
				$jetpack_logo->get_jp_emblem( true )
6829
			);
6830
6831
			wp_add_dashboard_widget(
6832
				'jetpack_summary_widget',
6833
				$widget_title,
6834
				array( __CLASS__, 'dashboard_widget' )
6835
			);
6836
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6837
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6838
6839
			// If we're inactive and not in development mode, sort our box to the top.
6840
			if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
6841
				global $wp_meta_boxes;
6842
6843
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6844
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6845
6846
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6847
			}
6848
		}
6849
	}
6850
6851
	/**
6852
	 * @param mixed $result Value for the user's option
6853
	 * @return mixed
6854
	 */
6855
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6856
		if ( ! is_array( $sorted ) ) {
6857
			return $sorted;
6858
		}
6859
6860
		foreach ( $sorted as $box_context => $ids ) {
6861
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6862
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6863
				continue;
6864
			}
6865
6866
			$ids_array = explode( ',', $ids );
6867
			$key       = array_search( 'dashboard_stats', $ids_array );
6868
6869
			if ( false !== $key ) {
6870
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6871
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6872
				$sorted[ $box_context ] = implode( ',', $ids_array );
6873
				// We've found it, stop searching, and just return.
6874
				break;
6875
			}
6876
		}
6877
6878
		return $sorted;
6879
	}
6880
6881
	public static function dashboard_widget() {
6882
		/**
6883
		 * Fires when the dashboard is loaded.
6884
		 *
6885
		 * @since 3.4.0
6886
		 */
6887
		do_action( 'jetpack_dashboard_widget' );
6888
	}
6889
6890
	public static function dashboard_widget_footer() {
6891
		?>
6892
		<footer>
6893
6894
		<div class="protect">
6895
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6896
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6897
				<p><?php echo esc_html_x( 'Blocked malicious login attempts', '{#} Blocked malicious login attempts -- number is on a prior line, text is a caption.', 'jetpack' ); ?></p>
6898
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
6899
				<a href="
6900
				<?php
6901
				echo esc_url(
6902
					wp_nonce_url(
6903
						self::admin_url(
6904
							array(
6905
								'action' => 'activate',
6906
								'module' => 'protect',
6907
							)
6908
						),
6909
						'jetpack_activate-protect'
6910
					)
6911
				);
6912
				?>
6913
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6914
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6915
				</a>
6916
			<?php else : ?>
6917
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6918
			<?php endif; ?>
6919
		</div>
6920
6921
		<div class="akismet">
6922
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6923
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6924
				<p><?php echo esc_html_x( 'Spam comments blocked by Akismet.', '{#} Spam comments blocked by Akismet -- number is on a prior line, text is a caption.', 'jetpack' ); ?></p>
6925
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6926
				<a href="
6927
				<?php
6928
				echo esc_url(
6929
					wp_nonce_url(
6930
						add_query_arg(
6931
							array(
6932
								'action' => 'activate',
6933
								'plugin' => 'akismet/akismet.php',
6934
							),
6935
							admin_url( 'plugins.php' )
6936
						),
6937
						'activate-plugin_akismet/akismet.php'
6938
					)
6939
				);
6940
				?>
6941
							" class="button button-jetpack">
6942
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6943
				</a>
6944
			<?php else : ?>
6945
				<p><a href="<?php echo esc_url( 'https://akismet.com/?utm_source=jetpack&utm_medium=link&utm_campaign=Jetpack%20Dashboard%20Widget%20Footer%20Link' ); ?>"><?php esc_html_e( 'Akismet can help to keep your blog safe from spam!', 'jetpack' ); ?></a></p>
6946
			<?php endif; ?>
6947
		</div>
6948
6949
		</footer>
6950
		<?php
6951
	}
6952
6953
	/*
6954
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6955
	 */
6956
	function jetpack_icon_user_connected( $columns ) {
6957
		$columns['user_jetpack'] = '';
6958
		return $columns;
6959
	}
6960
6961
	/*
6962
	 * Show Jetpack icon if the user is linked.
6963
	 */
6964
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6965
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
6966
			$jetpack_logo = new Jetpack_Logo();
6967
			$emblem_html  = sprintf(
6968
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6969
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6970
				$jetpack_logo->get_jp_emblem()
6971
			);
6972
			return $emblem_html;
6973
		}
6974
6975
		return $val;
6976
	}
6977
6978
	/*
6979
	 * Style the Jetpack user column
6980
	 */
6981
	function jetpack_user_col_style() {
6982
		global $current_screen;
6983
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
6984
			?>
6985
			<style>
6986
				.fixed .column-user_jetpack {
6987
					width: 21px;
6988
				}
6989
				.jp-emblem-user-admin svg {
6990
					width: 20px;
6991
					height: 20px;
6992
				}
6993
				.jp-emblem-user-admin path {
6994
					fill: #00BE28;
6995
				}
6996
			</style>
6997
			<?php
6998
		}
6999
	}
7000
7001
	/**
7002
	 * Checks if Akismet is active and working.
7003
	 *
7004
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7005
	 * that implied usage of methods present since more recent version.
7006
	 * See https://github.com/Automattic/jetpack/pull/9585
7007
	 *
7008
	 * @since  5.1.0
7009
	 *
7010
	 * @return bool True = Akismet available. False = Aksimet not available.
7011
	 */
7012
	public static function is_akismet_active() {
7013
		static $status = null;
7014
7015
		if ( ! is_null( $status ) ) {
7016
			return $status;
7017
		}
7018
7019
		// Check if a modern version of Akismet is active.
7020
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7021
			$status = false;
7022
			return $status;
7023
		}
7024
7025
		// Make sure there is a key known to Akismet at all before verifying key.
7026
		$akismet_key = Akismet::get_api_key();
7027
		if ( ! $akismet_key ) {
7028
			$status = false;
7029
			return $status;
7030
		}
7031
7032
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7033
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7034
7035
		// Do not used the cache result in wp-admin or REST API requests if the key isn't valid, in case someone is actively renewing, etc.
7036
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7037
		// We cache the result of the Akismet key verification for ten minutes.
7038
		if ( ! $akismet_key_state || $recheck ) {
7039
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7040
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7041
		}
7042
7043
		$status = 'valid' === $akismet_key_state;
7044
7045
		return $status;
7046
	}
7047
7048
	/**
7049
	 * @deprecated
7050
	 *
7051
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7052
	 */
7053
	public static function is_function_in_backtrace() {
7054
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7055
	}
7056
7057
	/**
7058
	 * Given a minified path, and a non-minified path, will return
7059
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7060
	 *
7061
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7062
	 * root Jetpack directory.
7063
	 *
7064
	 * @since 5.6.0
7065
	 *
7066
	 * @param string $min_path
7067
	 * @param string $non_min_path
7068
	 * @return string The URL to the file
7069
	 */
7070
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7071
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7072
	}
7073
7074
	/**
7075
	 * Checks for whether Jetpack Backup & Scan is enabled.
7076
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
7077
	 *
7078
	 * @return bool|int|mixed
7079
	 */
7080
	public static function is_rewind_enabled() {
7081
		if ( ! self::is_active() ) {
7082
			return false;
7083
		}
7084
7085
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7086
		if ( false === $rewind_enabled ) {
7087
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7088
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7089
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7090
				&& ! empty( $rewind_data['state'] )
7091
				&& 'active' === $rewind_data['state'] )
7092
				? 1
7093
				: 0;
7094
7095
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7096
		}
7097
		return $rewind_enabled;
7098
	}
7099
7100
	/**
7101
	 * Return Calypso environment value; used for developing Jetpack and pairing
7102
	 * it with different Calypso enrionments, such as localhost.
7103
	 *
7104
	 * @since 7.4.0
7105
	 *
7106
	 * @return string Calypso environment
7107
	 */
7108
	public static function get_calypso_env() {
7109
		if ( isset( $_GET['calypso_env'] ) ) {
7110
			return sanitize_key( $_GET['calypso_env'] );
7111
		}
7112
7113
		if ( getenv( 'CALYPSO_ENV' ) ) {
7114
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7115
		}
7116
7117
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7118
			return sanitize_key( CALYPSO_ENV );
7119
		}
7120
7121
		return '';
7122
	}
7123
7124
	/**
7125
	 * Checks whether or not TOS has been agreed upon.
7126
	 * Will return true if a user has clicked to register, or is already connected.
7127
	 */
7128
	public static function jetpack_tos_agreed() {
7129
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7130
7131
		$terms_of_service = new Terms_Of_Service();
7132
		return $terms_of_service->has_agreed();
7133
7134
	}
7135
7136
	/**
7137
	 * Handles activating default modules as well general cleanup for the new connection.
7138
	 *
7139
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7140
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7141
	 * @param boolean $send_state_messages          Whether to send state messages.
7142
	 * @return void
7143
	 */
7144
	public static function handle_post_authorization_actions(
7145
		$activate_sso = false,
7146
		$redirect_on_activation_error = false,
7147
		$send_state_messages = true
7148
	) {
7149
		$other_modules = $activate_sso
7150
			? array( 'sso' )
7151
			: array();
7152
7153
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7154
			self::delete_active_modules();
7155
7156
			self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
7157
		} else {
7158
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7159
		}
7160
7161
		// Since this is a fresh connection, be sure to clear out IDC options
7162
		Jetpack_IDC::clear_all_idc_options();
7163
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7164
7165
		// Start nonce cleaner
7166
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7167
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7168
7169
		if ( $send_state_messages ) {
7170
			self::state( 'message', 'authorized' );
7171
		}
7172
	}
7173
7174
	/**
7175
	 * Returns a boolean for whether backups UI should be displayed or not.
7176
	 *
7177
	 * @return bool Should backups UI be displayed?
7178
	 */
7179
	public static function show_backups_ui() {
7180
		/**
7181
		 * Whether UI for backups should be displayed.
7182
		 *
7183
		 * @since 6.5.0
7184
		 *
7185
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7186
		 */
7187
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7188
	}
7189
7190
	/*
7191
	 * Deprecated manage functions
7192
	 */
7193
	function prepare_manage_jetpack_notice() {
7194
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7195
	}
7196
	function manage_activate_screen() {
7197
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7198
	}
7199
	function admin_jetpack_manage_notice() {
7200
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7201
	}
7202
	function opt_out_jetpack_manage_url() {
7203
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7204
	}
7205
	function opt_in_jetpack_manage_url() {
7206
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7207
	}
7208
	function opt_in_jetpack_manage_notice() {
7209
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7210
	}
7211
	function can_display_jetpack_manage_notice() {
7212
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7213
	}
7214
7215
	/**
7216
	 * Clean leftoveruser meta.
7217
	 *
7218
	 * Delete Jetpack-related user meta when it is no longer needed.
7219
	 *
7220
	 * @since 7.3.0
7221
	 *
7222
	 * @param int $user_id User ID being updated.
7223
	 */
7224
	public static function user_meta_cleanup( $user_id ) {
7225
		$meta_keys = array(
7226
			// AtD removed from Jetpack 7.3
7227
			'AtD_options',
7228
			'AtD_check_when',
7229
			'AtD_guess_lang',
7230
			'AtD_ignored_phrases',
7231
		);
7232
7233
		foreach ( $meta_keys as $meta_key ) {
7234
			if ( get_user_meta( $user_id, $meta_key ) ) {
7235
				delete_user_meta( $user_id, $meta_key );
7236
			}
7237
		}
7238
	}
7239
7240
	/**
7241
	 * Checks if a Jetpack site is both active and not in development.
7242
	 *
7243
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7244
	 *
7245
	 * @return bool True if Jetpack is active and not in development.
7246
	 */
7247
	public static function is_active_and_not_development_mode() {
7248
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7249
			return false;
7250
		}
7251
		return true;
7252
	}
7253
}
7254