Completed
Push — add/redirect-everything ( 072b68 )
by
unknown
83:16 queued 66:54
created

class.jetpack.php (4 issues)

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

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6800
	 * 		@param string $path Additional path to be appended to the URL
0 ignored issues
show
There is no parameter named $path. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6801
	 * 		@param string $query Query parameters to be added to the URL
0 ignored issues
show
There is no parameter named $query. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6802
	 * 		@param string $anchor Anchor to be added to the URL
0 ignored issues
show
There is no parameter named $anchor. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6803
6804
	 * }
6805
	 *
6806
	 *
6807
	 * @return void
6808
	 */
6809
	public static function build_redirect_url( $source, $args = array() ) {
6810
6811
		$url = 'https://jetpack.com/redirect';
6812
6813
		$args = wp_parse_args($args);
6814
		$accepted = array( 'site', 'path', 'query', 'anchor' );
6815
6816
		$add = array(
6817
			'source' => urlencode( $source )
6818
		);
6819
6820
		foreach ( $args as $k => $arg ) {
6821
6822
			if ( ! in_array( $k, $accepted, true ) || empty( $arg ) ) {
6823
				continue;
6824
			}
6825
6826
			$add[$k] = urlencode( $arg );
6827
6828
		}
6829
6830
		if ( ! empty( $add ) ) {
6831
			$url = add_query_arg( $add, $url );
6832
		}
6833
6834
		return esc_url( $url );
6835
	}
6836
6837
	/**
6838
	 * Stores and prints out domains to prefetch for page speed optimization.
6839
	 *
6840
	 * @param mixed $new_urls
6841
	 */
6842
	public static function dns_prefetch( $new_urls = null ) {
6843
		static $prefetch_urls = array();
6844
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6845
			echo "\r\n";
6846
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6847
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6848
			}
6849
		} elseif ( ! empty( $new_urls ) ) {
6850
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6851
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6852
			}
6853
			foreach ( (array) $new_urls as $this_new_url ) {
6854
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6855
			}
6856
			$prefetch_urls = array_unique( $prefetch_urls );
6857
		}
6858
	}
6859
6860
	public function wp_dashboard_setup() {
6861
		if ( self::is_active() ) {
6862
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6863
		}
6864
6865
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6866
			$jetpack_logo = new Jetpack_Logo();
6867
			$widget_title = sprintf(
6868
				wp_kses(
6869
					/* translators: Placeholder is a Jetpack logo. */
6870
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6871
					array( 'span' => array() )
6872
				),
6873
				$jetpack_logo->get_jp_emblem( true )
6874
			);
6875
6876
			wp_add_dashboard_widget(
6877
				'jetpack_summary_widget',
6878
				$widget_title,
6879
				array( __CLASS__, 'dashboard_widget' )
6880
			);
6881
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6882
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6883
6884
			// If we're inactive and not in development mode, sort our box to the top.
6885
			if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
6886
				global $wp_meta_boxes;
6887
6888
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6889
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6890
6891
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6892
			}
6893
		}
6894
	}
6895
6896
	/**
6897
	 * @param mixed $result Value for the user's option
6898
	 * @return mixed
6899
	 */
6900
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6901
		if ( ! is_array( $sorted ) ) {
6902
			return $sorted;
6903
		}
6904
6905
		foreach ( $sorted as $box_context => $ids ) {
6906
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6907
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6908
				continue;
6909
			}
6910
6911
			$ids_array = explode( ',', $ids );
6912
			$key       = array_search( 'dashboard_stats', $ids_array );
6913
6914
			if ( false !== $key ) {
6915
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6916
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6917
				$sorted[ $box_context ] = implode( ',', $ids_array );
6918
				// We've found it, stop searching, and just return.
6919
				break;
6920
			}
6921
		}
6922
6923
		return $sorted;
6924
	}
6925
6926
	public static function dashboard_widget() {
6927
		/**
6928
		 * Fires when the dashboard is loaded.
6929
		 *
6930
		 * @since 3.4.0
6931
		 */
6932
		do_action( 'jetpack_dashboard_widget' );
6933
	}
6934
6935
	public static function dashboard_widget_footer() {
6936
		?>
6937
		<footer>
6938
6939
		<div class="protect">
6940
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6941
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6942
				<p class="blocked-count">
6943
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6944
				</p>
6945
				<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>
6946
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
6947
				<a href="
6948
				<?php
6949
				echo esc_url(
6950
					wp_nonce_url(
6951
						self::admin_url(
6952
							array(
6953
								'action' => 'activate',
6954
								'module' => 'protect',
6955
							)
6956
						),
6957
						'jetpack_activate-protect'
6958
					)
6959
				);
6960
				?>
6961
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6962
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
6963
				</a>
6964
			<?php else : ?>
6965
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
6966
			<?php endif; ?>
6967
		</div>
6968
6969
		<div class="akismet">
6970
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
6971
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6972
				<p class="blocked-count">
6973
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
6974
				</p>
6975
				<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>
6976
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6977
				<a href="
6978
				<?php
6979
				echo esc_url(
6980
					wp_nonce_url(
6981
						add_query_arg(
6982
							array(
6983
								'action' => 'activate',
6984
								'plugin' => 'akismet/akismet.php',
6985
							),
6986
							admin_url( 'plugins.php' )
6987
						),
6988
						'activate-plugin_akismet/akismet.php'
6989
					)
6990
				);
6991
				?>
6992
							" class="button button-jetpack">
6993
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
6994
				</a>
6995
			<?php else : ?>
6996
				<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>
6997
			<?php endif; ?>
6998
		</div>
6999
7000
		</footer>
7001
		<?php
7002
	}
7003
7004
	/*
7005
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7006
	 */
7007
	function jetpack_icon_user_connected( $columns ) {
7008
		$columns['user_jetpack'] = '';
7009
		return $columns;
7010
	}
7011
7012
	/*
7013
	 * Show Jetpack icon if the user is linked.
7014
	 */
7015
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7016
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
7017
			$jetpack_logo = new Jetpack_Logo();
7018
			$emblem_html  = sprintf(
7019
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7020
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7021
				$jetpack_logo->get_jp_emblem()
7022
			);
7023
			return $emblem_html;
7024
		}
7025
7026
		return $val;
7027
	}
7028
7029
	/*
7030
	 * Style the Jetpack user column
7031
	 */
7032
	function jetpack_user_col_style() {
7033
		global $current_screen;
7034
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7035
			?>
7036
			<style>
7037
				.fixed .column-user_jetpack {
7038
					width: 21px;
7039
				}
7040
				.jp-emblem-user-admin svg {
7041
					width: 20px;
7042
					height: 20px;
7043
				}
7044
				.jp-emblem-user-admin path {
7045
					fill: #00BE28;
7046
				}
7047
			</style>
7048
			<?php
7049
		}
7050
	}
7051
7052
	/**
7053
	 * Checks if Akismet is active and working.
7054
	 *
7055
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7056
	 * that implied usage of methods present since more recent version.
7057
	 * See https://github.com/Automattic/jetpack/pull/9585
7058
	 *
7059
	 * @since  5.1.0
7060
	 *
7061
	 * @return bool True = Akismet available. False = Aksimet not available.
7062
	 */
7063
	public static function is_akismet_active() {
7064
		static $status = null;
7065
7066
		if ( ! is_null( $status ) ) {
7067
			return $status;
7068
		}
7069
7070
		// Check if a modern version of Akismet is active.
7071
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7072
			$status = false;
7073
			return $status;
7074
		}
7075
7076
		// Make sure there is a key known to Akismet at all before verifying key.
7077
		$akismet_key = Akismet::get_api_key();
7078
		if ( ! $akismet_key ) {
7079
			$status = false;
7080
			return $status;
7081
		}
7082
7083
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7084
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7085
7086
		// 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.
7087
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7088
		// We cache the result of the Akismet key verification for ten minutes.
7089
		if ( ! $akismet_key_state || $recheck ) {
7090
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7091
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7092
		}
7093
7094
		$status = 'valid' === $akismet_key_state;
7095
7096
		return $status;
7097
	}
7098
7099
	/**
7100
	 * @deprecated
7101
	 *
7102
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7103
	 */
7104
	public static function is_function_in_backtrace() {
7105
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7106
	}
7107
7108
	/**
7109
	 * Given a minified path, and a non-minified path, will return
7110
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7111
	 *
7112
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7113
	 * root Jetpack directory.
7114
	 *
7115
	 * @since 5.6.0
7116
	 *
7117
	 * @param string $min_path
7118
	 * @param string $non_min_path
7119
	 * @return string The URL to the file
7120
	 */
7121
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7122
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7123
	}
7124
7125
	/**
7126
	 * Checks for whether Jetpack Backup & Scan is enabled.
7127
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
7128
	 *
7129
	 * @return bool|int|mixed
7130
	 */
7131
	public static function is_rewind_enabled() {
7132
		if ( ! self::is_active() ) {
7133
			return false;
7134
		}
7135
7136
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7137
		if ( false === $rewind_enabled ) {
7138
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7139
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7140
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7141
				&& ! empty( $rewind_data['state'] )
7142
				&& 'active' === $rewind_data['state'] )
7143
				? 1
7144
				: 0;
7145
7146
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7147
		}
7148
		return $rewind_enabled;
7149
	}
7150
7151
	/**
7152
	 * Return Calypso environment value; used for developing Jetpack and pairing
7153
	 * it with different Calypso enrionments, such as localhost.
7154
	 *
7155
	 * @since 7.4.0
7156
	 *
7157
	 * @return string Calypso environment
7158
	 */
7159
	public static function get_calypso_env() {
7160
		if ( isset( $_GET['calypso_env'] ) ) {
7161
			return sanitize_key( $_GET['calypso_env'] );
7162
		}
7163
7164
		if ( getenv( 'CALYPSO_ENV' ) ) {
7165
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7166
		}
7167
7168
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7169
			return sanitize_key( CALYPSO_ENV );
7170
		}
7171
7172
		return '';
7173
	}
7174
7175
	/**
7176
	 * Checks whether or not TOS has been agreed upon.
7177
	 * Will return true if a user has clicked to register, or is already connected.
7178
	 */
7179
	public static function jetpack_tos_agreed() {
7180
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7181
7182
		$terms_of_service = new Terms_Of_Service();
7183
		return $terms_of_service->has_agreed();
7184
7185
	}
7186
7187
	/**
7188
	 * Handles activating default modules as well general cleanup for the new connection.
7189
	 *
7190
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7191
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7192
	 * @param boolean $send_state_messages          Whether to send state messages.
7193
	 * @return void
7194
	 */
7195
	public static function handle_post_authorization_actions(
7196
		$activate_sso = false,
7197
		$redirect_on_activation_error = false,
7198
		$send_state_messages = true
7199
	) {
7200
		$other_modules = $activate_sso
7201
			? array( 'sso' )
7202
			: array();
7203
7204
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7205
			self::delete_active_modules();
7206
7207
			self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
7208
		} else {
7209
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7210
		}
7211
7212
		// Since this is a fresh connection, be sure to clear out IDC options
7213
		Jetpack_IDC::clear_all_idc_options();
7214
7215
		if ( $send_state_messages ) {
7216
			self::state( 'message', 'authorized' );
7217
		}
7218
	}
7219
7220
	/**
7221
	 * Returns a boolean for whether backups UI should be displayed or not.
7222
	 *
7223
	 * @return bool Should backups UI be displayed?
7224
	 */
7225
	public static function show_backups_ui() {
7226
		/**
7227
		 * Whether UI for backups should be displayed.
7228
		 *
7229
		 * @since 6.5.0
7230
		 *
7231
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7232
		 */
7233
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7234
	}
7235
7236
	/*
7237
	 * Deprecated manage functions
7238
	 */
7239
	function prepare_manage_jetpack_notice() {
7240
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7241
	}
7242
	function manage_activate_screen() {
7243
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7244
	}
7245
	function admin_jetpack_manage_notice() {
7246
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7247
	}
7248
	function opt_out_jetpack_manage_url() {
7249
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7250
	}
7251
	function opt_in_jetpack_manage_url() {
7252
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7253
	}
7254
	function opt_in_jetpack_manage_notice() {
7255
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7256
	}
7257
	function can_display_jetpack_manage_notice() {
7258
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7259
	}
7260
7261
	/**
7262
	 * Clean leftoveruser meta.
7263
	 *
7264
	 * Delete Jetpack-related user meta when it is no longer needed.
7265
	 *
7266
	 * @since 7.3.0
7267
	 *
7268
	 * @param int $user_id User ID being updated.
7269
	 */
7270
	public static function user_meta_cleanup( $user_id ) {
7271
		$meta_keys = array(
7272
			// AtD removed from Jetpack 7.3
7273
			'AtD_options',
7274
			'AtD_check_when',
7275
			'AtD_guess_lang',
7276
			'AtD_ignored_phrases',
7277
		);
7278
7279
		foreach ( $meta_keys as $meta_key ) {
7280
			if ( get_user_meta( $user_id, $meta_key ) ) {
7281
				delete_user_meta( $user_id, $meta_key );
7282
			}
7283
		}
7284
	}
7285
7286
	/**
7287
	 * Checks if a Jetpack site is both active and not in development.
7288
	 *
7289
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7290
	 *
7291
	 * @return bool True if Jetpack is active and not in development.
7292
	 */
7293
	public static function is_active_and_not_development_mode() {
7294
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7295
			return false;
7296
		}
7297
		return true;
7298
	}
7299
}
7300