Completed
Push — add/redirect-everything ( ffbe71...18e8a6 )
by
unknown
108:48 queued 100:57
created

class.jetpack.php (1 issue)

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

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

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