Completed
Push — recurring-payments/minimum-tra... ( a4df71...65f413 )
by
unknown
133:55 queued 127:48
created

class.jetpack.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

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

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

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

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