Completed
Push — fix/14559-block-style ( 31537f...285323 )
by Gary
06:50
created

class.jetpack.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

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

1
<?php
2
use Automattic\Jetpack\Assets;
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Config;
5
use Automattic\Jetpack\Connection\Client;
6
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
7
use Automattic\Jetpack\Connection\Utils as Connection_Utils;
8
use Automattic\Jetpack\Constants;
9
use Automattic\Jetpack\Partner;
10
use Automattic\Jetpack\Roles;
11
use Automattic\Jetpack\Status;
12
use Automattic\Jetpack\Sync\Functions;
13
use Automattic\Jetpack\Sync\Health;
14
use Automattic\Jetpack\Sync\Sender;
15
use Automattic\Jetpack\Sync\Users;
16
use Automattic\Jetpack\Terms_Of_Service;
17
use Automattic\Jetpack\Tracking;
18
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
19
20
/*
21
Options:
22
jetpack_options (array)
23
	An array of options.
24
	@see Jetpack_Options::get_option_names()
25
26
jetpack_register (string)
27
	Temporary verification secrets.
28
29
jetpack_activated (int)
30
	1: the plugin was activated normally
31
	2: the plugin was activated on this site because of a network-wide activation
32
	3: the plugin was auto-installed
33
	4: the plugin was manually disconnected (but is still installed)
34
35
jetpack_active_modules (array)
36
	Array of active module slugs.
37
38
jetpack_do_activate (bool)
39
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
40
*/
41
42
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
43
44
class Jetpack {
45
	public $xmlrpc_server = null;
46
47
	private $rest_authentication_status = null;
48
49
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
50
51
	/**
52
	 * @var array The handles of styles that are concatenated into jetpack.css.
53
	 *
54
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
55
	 */
56
	public $concatenated_style_handles = array(
57
		'jetpack-carousel',
58
		'grunion.css',
59
		'the-neverending-homepage',
60
		'jetpack_likes',
61
		'jetpack_related-posts',
62
		'sharedaddy',
63
		'jetpack-slideshow',
64
		'presentations',
65
		'quiz',
66
		'jetpack-subscriptions',
67
		'jetpack-responsive-videos-style',
68
		'jetpack-social-menu',
69
		'tiled-gallery',
70
		'jetpack_display_posts_widget',
71
		'gravatar-profile-widget',
72
		'goodreads-widget',
73
		'jetpack_social_media_icons_widget',
74
		'jetpack-top-posts-widget',
75
		'jetpack_image_widget',
76
		'jetpack-my-community-widget',
77
		'jetpack-authors-widget',
78
		'wordads',
79
		'eu-cookie-law-style',
80
		'flickr-widget-style',
81
		'jetpack-search-widget',
82
		'jetpack-simple-payments-widget-style',
83
		'jetpack-widget-social-icons-styles',
84
	);
85
86
	/**
87
	 * The handles of scripts that can be loaded asynchronously.
88
	 *
89
	 * @var array
90
	 */
91
	public $async_script_handles = array(
92
		'woocommerce-analytics',
93
	);
94
95
	/**
96
	 * Contains all assets that have had their URL rewritten to minified versions.
97
	 *
98
	 * @var array
99
	 */
100
	static $min_assets = array();
101
102
	public $plugins_to_deactivate = array(
103
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
104
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
105
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
106
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
107
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
108
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
109
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
110
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
111
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
112
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
113
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
114
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
115
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
116
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
117
	);
118
119
	/**
120
	 * Map of roles we care about, and their corresponding minimum capabilities.
121
	 *
122
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
123
	 *
124
	 * @access public
125
	 * @static
126
	 *
127
	 * @var array
128
	 */
129
	public static $capability_translations = array(
130
		'administrator' => 'manage_options',
131
		'editor'        => 'edit_others_posts',
132
		'author'        => 'publish_posts',
133
		'contributor'   => 'edit_posts',
134
		'subscriber'    => 'read',
135
	);
136
137
	/**
138
	 * Map of modules that have conflicts with plugins and should not be auto-activated
139
	 * if the plugins are active.  Used by filter_default_modules
140
	 *
141
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
142
	 * change `module-slug` and add this to your plugin:
143
	 *
144
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
145
	 * function my_jetpack_get_default_modules( $modules ) {
146
	 *     return array_diff( $modules, array( 'module-slug' ) );
147
	 * }
148
	 *
149
	 * @var array
150
	 */
151
	private $conflicting_plugins = array(
152
		'comments'           => array(
153
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
154
			'Disqus'                         => 'disqus-comment-system/disqus.php',
155
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
156
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
157
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
158
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
159
		),
160
		'comment-likes'      => array(
161
			'Epoch' => 'epoch/plugincore.php',
162
		),
163
		'contact-form'       => array(
164
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
165
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
166
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
167
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
168
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
169
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
170
		),
171
		'latex'              => array(
172
			'LaTeX for WordPress'     => 'latex/latex.php',
173
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
174
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
175
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
176
			'Enable Latex'            => 'enable-latex/enable-latex.php',
177
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
178
		),
179
		'protect'            => array(
180
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
181
			'Captcha'                           => 'captcha/captcha.php',
182
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
183
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
184
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
185
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
186
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
187
			'Security-protection'               => 'security-protection/security-protection.php',
188
			'Login Security'                    => 'login-security/login-security.php',
189
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
190
			'Wordfence Security'                => 'wordfence/wordfence.php',
191
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
192
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
193
		),
194
		'random-redirect'    => array(
195
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
196
		),
197
		'related-posts'      => array(
198
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
199
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
200
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
201
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
202
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
203
			'outbrain'                    => 'outbrain/outbrain.php',
204
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
205
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
206
		),
207
		'sharedaddy'         => array(
208
			'AddThis'     => 'addthis/addthis_social_widget.php',
209
			'Add To Any'  => 'add-to-any/add-to-any.php',
210
			'ShareThis'   => 'share-this/sharethis.php',
211
			'Shareaholic' => 'shareaholic/shareaholic.php',
212
		),
213
		'seo-tools'          => array(
214
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
215
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
216
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
217
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
218
			'The SEO Framework'              => 'autodescription/autodescription.php',
219
		),
220
		'verification-tools' => array(
221
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
222
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
223
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
224
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
225
			'The SEO Framework'              => 'autodescription/autodescription.php',
226
		),
227
		'widget-visibility'  => array(
228
			'Widget Logic'    => 'widget-logic/widget_logic.php',
229
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
230
		),
231
		'sitemaps'           => array(
232
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
233
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
234
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
235
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
236
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
237
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
238
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
239
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
240
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
241
			'The SEO Framework'                    => 'autodescription/autodescription.php',
242
			'Sitemap'                              => 'sitemap/sitemap.php',
243
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
244
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
245
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
246
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
247
		),
248
		'lazy-images'        => array(
249
			'Lazy Load'              => 'lazy-load/lazy-load.php',
250
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
251
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
252
		),
253
	);
254
255
	/**
256
	 * Plugins for which we turn off our Facebook OG Tags implementation.
257
	 *
258
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
259
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
260
	 *
261
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
262
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
263
	 */
264
	private $open_graph_conflicting_plugins = array(
265
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
266
		// 2 Click Social Media Buttons
267
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
268
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
269
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
270
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
271
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
272
		// Open Graph Meta Tags by Heateor
273
		'facebook/facebook.php',                                 // Facebook (official plugin)
274
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
275
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
276
		// Facebook Featured Image & OG Meta Tags
277
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
278
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
279
		// Facebook Open Graph Meta Tags for WordPress
280
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
281
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
282
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
283
		// Fedmich's Facebook Open Graph Meta
284
		'network-publisher/networkpub.php',                      // Network Publisher
285
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
286
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
287
		// NextScripts SNAP
288
		'og-tags/og-tags.php',                                   // OG Tags
289
		'opengraph/opengraph.php',                               // Open Graph
290
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
291
		// Open Graph Protocol Framework
292
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
293
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
294
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
295
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
296
		'sharepress/sharepress.php',                             // SharePress
297
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
298
		'social-discussions/social-discussions.php',             // Social Discussions
299
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
300
		'socialize/socialize.php',                               // Socialize
301
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
302
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
303
		// Tweet, Like, Google +1 and Share
304
		'wordbooker/wordbooker.php',                             // Wordbooker
305
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
306
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
307
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
308
		// WP Facebook Like Send & Open Graph Meta
309
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
310
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
311
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
312
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
313
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
314
	);
315
316
	/**
317
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
318
	 */
319
	private $twitter_cards_conflicting_plugins = array(
320
		// 'twitter/twitter.php',                       // The official one handles this on its own.
321
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
322
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
323
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
324
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
325
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
326
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
327
		'twitter-cards/twitter-cards.php',           // Twitter Cards
328
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
329
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
330
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
331
	);
332
333
	/**
334
	 * Message to display in admin_notice
335
	 *
336
	 * @var string
337
	 */
338
	public $message = '';
339
340
	/**
341
	 * Error to display in admin_notice
342
	 *
343
	 * @var string
344
	 */
345
	public $error = '';
346
347
	/**
348
	 * Modules that need more privacy description.
349
	 *
350
	 * @var string
351
	 */
352
	public $privacy_checks = '';
353
354
	/**
355
	 * Stats to record once the page loads
356
	 *
357
	 * @var array
358
	 */
359
	public $stats = array();
360
361
	/**
362
	 * Jetpack_Sync object
363
	 */
364
	public $sync;
365
366
	/**
367
	 * Verified data for JSON authorization request
368
	 */
369
	public $json_api_authorization_request = array();
370
371
	/**
372
	 * @var Automattic\Jetpack\Connection\Manager
373
	 */
374
	protected $connection_manager;
375
376
	/**
377
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
378
	 */
379
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
380
381
	/**
382
	 * Holds the singleton instance of this class
383
	 *
384
	 * @since 2.3.3
385
	 * @var Jetpack
386
	 */
387
	static $instance = false;
388
389
	/**
390
	 * Singleton
391
	 *
392
	 * @static
393
	 */
394
	public static function init() {
395
		if ( ! self::$instance ) {
396
			self::$instance = new Jetpack();
397
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
398
		}
399
400
		return self::$instance;
401
	}
402
403
	/**
404
	 * Must never be called statically
405
	 */
406
	function plugin_upgrade() {
407
		if ( self::is_active() ) {
408
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
409
			if ( JETPACK__VERSION != $version ) {
410
				// Prevent multiple upgrades at once - only a single process should trigger
411
				// an upgrade to avoid stampedes
412
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
413
					return;
414
				}
415
416
				// Set a short lock to prevent multiple instances of the upgrade
417
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
418
419
				// check which active modules actually exist and remove others from active_modules list
420
				$unfiltered_modules = self::get_active_modules();
421
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
422
				if ( array_diff( $unfiltered_modules, $modules ) ) {
423
					self::update_active_modules( $modules );
424
				}
425
426
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
427
428
				// Upgrade to 4.3.0
429
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
430
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
431
				}
432
433
				// Make sure Markdown for posts gets turned back on
434
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
435
					update_option( 'wpcom_publish_posts_with_markdown', true );
436
				}
437
438
				/*
439
				 * Minileven deprecation. 8.3.0.
440
				 * Only delete options if not using
441
				 * the replacement standalone Minileven plugin.
442
				 */
443
				if (
444
					! self::is_plugin_active( 'minileven-master/minileven.php' )
445
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
446
				) {
447
					if ( get_option( 'wp_mobile_custom_css' ) ) {
448
						delete_option( 'wp_mobile_custom_css' );
449
					}
450
					if ( get_option( 'wp_mobile_excerpt' ) ) {
451
						delete_option( 'wp_mobile_excerpt' );
452
					}
453
					if ( get_option( 'wp_mobile_featured_images' ) ) {
454
						delete_option( 'wp_mobile_featured_images' );
455
					}
456
					if ( get_option( 'wp_mobile_app_promos' ) ) {
457
						delete_option( 'wp_mobile_app_promos' );
458
					}
459
				}
460
461
				// Upgrade to 8.4.0.
462
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
463
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
464
				}
465
466
				if ( did_action( 'wp_loaded' ) ) {
467
					self::upgrade_on_load();
468
				} else {
469
					add_action(
470
						'wp_loaded',
471
						array( __CLASS__, 'upgrade_on_load' )
472
					);
473
				}
474
			}
475
		}
476
	}
477
478
	/**
479
	 * Runs upgrade routines that need to have modules loaded.
480
	 */
481
	static function upgrade_on_load() {
482
483
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
484
		// This can happen in case Jetpack has been just upgraded and is
485
		// being initialized late during the page load. In this case we wait
486
		// until the next proper admin page load with Jetpack active.
487
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
488
			delete_transient( self::$plugin_upgrade_lock_key );
489
490
			return;
491
		}
492
493
		self::maybe_set_version_option();
494
495
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
496
			Jetpack_Widget_Conditions::migrate_post_type_rules();
497
		}
498
499
		if (
500
			class_exists( 'Jetpack_Sitemap_Manager' )
501
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
502
		) {
503
			do_action( 'jetpack_sitemaps_purge_data' );
504
		}
505
506
		// Delete old stats cache
507
		delete_option( 'jetpack_restapi_stats_cache' );
508
509
		delete_transient( self::$plugin_upgrade_lock_key );
510
	}
511
512
	/**
513
	 * Saves all the currently active modules to options.
514
	 * Also fires Action hooks for each newly activated and deactivated module.
515
	 *
516
	 * @param $modules Array Array of active modules to be saved in options.
517
	 *
518
	 * @return $success bool true for success, false for failure.
519
	 */
520
	static function update_active_modules( $modules ) {
521
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
522
		$active_modules       = self::get_active_modules();
523
		$new_active_modules   = array_diff( $modules, $current_modules );
524
		$new_inactive_modules = array_diff( $active_modules, $modules );
525
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
526
		$reindexed_modules    = array_values( $new_current_modules );
527
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
528
529
		foreach ( $new_active_modules as $module ) {
530
			/**
531
			 * Fires when a specific module is activated.
532
			 *
533
			 * @since 1.9.0
534
			 *
535
			 * @param string $module Module slug.
536
			 * @param boolean $success whether the module was activated. @since 4.2
537
			 */
538
			do_action( 'jetpack_activate_module', $module, $success );
539
			/**
540
			 * Fires when a module is activated.
541
			 * The dynamic part of the filter, $module, is the module slug.
542
			 *
543
			 * @since 1.9.0
544
			 *
545
			 * @param string $module Module slug.
546
			 */
547
			do_action( "jetpack_activate_module_$module", $module );
548
		}
549
550
		foreach ( $new_inactive_modules as $module ) {
551
			/**
552
			 * Fired after a module has been deactivated.
553
			 *
554
			 * @since 4.2.0
555
			 *
556
			 * @param string $module Module slug.
557
			 * @param boolean $success whether the module was deactivated.
558
			 */
559
			do_action( 'jetpack_deactivate_module', $module, $success );
560
			/**
561
			 * Fires when a module is deactivated.
562
			 * The dynamic part of the filter, $module, is the module slug.
563
			 *
564
			 * @since 1.9.0
565
			 *
566
			 * @param string $module Module slug.
567
			 */
568
			do_action( "jetpack_deactivate_module_$module", $module );
569
		}
570
571
		return $success;
572
	}
573
574
	static function delete_active_modules() {
575
		self::update_active_modules( array() );
576
	}
577
578
	/**
579
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
580
	 * available.
581
	 */
582
	public function add_configure_hook() {
583
		global $wp_filter;
584
585
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
586
		if ( false !== $current_priority ) {
587
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
588
		}
589
590
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
591
		sort( $taken_priorities );
592
593
		$first_priority = array_shift( $taken_priorities );
594
595
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
596
			$new_priority = - PHP_INT_MAX;
597
		} else {
598
			$new_priority = $first_priority - 1;
599
		}
600
601
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
602
	}
603
604
	/**
605
	 * Constructor.  Initializes WordPress hooks
606
	 */
607
	private function __construct() {
608
		/*
609
		 * Check for and alert any deprecated hooks
610
		 */
611
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
612
613
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
614
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
615
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
616
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
617
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
618
619
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
620
621
		add_filter(
622
			'jetpack_signature_check_token',
623
			array( __CLASS__, 'verify_onboarding_token' ),
624
			10,
625
			3
626
		);
627
628
		/**
629
		 * Prepare Gutenberg Editor functionality
630
		 */
631
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
632
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
633
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
634
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
635
636
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
637
638
		// Unlink user before deleting the user from WP.com.
639
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
640
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
641
642
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
643
644
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
645
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
646
647
		add_action( 'admin_init', array( $this, 'admin_init' ) );
648
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
649
650
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
651
652
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
653
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
654
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
655
656
		// returns HTTPS support status
657
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
658
659
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
660
661
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
662
663
		/**
664
		 * These actions run checks to load additional files.
665
		 * They check for external files or plugins, so they need to run as late as possible.
666
		 */
667
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
668
		add_action( 'amp_story_head', array( $this, 'check_open_graph' ), 1 );
669
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
670
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
671
672
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
673
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
674
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
675
676
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
677
678
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
679
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
680
681
		// A filter to control all just in time messages
682
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
683
684
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
685
686
		// Hide edit post link if mobile app.
687
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
688
			add_filter( 'get_edit_post_link', '__return_empty_string' );
689
		}
690
691
		// Update the Jetpack plan from API on heartbeats
692
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
693
694
		/**
695
		 * This is the hack to concatenate all css files into one.
696
		 * For description and reasoning see the implode_frontend_css method
697
		 *
698
		 * Super late priority so we catch all the registered styles
699
		 */
700
		if ( ! is_admin() ) {
701
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
702
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
703
		}
704
705
		/**
706
		 * These are sync actions that we need to keep track of for jitms
707
		 */
708
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
709
710
		// Actually push the stats on shutdown.
711
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
712
			add_action( 'shutdown', array( $this, 'push_stats' ) );
713
		}
714
715
		/*
716
		 * Load some scripts asynchronously.
717
		 */
718
		add_action( 'script_loader_tag', array( $this, 'script_add_async' ), 10, 3 );
719
720
		// Actions for Manager::authorize().
721
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
722
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
723
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
724
725
		// Filters for the Manager::get_token() urls and request body.
726
		add_filter( 'jetpack_token_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
727
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
728
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
729
	}
730
731
	/**
732
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
733
	 * Config object.
734
	 */
735
	public function configure() {
736
		$config = new Config();
737
738
		foreach (
739
			array(
740
				'connection',
741
				'sync',
742
				'tracking',
743
				'tos',
744
			)
745
			as $feature
746
		) {
747
			$config->ensure( $feature );
748
		}
749
750
		if ( is_admin() ) {
751
			$config->ensure( 'jitm' );
752
		}
753
754
		if ( ! $this->connection_manager ) {
755
			$this->connection_manager = new Connection_Manager();
756
		}
757
758
		/*
759
		 * Load things that should only be in Network Admin.
760
		 *
761
		 * For now blow away everything else until a more full
762
		 * understanding of what is needed at the network level is
763
		 * available
764
		 */
765
		if ( is_multisite() ) {
766
			$network = Jetpack_Network::init();
767
			$network->set_connection( $this->connection_manager );
768
		}
769
770
		if ( $this->connection_manager->is_active() ) {
771
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
772
773
			Jetpack_Heartbeat::init();
774
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
775
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
776
				Jetpack_Search_Performance_Logger::init();
777
			}
778
		}
779
780
		// Initialize remote file upload request handlers.
781
		$this->add_remote_request_handlers();
782
783
		/*
784
		 * Enable enhanced handling of previewing sites in Calypso
785
		 */
786
		if ( self::is_active() ) {
787
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
788
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
789
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
790
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
791
		}
792
793
		/*
794
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
795
		 * We should make sure to only do this for front end links.
796
		 */
797
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
798
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
799
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
800
801
			/*
802
			 * We'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
803
			 * so they point moderation links on emails to Calypso.
804
			 */
805
			jetpack_require_lib( 'functions.wp-notify' );
806
		}
807
808
	}
809
810
	/**
811
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
812
	 * initialization code.
813
	 *
814
	 * @action plugins_loaded
815
	 */
816
	public function late_initialization() {
817
		add_action( 'plugins_loaded', array( 'Jetpack', 'plugin_textdomain' ), 99 );
818
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
819
820
		Partner::init();
821
822
		/**
823
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
824
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
825
		 *
826
		 * @since 8.1.0
827
		 *
828
		 * @param Jetpack $jetpack the main plugin class object.
829
		 */
830
		do_action( 'jetpack_loaded', $this );
831
832
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
833
	}
834
835
	/**
836
	 * Sets up the XMLRPC request handlers.
837
	 *
838
	 * @deprecated since 7.7.0
839
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
840
	 *
841
	 * @param Array                 $request_params Incoming request parameters.
842
	 * @param Boolean               $is_active      Whether the connection is currently active.
843
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
844
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
845
	 */
846 View Code Duplication
	public function setup_xmlrpc_handlers(
847
		$request_params,
848
		$is_active,
849
		$is_signed,
850
		Jetpack_XMLRPC_Server $xmlrpc_server = null
851
	) {
852
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
853
854
		if ( ! $this->connection_manager ) {
855
			$this->connection_manager = new Connection_Manager();
856
		}
857
858
		return $this->connection_manager->setup_xmlrpc_handlers(
859
			$request_params,
860
			$is_active,
861
			$is_signed,
862
			$xmlrpc_server
863
		);
864
	}
865
866
	/**
867
	 * Initialize REST API registration connector.
868
	 *
869
	 * @deprecated since 7.7.0
870
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
871
	 */
872 View Code Duplication
	public function initialize_rest_api_registration_connector() {
873
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
874
875
		if ( ! $this->connection_manager ) {
876
			$this->connection_manager = new Connection_Manager();
877
		}
878
879
		$this->connection_manager->initialize_rest_api_registration_connector();
880
	}
881
882
	/**
883
	 * This is ported over from the manage module, which has been deprecated and baked in here.
884
	 *
885
	 * @param $domains
886
	 */
887
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
888
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
889
	}
890
891
	/**
892
	 * Return $domains, with 'wordpress.com' appended.
893
	 * This is ported over from the manage module, which has been deprecated and baked in here.
894
	 *
895
	 * @param $domains
896
	 * @return array
897
	 */
898
	function allow_wpcom_domain( $domains ) {
899
		if ( empty( $domains ) ) {
900
			$domains = array();
901
		}
902
		$domains[] = 'wordpress.com';
903
		return array_unique( $domains );
904
	}
905
906
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
907
		$post = get_post( $post_id );
908
909
		if ( empty( $post ) ) {
910
			return $default_url;
911
		}
912
913
		$post_type = $post->post_type;
914
915
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
916
		// https://en.support.wordpress.com/custom-post-types/
917
		$allowed_post_types = array(
918
			'post'                => 'post',
919
			'page'                => 'page',
920
			'jetpack-portfolio'   => 'edit/jetpack-portfolio',
921
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
922
		);
923
924
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
925
			return $default_url;
926
		}
927
928
		$path_prefix = $allowed_post_types[ $post_type ];
929
930
		$site_slug = self::build_raw_urls( get_home_url() );
931
932
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
933
	}
934
935
	function point_edit_comment_links_to_calypso( $url ) {
936
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
937
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
938
		return esc_url(
939
			sprintf(
940
				'https://wordpress.com/comment/%s/%d',
941
				self::build_raw_urls( get_home_url() ),
942
				$query_args['amp;c']
943
			)
944
		);
945
	}
946
947
	function jetpack_track_last_sync_callback( $params ) {
948
		/**
949
		 * Filter to turn off jitm caching
950
		 *
951
		 * @since 5.4.0
952
		 *
953
		 * @param bool false Whether to cache just in time messages
954
		 */
955
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
956
			return $params;
957
		}
958
959
		if ( is_array( $params ) && isset( $params[0] ) ) {
960
			$option = $params[0];
961
			if ( 'active_plugins' === $option ) {
962
				// use the cache if we can, but not terribly important if it gets evicted
963
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
964
			}
965
		}
966
967
		return $params;
968
	}
969
970
	function jetpack_connection_banner_callback() {
971
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
972
973
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
974
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
975
			wp_send_json_success();
976
		}
977
978
		wp_die();
979
	}
980
981
	/**
982
	 * Removes all XML-RPC methods that are not `jetpack.*`.
983
	 * Only used in our alternate XML-RPC endpoint, where we want to
984
	 * ensure that Core and other plugins' methods are not exposed.
985
	 *
986
	 * @deprecated since 7.7.0
987
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
988
	 *
989
	 * @param array $methods A list of registered WordPress XMLRPC methods.
990
	 * @return array Filtered $methods
991
	 */
992 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
993
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
994
995
		if ( ! $this->connection_manager ) {
996
			$this->connection_manager = new Connection_Manager();
997
		}
998
999
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1000
	}
1001
1002
	/**
1003
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1004
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1005
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1006
	 * which is accessible via a different URI. Most of the below is copied directly
1007
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1008
	 *
1009
	 * @deprecated since 7.7.0
1010
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1011
	 */
1012 View Code Duplication
	public function alternate_xmlrpc() {
1013
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1014
1015
		if ( ! $this->connection_manager ) {
1016
			$this->connection_manager = new Connection_Manager();
1017
		}
1018
1019
		$this->connection_manager->alternate_xmlrpc();
1020
	}
1021
1022
	/**
1023
	 * The callback for the JITM ajax requests.
1024
	 *
1025
	 * @deprecated since 7.9.0
1026
	 */
1027
	function jetpack_jitm_ajax_callback() {
1028
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1029
	}
1030
1031
	/**
1032
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1033
	 */
1034
	function push_stats() {
1035
		if ( ! empty( $this->stats ) ) {
1036
			$this->do_stats( 'server_side' );
1037
		}
1038
	}
1039
1040
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1041
		$is_development_mode = ( new Status() )->is_development_mode();
1042
		switch ( $cap ) {
1043
			case 'jetpack_connect':
1044
			case 'jetpack_reconnect':
1045
				if ( $is_development_mode ) {
1046
					$caps = array( 'do_not_allow' );
1047
					break;
1048
				}
1049
				/**
1050
				 * Pass through. If it's not development mode, these should match disconnect.
1051
				 * Let users disconnect if it's development mode, just in case things glitch.
1052
				 */
1053
			case 'jetpack_disconnect':
1054
				/**
1055
				 * In multisite, can individual site admins manage their own connection?
1056
				 *
1057
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1058
				 */
1059
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1060
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1061
						/**
1062
						 * We need to update the option name -- it's terribly unclear which
1063
						 * direction the override goes.
1064
						 *
1065
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1066
						 */
1067
						$caps = array( 'do_not_allow' );
1068
						break;
1069
					}
1070
				}
1071
1072
				$caps = array( 'manage_options' );
1073
				break;
1074
			case 'jetpack_manage_modules':
1075
			case 'jetpack_activate_modules':
1076
			case 'jetpack_deactivate_modules':
1077
				$caps = array( 'manage_options' );
1078
				break;
1079
			case 'jetpack_configure_modules':
1080
				$caps = array( 'manage_options' );
1081
				break;
1082
			case 'jetpack_manage_autoupdates':
1083
				$caps = array(
1084
					'manage_options',
1085
					'update_plugins',
1086
				);
1087
				break;
1088
			case 'jetpack_network_admin_page':
1089
			case 'jetpack_network_settings_page':
1090
				$caps = array( 'manage_network_plugins' );
1091
				break;
1092
			case 'jetpack_network_sites_page':
1093
				$caps = array( 'manage_sites' );
1094
				break;
1095
			case 'jetpack_admin_page':
1096
				if ( $is_development_mode ) {
1097
					$caps = array( 'manage_options' );
1098
					break;
1099
				} else {
1100
					$caps = array( 'read' );
1101
				}
1102
				break;
1103
			case 'jetpack_connect_user':
1104
				if ( $is_development_mode ) {
1105
					$caps = array( 'do_not_allow' );
1106
					break;
1107
				}
1108
				$caps = array( 'read' );
1109
				break;
1110
		}
1111
		return $caps;
1112
	}
1113
1114
	/**
1115
	 * Require a Jetpack authentication.
1116
	 *
1117
	 * @deprecated since 7.7.0
1118
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1119
	 */
1120 View Code Duplication
	public function require_jetpack_authentication() {
1121
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1122
1123
		if ( ! $this->connection_manager ) {
1124
			$this->connection_manager = new Connection_Manager();
1125
		}
1126
1127
		$this->connection_manager->require_jetpack_authentication();
1128
	}
1129
1130
	/**
1131
	 * Load language files
1132
	 *
1133
	 * @action plugins_loaded
1134
	 */
1135
	public static function plugin_textdomain() {
1136
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1137
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1138
	}
1139
1140
	/**
1141
	 * Register assets for use in various modules and the Jetpack admin page.
1142
	 *
1143
	 * @uses wp_script_is, wp_register_script, plugins_url
1144
	 * @action wp_loaded
1145
	 * @return null
1146
	 */
1147
	public function register_assets() {
1148
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1149
			wp_register_script(
1150
				'spin',
1151
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1152
				false,
1153
				'1.3'
1154
			);
1155
		}
1156
1157 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1158
			wp_register_script(
1159
				'jquery.spin',
1160
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1161
				array( 'jquery', 'spin' ),
1162
				'1.3'
1163
			);
1164
		}
1165
1166 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1167
			wp_register_script(
1168
				'jetpack-gallery-settings',
1169
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1170
				array( 'media-views' ),
1171
				'20121225'
1172
			);
1173
		}
1174
1175 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1176
			wp_register_script(
1177
				'jetpack-twitter-timeline',
1178
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1179
				array( 'jquery' ),
1180
				'4.0.0',
1181
				true
1182
			);
1183
		}
1184
1185
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1186
			wp_register_script(
1187
				'jetpack-facebook-embed',
1188
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1189
				array(),
1190
				null,
1191
				true
1192
			);
1193
1194
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1195
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1196
			if ( ! is_numeric( $fb_app_id ) ) {
1197
				$fb_app_id = '';
1198
			}
1199
			wp_localize_script(
1200
				'jetpack-facebook-embed',
1201
				'jpfbembed',
1202
				array(
1203
					'appid'  => $fb_app_id,
1204
					'locale' => $this->get_locale(),
1205
				)
1206
			);
1207
		}
1208
1209
		/**
1210
		 * As jetpack_register_genericons is by default fired off a hook,
1211
		 * the hook may have already fired by this point.
1212
		 * So, let's just trigger it manually.
1213
		 */
1214
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1215
		jetpack_register_genericons();
1216
1217
		/**
1218
		 * Register the social logos
1219
		 */
1220
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1221
		jetpack_register_social_logos();
1222
1223 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1224
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1225
		}
1226
	}
1227
1228
	/**
1229
	 * Guess locale from language code.
1230
	 *
1231
	 * @param string $lang Language code.
1232
	 * @return string|bool
1233
	 */
1234 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1235
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1236
			return 'en_US';
1237
		}
1238
1239
		if ( ! class_exists( 'GP_Locales' ) ) {
1240
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1241
				return false;
1242
			}
1243
1244
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1245
		}
1246
1247
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1248
			// WP.com: get_locale() returns 'it'
1249
			$locale = GP_Locales::by_slug( $lang );
1250
		} else {
1251
			// Jetpack: get_locale() returns 'it_IT';
1252
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1253
		}
1254
1255
		if ( ! $locale ) {
1256
			return false;
1257
		}
1258
1259
		if ( empty( $locale->facebook_locale ) ) {
1260
			if ( empty( $locale->wp_locale ) ) {
1261
				return false;
1262
			} else {
1263
				// Facebook SDK is smart enough to fall back to en_US if a
1264
				// locale isn't supported. Since supported Facebook locales
1265
				// can fall out of sync, we'll attempt to use the known
1266
				// wp_locale value and rely on said fallback.
1267
				return $locale->wp_locale;
1268
			}
1269
		}
1270
1271
		return $locale->facebook_locale;
1272
	}
1273
1274
	/**
1275
	 * Get the locale.
1276
	 *
1277
	 * @return string|bool
1278
	 */
1279
	function get_locale() {
1280
		$locale = $this->guess_locale_from_lang( get_locale() );
1281
1282
		if ( ! $locale ) {
1283
			$locale = 'en_US';
1284
		}
1285
1286
		return $locale;
1287
	}
1288
1289
	/**
1290
	 * Return the network_site_url so that .com knows what network this site is a part of.
1291
	 *
1292
	 * @param  bool $option
1293
	 * @return string
1294
	 */
1295
	public function jetpack_main_network_site_option( $option ) {
1296
		return network_site_url();
1297
	}
1298
	/**
1299
	 * Network Name.
1300
	 */
1301
	static function network_name( $option = null ) {
1302
		global $current_site;
1303
		return $current_site->site_name;
1304
	}
1305
	/**
1306
	 * Does the network allow new user and site registrations.
1307
	 *
1308
	 * @return string
1309
	 */
1310
	static function network_allow_new_registrations( $option = null ) {
1311
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1312
	}
1313
	/**
1314
	 * Does the network allow admins to add new users.
1315
	 *
1316
	 * @return boolian
1317
	 */
1318
	static function network_add_new_users( $option = null ) {
1319
		return (bool) get_site_option( 'add_new_users' );
1320
	}
1321
	/**
1322
	 * File upload psace left per site in MB.
1323
	 *  -1 means NO LIMIT.
1324
	 *
1325
	 * @return number
1326
	 */
1327
	static function network_site_upload_space( $option = null ) {
1328
		// value in MB
1329
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1330
	}
1331
1332
	/**
1333
	 * Network allowed file types.
1334
	 *
1335
	 * @return string
1336
	 */
1337
	static function network_upload_file_types( $option = null ) {
1338
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1339
	}
1340
1341
	/**
1342
	 * Maximum file upload size set by the network.
1343
	 *
1344
	 * @return number
1345
	 */
1346
	static function network_max_upload_file_size( $option = null ) {
1347
		// value in KB
1348
		return get_site_option( 'fileupload_maxk', 300 );
1349
	}
1350
1351
	/**
1352
	 * Lets us know if a site allows admins to manage the network.
1353
	 *
1354
	 * @return array
1355
	 */
1356
	static function network_enable_administration_menus( $option = null ) {
1357
		return get_site_option( 'menu_items' );
1358
	}
1359
1360
	/**
1361
	 * If a user has been promoted to or demoted from admin, we need to clear the
1362
	 * jetpack_other_linked_admins transient.
1363
	 *
1364
	 * @since 4.3.2
1365
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1366
	 *
1367
	 * @param int    $user_id   The user ID whose role changed.
1368
	 * @param string $role      The new role.
1369
	 * @param array  $old_roles An array of the user's previous roles.
1370
	 */
1371
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1372
		if ( 'administrator' == $role
1373
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1374
			|| is_null( $old_roles )
1375
		) {
1376
			delete_transient( 'jetpack_other_linked_admins' );
1377
		}
1378
	}
1379
1380
	/**
1381
	 * Checks to see if there are any other users available to become primary
1382
	 * Users must both:
1383
	 * - Be linked to wpcom
1384
	 * - Be an admin
1385
	 *
1386
	 * @return mixed False if no other users are linked, Int if there are.
1387
	 */
1388
	static function get_other_linked_admins() {
1389
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1390
1391
		if ( false === $other_linked_users ) {
1392
			$admins = get_users( array( 'role' => 'administrator' ) );
1393
			if ( count( $admins ) > 1 ) {
1394
				$available = array();
1395
				foreach ( $admins as $admin ) {
1396
					if ( self::is_user_connected( $admin->ID ) ) {
1397
						$available[] = $admin->ID;
1398
					}
1399
				}
1400
1401
				$count_connected_admins = count( $available );
1402
				if ( count( $available ) > 1 ) {
1403
					$other_linked_users = $count_connected_admins;
1404
				} else {
1405
					$other_linked_users = 0;
1406
				}
1407
			} else {
1408
				$other_linked_users = 0;
1409
			}
1410
1411
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1412
		}
1413
1414
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1415
	}
1416
1417
	/**
1418
	 * Return whether we are dealing with a multi network setup or not.
1419
	 * The reason we are type casting this is because we want to avoid the situation where
1420
	 * the result is false since when is_main_network_option return false it cases
1421
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1422
	 * database which could be set to anything as opposed to what this function returns.
1423
	 *
1424
	 * @param  bool $option
1425
	 *
1426
	 * @return boolean
1427
	 */
1428
	public function is_main_network_option( $option ) {
1429
		// return '1' or ''
1430
		return (string) (bool) self::is_multi_network();
1431
	}
1432
1433
	/**
1434
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1435
	 *
1436
	 * @param  string $option
1437
	 * @return boolean
1438
	 */
1439
	public function is_multisite( $option ) {
1440
		return (string) (bool) is_multisite();
1441
	}
1442
1443
	/**
1444
	 * Implemented since there is no core is multi network function
1445
	 * Right now there is no way to tell if we which network is the dominant network on the system
1446
	 *
1447
	 * @since  3.3
1448
	 * @return boolean
1449
	 */
1450 View Code Duplication
	public static function is_multi_network() {
1451
		global  $wpdb;
1452
1453
		// if we don't have a multi site setup no need to do any more
1454
		if ( ! is_multisite() ) {
1455
			return false;
1456
		}
1457
1458
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1459
		if ( $num_sites > 1 ) {
1460
			return true;
1461
		} else {
1462
			return false;
1463
		}
1464
	}
1465
1466
	/**
1467
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1468
	 *
1469
	 * @return null
1470
	 */
1471
	function update_jetpack_main_network_site_option() {
1472
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1473
	}
1474
	/**
1475
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1476
	 */
1477
	function update_jetpack_network_settings() {
1478
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1479
		// Only sync this info for the main network site.
1480
	}
1481
1482
	/**
1483
	 * Get back if the current site is single user site.
1484
	 *
1485
	 * @return bool
1486
	 */
1487 View Code Duplication
	public static function is_single_user_site() {
1488
		global $wpdb;
1489
1490
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1491
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1492
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1493
		}
1494
		return 1 === (int) $some_users;
1495
	}
1496
1497
	/**
1498
	 * Returns true if the site has file write access false otherwise.
1499
	 *
1500
	 * @return string ( '1' | '0' )
1501
	 **/
1502
	public static function file_system_write_access() {
1503
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1504
			require_once ABSPATH . 'wp-admin/includes/file.php';
1505
		}
1506
1507
		require_once ABSPATH . 'wp-admin/includes/template.php';
1508
1509
		$filesystem_method = get_filesystem_method();
1510
		if ( $filesystem_method === 'direct' ) {
1511
			return 1;
1512
		}
1513
1514
		ob_start();
1515
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1516
		ob_end_clean();
1517
		if ( $filesystem_credentials_are_stored ) {
1518
			return 1;
1519
		}
1520
		return 0;
1521
	}
1522
1523
	/**
1524
	 * Finds out if a site is using a version control system.
1525
	 *
1526
	 * @return string ( '1' | '0' )
1527
	 **/
1528
	public static function is_version_controlled() {
1529
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1530
		return (string) (int) Functions::is_version_controlled();
1531
	}
1532
1533
	/**
1534
	 * Determines whether the current theme supports featured images or not.
1535
	 *
1536
	 * @return string ( '1' | '0' )
1537
	 */
1538
	public static function featured_images_enabled() {
1539
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1540
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1541
	}
1542
1543
	/**
1544
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1545
	 *
1546
	 * @deprecated 4.7 use get_avatar_url instead.
1547
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1548
	 * @param int               $size Size of the avatar image
1549
	 * @param string            $default URL to a default image to use if no avatar is available
1550
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1551
	 *
1552
	 * @return array
1553
	 */
1554
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1555
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1556
		return get_avatar_url(
1557
			$id_or_email,
1558
			array(
1559
				'size'          => $size,
1560
				'default'       => $default,
1561
				'force_default' => $force_display,
1562
			)
1563
		);
1564
	}
1565
1566
	/**
1567
	 * jetpack_updates is saved in the following schema:
1568
	 *
1569
	 * array (
1570
	 *      'plugins'                       => (int) Number of plugin updates available.
1571
	 *      'themes'                        => (int) Number of theme updates available.
1572
	 *      'wordpress'                     => (int) Number of WordPress core updates available. // phpcs:ignore WordPress.WP.CapitalPDangit.Misspelled
1573
	 *      'translations'                  => (int) Number of translation updates available.
1574
	 *      'total'                         => (int) Total of all available updates.
1575
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1576
	 * )
1577
	 *
1578
	 * @return array
1579
	 */
1580
	public static function get_updates() {
1581
		$update_data = wp_get_update_data();
1582
1583
		// Stores the individual update counts as well as the total count.
1584
		if ( isset( $update_data['counts'] ) ) {
1585
			$updates = $update_data['counts'];
1586
		}
1587
1588
		// If we need to update WordPress core, let's find the latest version number.
1589 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1590
			$cur = get_preferred_from_update_core();
1591
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1592
				$updates['wp_update_version'] = $cur->current;
1593
			}
1594
		}
1595
		return isset( $updates ) ? $updates : array();
1596
	}
1597
1598
	public static function get_update_details() {
1599
		$update_details = array(
1600
			'update_core'    => get_site_transient( 'update_core' ),
1601
			'update_plugins' => get_site_transient( 'update_plugins' ),
1602
			'update_themes'  => get_site_transient( 'update_themes' ),
1603
		);
1604
		return $update_details;
1605
	}
1606
1607
	public static function refresh_update_data() {
1608
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1609
1610
	}
1611
1612
	public static function refresh_theme_data() {
1613
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1614
	}
1615
1616
	/**
1617
	 * Is Jetpack active?
1618
	 */
1619
	public static function is_active() {
1620
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1621
	}
1622
1623
	/**
1624
	 * Make an API call to WordPress.com for plan status
1625
	 *
1626
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1627
	 *
1628
	 * @return bool True if plan is updated, false if no update
1629
	 */
1630
	public static function refresh_active_plan_from_wpcom() {
1631
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1632
		return Jetpack_Plan::refresh_from_wpcom();
1633
	}
1634
1635
	/**
1636
	 * Get the plan that this Jetpack site is currently using
1637
	 *
1638
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1639
	 * @return array Active Jetpack plan details.
1640
	 */
1641
	public static function get_active_plan() {
1642
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1643
		return Jetpack_Plan::get();
1644
	}
1645
1646
	/**
1647
	 * Determine whether the active plan supports a particular feature
1648
	 *
1649
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1650
	 * @return bool True if plan supports feature, false if not.
1651
	 */
1652
	public static function active_plan_supports( $feature ) {
1653
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1654
		return Jetpack_Plan::supports( $feature );
1655
	}
1656
1657
	/**
1658
	 * Deprecated: Is Jetpack in development (offline) mode?
1659
	 *
1660
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1661
	 * and themes still use it, and we do not want to flood them with notices.
1662
	 *
1663
	 * Please use Automattic\Jetpack\Status()->is_development_mode() instead.
1664
	 *
1665
	 * @deprecated since 8.0.
1666
	 */
1667
	public static function is_development_mode() {
1668
		return ( new Status() )->is_development_mode();
1669
	}
1670
1671
	/**
1672
	 * Whether the site is currently onboarding or not.
1673
	 * A site is considered as being onboarded if it currently has an onboarding token.
1674
	 *
1675
	 * @since 5.8
1676
	 *
1677
	 * @access public
1678
	 * @static
1679
	 *
1680
	 * @return bool True if the site is currently onboarding, false otherwise
1681
	 */
1682
	public static function is_onboarding() {
1683
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1684
	}
1685
1686
	/**
1687
	 * Determines reason for Jetpack development mode.
1688
	 */
1689
	public static function development_mode_trigger_text() {
1690
		if ( ! ( new Status() )->is_development_mode() ) {
1691
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1692
		}
1693
1694
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1695
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1696
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1697
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1698
		} else {
1699
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1700
		}
1701
1702
		return $notice;
1703
1704
	}
1705
	/**
1706
	 * Get Jetpack development mode notice text and notice class.
1707
	 *
1708
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_development_mode
1709
	 */
1710
	public static function show_development_mode_notice() {
1711
		if ( ( new Status() )->is_development_mode() ) {
1712
			$notice = sprintf(
1713
				/* translators: %s is a URL */
1714
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1715
				'https://jetpack.com/support/development-mode/'
1716
			);
1717
1718
			$notice .= ' ' . self::development_mode_trigger_text();
1719
1720
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1721
		}
1722
1723
		// Throw up a notice if using a development version and as for feedback.
1724
		if ( self::is_development_version() ) {
1725
			/* translators: %s is a URL */
1726
			$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/' );
1727
1728
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1729
		}
1730
		// Throw up a notice if using staging mode
1731
		if ( ( new Status() )->is_staging_site() ) {
1732
			/* translators: %s is a URL */
1733
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1734
1735
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1736
		}
1737
	}
1738
1739
	/**
1740
	 * Whether Jetpack's version maps to a public release, or a development version.
1741
	 */
1742
	public static function is_development_version() {
1743
		/**
1744
		 * Allows filtering whether this is a development version of Jetpack.
1745
		 *
1746
		 * This filter is especially useful for tests.
1747
		 *
1748
		 * @since 4.3.0
1749
		 *
1750
		 * @param bool $development_version Is this a develoment version of Jetpack?
1751
		 */
1752
		return (bool) apply_filters(
1753
			'jetpack_development_version',
1754
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1755
		);
1756
	}
1757
1758
	/**
1759
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1760
	 */
1761
	public static function is_user_connected( $user_id = false ) {
1762
		return self::connection()->is_user_connected( $user_id );
1763
	}
1764
1765
	/**
1766
	 * Get the wpcom user data of the current|specified connected user.
1767
	 */
1768 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1769
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1770
		if ( ! $user_id ) {
1771
			$user_id = get_current_user_id();
1772
		}
1773
1774
		$transient_key = "jetpack_connected_user_data_$user_id";
1775
1776
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1777
			return $cached_user_data;
1778
		}
1779
1780
		$xml = new Jetpack_IXR_Client(
1781
			array(
1782
				'user_id' => $user_id,
1783
			)
1784
		);
1785
		$xml->query( 'wpcom.getUser' );
1786
		if ( ! $xml->isError() ) {
1787
			$user_data = $xml->getResponse();
1788
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1789
			return $user_data;
1790
		}
1791
1792
		return false;
1793
	}
1794
1795
	/**
1796
	 * Get the wpcom email of the current|specified connected user.
1797
	 */
1798 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1799
		if ( ! $user_id ) {
1800
			$user_id = get_current_user_id();
1801
		}
1802
1803
		$xml = new Jetpack_IXR_Client(
1804
			array(
1805
				'user_id' => $user_id,
1806
			)
1807
		);
1808
		$xml->query( 'wpcom.getUserEmail' );
1809
		if ( ! $xml->isError() ) {
1810
			return $xml->getResponse();
1811
		}
1812
		return false;
1813
	}
1814
1815
	/**
1816
	 * Get the wpcom email of the master user.
1817
	 */
1818
	public static function get_master_user_email() {
1819
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1820
		if ( $master_user_id ) {
1821
			return self::get_connected_user_email( $master_user_id );
1822
		}
1823
		return '';
1824
	}
1825
1826
	/**
1827
	 * Whether the current user is the connection owner.
1828
	 *
1829
	 * @deprecated since 7.7
1830
	 *
1831
	 * @return bool Whether the current user is the connection owner.
1832
	 */
1833
	public function current_user_is_connection_owner() {
1834
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1835
		return self::connection()->is_connection_owner();
1836
	}
1837
1838
	/**
1839
	 * Gets current user IP address.
1840
	 *
1841
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1842
	 *
1843
	 * @return string                  Current user IP address.
1844
	 */
1845
	public static function current_user_ip( $check_all_headers = false ) {
1846
		if ( $check_all_headers ) {
1847
			foreach ( array(
1848
				'HTTP_CF_CONNECTING_IP',
1849
				'HTTP_CLIENT_IP',
1850
				'HTTP_X_FORWARDED_FOR',
1851
				'HTTP_X_FORWARDED',
1852
				'HTTP_X_CLUSTER_CLIENT_IP',
1853
				'HTTP_FORWARDED_FOR',
1854
				'HTTP_FORWARDED',
1855
				'HTTP_VIA',
1856
			) as $key ) {
1857
				if ( ! empty( $_SERVER[ $key ] ) ) {
1858
					return $_SERVER[ $key ];
1859
				}
1860
			}
1861
		}
1862
1863
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1864
	}
1865
1866
	/**
1867
	 * Synchronize connected user role changes
1868
	 */
1869
	function user_role_change( $user_id ) {
1870
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1871
		Users::user_role_change( $user_id );
1872
	}
1873
1874
	/**
1875
	 * Loads the currently active modules.
1876
	 */
1877
	public static function load_modules() {
1878
		$is_development_mode = ( new Status() )->is_development_mode();
1879
		if (
1880
			! self::is_active()
1881
			&& ! $is_development_mode
1882
			&& ! self::is_onboarding()
1883
			&& (
1884
				! is_multisite()
1885
				|| ! get_site_option( 'jetpack_protect_active' )
1886
			)
1887
		) {
1888
			return;
1889
		}
1890
1891
		$version = Jetpack_Options::get_option( 'version' );
1892 View Code Duplication
		if ( ! $version ) {
1893
			$version = $old_version = JETPACK__VERSION . ':' . time();
1894
			/** This action is documented in class.jetpack.php */
1895
			do_action( 'updating_jetpack_version', $version, false );
1896
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1897
		}
1898
		list( $version ) = explode( ':', $version );
1899
1900
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1901
1902
		$modules_data = array();
1903
1904
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1905
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1906
			$updated_modules = array();
1907
			foreach ( $modules as $module ) {
1908
				$modules_data[ $module ] = self::get_module( $module );
1909
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1910
					continue;
1911
				}
1912
1913
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1914
					continue;
1915
				}
1916
1917
				$updated_modules[] = $module;
1918
			}
1919
1920
			$modules = array_diff( $modules, $updated_modules );
1921
		}
1922
1923
		foreach ( $modules as $index => $module ) {
1924
			// If we're in dev mode, disable modules requiring a connection
1925
			if ( $is_development_mode ) {
1926
				// Prime the pump if we need to
1927
				if ( empty( $modules_data[ $module ] ) ) {
1928
					$modules_data[ $module ] = self::get_module( $module );
1929
				}
1930
				// If the module requires a connection, but we're in local mode, don't include it.
1931
				if ( $modules_data[ $module ]['requires_connection'] ) {
1932
					continue;
1933
				}
1934
			}
1935
1936
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1937
				continue;
1938
			}
1939
1940
			if ( ! include_once self::get_module_path( $module ) ) {
1941
				unset( $modules[ $index ] );
1942
				self::update_active_modules( array_values( $modules ) );
1943
				continue;
1944
			}
1945
1946
			/**
1947
			 * Fires when a specific module is loaded.
1948
			 * The dynamic part of the hook, $module, is the module slug.
1949
			 *
1950
			 * @since 1.1.0
1951
			 */
1952
			do_action( 'jetpack_module_loaded_' . $module );
1953
		}
1954
1955
		/**
1956
		 * Fires when all the modules are loaded.
1957
		 *
1958
		 * @since 1.1.0
1959
		 */
1960
		do_action( 'jetpack_modules_loaded' );
1961
1962
		// 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.
1963
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1964
	}
1965
1966
	/**
1967
	 * Check if Jetpack's REST API compat file should be included
1968
	 *
1969
	 * @action plugins_loaded
1970
	 * @return null
1971
	 */
1972
	public function check_rest_api_compat() {
1973
		/**
1974
		 * Filters the list of REST API compat files to be included.
1975
		 *
1976
		 * @since 2.2.5
1977
		 *
1978
		 * @param array $args Array of REST API compat files to include.
1979
		 */
1980
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1981
1982
		if ( function_exists( 'bbpress' ) ) {
1983
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1984
		}
1985
1986
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
1987
			require_once $_jetpack_rest_api_compat_include;
1988
		}
1989
	}
1990
1991
	/**
1992
	 * Gets all plugins currently active in values, regardless of whether they're
1993
	 * traditionally activated or network activated.
1994
	 *
1995
	 * @todo Store the result in core's object cache maybe?
1996
	 */
1997
	public static function get_active_plugins() {
1998
		$active_plugins = (array) get_option( 'active_plugins', array() );
1999
2000
		if ( is_multisite() ) {
2001
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2002
			// whereas active_plugins stores them in the values.
2003
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2004
			if ( $network_plugins ) {
2005
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2006
			}
2007
		}
2008
2009
		sort( $active_plugins );
2010
2011
		return array_unique( $active_plugins );
2012
	}
2013
2014
	/**
2015
	 * Gets and parses additional plugin data to send with the heartbeat data
2016
	 *
2017
	 * @since 3.8.1
2018
	 *
2019
	 * @return array Array of plugin data
2020
	 */
2021
	public static function get_parsed_plugin_data() {
2022
		if ( ! function_exists( 'get_plugins' ) ) {
2023
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2024
		}
2025
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2026
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2027
		$active_plugins = self::get_active_plugins();
2028
2029
		$plugins = array();
2030
		foreach ( $all_plugins as $path => $plugin_data ) {
2031
			$plugins[ $path ] = array(
2032
				'is_active' => in_array( $path, $active_plugins ),
2033
				'file'      => $path,
2034
				'name'      => $plugin_data['Name'],
2035
				'version'   => $plugin_data['Version'],
2036
				'author'    => $plugin_data['Author'],
2037
			);
2038
		}
2039
2040
		return $plugins;
2041
	}
2042
2043
	/**
2044
	 * Gets and parses theme data to send with the heartbeat data
2045
	 *
2046
	 * @since 3.8.1
2047
	 *
2048
	 * @return array Array of theme data
2049
	 */
2050
	public static function get_parsed_theme_data() {
2051
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2052
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2053
2054
		$themes = array();
2055
		foreach ( $all_themes as $slug => $theme_data ) {
2056
			$theme_headers = array();
2057
			foreach ( $header_keys as $header_key ) {
2058
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2059
			}
2060
2061
			$themes[ $slug ] = array(
2062
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2063
				'slug'            => $slug,
2064
				'theme_root'      => $theme_data->get_theme_root_uri(),
2065
				'parent'          => $theme_data->parent(),
2066
				'headers'         => $theme_headers,
2067
			);
2068
		}
2069
2070
		return $themes;
2071
	}
2072
2073
	/**
2074
	 * Checks whether a specific plugin is active.
2075
	 *
2076
	 * We don't want to store these in a static variable, in case
2077
	 * there are switch_to_blog() calls involved.
2078
	 */
2079
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2080
		return in_array( $plugin, self::get_active_plugins() );
2081
	}
2082
2083
	/**
2084
	 * Check if Jetpack's Open Graph tags should be used.
2085
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2086
	 *
2087
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2088
	 * @action plugins_loaded
2089
	 * @return null
2090
	 */
2091
	public function check_open_graph() {
2092
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2093
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2094
		}
2095
2096
		$active_plugins = self::get_active_plugins();
2097
2098
		if ( ! empty( $active_plugins ) ) {
2099
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2100
				if ( in_array( $plugin, $active_plugins ) ) {
2101
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2102
					break;
2103
				}
2104
			}
2105
		}
2106
2107
		/**
2108
		 * Allow the addition of Open Graph Meta Tags to all pages.
2109
		 *
2110
		 * @since 2.0.3
2111
		 *
2112
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2113
		 */
2114
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2115
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2116
		}
2117
	}
2118
2119
	/**
2120
	 * Check if Jetpack's Twitter tags should be used.
2121
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2122
	 *
2123
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2124
	 * @action plugins_loaded
2125
	 * @return null
2126
	 */
2127
	public function check_twitter_tags() {
2128
2129
		$active_plugins = self::get_active_plugins();
2130
2131
		if ( ! empty( $active_plugins ) ) {
2132
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2133
				if ( in_array( $plugin, $active_plugins ) ) {
2134
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2135
					break;
2136
				}
2137
			}
2138
		}
2139
2140
		/**
2141
		 * Allow Twitter Card Meta tags to be disabled.
2142
		 *
2143
		 * @since 2.6.0
2144
		 *
2145
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2146
		 */
2147
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2148
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2149
		}
2150
	}
2151
2152
	/**
2153
	 * Allows plugins to submit security reports.
2154
	 *
2155
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2156
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2157
	 * @param array  $args         See definitions above
2158
	 */
2159
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2160
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2161
	}
2162
2163
	/* Jetpack Options API */
2164
2165
	public static function get_option_names( $type = 'compact' ) {
2166
		return Jetpack_Options::get_option_names( $type );
2167
	}
2168
2169
	/**
2170
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2171
	 *
2172
	 * @param string $name    Option name
2173
	 * @param mixed  $default (optional)
2174
	 */
2175
	public static function get_option( $name, $default = false ) {
2176
		return Jetpack_Options::get_option( $name, $default );
2177
	}
2178
2179
	/**
2180
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2181
	 *
2182
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2183
	 * @param string $name  Option name
2184
	 * @param mixed  $value Option value
2185
	 */
2186
	public static function update_option( $name, $value ) {
2187
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2188
		return Jetpack_Options::update_option( $name, $value );
2189
	}
2190
2191
	/**
2192
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2193
	 *
2194
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2195
	 * @param array $array array( option name => option value, ... )
2196
	 */
2197
	public static function update_options( $array ) {
2198
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2199
		return Jetpack_Options::update_options( $array );
2200
	}
2201
2202
	/**
2203
	 * Deletes the given option.  May be passed multiple option names as an array.
2204
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2205
	 *
2206
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2207
	 * @param string|array $names
2208
	 */
2209
	public static function delete_option( $names ) {
2210
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2211
		return Jetpack_Options::delete_option( $names );
2212
	}
2213
2214
	/**
2215
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2216
	 *
2217
	 * Enters a user token into the user_tokens option
2218
	 *
2219
	 * @param int    $user_id The user id.
2220
	 * @param string $token The user token.
2221
	 * @param bool   $is_master_user Whether the user is the master user.
2222
	 * @return bool
2223
	 */
2224
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2225
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2226
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2227
	}
2228
2229
	/**
2230
	 * Returns an array of all PHP files in the specified absolute path.
2231
	 * Equivalent to glob( "$absolute_path/*.php" ).
2232
	 *
2233
	 * @param string $absolute_path The absolute path of the directory to search.
2234
	 * @return array Array of absolute paths to the PHP files.
2235
	 */
2236
	public static function glob_php( $absolute_path ) {
2237
		if ( function_exists( 'glob' ) ) {
2238
			return glob( "$absolute_path/*.php" );
2239
		}
2240
2241
		$absolute_path = untrailingslashit( $absolute_path );
2242
		$files         = array();
2243
		if ( ! $dir = @opendir( $absolute_path ) ) {
2244
			return $files;
2245
		}
2246
2247
		while ( false !== $file = readdir( $dir ) ) {
2248
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2249
				continue;
2250
			}
2251
2252
			$file = "$absolute_path/$file";
2253
2254
			if ( ! is_file( $file ) ) {
2255
				continue;
2256
			}
2257
2258
			$files[] = $file;
2259
		}
2260
2261
		closedir( $dir );
2262
2263
		return $files;
2264
	}
2265
2266
	public static function activate_new_modules( $redirect = false ) {
2267
		if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
2268
			return;
2269
		}
2270
2271
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2272 View Code Duplication
		if ( ! $jetpack_old_version ) {
2273
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2274
			/** This action is documented in class.jetpack.php */
2275
			do_action( 'updating_jetpack_version', $version, false );
2276
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2277
		}
2278
2279
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2280
2281
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2282
			return;
2283
		}
2284
2285
		$active_modules     = self::get_active_modules();
2286
		$reactivate_modules = array();
2287
		foreach ( $active_modules as $active_module ) {
2288
			$module = self::get_module( $active_module );
2289
			if ( ! isset( $module['changed'] ) ) {
2290
				continue;
2291
			}
2292
2293
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2294
				continue;
2295
			}
2296
2297
			$reactivate_modules[] = $active_module;
2298
			self::deactivate_module( $active_module );
2299
		}
2300
2301
		$new_version = JETPACK__VERSION . ':' . time();
2302
		/** This action is documented in class.jetpack.php */
2303
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2304
		Jetpack_Options::update_options(
2305
			array(
2306
				'version'     => $new_version,
2307
				'old_version' => $jetpack_old_version,
2308
			)
2309
		);
2310
2311
		self::state( 'message', 'modules_activated' );
2312
		self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
2313
2314
		if ( $redirect ) {
2315
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2316
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2317
				$page = $_GET['page'];
2318
			}
2319
2320
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2321
			exit;
2322
		}
2323
	}
2324
2325
	/**
2326
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2327
	 * Make sure to tuck away module "library" files in a sub-directory.
2328
	 */
2329
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2330
		static $modules = null;
2331
2332
		if ( ! isset( $modules ) ) {
2333
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2334
			// Use the cache if we're on the front-end and it's available...
2335
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2336
				$modules = $available_modules_option[ JETPACK__VERSION ];
2337
			} else {
2338
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2339
2340
				$modules = array();
2341
2342
				foreach ( $files as $file ) {
2343
					if ( ! $headers = self::get_module( $file ) ) {
2344
						continue;
2345
					}
2346
2347
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2348
				}
2349
2350
				Jetpack_Options::update_option(
2351
					'available_modules',
2352
					array(
2353
						JETPACK__VERSION => $modules,
2354
					)
2355
				);
2356
			}
2357
		}
2358
2359
		/**
2360
		 * Filters the array of modules available to be activated.
2361
		 *
2362
		 * @since 2.4.0
2363
		 *
2364
		 * @param array $modules Array of available modules.
2365
		 * @param string $min_version Minimum version number required to use modules.
2366
		 * @param string $max_version Maximum version number required to use modules.
2367
		 */
2368
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2369
2370
		if ( ! $min_version && ! $max_version ) {
2371
			return array_keys( $mods );
2372
		}
2373
2374
		$r = array();
2375
		foreach ( $mods as $slug => $introduced ) {
2376
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2377
				continue;
2378
			}
2379
2380
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2381
				continue;
2382
			}
2383
2384
			$r[] = $slug;
2385
		}
2386
2387
		return $r;
2388
	}
2389
2390
	/**
2391
	 * Default modules loaded on activation.
2392
	 */
2393
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2394
		$return = array();
2395
2396
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2397
			$module_data = self::get_module( $module );
2398
2399
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2400
				case 'yes':
2401
					$return[] = $module;
2402
					break;
2403
				case 'public':
2404
					if ( Jetpack_Options::get_option( 'public' ) ) {
2405
						$return[] = $module;
2406
					}
2407
					break;
2408
				case 'no':
2409
				default:
2410
					break;
2411
			}
2412
		}
2413
		/**
2414
		 * Filters the array of default modules.
2415
		 *
2416
		 * @since 2.5.0
2417
		 *
2418
		 * @param array $return Array of default modules.
2419
		 * @param string $min_version Minimum version number required to use modules.
2420
		 * @param string $max_version Maximum version number required to use modules.
2421
		 */
2422
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2423
	}
2424
2425
	/**
2426
	 * Checks activated modules during auto-activation to determine
2427
	 * if any of those modules are being deprecated.  If so, close
2428
	 * them out, and add any replacement modules.
2429
	 *
2430
	 * Runs at priority 99 by default.
2431
	 *
2432
	 * This is run late, so that it can still activate a module if
2433
	 * the new module is a replacement for another that the user
2434
	 * currently has active, even if something at the normal priority
2435
	 * would kibosh everything.
2436
	 *
2437
	 * @since 2.6
2438
	 * @uses jetpack_get_default_modules filter
2439
	 * @param array $modules
2440
	 * @return array
2441
	 */
2442
	function handle_deprecated_modules( $modules ) {
2443
		$deprecated_modules = array(
2444
			'debug'            => null,  // Closed out and moved to the debugger library.
2445
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2446
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2447
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2448
		);
2449
2450
		// Don't activate SSO if they never completed activating WPCC.
2451
		if ( self::is_module_active( 'wpcc' ) ) {
2452
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2453
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2454
				$deprecated_modules['wpcc'] = null;
2455
			}
2456
		}
2457
2458
		foreach ( $deprecated_modules as $module => $replacement ) {
2459
			if ( self::is_module_active( $module ) ) {
2460
				self::deactivate_module( $module );
2461
				if ( $replacement ) {
2462
					$modules[] = $replacement;
2463
				}
2464
			}
2465
		}
2466
2467
		return array_unique( $modules );
2468
	}
2469
2470
	/**
2471
	 * Checks activated plugins during auto-activation to determine
2472
	 * if any of those plugins are in the list with a corresponding module
2473
	 * that is not compatible with the plugin. The module will not be allowed
2474
	 * to auto-activate.
2475
	 *
2476
	 * @since 2.6
2477
	 * @uses jetpack_get_default_modules filter
2478
	 * @param array $modules
2479
	 * @return array
2480
	 */
2481
	function filter_default_modules( $modules ) {
2482
2483
		$active_plugins = self::get_active_plugins();
2484
2485
		if ( ! empty( $active_plugins ) ) {
2486
2487
			// For each module we'd like to auto-activate...
2488
			foreach ( $modules as $key => $module ) {
2489
				// If there are potential conflicts for it...
2490
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2491
					// For each potential conflict...
2492
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2493
						// If that conflicting plugin is active...
2494
						if ( in_array( $plugin, $active_plugins ) ) {
2495
							// Remove that item from being auto-activated.
2496
							unset( $modules[ $key ] );
2497
						}
2498
					}
2499
				}
2500
			}
2501
		}
2502
2503
		return $modules;
2504
	}
2505
2506
	/**
2507
	 * Extract a module's slug from its full path.
2508
	 */
2509
	public static function get_module_slug( $file ) {
2510
		return str_replace( '.php', '', basename( $file ) );
2511
	}
2512
2513
	/**
2514
	 * Generate a module's path from its slug.
2515
	 */
2516
	public static function get_module_path( $slug ) {
2517
		/**
2518
		 * Filters the path of a modules.
2519
		 *
2520
		 * @since 7.4.0
2521
		 *
2522
		 * @param array $return The absolute path to a module's root php file
2523
		 * @param string $slug The module slug
2524
		 */
2525
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2526
	}
2527
2528
	/**
2529
	 * Load module data from module file. Headers differ from WordPress
2530
	 * plugin headers to avoid them being identified as standalone
2531
	 * plugins on the WordPress plugins page.
2532
	 */
2533
	public static function get_module( $module ) {
2534
		$headers = array(
2535
			'name'                      => 'Module Name',
2536
			'description'               => 'Module Description',
2537
			'sort'                      => 'Sort Order',
2538
			'recommendation_order'      => 'Recommendation Order',
2539
			'introduced'                => 'First Introduced',
2540
			'changed'                   => 'Major Changes In',
2541
			'deactivate'                => 'Deactivate',
2542
			'free'                      => 'Free',
2543
			'requires_connection'       => 'Requires Connection',
2544
			'auto_activate'             => 'Auto Activate',
2545
			'module_tags'               => 'Module Tags',
2546
			'feature'                   => 'Feature',
2547
			'additional_search_queries' => 'Additional Search Queries',
2548
			'plan_classes'              => 'Plans',
2549
		);
2550
2551
		$file = self::get_module_path( self::get_module_slug( $module ) );
2552
2553
		$mod = self::get_file_data( $file, $headers );
2554
		if ( empty( $mod['name'] ) ) {
2555
			return false;
2556
		}
2557
2558
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2559
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2560
		$mod['deactivate']           = empty( $mod['deactivate'] );
2561
		$mod['free']                 = empty( $mod['free'] );
2562
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2563
2564
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2565
			$mod['auto_activate'] = 'No';
2566
		} else {
2567
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2568
		}
2569
2570
		if ( $mod['module_tags'] ) {
2571
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2572
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2573
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2574
		} else {
2575
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2576
		}
2577
2578 View Code Duplication
		if ( $mod['plan_classes'] ) {
2579
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2580
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2581
		} else {
2582
			$mod['plan_classes'] = array( 'free' );
2583
		}
2584
2585 View Code Duplication
		if ( $mod['feature'] ) {
2586
			$mod['feature'] = explode( ',', $mod['feature'] );
2587
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2588
		} else {
2589
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2590
		}
2591
2592
		/**
2593
		 * Filters the feature array on a module.
2594
		 *
2595
		 * This filter allows you to control where each module is filtered: Recommended,
2596
		 * and the default "Other" listing.
2597
		 *
2598
		 * @since 3.5.0
2599
		 *
2600
		 * @param array   $mod['feature'] The areas to feature this module:
2601
		 *     'Recommended' shows on the main Jetpack admin screen.
2602
		 *     'Other' should be the default if no other value is in the array.
2603
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2604
		 * @param array   $mod All the currently assembled module data.
2605
		 */
2606
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2607
2608
		/**
2609
		 * Filter the returned data about a module.
2610
		 *
2611
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2612
		 * so please be careful.
2613
		 *
2614
		 * @since 3.6.0
2615
		 *
2616
		 * @param array   $mod    The details of the requested module.
2617
		 * @param string  $module The slug of the module, e.g. sharedaddy
2618
		 * @param string  $file   The path to the module source file.
2619
		 */
2620
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2621
	}
2622
2623
	/**
2624
	 * Like core's get_file_data implementation, but caches the result.
2625
	 */
2626
	public static function get_file_data( $file, $headers ) {
2627
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2628
		$file_name = basename( $file );
2629
2630
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2631
2632
		$file_data_option = get_transient( $cache_key );
2633
2634
		if ( ! is_array( $file_data_option ) ) {
2635
			delete_transient( $cache_key );
2636
			$file_data_option = false;
2637
		}
2638
2639
		if ( false === $file_data_option ) {
2640
			$file_data_option = array();
2641
		}
2642
2643
		$key           = md5( $file_name . serialize( $headers ) );
2644
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2645
2646
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2647
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2648
			return $file_data_option[ $key ];
2649
		}
2650
2651
		$data = get_file_data( $file, $headers );
2652
2653
		$file_data_option[ $key ] = $data;
2654
2655
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2656
2657
		return $data;
2658
	}
2659
2660
2661
	/**
2662
	 * Return translated module tag.
2663
	 *
2664
	 * @param string $tag Tag as it appears in each module heading.
2665
	 *
2666
	 * @return mixed
2667
	 */
2668
	public static function translate_module_tag( $tag ) {
2669
		return jetpack_get_module_i18n_tag( $tag );
2670
	}
2671
2672
	/**
2673
	 * Get i18n strings as a JSON-encoded string
2674
	 *
2675
	 * @return string The locale as JSON
2676
	 */
2677
	public static function get_i18n_data_json() {
2678
2679
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2680
		// JSON files with the file they should be included for. This is an md5
2681
		// of '_inc/build/admin.js'.
2682
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2683
2684
		$i18n_json =
2685
				   JETPACK__PLUGIN_DIR
2686
				   . 'languages/json/jetpack-'
2687
				   . get_user_locale()
2688
				   . '-'
2689
				   . $path_md5
2690
				   . '.json';
2691
2692
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2693
			$locale_data = @file_get_contents( $i18n_json );
2694
			if ( $locale_data ) {
2695
				return $locale_data;
2696
			}
2697
		}
2698
2699
		// Return valid empty Jed locale
2700
		return '{ "locale_data": { "messages": { "": {} } } }';
2701
	}
2702
2703
	/**
2704
	 * Add locale data setup to wp-i18n
2705
	 *
2706
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2707
	 *
2708
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2709
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2710
	 *
2711
	 * This method provides a safe way to request the setup multiple times but add the script at
2712
	 * most once.
2713
	 *
2714
	 * @since 6.7.0
2715
	 *
2716
	 * @return void
2717
	 */
2718
	public static function setup_wp_i18n_locale_data() {
2719
		static $script_added = false;
2720
		if ( ! $script_added ) {
2721
			$script_added = true;
2722
			wp_add_inline_script(
2723
				'wp-i18n',
2724
				'wp.i18n.setLocaleData( ' . self::get_i18n_data_json() . ', \'jetpack\' );'
2725
			);
2726
		}
2727
	}
2728
2729
	/**
2730
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2731
	 *
2732
	 * @since 3.9.2
2733
	 *
2734
	 * @param array $modules
2735
	 *
2736
	 * @return string|void
2737
	 */
2738
	public static function get_translated_modules( $modules ) {
2739
		foreach ( $modules as $index => $module ) {
2740
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2741
			if ( isset( $module['name'] ) ) {
2742
				$modules[ $index ]['name'] = $i18n_module['name'];
2743
			}
2744
			if ( isset( $module['description'] ) ) {
2745
				$modules[ $index ]['description']       = $i18n_module['description'];
2746
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2747
			}
2748
		}
2749
		return $modules;
2750
	}
2751
2752
	/**
2753
	 * Get a list of activated modules as an array of module slugs.
2754
	 */
2755
	public static function get_active_modules() {
2756
		$active = Jetpack_Options::get_option( 'active_modules' );
2757
2758
		if ( ! is_array( $active ) ) {
2759
			$active = array();
2760
		}
2761
2762
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2763
			$active[] = 'vaultpress';
2764
		} else {
2765
			$active = array_diff( $active, array( 'vaultpress' ) );
2766
		}
2767
2768
		// If protect is active on the main site of a multisite, it should be active on all sites.
2769
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2770
			$active[] = 'protect';
2771
		}
2772
2773
		/**
2774
		 * Allow filtering of the active modules.
2775
		 *
2776
		 * Gives theme and plugin developers the power to alter the modules that
2777
		 * are activated on the fly.
2778
		 *
2779
		 * @since 5.8.0
2780
		 *
2781
		 * @param array $active Array of active module slugs.
2782
		 */
2783
		$active = apply_filters( 'jetpack_active_modules', $active );
2784
2785
		return array_unique( $active );
2786
	}
2787
2788
	/**
2789
	 * Check whether or not a Jetpack module is active.
2790
	 *
2791
	 * @param string $module The slug of a Jetpack module.
2792
	 * @return bool
2793
	 *
2794
	 * @static
2795
	 */
2796
	public static function is_module_active( $module ) {
2797
		return in_array( $module, self::get_active_modules() );
2798
	}
2799
2800
	public static function is_module( $module ) {
2801
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2802
	}
2803
2804
	/**
2805
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2806
	 *
2807
	 * @param bool $catch True to start catching, False to stop.
2808
	 *
2809
	 * @static
2810
	 */
2811
	public static function catch_errors( $catch ) {
2812
		static $display_errors, $error_reporting;
2813
2814
		if ( $catch ) {
2815
			$display_errors  = @ini_set( 'display_errors', 1 );
2816
			$error_reporting = @error_reporting( E_ALL );
2817
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2818
		} else {
2819
			@ini_set( 'display_errors', $display_errors );
2820
			@error_reporting( $error_reporting );
2821
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2822
		}
2823
	}
2824
2825
	/**
2826
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2827
	 */
2828
	public static function catch_errors_on_shutdown() {
2829
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2830
	}
2831
2832
	/**
2833
	 * Rewrite any string to make paths easier to read.
2834
	 *
2835
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2836
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2837
	 *
2838
	 * @param $string
2839
	 * @return mixed
2840
	 */
2841
	public static function alias_directories( $string ) {
2842
		// ABSPATH has a trailing slash.
2843
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2844
		// WP_CONTENT_DIR does not have a trailing slash.
2845
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2846
2847
		return $string;
2848
	}
2849
2850
	public static function activate_default_modules(
2851
		$min_version = false,
2852
		$max_version = false,
2853
		$other_modules = array(),
2854
		$redirect = null,
2855
		$send_state_messages = null
2856
	) {
2857
		$jetpack = self::init();
2858
2859
		if ( is_null( $redirect ) ) {
2860
			if (
2861
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2862
			||
2863
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2864
			||
2865
				( defined( 'WP_CLI' ) && WP_CLI )
2866
			||
2867
				( defined( 'DOING_CRON' ) && DOING_CRON )
2868
			||
2869
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2870
			) {
2871
				$redirect = false;
2872
			} elseif ( is_admin() ) {
2873
				$redirect = true;
2874
			} else {
2875
				$redirect = false;
2876
			}
2877
		}
2878
2879
		if ( is_null( $send_state_messages ) ) {
2880
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2881
		}
2882
2883
		$modules = self::get_default_modules( $min_version, $max_version );
2884
		$modules = array_merge( $other_modules, $modules );
2885
2886
		// Look for standalone plugins and disable if active.
2887
2888
		$to_deactivate = array();
2889
		foreach ( $modules as $module ) {
2890
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2891
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2892
			}
2893
		}
2894
2895
		$deactivated = array();
2896
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2897
			list( $probable_file, $probable_title ) = $deactivate_me;
2898
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2899
				$deactivated[] = $module;
2900
			}
2901
		}
2902
2903
		if ( $deactivated ) {
2904
			if ( $send_state_messages ) {
2905
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2906
			}
2907
2908
			if ( $redirect ) {
2909
				$url = add_query_arg(
2910
					array(
2911
						'action'   => 'activate_default_modules',
2912
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2913
					),
2914
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2915
				);
2916
				wp_safe_redirect( $url );
2917
				exit;
2918
			}
2919
		}
2920
2921
		/**
2922
		 * Fires before default modules are activated.
2923
		 *
2924
		 * @since 1.9.0
2925
		 *
2926
		 * @param string $min_version Minimum version number required to use modules.
2927
		 * @param string $max_version Maximum version number required to use modules.
2928
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2929
		 */
2930
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2931
2932
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2933
		if ( $send_state_messages ) {
2934
			self::restate();
2935
			self::catch_errors( true );
2936
		}
2937
2938
		$active = self::get_active_modules();
2939
2940
		foreach ( $modules as $module ) {
2941
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2942
				$active[] = $module;
2943
				self::update_active_modules( $active );
2944
				continue;
2945
			}
2946
2947
			if ( $send_state_messages && in_array( $module, $active ) ) {
2948
				$module_info = self::get_module( $module );
2949 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2950
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2951
					if ( $active_state = self::state( $state ) ) {
2952
						$active_state = explode( ',', $active_state );
2953
					} else {
2954
						$active_state = array();
2955
					}
2956
					$active_state[] = $module;
2957
					self::state( $state, implode( ',', $active_state ) );
2958
				}
2959
				continue;
2960
			}
2961
2962
			$file = self::get_module_path( $module );
2963
			if ( ! file_exists( $file ) ) {
2964
				continue;
2965
			}
2966
2967
			// we'll override this later if the plugin can be included without fatal error
2968
			if ( $redirect ) {
2969
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2970
			}
2971
2972
			if ( $send_state_messages ) {
2973
				self::state( 'error', 'module_activation_failed' );
2974
				self::state( 'module', $module );
2975
			}
2976
2977
			ob_start();
2978
			require_once $file;
2979
2980
			$active[] = $module;
2981
2982 View Code Duplication
			if ( $send_state_messages ) {
2983
2984
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2985
				if ( $active_state = self::state( $state ) ) {
2986
					$active_state = explode( ',', $active_state );
2987
				} else {
2988
					$active_state = array();
2989
				}
2990
				$active_state[] = $module;
2991
				self::state( $state, implode( ',', $active_state ) );
2992
			}
2993
2994
			self::update_active_modules( $active );
2995
2996
			ob_end_clean();
2997
		}
2998
2999
		if ( $send_state_messages ) {
3000
			self::state( 'error', false );
3001
			self::state( 'module', false );
3002
		}
3003
3004
		self::catch_errors( false );
3005
		/**
3006
		 * Fires when default modules are activated.
3007
		 *
3008
		 * @since 1.9.0
3009
		 *
3010
		 * @param string $min_version Minimum version number required to use modules.
3011
		 * @param string $max_version Maximum version number required to use modules.
3012
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
3013
		 */
3014
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
3015
	}
3016
3017
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3018
		/**
3019
		 * Fires before a module is activated.
3020
		 *
3021
		 * @since 2.6.0
3022
		 *
3023
		 * @param string $module Module slug.
3024
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3025
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3026
		 */
3027
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3028
3029
		$jetpack = self::init();
3030
3031
		if ( ! strlen( $module ) ) {
3032
			return false;
3033
		}
3034
3035
		if ( ! self::is_module( $module ) ) {
3036
			return false;
3037
		}
3038
3039
		// If it's already active, then don't do it again
3040
		$active = self::get_active_modules();
3041
		foreach ( $active as $act ) {
3042
			if ( $act == $module ) {
3043
				return true;
3044
			}
3045
		}
3046
3047
		$module_data = self::get_module( $module );
3048
3049
		$is_development_mode = ( new Status() )->is_development_mode();
3050
		if ( ! self::is_active() ) {
3051
			if ( ! $is_development_mode && ! self::is_onboarding() ) {
3052
				return false;
3053
			}
3054
3055
			// If we're not connected but in development mode, make sure the module doesn't require a connection
3056
			if ( $is_development_mode && $module_data['requires_connection'] ) {
3057
				return false;
3058
			}
3059
		}
3060
3061
		// Check and see if the old plugin is active
3062
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3063
			// Deactivate the old plugin
3064
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3065
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3066
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3067
				self::state( 'deactivated_plugins', $module );
3068
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3069
				exit;
3070
			}
3071
		}
3072
3073
		// Protect won't work with mis-configured IPs
3074
		if ( 'protect' === $module ) {
3075
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3076
			if ( ! jetpack_protect_get_ip() ) {
3077
				self::state( 'message', 'protect_misconfigured_ip' );
3078
				return false;
3079
			}
3080
		}
3081
3082
		if ( ! Jetpack_Plan::supports( $module ) ) {
3083
			return false;
3084
		}
3085
3086
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3087
		self::state( 'module', $module );
3088
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3089
3090
		self::catch_errors( true );
3091
		ob_start();
3092
		require self::get_module_path( $module );
3093
		/** This action is documented in class.jetpack.php */
3094
		do_action( 'jetpack_activate_module', $module );
3095
		$active[] = $module;
3096
		self::update_active_modules( $active );
3097
3098
		self::state( 'error', false ); // the override
3099
		ob_end_clean();
3100
		self::catch_errors( false );
3101
3102
		if ( $redirect ) {
3103
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3104
		}
3105
		if ( $exit ) {
3106
			exit;
3107
		}
3108
		return true;
3109
	}
3110
3111
	function activate_module_actions( $module ) {
3112
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3113
	}
3114
3115
	public static function deactivate_module( $module ) {
3116
		/**
3117
		 * Fires when a module is deactivated.
3118
		 *
3119
		 * @since 1.9.0
3120
		 *
3121
		 * @param string $module Module slug.
3122
		 */
3123
		do_action( 'jetpack_pre_deactivate_module', $module );
3124
3125
		$jetpack = self::init();
3126
3127
		$active = self::get_active_modules();
3128
		$new    = array_filter( array_diff( $active, (array) $module ) );
3129
3130
		return self::update_active_modules( $new );
3131
	}
3132
3133
	public static function enable_module_configurable( $module ) {
3134
		$module = self::get_module_slug( $module );
3135
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3136
	}
3137
3138
	/**
3139
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3140
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3141
	 *
3142
	 * @param string $module Module slug
3143
	 * @return string $url module configuration URL
3144
	 */
3145
	public static function module_configuration_url( $module ) {
3146
		$module      = self::get_module_slug( $module );
3147
		$default_url = self::admin_url() . "#/settings?term=$module";
3148
		/**
3149
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3150
		 *
3151
		 * @since 6.9.0
3152
		 *
3153
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3154
		 */
3155
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3156
3157
		return $url;
3158
	}
3159
3160
	/* Installation */
3161
	public static function bail_on_activation( $message, $deactivate = true ) {
3162
		?>
3163
<!doctype html>
3164
<html>
3165
<head>
3166
<meta charset="<?php bloginfo( 'charset' ); ?>">
3167
<style>
3168
* {
3169
	text-align: center;
3170
	margin: 0;
3171
	padding: 0;
3172
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3173
}
3174
p {
3175
	margin-top: 1em;
3176
	font-size: 18px;
3177
}
3178
</style>
3179
<body>
3180
<p><?php echo esc_html( $message ); ?></p>
3181
</body>
3182
</html>
3183
		<?php
3184
		if ( $deactivate ) {
3185
			$plugins = get_option( 'active_plugins' );
3186
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3187
			$update  = false;
3188
			foreach ( $plugins as $i => $plugin ) {
3189
				if ( $plugin === $jetpack ) {
3190
					$plugins[ $i ] = false;
3191
					$update        = true;
3192
				}
3193
			}
3194
3195
			if ( $update ) {
3196
				update_option( 'active_plugins', array_filter( $plugins ) );
3197
			}
3198
		}
3199
		exit;
3200
	}
3201
3202
	/**
3203
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3204
	 *
3205
	 * @static
3206
	 */
3207
	public static function plugin_activation( $network_wide ) {
3208
		Jetpack_Options::update_option( 'activated', 1 );
3209
3210
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3211
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3212
		}
3213
3214
		if ( $network_wide ) {
3215
			self::state( 'network_nag', true );
3216
		}
3217
3218
		// For firing one-off events (notices) immediately after activation
3219
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3220
3221
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3222
3223
		Health::on_jetpack_activated();
3224
3225
		self::plugin_initialize();
3226
	}
3227
3228
	public static function get_activation_source( $referer_url ) {
3229
3230
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3231
			return array( 'wp-cli', null );
3232
		}
3233
3234
		$referer = wp_parse_url( $referer_url );
3235
3236
		$source_type  = 'unknown';
3237
		$source_query = null;
3238
3239
		if ( ! is_array( $referer ) ) {
3240
			return array( $source_type, $source_query );
3241
		}
3242
3243
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3244
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3245
3246
		if ( isset( $referer['query'] ) ) {
3247
			parse_str( $referer['query'], $query_parts );
3248
		} else {
3249
			$query_parts = array();
3250
		}
3251
3252
		if ( $plugins_path === $referer['path'] ) {
3253
			$source_type = 'list';
3254
		} elseif ( $plugins_install_path === $referer['path'] ) {
3255
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3256
			switch ( $tab ) {
3257
				case 'popular':
3258
					$source_type = 'popular';
3259
					break;
3260
				case 'recommended':
3261
					$source_type = 'recommended';
3262
					break;
3263
				case 'favorites':
3264
					$source_type = 'favorites';
3265
					break;
3266
				case 'search':
3267
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3268
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3269
					break;
3270
				default:
3271
					$source_type = 'featured';
3272
			}
3273
		}
3274
3275
		return array( $source_type, $source_query );
3276
	}
3277
3278
	/**
3279
	 * Runs before bumping version numbers up to a new version
3280
	 *
3281
	 * @param  string $version    Version:timestamp
3282
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3283
	 * @return null              [description]
3284
	 */
3285
	public static function do_version_bump( $version, $old_version ) {
3286
		if ( ! $old_version ) { // For new sites
3287
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3288
		}
3289
	}
3290
3291
	/**
3292
	 * Sets the internal version number and activation state.
3293
	 *
3294
	 * @static
3295
	 */
3296
	public static function plugin_initialize() {
3297
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3298
			Jetpack_Options::update_option( 'activated', 2 );
3299
		}
3300
3301 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3302
			$version = $old_version = JETPACK__VERSION . ':' . time();
3303
			/** This action is documented in class.jetpack.php */
3304
			do_action( 'updating_jetpack_version', $version, false );
3305
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3306
		}
3307
3308
		self::load_modules();
3309
3310
		Jetpack_Options::delete_option( 'do_activate' );
3311
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3312
	}
3313
3314
	/**
3315
	 * Removes all connection options
3316
	 *
3317
	 * @static
3318
	 */
3319
	public static function plugin_deactivation() {
3320
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3321
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3322
			Jetpack_Network::init()->deactivate();
3323
		} else {
3324
			self::disconnect( false );
3325
			// Jetpack_Heartbeat::init()->deactivate();
3326
		}
3327
	}
3328
3329
	/**
3330
	 * Disconnects from the Jetpack servers.
3331
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3332
	 *
3333
	 * @static
3334
	 */
3335
	public static function disconnect( $update_activated_state = true ) {
3336
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3337
		$connection = self::connection();
3338
		$connection->clean_nonces( true );
3339
3340
		// If the site is in an IDC because sync is not allowed,
3341
		// let's make sure to not disconnect the production site.
3342
		if ( ! self::validate_sync_error_idc_option() ) {
3343
			$tracking = new Tracking();
3344
			$tracking->record_user_event( 'disconnect_site', array() );
3345
3346
			$connection->disconnect_site_wpcom();
3347
		}
3348
3349
		$connection->delete_all_connection_tokens();
3350
		Jetpack_IDC::clear_all_idc_options();
3351
3352
		if ( $update_activated_state ) {
3353
			Jetpack_Options::update_option( 'activated', 4 );
3354
		}
3355
3356
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3357
			// Check then record unique disconnection if site has never been disconnected previously
3358
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3359
				$jetpack_unique_connection['disconnected'] = 1;
3360
			} else {
3361
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3362
					// track unique disconnect
3363
					$jetpack = self::init();
3364
3365
					$jetpack->stat( 'connections', 'unique-disconnect' );
3366
					$jetpack->do_stats( 'server_side' );
3367
				}
3368
				// increment number of times disconnected
3369
				$jetpack_unique_connection['disconnected'] += 1;
3370
			}
3371
3372
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3373
		}
3374
3375
		// Delete all the sync related data. Since it could be taking up space.
3376
		Sender::get_instance()->uninstall();
3377
3378
		// Disable the Heartbeat cron
3379
		Jetpack_Heartbeat::init()->deactivate();
3380
	}
3381
3382
	/**
3383
	 * Unlinks the current user from the linked WordPress.com user.
3384
	 *
3385
	 * @deprecated since 7.7
3386
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3387
	 *
3388
	 * @param Integer $user_id the user identifier.
3389
	 * @return Boolean Whether the disconnection of the user was successful.
3390
	 */
3391
	public static function unlink_user( $user_id = null ) {
3392
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3393
		return Connection_Manager::disconnect_user( $user_id );
3394
	}
3395
3396
	/**
3397
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3398
	 */
3399
	public static function try_registration() {
3400
		$terms_of_service = new Terms_Of_Service();
3401
		// The user has agreed to the TOS at some point by now.
3402
		$terms_of_service->agree();
3403
3404
		// Let's get some testing in beta versions and such.
3405
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3406
			// Before attempting to connect, let's make sure that the domains are viable.
3407
			$domains_to_check = array_unique(
3408
				array(
3409
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3410
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3411
				)
3412
			);
3413
			foreach ( $domains_to_check as $domain ) {
3414
				$result = self::connection()->is_usable_domain( $domain );
3415
				if ( is_wp_error( $result ) ) {
3416
					return $result;
3417
				}
3418
			}
3419
		}
3420
3421
		$result = self::register();
3422
3423
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3424
		if ( ! $result || is_wp_error( $result ) ) {
3425
			return $result;
3426
		} else {
3427
			return true;
3428
		}
3429
	}
3430
3431
	/**
3432
	 * Tracking an internal event log. Try not to put too much chaff in here.
3433
	 *
3434
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3435
	 */
3436
	public static function log( $code, $data = null ) {
3437
		// only grab the latest 200 entries
3438
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3439
3440
		// Append our event to the log
3441
		$log_entry = array(
3442
			'time'    => time(),
3443
			'user_id' => get_current_user_id(),
3444
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3445
			'code'    => $code,
3446
		);
3447
		// Don't bother storing it unless we've got some.
3448
		if ( ! is_null( $data ) ) {
3449
			$log_entry['data'] = $data;
3450
		}
3451
		$log[] = $log_entry;
3452
3453
		// Try add_option first, to make sure it's not autoloaded.
3454
		// @todo: Add an add_option method to Jetpack_Options
3455
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3456
			Jetpack_Options::update_option( 'log', $log );
3457
		}
3458
3459
		/**
3460
		 * Fires when Jetpack logs an internal event.
3461
		 *
3462
		 * @since 3.0.0
3463
		 *
3464
		 * @param array $log_entry {
3465
		 *  Array of details about the log entry.
3466
		 *
3467
		 *  @param string time Time of the event.
3468
		 *  @param int user_id ID of the user who trigerred the event.
3469
		 *  @param int blog_id Jetpack Blog ID.
3470
		 *  @param string code Unique name for the event.
3471
		 *  @param string data Data about the event.
3472
		 * }
3473
		 */
3474
		do_action( 'jetpack_log_entry', $log_entry );
3475
	}
3476
3477
	/**
3478
	 * Get the internal event log.
3479
	 *
3480
	 * @param $event (string) - only return the specific log events
3481
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3482
	 *
3483
	 * @return array of log events || WP_Error for invalid params
3484
	 */
3485
	public static function get_log( $event = false, $num = false ) {
3486
		if ( $event && ! is_string( $event ) ) {
3487
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3488
		}
3489
3490
		if ( $num && ! is_numeric( $num ) ) {
3491
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3492
		}
3493
3494
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3495
3496
		// If nothing set - act as it did before, otherwise let's start customizing the output
3497
		if ( ! $num && ! $event ) {
3498
			return $entire_log;
3499
		} else {
3500
			$entire_log = array_reverse( $entire_log );
3501
		}
3502
3503
		$custom_log_output = array();
3504
3505
		if ( $event ) {
3506
			foreach ( $entire_log as $log_event ) {
3507
				if ( $event == $log_event['code'] ) {
3508
					$custom_log_output[] = $log_event;
3509
				}
3510
			}
3511
		} else {
3512
			$custom_log_output = $entire_log;
3513
		}
3514
3515
		if ( $num ) {
3516
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3517
		}
3518
3519
		return $custom_log_output;
3520
	}
3521
3522
	/**
3523
	 * Log modification of important settings.
3524
	 */
3525
	public static function log_settings_change( $option, $old_value, $value ) {
3526
		switch ( $option ) {
3527
			case 'jetpack_sync_non_public_post_stati':
3528
				self::log( $option, $value );
3529
				break;
3530
		}
3531
	}
3532
3533
	/**
3534
	 * Return stat data for WPCOM sync
3535
	 */
3536
	public static function get_stat_data( $encode = true, $extended = true ) {
3537
		$data = Jetpack_Heartbeat::generate_stats_array();
3538
3539
		if ( $extended ) {
3540
			$additional_data = self::get_additional_stat_data();
3541
			$data            = array_merge( $data, $additional_data );
3542
		}
3543
3544
		if ( $encode ) {
3545
			return json_encode( $data );
3546
		}
3547
3548
		return $data;
3549
	}
3550
3551
	/**
3552
	 * Get additional stat data to sync to WPCOM
3553
	 */
3554
	public static function get_additional_stat_data( $prefix = '' ) {
3555
		$return[ "{$prefix}themes" ]        = self::get_parsed_theme_data();
3556
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3557
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3558
		$return[ "{$prefix}site-count" ]    = 0;
3559
3560
		if ( function_exists( 'get_blog_count' ) ) {
3561
			$return[ "{$prefix}site-count" ] = get_blog_count();
3562
		}
3563
		return $return;
3564
	}
3565
3566
	private static function get_site_user_count() {
3567
		global $wpdb;
3568
3569
		if ( function_exists( 'wp_is_large_network' ) ) {
3570
			if ( wp_is_large_network( 'users' ) ) {
3571
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3572
			}
3573
		}
3574
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3575
			// It wasn't there, so regenerate the data and save the transient
3576
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3577
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3578
		}
3579
		return $user_count;
3580
	}
3581
3582
	/* Admin Pages */
3583
3584
	function admin_init() {
3585
		// If the plugin is not connected, display a connect message.
3586
		if (
3587
			// the plugin was auto-activated and needs its candy
3588
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3589
		||
3590
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3591
			! Jetpack_Options::get_option( 'activated' )
3592
		) {
3593
			self::plugin_initialize();
3594
		}
3595
3596
		$is_development_mode = ( new Status() )->is_development_mode();
3597
		if ( ! self::is_active() && ! $is_development_mode ) {
3598
			Jetpack_Connection_Banner::init();
3599
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3600
			// Upgrade: 1.1 -> 1.1.1
3601
			// Check and see if host can verify the Jetpack servers' SSL certificate
3602
			$args       = array();
3603
			$connection = self::connection();
3604
			Client::_wp_remote_request(
3605
				Connection_Utils::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3606
				$args,
3607
				true
3608
			);
3609
		}
3610
3611
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3612
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3613
		}
3614
3615
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3616
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3617
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3618
3619
		if ( self::is_active() || $is_development_mode ) {
3620
			// Artificially throw errors in certain whitelisted cases during plugin activation
3621
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3622
		}
3623
3624
		// Add custom column in wp-admin/users.php to show whether user is linked.
3625
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3626
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3627
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3628
	}
3629
3630
	function admin_body_class( $admin_body_class = '' ) {
3631
		$classes = explode( ' ', trim( $admin_body_class ) );
3632
3633
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3634
3635
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3636
		return " $admin_body_class ";
3637
	}
3638
3639
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3640
		return $admin_body_class . ' jetpack-pagestyles ';
3641
	}
3642
3643
	/**
3644
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3645
	 * This function artificially throws errors for such cases (whitelisted).
3646
	 *
3647
	 * @param string $plugin The activated plugin.
3648
	 */
3649
	function throw_error_on_activate_plugin( $plugin ) {
3650
		$active_modules = self::get_active_modules();
3651
3652
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3653
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3654
			$throw = false;
3655
3656
			// Try and make sure it really was the stats plugin
3657
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3658
				if ( 'stats.php' == basename( $plugin ) ) {
3659
					$throw = true;
3660
				}
3661
			} else {
3662
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3663
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3664
					$throw = true;
3665
				}
3666
			}
3667
3668
			if ( $throw ) {
3669
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3670
			}
3671
		}
3672
	}
3673
3674
	function intercept_plugin_error_scrape_init() {
3675
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3676
	}
3677
3678
	function intercept_plugin_error_scrape( $action, $result ) {
3679
		if ( ! $result ) {
3680
			return;
3681
		}
3682
3683
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3684
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3685
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3686
			}
3687
		}
3688
	}
3689
3690
	/**
3691
	 * Register the remote file upload request handlers, if needed.
3692
	 *
3693
	 * @access public
3694
	 */
3695
	public function add_remote_request_handlers() {
3696
		// Remote file uploads are allowed only via AJAX requests.
3697
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3698
			return;
3699
		}
3700
3701
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3702
		$remote_request_actions = array(
3703
			'jetpack_upload_file',
3704
			'jetpack_update_file',
3705
		);
3706
3707
		// phpcs:ignore WordPress.Security.NonceVerification
3708
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3709
			return;
3710
		}
3711
3712
		// Require Jetpack authentication for the remote file upload AJAX requests.
3713
		if ( ! $this->connection_manager ) {
3714
			$this->connection_manager = new Connection_Manager();
3715
		}
3716
3717
		$this->connection_manager->require_jetpack_authentication();
3718
3719
		// Register the remote file upload AJAX handlers.
3720
		foreach ( $remote_request_actions as $action ) {
3721
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3722
		}
3723
	}
3724
3725
	/**
3726
	 * Handler for Jetpack remote file uploads.
3727
	 *
3728
	 * @access public
3729
	 */
3730
	public function remote_request_handlers() {
3731
		$action = current_filter();
3732
3733
		switch ( current_filter() ) {
3734
			case 'wp_ajax_nopriv_jetpack_upload_file':
3735
				$response = $this->upload_handler();
3736
				break;
3737
3738
			case 'wp_ajax_nopriv_jetpack_update_file':
3739
				$response = $this->upload_handler( true );
3740
				break;
3741
			default:
3742
				$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3743
				break;
3744
		}
3745
3746
		if ( ! $response ) {
3747
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3748
		}
3749
3750
		if ( is_wp_error( $response ) ) {
3751
			$status_code       = $response->get_error_data();
3752
			$error             = $response->get_error_code();
3753
			$error_description = $response->get_error_message();
3754
3755
			if ( ! is_int( $status_code ) ) {
3756
				$status_code = 400;
3757
			}
3758
3759
			status_header( $status_code );
3760
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3761
		}
3762
3763
		status_header( 200 );
3764
		if ( true === $response ) {
3765
			exit;
3766
		}
3767
3768
		die( json_encode( (object) $response ) );
3769
	}
3770
3771
	/**
3772
	 * Uploads a file gotten from the global $_FILES.
3773
	 * If `$update_media_item` is true and `post_id` is defined
3774
	 * the attachment file of the media item (gotten through of the post_id)
3775
	 * will be updated instead of add a new one.
3776
	 *
3777
	 * @param  boolean $update_media_item - update media attachment
3778
	 * @return array - An array describing the uploadind files process
3779
	 */
3780
	function upload_handler( $update_media_item = false ) {
3781
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3782
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3783
		}
3784
3785
		$user = wp_authenticate( '', '' );
3786
		if ( ! $user || is_wp_error( $user ) ) {
3787
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3788
		}
3789
3790
		wp_set_current_user( $user->ID );
3791
3792
		if ( ! current_user_can( 'upload_files' ) ) {
3793
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3794
		}
3795
3796
		if ( empty( $_FILES ) ) {
3797
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3798
		}
3799
3800
		foreach ( array_keys( $_FILES ) as $files_key ) {
3801
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3802
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3803
			}
3804
		}
3805
3806
		$media_keys = array_keys( $_FILES['media'] );
3807
3808
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3809
		if ( ! $token || is_wp_error( $token ) ) {
3810
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3811
		}
3812
3813
		$uploaded_files = array();
3814
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3815
		unset( $GLOBALS['post'] );
3816
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3817
			$file = array();
3818
			foreach ( $media_keys as $media_key ) {
3819
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3820
			}
3821
3822
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3823
3824
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3825
			if ( $hmac_provided !== $hmac_file ) {
3826
				$uploaded_files[ $index ] = (object) array(
3827
					'error'             => 'invalid_hmac',
3828
					'error_description' => 'The corresponding HMAC for this file does not match',
3829
				);
3830
				continue;
3831
			}
3832
3833
			$_FILES['.jetpack.upload.'] = $file;
3834
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3835
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3836
				$post_id = 0;
3837
			}
3838
3839
			if ( $update_media_item ) {
3840
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3841
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3842
				}
3843
3844
				$media_array = $_FILES['media'];
3845
3846
				$file_array['name']     = $media_array['name'][0];
3847
				$file_array['type']     = $media_array['type'][0];
3848
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3849
				$file_array['error']    = $media_array['error'][0];
3850
				$file_array['size']     = $media_array['size'][0];
3851
3852
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3853
3854
				if ( is_wp_error( $edited_media_item ) ) {
3855
					return $edited_media_item;
3856
				}
3857
3858
				$response = (object) array(
3859
					'id'   => (string) $post_id,
3860
					'file' => (string) $edited_media_item->post_title,
3861
					'url'  => (string) wp_get_attachment_url( $post_id ),
3862
					'type' => (string) $edited_media_item->post_mime_type,
3863
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3864
				);
3865
3866
				return (array) array( $response );
3867
			}
3868
3869
			$attachment_id = media_handle_upload(
3870
				'.jetpack.upload.',
3871
				$post_id,
3872
				array(),
3873
				array(
3874
					'action' => 'jetpack_upload_file',
3875
				)
3876
			);
3877
3878
			if ( ! $attachment_id ) {
3879
				$uploaded_files[ $index ] = (object) array(
3880
					'error'             => 'unknown',
3881
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3882
				);
3883
			} elseif ( is_wp_error( $attachment_id ) ) {
3884
				$uploaded_files[ $index ] = (object) array(
3885
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3886
					'error_description' => $attachment_id->get_error_message(),
3887
				);
3888
			} else {
3889
				$attachment               = get_post( $attachment_id );
3890
				$uploaded_files[ $index ] = (object) array(
3891
					'id'   => (string) $attachment_id,
3892
					'file' => $attachment->post_title,
3893
					'url'  => wp_get_attachment_url( $attachment_id ),
3894
					'type' => $attachment->post_mime_type,
3895
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3896
				);
3897
				// Zip files uploads are not supported unless they are done for installation purposed
3898
				// lets delete them in case something goes wrong in this whole process
3899
				if ( 'application/zip' === $attachment->post_mime_type ) {
3900
					// Schedule a cleanup for 2 hours from now in case of failed install.
3901
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3902
				}
3903
			}
3904
		}
3905
		if ( ! is_null( $global_post ) ) {
3906
			$GLOBALS['post'] = $global_post;
3907
		}
3908
3909
		return $uploaded_files;
3910
	}
3911
3912
	/**
3913
	 * Add help to the Jetpack page
3914
	 *
3915
	 * @since Jetpack (1.2.3)
3916
	 * @return false if not the Jetpack page
3917
	 */
3918
	function admin_help() {
3919
		$current_screen = get_current_screen();
3920
3921
		// Overview
3922
		$current_screen->add_help_tab(
3923
			array(
3924
				'id'      => 'home',
3925
				'title'   => __( 'Home', 'jetpack' ),
3926
				'content' =>
3927
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3928
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3929
					'<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>',
3930
			)
3931
		);
3932
3933
		// Screen Content
3934
		if ( current_user_can( 'manage_options' ) ) {
3935
			$current_screen->add_help_tab(
3936
				array(
3937
					'id'      => 'settings',
3938
					'title'   => __( 'Settings', 'jetpack' ),
3939
					'content' =>
3940
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3941
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3942
						'<ol>' .
3943
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3944
							'<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>' .
3945
						'</ol>' .
3946
						'<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>',
3947
				)
3948
			);
3949
		}
3950
3951
		// Help Sidebar
3952
		$current_screen->set_help_sidebar(
3953
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3954
			'<p><a href="https://jetpack.com/faq/" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3955
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3956
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3957
		);
3958
	}
3959
3960
	function admin_menu_css() {
3961
		wp_enqueue_style( 'jetpack-icons' );
3962
	}
3963
3964
	function admin_menu_order() {
3965
		return true;
3966
	}
3967
3968 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3969
		$jp_menu_order = array();
3970
3971
		foreach ( $menu_order as $index => $item ) {
3972
			if ( $item != 'jetpack' ) {
3973
				$jp_menu_order[] = $item;
3974
			}
3975
3976
			if ( $index == 0 ) {
3977
				$jp_menu_order[] = 'jetpack';
3978
			}
3979
		}
3980
3981
		return $jp_menu_order;
3982
	}
3983
3984
	function admin_banner_styles() {
3985
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3986
3987 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3988
			wp_register_style(
3989
				'jetpack-dops-style',
3990
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3991
				array(),
3992
				JETPACK__VERSION
3993
			);
3994
		}
3995
3996
		wp_enqueue_style(
3997
			'jetpack',
3998
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3999
			array( 'jetpack-dops-style' ),
4000
			JETPACK__VERSION . '-20121016'
4001
		);
4002
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4003
		wp_style_add_data( 'jetpack', 'suffix', $min );
4004
	}
4005
4006
	function plugin_action_links( $actions ) {
4007
4008
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4009
4010
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_development_mode() ) ) {
4011
			return array_merge(
4012
				$jetpack_home,
4013
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4014
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4015
				$actions
4016
			);
4017
		}
4018
4019
		return array_merge( $jetpack_home, $actions );
4020
	}
4021
4022
	/*
4023
	 * Registration flow:
4024
	 * 1 - ::admin_page_load() action=register
4025
	 * 2 - ::try_registration()
4026
	 * 3 - ::register()
4027
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4028
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4029
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4030
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4031
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4032
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4033
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4034
	 *       jetpack_id, jetpack_secret, jetpack_public
4035
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4036
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4037
	 * 5 - user logs in with WP.com account
4038
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4039
	 *		- Manager::authorize()
4040
	 *		- Manager::get_token()
4041
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4042
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4043
	 *			- which responds with access_token, token_type, scope
4044
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4045
	 *		- Jetpack::activate_default_modules()
4046
	 *     		- Deactivates deprecated plugins
4047
	 *     		- Activates all default modules
4048
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4049
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4050
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4051
	 *     Done!
4052
	 */
4053
4054
	/**
4055
	 * Handles the page load events for the Jetpack admin page
4056
	 */
4057
	function admin_page_load() {
4058
		$error = false;
4059
4060
		// Make sure we have the right body class to hook stylings for subpages off of.
4061
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4062
4063
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4064
			// Should only be used in intermediate redirects to preserve state across redirects
4065
			self::restate();
4066
		}
4067
4068
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4069
			// @todo: Add validation against a known whitelist
4070
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4071
			// User clicked in the iframe to link their accounts
4072
			if ( ! self::is_user_connected() ) {
4073
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4074
4075
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4076
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4077
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4078
4079
				if ( isset( $_GET['notes_iframe'] ) ) {
4080
					$connect_url .= '&notes_iframe';
4081
				}
4082
				wp_redirect( $connect_url );
4083
				exit;
4084
			} else {
4085
				if ( ! isset( $_GET['calypso_env'] ) ) {
4086
					self::state( 'message', 'already_authorized' );
4087
					wp_safe_redirect( self::admin_url() );
4088
					exit;
4089
				} else {
4090
					$connect_url  = $this->build_connect_url( true, false, $from );
4091
					$connect_url .= '&already_authorized=true';
4092
					wp_redirect( $connect_url );
4093
					exit;
4094
				}
4095
			}
4096
		}
4097
4098
		if ( isset( $_GET['action'] ) ) {
4099
			switch ( $_GET['action'] ) {
4100
				case 'authorize':
4101
					if ( self::is_active() && self::is_user_connected() ) {
4102
						self::state( 'message', 'already_authorized' );
4103
						wp_safe_redirect( self::admin_url() );
4104
						exit;
4105
					}
4106
					self::log( 'authorize' );
4107
					$client_server = new Jetpack_Client_Server();
4108
					$client_server->client_authorize();
4109
					exit;
4110
				case 'register':
4111
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4112
						$error = 'cheatin';
4113
						break;
4114
					}
4115
					check_admin_referer( 'jetpack-register' );
4116
					self::log( 'register' );
4117
					self::maybe_set_version_option();
4118
					$registered = self::try_registration();
4119
					if ( is_wp_error( $registered ) ) {
4120
						$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...
4121
						self::state( 'error', $error );
4122
						self::state( 'error', $registered->get_error_message() );
4123
4124
						/**
4125
						 * Jetpack registration Error.
4126
						 *
4127
						 * @since 7.5.0
4128
						 *
4129
						 * @param string|int $error The error code.
4130
						 * @param \WP_Error $registered The error object.
4131
						 */
4132
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4133
						break;
4134
					}
4135
4136
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4137
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4138
4139
					/**
4140
					 * Jetpack registration Success.
4141
					 *
4142
					 * @since 7.5.0
4143
					 *
4144
					 * @param string $from 'from' GET parameter;
4145
					 */
4146
					do_action( 'jetpack_connection_register_success', $from );
4147
4148
					$url = $this->build_connect_url( true, $redirect, $from );
4149
4150
					if ( ! empty( $_GET['onboarding'] ) ) {
4151
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4152
					}
4153
4154
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4155
						$url = add_query_arg( 'auth_approved', 'true', $url );
4156
					}
4157
4158
					wp_redirect( $url );
4159
					exit;
4160
				case 'activate':
4161
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4162
						$error = 'cheatin';
4163
						break;
4164
					}
4165
4166
					$module = stripslashes( $_GET['module'] );
4167
					check_admin_referer( "jetpack_activate-$module" );
4168
					self::log( 'activate', $module );
4169
					if ( ! self::activate_module( $module ) ) {
4170
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4171
					}
4172
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4173
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4174
					exit;
4175
				case 'activate_default_modules':
4176
					check_admin_referer( 'activate_default_modules' );
4177
					self::log( 'activate_default_modules' );
4178
					self::restate();
4179
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4180
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4181
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4182
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4183
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4184
					exit;
4185
				case 'disconnect':
4186
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4187
						$error = 'cheatin';
4188
						break;
4189
					}
4190
4191
					check_admin_referer( 'jetpack-disconnect' );
4192
					self::log( 'disconnect' );
4193
					self::disconnect();
4194
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4195
					exit;
4196
				case 'reconnect':
4197
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4198
						$error = 'cheatin';
4199
						break;
4200
					}
4201
4202
					check_admin_referer( 'jetpack-reconnect' );
4203
					self::log( 'reconnect' );
4204
					$this->disconnect();
4205
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4206
					exit;
4207 View Code Duplication
				case 'deactivate':
4208
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4209
						$error = 'cheatin';
4210
						break;
4211
					}
4212
4213
					$modules = stripslashes( $_GET['module'] );
4214
					check_admin_referer( "jetpack_deactivate-$modules" );
4215
					foreach ( explode( ',', $modules ) as $module ) {
4216
						self::log( 'deactivate', $module );
4217
						self::deactivate_module( $module );
4218
						self::state( 'message', 'module_deactivated' );
4219
					}
4220
					self::state( 'module', $modules );
4221
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4222
					exit;
4223
				case 'unlink':
4224
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4225
					check_admin_referer( 'jetpack-unlink' );
4226
					self::log( 'unlink' );
4227
					Connection_Manager::disconnect_user();
4228
					self::state( 'message', 'unlinked' );
4229
					if ( 'sub-unlink' == $redirect ) {
4230
						wp_safe_redirect( admin_url() );
4231
					} else {
4232
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4233
					}
4234
					exit;
4235
				case 'onboard':
4236
					if ( ! current_user_can( 'manage_options' ) ) {
4237
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4238
					} else {
4239
						self::create_onboarding_token();
4240
						$url = $this->build_connect_url( true );
4241
4242
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4243
							$url = add_query_arg( 'onboarding', $token, $url );
4244
						}
4245
4246
						$calypso_env = $this->get_calypso_env();
4247
						if ( ! empty( $calypso_env ) ) {
4248
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4249
						}
4250
4251
						wp_redirect( $url );
4252
						exit;
4253
					}
4254
					exit;
4255
				default:
4256
					/**
4257
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4258
					 *
4259
					 * @since 2.6.0
4260
					 *
4261
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4262
					 */
4263
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4264
			}
4265
		}
4266
4267
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4268
			self::activate_new_modules( true );
4269
		}
4270
4271
		$message_code = self::state( 'message' );
4272
		if ( self::state( 'optin-manage' ) ) {
4273
			$activated_manage = $message_code;
4274
			$message_code     = 'jetpack-manage';
4275
		}
4276
4277
		switch ( $message_code ) {
4278
			case 'jetpack-manage':
4279
				$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>';
4280
				if ( $activated_manage ) {
4281
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4282
				}
4283
				break;
4284
4285
		}
4286
4287
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4288
4289
		if ( ! empty( $deactivated_plugins ) ) {
4290
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4291
			$deactivated_titles  = array();
4292
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4293
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4294
					continue;
4295
				}
4296
4297
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4298
			}
4299
4300
			if ( $deactivated_titles ) {
4301
				if ( $this->message ) {
4302
					$this->message .= "<br /><br />\n";
4303
				}
4304
4305
				$this->message .= wp_sprintf(
4306
					_n(
4307
						'Jetpack contains the most recent version of the old %l plugin.',
4308
						'Jetpack contains the most recent versions of the old %l plugins.',
4309
						count( $deactivated_titles ),
4310
						'jetpack'
4311
					),
4312
					$deactivated_titles
4313
				);
4314
4315
				$this->message .= "<br />\n";
4316
4317
				$this->message .= _n(
4318
					'The old version has been deactivated and can be removed from your site.',
4319
					'The old versions have been deactivated and can be removed from your site.',
4320
					count( $deactivated_titles ),
4321
					'jetpack'
4322
				);
4323
			}
4324
		}
4325
4326
		$this->privacy_checks = self::state( 'privacy_checks' );
4327
4328
		if ( $this->message || $this->error || $this->privacy_checks ) {
4329
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4330
		}
4331
4332
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4333
	}
4334
4335
	function admin_notices() {
4336
4337
		if ( $this->error ) {
4338
			?>
4339
<div id="message" class="jetpack-message jetpack-err">
4340
	<div class="squeezer">
4341
		<h2>
4342
			<?php
4343
			echo wp_kses(
4344
				$this->error,
4345
				array(
4346
					'a'      => array( 'href' => array() ),
4347
					'small'  => true,
4348
					'code'   => true,
4349
					'strong' => true,
4350
					'br'     => true,
4351
					'b'      => true,
4352
				)
4353
			);
4354
			?>
4355
			</h2>
4356
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4357
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4358
<?php	endif; ?>
4359
	</div>
4360
</div>
4361
			<?php
4362
		}
4363
4364
		if ( $this->message ) {
4365
			?>
4366
<div id="message" class="jetpack-message">
4367
	<div class="squeezer">
4368
		<h2>
4369
			<?php
4370
			echo wp_kses(
4371
				$this->message,
4372
				array(
4373
					'strong' => array(),
4374
					'a'      => array( 'href' => true ),
4375
					'br'     => true,
4376
				)
4377
			);
4378
			?>
4379
			</h2>
4380
	</div>
4381
</div>
4382
			<?php
4383
		}
4384
4385
		if ( $this->privacy_checks ) :
4386
			$module_names = $module_slugs = array();
4387
4388
			$privacy_checks = explode( ',', $this->privacy_checks );
4389
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4390
			foreach ( $privacy_checks as $module_slug ) {
4391
				$module = self::get_module( $module_slug );
4392
				if ( ! $module ) {
4393
					continue;
4394
				}
4395
4396
				$module_slugs[] = $module_slug;
4397
				$module_names[] = "<strong>{$module['name']}</strong>";
4398
			}
4399
4400
			$module_slugs = join( ',', $module_slugs );
4401
			?>
4402
<div id="message" class="jetpack-message jetpack-err">
4403
	<div class="squeezer">
4404
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4405
		<p>
4406
			<?php
4407
			echo wp_kses(
4408
				wptexturize(
4409
					wp_sprintf(
4410
						_nx(
4411
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4412
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4413
							count( $privacy_checks ),
4414
							'%l = list of Jetpack module/feature names',
4415
							'jetpack'
4416
						),
4417
						$module_names
4418
					)
4419
				),
4420
				array( 'strong' => true )
4421
			);
4422
4423
			echo "\n<br />\n";
4424
4425
			echo wp_kses(
4426
				sprintf(
4427
					_nx(
4428
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4429
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4430
						count( $privacy_checks ),
4431
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4432
						'jetpack'
4433
					),
4434
					wp_nonce_url(
4435
						self::admin_url(
4436
							array(
4437
								'page'   => 'jetpack',
4438
								'action' => 'deactivate',
4439
								'module' => urlencode( $module_slugs ),
4440
							)
4441
						),
4442
						"jetpack_deactivate-$module_slugs"
4443
					),
4444
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4445
				),
4446
				array(
4447
					'a' => array(
4448
						'href'  => true,
4449
						'title' => true,
4450
					),
4451
				)
4452
			);
4453
			?>
4454
		</p>
4455
	</div>
4456
</div>
4457
			<?php
4458
endif;
4459
	}
4460
4461
	/**
4462
	 * We can't always respond to a signed XML-RPC request with a
4463
	 * helpful error message. In some circumstances, doing so could
4464
	 * leak information.
4465
	 *
4466
	 * Instead, track that the error occurred via a Jetpack_Option,
4467
	 * and send that data back in the heartbeat.
4468
	 * All this does is increment a number, but it's enough to find
4469
	 * trends.
4470
	 *
4471
	 * @param WP_Error $xmlrpc_error The error produced during
4472
	 *                               signature validation.
4473
	 */
4474
	function track_xmlrpc_error( $xmlrpc_error ) {
4475
		$code = is_wp_error( $xmlrpc_error )
4476
			? $xmlrpc_error->get_error_code()
4477
			: 'should-not-happen';
4478
4479
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4480
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4481
			// No need to update the option if we already have
4482
			// this code stored.
4483
			return;
4484
		}
4485
		$xmlrpc_errors[ $code ] = true;
4486
4487
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
4488
	}
4489
4490
	/**
4491
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4492
	 */
4493
	function stat( $group, $detail ) {
4494
		if ( ! isset( $this->stats[ $group ] ) ) {
4495
			$this->stats[ $group ] = array();
4496
		}
4497
		$this->stats[ $group ][] = $detail;
4498
	}
4499
4500
	/**
4501
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4502
	 */
4503
	function do_stats( $method = '' ) {
4504
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4505
			foreach ( $this->stats as $group => $stats ) {
4506
				if ( is_array( $stats ) && count( $stats ) ) {
4507
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4508
					if ( 'server_side' === $method ) {
4509
						self::do_server_side_stat( $args );
4510
					} else {
4511
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4512
					}
4513
				}
4514
				unset( $this->stats[ $group ] );
4515
			}
4516
		}
4517
	}
4518
4519
	/**
4520
	 * Runs stats code for a one-off, server-side.
4521
	 *
4522
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4523
	 *
4524
	 * @return bool If it worked.
4525
	 */
4526
	static function do_server_side_stat( $args ) {
4527
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4528
		if ( is_wp_error( $response ) ) {
4529
			return false;
4530
		}
4531
4532
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4533
			return false;
4534
		}
4535
4536
		return true;
4537
	}
4538
4539
	/**
4540
	 * Builds the stats url.
4541
	 *
4542
	 * @param $args array|string The arguments to append to the URL.
4543
	 *
4544
	 * @return string The URL to be pinged.
4545
	 */
4546
	static function build_stats_url( $args ) {
4547
		$defaults = array(
4548
			'v'    => 'wpcom2',
4549
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4550
		);
4551
		$args     = wp_parse_args( $args, $defaults );
4552
		/**
4553
		 * Filter the URL used as the Stats tracking pixel.
4554
		 *
4555
		 * @since 2.3.2
4556
		 *
4557
		 * @param string $url Base URL used as the Stats tracking pixel.
4558
		 */
4559
		$base_url = apply_filters(
4560
			'jetpack_stats_base_url',
4561
			'https://pixel.wp.com/g.gif'
4562
		);
4563
		$url      = add_query_arg( $args, $base_url );
4564
		return $url;
4565
	}
4566
4567
	/**
4568
	 * Get the role of the current user.
4569
	 *
4570
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4571
	 *
4572
	 * @access public
4573
	 * @static
4574
	 *
4575
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4576
	 */
4577
	public static function translate_current_user_to_role() {
4578
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4579
4580
		$roles = new Roles();
4581
		return $roles->translate_current_user_to_role();
4582
	}
4583
4584
	/**
4585
	 * Get the role of a particular user.
4586
	 *
4587
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4588
	 *
4589
	 * @access public
4590
	 * @static
4591
	 *
4592
	 * @param \WP_User $user User object.
4593
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4594
	 */
4595
	public static function translate_user_to_role( $user ) {
4596
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4597
4598
		$roles = new Roles();
4599
		return $roles->translate_user_to_role( $user );
4600
	}
4601
4602
	/**
4603
	 * Get the minimum capability for a role.
4604
	 *
4605
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4606
	 *
4607
	 * @access public
4608
	 * @static
4609
	 *
4610
	 * @param string $role Role name.
4611
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4612
	 */
4613
	public static function translate_role_to_cap( $role ) {
4614
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4615
4616
		$roles = new Roles();
4617
		return $roles->translate_role_to_cap( $role );
4618
	}
4619
4620
	/**
4621
	 * Sign a user role with the master access token.
4622
	 * If not specified, will default to the current user.
4623
	 *
4624
	 * @deprecated since 7.7
4625
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4626
	 *
4627
	 * @access public
4628
	 * @static
4629
	 *
4630
	 * @param string $role    User role.
4631
	 * @param int    $user_id ID of the user.
4632
	 * @return string Signed user role.
4633
	 */
4634
	public static function sign_role( $role, $user_id = null ) {
4635
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4636
		return self::connection()->sign_role( $role, $user_id );
4637
	}
4638
4639
	/**
4640
	 * Builds a URL to the Jetpack connection auth page
4641
	 *
4642
	 * @since 3.9.5
4643
	 *
4644
	 * @param bool        $raw If true, URL will not be escaped.
4645
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4646
	 *                              If string, will be a custom redirect.
4647
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4648
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4649
	 *
4650
	 * @return string Connect URL
4651
	 */
4652
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4653
		$site_id    = Jetpack_Options::get_option( 'id' );
4654
		$blog_token = Jetpack_Data::get_access_token();
4655
4656
		if ( $register || ! $blog_token || ! $site_id ) {
4657
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4658
4659
			if ( ! empty( $redirect ) ) {
4660
				$url = add_query_arg(
4661
					'redirect',
4662
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4663
					$url
4664
				);
4665
			}
4666
4667
			if ( is_network_admin() ) {
4668
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4669
			}
4670
4671
			$calypso_env = self::get_calypso_env();
4672
4673
			if ( ! empty( $calypso_env ) ) {
4674
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4675
			}
4676
		} else {
4677
4678
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4679
			// because otherwise this logic can get us in to a loop.
4680
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4681
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4682
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4683
4684
				$response = Client::wpcom_json_api_request_as_blog(
4685
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4686
					'1.1'
4687
				);
4688
4689
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4690
4691
					// Generating a register URL instead to refresh the existing token
4692
					return $this->build_connect_url( $raw, $redirect, $from, true );
4693
				}
4694
			}
4695
4696
			$url = $this->build_authorize_url( $redirect );
4697
		}
4698
4699
		if ( $from ) {
4700
			$url = add_query_arg( 'from', $from, $url );
4701
		}
4702
4703
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4704
		/**
4705
		 * Filter the URL used when connecting a user to a WordPress.com account.
4706
		 *
4707
		 * @since 8.1.0
4708
		 *
4709
		 * @param string $url Connection URL.
4710
		 * @param bool   $raw If true, URL will not be escaped.
4711
		 */
4712
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
4713
	}
4714
4715
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4716
4717
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4718
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4719
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4720
4721
		if ( $iframe ) {
4722
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4723
		}
4724
4725
		$c8n = self::connection();
4726
		$url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
4727
4728
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4729
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4730
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4731
4732
		if ( $iframe ) {
4733
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4734
		}
4735
4736
		return $url;
4737
	}
4738
4739
	/**
4740
	 * Filters the connection URL parameter array.
4741
	 *
4742
	 * @param Array $args default URL parameters used by the package.
4743
	 * @return Array the modified URL arguments array.
4744
	 */
4745
	public static function filter_connect_request_body( $args ) {
4746
		if (
4747
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4748
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4749
		) {
4750
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4751
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4752
				? $gp_locale->slug
4753
				: '';
4754
		}
4755
4756
		$tracking        = new Tracking();
4757
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4758
4759
		$args = array_merge(
4760
			$args,
4761
			array(
4762
				'_ui' => $tracks_identity['_ui'],
4763
				'_ut' => $tracks_identity['_ut'],
4764
			)
4765
		);
4766
4767
		$calypso_env = self::get_calypso_env();
4768
4769
		if ( ! empty( $calypso_env ) ) {
4770
			$args['calypso_env'] = $calypso_env;
4771
		}
4772
4773
		return $args;
4774
	}
4775
4776
	/**
4777
	 * Filters the URL that will process the connection data. It can be different from the URL
4778
	 * that we send the user to after everything is done.
4779
	 *
4780
	 * @param String $processing_url the default redirect URL used by the package.
4781
	 * @return String the modified URL.
4782
	 */
4783
	public static function filter_connect_processing_url( $processing_url ) {
4784
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4785
		return $processing_url;
4786
	}
4787
4788
	/**
4789
	 * Filters the redirection URL that is used for connect requests. The redirect
4790
	 * URL should return the user back to the Jetpack console.
4791
	 *
4792
	 * @param String $redirect the default redirect URL used by the package.
4793
	 * @return String the modified URL.
4794
	 */
4795
	public static function filter_connect_redirect_url( $redirect ) {
4796
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4797
		$redirect           = $redirect
4798
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4799
			: $jetpack_admin_page;
4800
4801
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4802
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4803
		}
4804
4805
		return $redirect;
4806
	}
4807
4808
	/**
4809
	 * This action fires at the beginning of the Manager::authorize method.
4810
	 */
4811
	public static function authorize_starting() {
4812
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4813
		// Checking if site has been active/connected previously before recording unique connection.
4814
		if ( ! $jetpack_unique_connection ) {
4815
			// jetpack_unique_connection option has never been set.
4816
			$jetpack_unique_connection = array(
4817
				'connected'    => 0,
4818
				'disconnected' => 0,
4819
				'version'      => '3.6.1',
4820
			);
4821
4822
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4823
4824
			// Track unique connection.
4825
			$jetpack = self::init();
4826
4827
			$jetpack->stat( 'connections', 'unique-connection' );
4828
			$jetpack->do_stats( 'server_side' );
4829
		}
4830
4831
		// Increment number of times connected.
4832
		$jetpack_unique_connection['connected'] += 1;
4833
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4834
	}
4835
4836
	/**
4837
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4838
	 * linked.
4839
	 */
4840
	public static function authorize_ending_linked() {
4841
		// Don't activate anything since we are just connecting a user.
4842
		self::state( 'message', 'linked' );
4843
	}
4844
4845
	/**
4846
	 * This action fires at the end of the Manager::authorize method when the master user is
4847
	 * authorized.
4848
	 *
4849
	 * @param array $data The request data.
4850
	 */
4851
	public static function authorize_ending_authorized( $data ) {
4852
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4853
		self::invalidate_onboarding_token();
4854
4855
		// If redirect_uri is SSO, ensure SSO module is enabled.
4856
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4857
4858
		/** This filter is documented in class.jetpack-cli.php */
4859
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4860
4861
		$activate_sso = (
4862
			isset( $redirect_options['action'] ) &&
4863
			'jetpack-sso' === $redirect_options['action'] &&
4864
			$jetpack_start_enable_sso
4865
		);
4866
4867
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4868
4869
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4870
	}
4871
4872
	/**
4873
	 * Get our assumed site creation date.
4874
	 * Calculated based on the earlier date of either:
4875
	 * - Earliest admin user registration date.
4876
	 * - Earliest date of post of any post type.
4877
	 *
4878
	 * @since 7.2.0
4879
	 * @deprecated since 7.8.0
4880
	 *
4881
	 * @return string Assumed site creation date and time.
4882
	 */
4883
	public static function get_assumed_site_creation_date() {
4884
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4885
		return self::connection()->get_assumed_site_creation_date();
4886
	}
4887
4888 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4889
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4890
4891
		if ( $activation_source_name ) {
4892
			$args['_as'] = urlencode( $activation_source_name );
4893
		}
4894
4895
		if ( $activation_source_keyword ) {
4896
			$args['_ak'] = urlencode( $activation_source_keyword );
4897
		}
4898
	}
4899
4900
	function build_reconnect_url( $raw = false ) {
4901
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4902
		return $raw ? $url : esc_url( $url );
4903
	}
4904
4905
	public static function admin_url( $args = null ) {
4906
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4907
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4908
		return $url;
4909
	}
4910
4911
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4912
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4913
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4914
	}
4915
4916
	function dismiss_jetpack_notice() {
4917
4918
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4919
			return;
4920
		}
4921
4922
		switch ( $_GET['jetpack-notice'] ) {
4923
			case 'dismiss':
4924
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4925
4926
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4927
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4928
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4929
				}
4930
				break;
4931
		}
4932
	}
4933
4934
	public static function sort_modules( $a, $b ) {
4935
		if ( $a['sort'] == $b['sort'] ) {
4936
			return 0;
4937
		}
4938
4939
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4940
	}
4941
4942
	function ajax_recheck_ssl() {
4943
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4944
		$result = self::permit_ssl( true );
4945
		wp_send_json(
4946
			array(
4947
				'enabled' => $result,
4948
				'message' => get_transient( 'jetpack_https_test_message' ),
4949
			)
4950
		);
4951
	}
4952
4953
	/* Client API */
4954
4955
	/**
4956
	 * Returns the requested Jetpack API URL
4957
	 *
4958
	 * @deprecated since 7.7
4959
	 * @return string
4960
	 */
4961
	public static function api_url( $relative_url ) {
4962
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
4963
		$connection = self::connection();
4964
		return $connection->api_url( $relative_url );
4965
	}
4966
4967
	/**
4968
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
4969
	 *
4970
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4971
	 */
4972
	public static function fix_url_for_bad_hosts( $url ) {
4973
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
4974
		return Connection_Utils::fix_url_for_bad_hosts( $url );
4975
	}
4976
4977
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4978
		// Default to a blog token.
4979
		$token_type = 'blog';
4980
4981
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4982
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4983
			if ( ! empty( $_GET['onboarding'] ) ) {
4984
				$jpo = $_GET;
4985
			} else {
4986
				$jpo = json_decode( $request_data, true );
4987
			}
4988
4989
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4990
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4991
4992
			if (
4993
				isset( $jpo_user )
4994
				&& isset( $jpo_token )
4995
				&& is_email( $jpo_user )
4996
				&& ctype_alnum( $jpo_token )
4997
				&& isset( $_GET['rest_route'] )
4998
				&& self::validate_onboarding_token_action(
4999
					$jpo_token,
5000
					$_GET['rest_route']
5001
				)
5002
			) {
5003
				$jp_user = get_user_by( 'email', $jpo_user );
5004
				if ( is_a( $jp_user, 'WP_User' ) ) {
5005
					wp_set_current_user( $jp_user->ID );
5006
					$user_can = is_multisite()
5007
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5008
						: current_user_can( 'manage_options' );
5009
					if ( $user_can ) {
5010
						$token_type              = 'user';
5011
						$token->external_user_id = $jp_user->ID;
5012
					}
5013
				}
5014
			}
5015
5016
			$token_data['type']    = $token_type;
5017
			$token_data['user_id'] = $token->external_user_id;
5018
		}
5019
5020
		return $token_data;
5021
	}
5022
5023
	/**
5024
	 * Create a random secret for validating onboarding payload
5025
	 *
5026
	 * @return string Secret token
5027
	 */
5028
	public static function create_onboarding_token() {
5029
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5030
			$token = wp_generate_password( 32, false );
5031
			Jetpack_Options::update_option( 'onboarding', $token );
5032
		}
5033
5034
		return $token;
5035
	}
5036
5037
	/**
5038
	 * Remove the onboarding token
5039
	 *
5040
	 * @return bool True on success, false on failure
5041
	 */
5042
	public static function invalidate_onboarding_token() {
5043
		return Jetpack_Options::delete_option( 'onboarding' );
5044
	}
5045
5046
	/**
5047
	 * Validate an onboarding token for a specific action
5048
	 *
5049
	 * @return boolean True if token/action pair is accepted, false if not
5050
	 */
5051
	public static function validate_onboarding_token_action( $token, $action ) {
5052
		// Compare tokens, bail if tokens do not match
5053
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5054
			return false;
5055
		}
5056
5057
		// List of valid actions we can take
5058
		$valid_actions = array(
5059
			'/jetpack/v4/settings',
5060
		);
5061
5062
		// Whitelist the action
5063
		if ( ! in_array( $action, $valid_actions ) ) {
5064
			return false;
5065
		}
5066
5067
		return true;
5068
	}
5069
5070
	/**
5071
	 * Checks to see if the URL is using SSL to connect with Jetpack
5072
	 *
5073
	 * @since 2.3.3
5074
	 * @return boolean
5075
	 */
5076
	public static function permit_ssl( $force_recheck = false ) {
5077
		// Do some fancy tests to see if ssl is being supported
5078
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5079
			$message = '';
5080
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5081
				$ssl = 0;
5082
			} else {
5083
				switch ( JETPACK_CLIENT__HTTPS ) {
5084
					case 'NEVER':
5085
						$ssl     = 0;
5086
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5087
						break;
5088
					case 'ALWAYS':
5089
					case 'AUTO':
5090
					default:
5091
						$ssl = 1;
5092
						break;
5093
				}
5094
5095
				// If it's not 'NEVER', test to see
5096
				if ( $ssl ) {
5097
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5098
						$ssl     = 0;
5099
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5100
					} else {
5101
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5102
						if ( is_wp_error( $response ) ) {
5103
							$ssl     = 0;
5104
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5105
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5106
							$ssl     = 0;
5107
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5108
						}
5109
					}
5110
				}
5111
			}
5112
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5113
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5114
		}
5115
5116
		return (bool) $ssl;
5117
	}
5118
5119
	/*
5120
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5121
	 */
5122
	public function alert_auto_ssl_fail() {
5123
		if ( ! current_user_can( 'manage_options' ) ) {
5124
			return;
5125
		}
5126
5127
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5128
		?>
5129
5130
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5131
			<div class="jp-banner__content">
5132
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5133
				<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>
5134
				<p>
5135
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5136
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5137
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5138
				</p>
5139
				<p>
5140
					<?php
5141
					printf(
5142
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5143
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5144
						esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' )
5145
					);
5146
					?>
5147
				</p>
5148
			</div>
5149
		</div>
5150
		<style>
5151
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5152
		</style>
5153
		<script type="text/javascript">
5154
			jQuery( document ).ready( function( $ ) {
5155
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5156
					var $this = $( this );
5157
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5158
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5159
					e.preventDefault();
5160
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5161
					$.post( ajaxurl, data )
5162
					  .done( function( response ) {
5163
						  if ( response.enabled ) {
5164
							  $( '#jetpack-ssl-warning' ).hide();
5165
						  } else {
5166
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5167
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5168
						  }
5169
					  }.bind( $this ) );
5170
				} );
5171
			} );
5172
		</script>
5173
5174
		<?php
5175
	}
5176
5177
	/**
5178
	 * Returns the Jetpack XML-RPC API
5179
	 *
5180
	 * @deprecated 8.0 Use Connection_Manager instead.
5181
	 * @return string
5182
	 */
5183
	public static function xmlrpc_api_url() {
5184
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5185
		return self::connection()->xmlrpc_api_url();
5186
	}
5187
5188
	/**
5189
	 * Returns the connection manager object.
5190
	 *
5191
	 * @return Automattic\Jetpack\Connection\Manager
5192
	 */
5193
	public static function connection() {
5194
		$jetpack = static::init();
5195
5196
		// If the connection manager hasn't been instantiated, do that now.
5197
		if ( ! $jetpack->connection_manager ) {
5198
			$jetpack->connection_manager = new Connection_Manager();
5199
		}
5200
5201
		return $jetpack->connection_manager;
5202
	}
5203
5204
	/**
5205
	 * Creates two secret tokens and the end of life timestamp for them.
5206
	 *
5207
	 * Note these tokens are unique per call, NOT static per site for connecting.
5208
	 *
5209
	 * @since 2.6
5210
	 * @param String  $action  The action name.
5211
	 * @param Integer $user_id The user identifier.
5212
	 * @param Integer $exp     Expiration time in seconds.
5213
	 * @return array
5214
	 */
5215
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5216
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5217
	}
5218
5219
	public static function get_secrets( $action, $user_id ) {
5220
		$secrets = self::connection()->get_secrets( $action, $user_id );
5221
5222
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5223
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
5224
		}
5225
5226
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5227
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
5228
		}
5229
5230
		return $secrets;
5231
	}
5232
5233
	/**
5234
	 * @deprecated 7.5 Use Connection_Manager instead.
5235
	 *
5236
	 * @param $action
5237
	 * @param $user_id
5238
	 */
5239
	public static function delete_secrets( $action, $user_id ) {
5240
		return self::connection()->delete_secrets( $action, $user_id );
5241
	}
5242
5243
	/**
5244
	 * Builds the timeout limit for queries talking with the wpcom servers.
5245
	 *
5246
	 * Based on local php max_execution_time in php.ini
5247
	 *
5248
	 * @since 2.6
5249
	 * @return int
5250
	 * @deprecated
5251
	 **/
5252
	public function get_remote_query_timeout_limit() {
5253
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5254
		return self::get_max_execution_time();
5255
	}
5256
5257
	/**
5258
	 * Builds the timeout limit for queries talking with the wpcom servers.
5259
	 *
5260
	 * Based on local php max_execution_time in php.ini
5261
	 *
5262
	 * @since 5.4
5263
	 * @return int
5264
	 **/
5265
	public static function get_max_execution_time() {
5266
		$timeout = (int) ini_get( 'max_execution_time' );
5267
5268
		// Ensure exec time set in php.ini
5269
		if ( ! $timeout ) {
5270
			$timeout = 30;
5271
		}
5272
		return $timeout;
5273
	}
5274
5275
	/**
5276
	 * Sets a minimum request timeout, and returns the current timeout
5277
	 *
5278
	 * @since 5.4
5279
	 **/
5280 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5281
		$timeout = self::get_max_execution_time();
5282
		if ( $timeout < $min_timeout ) {
5283
			$timeout = $min_timeout;
5284
			set_time_limit( $timeout );
5285
		}
5286
		return $timeout;
5287
	}
5288
5289
	/**
5290
	 * Takes the response from the Jetpack register new site endpoint and
5291
	 * verifies it worked properly.
5292
	 *
5293
	 * @since 2.6
5294
	 * @deprecated since 7.7.0
5295
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5296
	 **/
5297
	public function validate_remote_register_response() {
5298
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5299
	}
5300
5301
	/**
5302
	 * @return bool|WP_Error
5303
	 */
5304
	public static function register() {
5305
		$tracking = new Tracking();
5306
		$tracking->record_user_event( 'jpc_register_begin' );
5307
5308
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5309
5310
		$connection   = self::connection();
5311
		$registration = $connection->register();
5312
5313
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5314
5315
		if ( ! $registration || is_wp_error( $registration ) ) {
5316
			return $registration;
5317
		}
5318
5319
		return true;
5320
	}
5321
5322
	/**
5323
	 * Filters the registration request body to include tracking properties.
5324
	 *
5325
	 * @param Array $properties
5326
	 * @return Array amended properties.
5327
	 */
5328 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5329
		$tracking        = new Tracking();
5330
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5331
5332
		return array_merge(
5333
			$properties,
5334
			array(
5335
				'_ui' => $tracks_identity['_ui'],
5336
				'_ut' => $tracks_identity['_ut'],
5337
			)
5338
		);
5339
	}
5340
5341
	/**
5342
	 * Filters the token request body to include tracking properties.
5343
	 *
5344
	 * @param Array $properties
5345
	 * @return Array amended properties.
5346
	 */
5347 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5348
		$tracking        = new Tracking();
5349
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5350
5351
		return array_merge(
5352
			$properties,
5353
			array(
5354
				'_ui' => $tracks_identity['_ui'],
5355
				'_ut' => $tracks_identity['_ut'],
5356
			)
5357
		);
5358
	}
5359
5360
	/**
5361
	 * If the db version is showing something other that what we've got now, bump it to current.
5362
	 *
5363
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5364
	 */
5365
	public static function maybe_set_version_option() {
5366
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5367
		if ( JETPACK__VERSION != $version ) {
5368
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5369
5370
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5371
				/** This action is documented in class.jetpack.php */
5372
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5373
			}
5374
5375
			return true;
5376
		}
5377
		return false;
5378
	}
5379
5380
	/* Client Server API */
5381
5382
	/**
5383
	 * Loads the Jetpack XML-RPC client.
5384
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5385
	 *
5386
	 * @deprecated since 7.7.0
5387
	 */
5388
	public static function load_xml_rpc_client() {
5389
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5390
	}
5391
5392
	/**
5393
	 * Resets the saved authentication state in between testing requests.
5394
	 */
5395
	public function reset_saved_auth_state() {
5396
		$this->rest_authentication_status = null;
5397
5398
		if ( ! $this->connection_manager ) {
5399
			$this->connection_manager = new Connection_Manager();
5400
		}
5401
5402
		$this->connection_manager->reset_saved_auth_state();
5403
	}
5404
5405
	/**
5406
	 * Verifies the signature of the current request.
5407
	 *
5408
	 * @deprecated since 7.7.0
5409
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5410
	 *
5411
	 * @return false|array
5412
	 */
5413
	public function verify_xml_rpc_signature() {
5414
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5415
		return self::connection()->verify_xml_rpc_signature();
5416
	}
5417
5418
	/**
5419
	 * Verifies the signature of the current request.
5420
	 *
5421
	 * This function has side effects and should not be used. Instead,
5422
	 * use the memoized version `->verify_xml_rpc_signature()`.
5423
	 *
5424
	 * @deprecated since 7.7.0
5425
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5426
	 * @internal
5427
	 */
5428
	private function internal_verify_xml_rpc_signature() {
5429
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5430
	}
5431
5432
	/**
5433
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5434
	 *
5435
	 * @deprecated since 7.7.0
5436
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5437
	 *
5438
	 * @param \WP_User|mixed $user     User object if authenticated.
5439
	 * @param string         $username Username.
5440
	 * @param string         $password Password string.
5441
	 * @return \WP_User|mixed Authenticated user or error.
5442
	 */
5443 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5444
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5445
5446
		if ( ! $this->connection_manager ) {
5447
			$this->connection_manager = new Connection_Manager();
5448
		}
5449
5450
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5451
	}
5452
5453
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5454
	// Uses the existing XMLRPC request signing implementation.
5455
	function wp_rest_authenticate( $user ) {
5456
		if ( ! empty( $user ) ) {
5457
			// Another authentication method is in effect.
5458
			return $user;
5459
		}
5460
5461
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5462
			// Nothing to do for this authentication method.
5463
			return null;
5464
		}
5465
5466
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5467
			// Nothing to do for this authentication method.
5468
			return null;
5469
		}
5470
5471
		// Ensure that we always have the request body available.  At this
5472
		// point, the WP REST API code to determine the request body has not
5473
		// run yet.  That code may try to read from 'php://input' later, but
5474
		// this can only be done once per request in PHP versions prior to 5.6.
5475
		// So we will go ahead and perform this read now if needed, and save
5476
		// the request body where both the Jetpack signature verification code
5477
		// and the WP REST API code can see it.
5478
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5479
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5480
		}
5481
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5482
5483
		// Only support specific request parameters that have been tested and
5484
		// are known to work with signature verification.  A different method
5485
		// can be passed to the WP REST API via the '?_method=' parameter if
5486
		// needed.
5487
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5488
			$this->rest_authentication_status = new WP_Error(
5489
				'rest_invalid_request',
5490
				__( 'This request method is not supported.', 'jetpack' ),
5491
				array( 'status' => 400 )
5492
			);
5493
			return null;
5494
		}
5495
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5496
			$this->rest_authentication_status = new WP_Error(
5497
				'rest_invalid_request',
5498
				__( 'This request method does not support body parameters.', 'jetpack' ),
5499
				array( 'status' => 400 )
5500
			);
5501
			return null;
5502
		}
5503
5504
		if ( ! $this->connection_manager ) {
5505
			$this->connection_manager = new Connection_Manager();
5506
		}
5507
5508
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5509
5510
		if (
5511
			$verified &&
5512
			isset( $verified['type'] ) &&
5513
			'user' === $verified['type'] &&
5514
			! empty( $verified['user_id'] )
5515
		) {
5516
			// Authentication successful.
5517
			$this->rest_authentication_status = true;
5518
			return $verified['user_id'];
5519
		}
5520
5521
		// Something else went wrong.  Probably a signature error.
5522
		$this->rest_authentication_status = new WP_Error(
5523
			'rest_invalid_signature',
5524
			__( 'The request is not signed correctly.', 'jetpack' ),
5525
			array( 'status' => 400 )
5526
		);
5527
		return null;
5528
	}
5529
5530
	/**
5531
	 * Report authentication status to the WP REST API.
5532
	 *
5533
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5534
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5535
	 */
5536
	public function wp_rest_authentication_errors( $value ) {
5537
		if ( $value !== null ) {
5538
			return $value;
5539
		}
5540
		return $this->rest_authentication_status;
5541
	}
5542
5543
	/**
5544
	 * Add our nonce to this request.
5545
	 *
5546
	 * @deprecated since 7.7.0
5547
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5548
	 *
5549
	 * @param int    $timestamp Timestamp of the request.
5550
	 * @param string $nonce     Nonce string.
5551
	 */
5552 View Code Duplication
	public function add_nonce( $timestamp, $nonce ) {
5553
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5554
5555
		if ( ! $this->connection_manager ) {
5556
			$this->connection_manager = new Connection_Manager();
5557
		}
5558
5559
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5560
	}
5561
5562
	/**
5563
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5564
	 * Capture it here so we can verify the signature later.
5565
	 *
5566
	 * @deprecated since 7.7.0
5567
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5568
	 *
5569
	 * @param array $methods XMLRPC methods.
5570
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5571
	 */
5572 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5573
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5574
5575
		if ( ! $this->connection_manager ) {
5576
			$this->connection_manager = new Connection_Manager();
5577
		}
5578
5579
		return $this->connection_manager->xmlrpc_methods( $methods );
5580
	}
5581
5582
	/**
5583
	 * Register additional public XMLRPC methods.
5584
	 *
5585
	 * @deprecated since 7.7.0
5586
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5587
	 *
5588
	 * @param array $methods Public XMLRPC methods.
5589
	 * @return array Public XMLRPC methods, with the getOptions one.
5590
	 */
5591 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5592
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5593
5594
		if ( ! $this->connection_manager ) {
5595
			$this->connection_manager = new Connection_Manager();
5596
		}
5597
5598
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5599
	}
5600
5601
	/**
5602
	 * Handles a getOptions XMLRPC method call.
5603
	 *
5604
	 * @deprecated since 7.7.0
5605
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5606
	 *
5607
	 * @param array $args method call arguments.
5608
	 * @return array an amended XMLRPC server options array.
5609
	 */
5610 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5611
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5612
5613
		if ( ! $this->connection_manager ) {
5614
			$this->connection_manager = new Connection_Manager();
5615
		}
5616
5617
		return $this->connection_manager->jetpack_getOptions( $args );
5618
	}
5619
5620
	/**
5621
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5622
	 *
5623
	 * @deprecated since 7.7.0
5624
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5625
	 *
5626
	 * @param array $options Standard Core options.
5627
	 * @return array Amended options.
5628
	 */
5629 View Code Duplication
	public function xmlrpc_options( $options ) {
5630
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5631
5632
		if ( ! $this->connection_manager ) {
5633
			$this->connection_manager = new Connection_Manager();
5634
		}
5635
5636
		return $this->connection_manager->xmlrpc_options( $options );
5637
	}
5638
5639
	/**
5640
	 * Cleans nonces that were saved when calling ::add_nonce.
5641
	 *
5642
	 * @deprecated since 7.7.0
5643
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5644
	 *
5645
	 * @param bool $all whether to clean even non-expired nonces.
5646
	 */
5647
	public static function clean_nonces( $all = false ) {
5648
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5649
		return self::connection()->clean_nonces( $all );
5650
	}
5651
5652
	/**
5653
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5654
	 * SET: state( $key, $value );
5655
	 * GET: $value = state( $key );
5656
	 *
5657
	 * @param string $key
5658
	 * @param string $value
5659
	 * @param bool   $restate private
5660
	 */
5661
	public static function state( $key = null, $value = null, $restate = false ) {
5662
		static $state = array();
5663
		static $path, $domain;
5664
		if ( ! isset( $path ) ) {
5665
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5666
			$admin_url = self::admin_url();
5667
			$bits      = wp_parse_url( $admin_url );
5668
5669
			if ( is_array( $bits ) ) {
5670
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5671
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5672
			} else {
5673
				$path = $domain = null;
5674
			}
5675
		}
5676
5677
		// Extract state from cookies and delete cookies
5678
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5679
			$yum = $_COOKIE['jetpackState'];
5680
			unset( $_COOKIE['jetpackState'] );
5681
			foreach ( $yum as $k => $v ) {
5682
				if ( strlen( $v ) ) {
5683
					$state[ $k ] = $v;
5684
				}
5685
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5686
			}
5687
		}
5688
5689
		if ( $restate ) {
5690
			foreach ( $state as $k => $v ) {
5691
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5692
			}
5693
			return;
5694
		}
5695
5696
		// Get a state variable
5697
		if ( isset( $key ) && ! isset( $value ) ) {
5698
			if ( array_key_exists( $key, $state ) ) {
5699
				return $state[ $key ];
5700
			}
5701
			return null;
5702
		}
5703
5704
		// Set a state variable
5705
		if ( isset( $key ) && isset( $value ) ) {
5706
			if ( is_array( $value ) && isset( $value[0] ) ) {
5707
				$value = $value[0];
5708
			}
5709
			$state[ $key ] = $value;
5710
			if ( ! headers_sent() ) {
5711
				setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5712
			}
5713
		}
5714
	}
5715
5716
	public static function restate() {
5717
		self::state( null, null, true );
5718
	}
5719
5720
	public static function check_privacy( $file ) {
5721
		static $is_site_publicly_accessible = null;
5722
5723
		if ( is_null( $is_site_publicly_accessible ) ) {
5724
			$is_site_publicly_accessible = false;
5725
5726
			$rpc = new Jetpack_IXR_Client();
5727
5728
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5729
			if ( $success ) {
5730
				$response = $rpc->getResponse();
5731
				if ( $response ) {
5732
					$is_site_publicly_accessible = true;
5733
				}
5734
			}
5735
5736
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5737
		}
5738
5739
		if ( $is_site_publicly_accessible ) {
5740
			return;
5741
		}
5742
5743
		$module_slug = self::get_module_slug( $file );
5744
5745
		$privacy_checks = self::state( 'privacy_checks' );
5746
		if ( ! $privacy_checks ) {
5747
			$privacy_checks = $module_slug;
5748
		} else {
5749
			$privacy_checks .= ",$module_slug";
5750
		}
5751
5752
		self::state( 'privacy_checks', $privacy_checks );
5753
	}
5754
5755
	/**
5756
	 * Helper method for multicall XMLRPC.
5757
	 *
5758
	 * @param ...$args Args for the async_call.
5759
	 */
5760
	public static function xmlrpc_async_call( ...$args ) {
5761
		global $blog_id;
5762
		static $clients = array();
5763
5764
		$client_blog_id = is_multisite() ? $blog_id : 0;
5765
5766
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5767
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5768
			if ( function_exists( 'ignore_user_abort' ) ) {
5769
				ignore_user_abort( true );
5770
			}
5771
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5772
		}
5773
5774
		if ( ! empty( $args[0] ) ) {
5775
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5776
		} elseif ( is_multisite() ) {
5777
			foreach ( $clients as $client_blog_id => $client ) {
5778
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5779
					continue;
5780
				}
5781
5782
				$switch_success = switch_to_blog( $client_blog_id, true );
5783
				if ( ! $switch_success ) {
5784
					continue;
5785
				}
5786
5787
				flush();
5788
				$client->query();
5789
5790
				restore_current_blog();
5791
			}
5792
		} else {
5793
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5794
				flush();
5795
				$clients[0]->query();
5796
			}
5797
		}
5798
	}
5799
5800
	public static function staticize_subdomain( $url ) {
5801
5802
		// Extract hostname from URL
5803
		$host = wp_parse_url( $url, PHP_URL_HOST );
5804
5805
		// Explode hostname on '.'
5806
		$exploded_host = explode( '.', $host );
5807
5808
		// Retrieve the name and TLD
5809
		if ( count( $exploded_host ) > 1 ) {
5810
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5811
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5812
			// Rebuild domain excluding subdomains
5813
			$domain = $name . '.' . $tld;
5814
		} else {
5815
			$domain = $host;
5816
		}
5817
		// Array of Automattic domains
5818
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5819
5820
		// Return $url if not an Automattic domain
5821
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5822
			return $url;
5823
		}
5824
5825
		if ( is_ssl() ) {
5826
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5827
		}
5828
5829
		srand( crc32( basename( $url ) ) );
5830
		$static_counter = rand( 0, 2 );
5831
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5832
5833
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5834
	}
5835
5836
	/* JSON API Authorization */
5837
5838
	/**
5839
	 * Handles the login action for Authorizing the JSON API
5840
	 */
5841
	function login_form_json_api_authorization() {
5842
		$this->verify_json_api_authorization_request();
5843
5844
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5845
5846
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5847
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5848
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5849
	}
5850
5851
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5852
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5853
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5854
			return $url;
5855
		}
5856
5857
		$parsed_url = wp_parse_url( $url );
5858
		$url        = strtok( $url, '?' );
5859
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5860
		if ( ! empty( $parsed_url['query'] ) ) {
5861
			$url .= "&{$parsed_url['query']}";
5862
		}
5863
5864
		return $url;
5865
	}
5866
5867
	// Make sure the POSTed request is handled by the same action
5868
	function preserve_action_in_login_form_for_json_api_authorization() {
5869
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5870
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5871
	}
5872
5873
	// If someone logs in to approve API access, store the Access Code in usermeta
5874
	function store_json_api_authorization_token( $user_login, $user ) {
5875
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5876
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5877
		$token = wp_generate_password( 32, false );
5878
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5879
	}
5880
5881
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5882
	function allow_wpcom_public_api_domain( $domains ) {
5883
		$domains[] = 'public-api.wordpress.com';
5884
		return $domains;
5885
	}
5886
5887
	static function is_redirect_encoded( $redirect_url ) {
5888
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5889
	}
5890
5891
	// Add all wordpress.com environments to the safe redirect whitelist
5892
	function allow_wpcom_environments( $domains ) {
5893
		$domains[] = 'wordpress.com';
5894
		$domains[] = 'wpcalypso.wordpress.com';
5895
		$domains[] = 'horizon.wordpress.com';
5896
		$domains[] = 'calypso.localhost';
5897
		return $domains;
5898
	}
5899
5900
	// Add the Access Code details to the public-api.wordpress.com redirect
5901
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5902
		return add_query_arg(
5903
			urlencode_deep(
5904
				array(
5905
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5906
					'jetpack-user-id' => (int) $user->ID,
5907
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5908
				)
5909
			),
5910
			$redirect_to
5911
		);
5912
	}
5913
5914
5915
	/**
5916
	 * Verifies the request by checking the signature
5917
	 *
5918
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5919
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5920
	 *
5921
	 * @param null|array $environment
5922
	 */
5923
	function verify_json_api_authorization_request( $environment = null ) {
5924
		$environment = is_null( $environment )
5925
			? $_REQUEST
5926
			: $environment;
5927
5928
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
5929
		$token                                     = Jetpack_Data::get_access_token( $envUserId, $envToken );
5930
		if ( ! $token || empty( $token->secret ) ) {
5931
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5932
		}
5933
5934
		$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' );
5935
5936
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5937
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5938
			/**
5939
			 * Jetpack authorisation request Error.
5940
			 *
5941
			 * @since 7.5.0
5942
			 */
5943
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5944
			$die_error = sprintf(
5945
				/* translators: %s is a URL */
5946
				__( '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' ),
5947
				'https://jetpack.com/support/double-encoding/'
5948
			);
5949
		}
5950
5951
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5952
5953
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5954
			$signature = $jetpack_signature->sign_request(
5955
				$environment['token'],
5956
				$environment['timestamp'],
5957
				$environment['nonce'],
5958
				'',
5959
				'GET',
5960
				$environment['jetpack_json_api_original_query'],
5961
				null,
5962
				true
5963
			);
5964
		} else {
5965
			$signature = $jetpack_signature->sign_current_request(
5966
				array(
5967
					'body'   => null,
5968
					'method' => 'GET',
5969
				)
5970
			);
5971
		}
5972
5973
		if ( ! $signature ) {
5974
			wp_die( $die_error );
5975
		} elseif ( is_wp_error( $signature ) ) {
5976
			wp_die( $die_error );
5977
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5978
			if ( is_ssl() ) {
5979
				// 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
5980
				$signature = $jetpack_signature->sign_current_request(
5981
					array(
5982
						'scheme' => 'http',
5983
						'body'   => null,
5984
						'method' => 'GET',
5985
					)
5986
				);
5987
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5988
					wp_die( $die_error );
5989
				}
5990
			} else {
5991
				wp_die( $die_error );
5992
			}
5993
		}
5994
5995
		$timestamp = (int) $environment['timestamp'];
5996
		$nonce     = stripslashes( (string) $environment['nonce'] );
5997
5998
		if ( ! $this->connection_manager ) {
5999
			$this->connection_manager = new Connection_Manager();
6000
		}
6001
6002
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
6003
			// De-nonce the nonce, at least for 5 minutes.
6004
			// 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)
6005
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6006
			if ( $old_nonce_time < time() - 300 ) {
6007
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6008
			}
6009
		}
6010
6011
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6012
		$data_filters = array(
6013
			'state'        => 'opaque',
6014
			'client_id'    => 'int',
6015
			'client_title' => 'string',
6016
			'client_image' => 'url',
6017
		);
6018
6019
		foreach ( $data_filters as $key => $sanitation ) {
6020
			if ( ! isset( $data->$key ) ) {
6021
				wp_die( $die_error );
6022
			}
6023
6024
			switch ( $sanitation ) {
6025
				case 'int':
6026
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6027
					break;
6028
				case 'opaque':
6029
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6030
					break;
6031
				case 'string':
6032
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6033
					break;
6034
				case 'url':
6035
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6036
					break;
6037
			}
6038
		}
6039
6040
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6041
			wp_die( $die_error );
6042
		}
6043
	}
6044
6045
	function login_message_json_api_authorization( $message ) {
6046
		return '<p class="message">' . sprintf(
6047
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6048
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6049
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6050
	}
6051
6052
	/**
6053
	 * Get $content_width, but with a <s>twist</s> filter.
6054
	 */
6055
	public static function get_content_width() {
6056
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6057
			? $GLOBALS['content_width']
6058
			: false;
6059
		/**
6060
		 * Filter the Content Width value.
6061
		 *
6062
		 * @since 2.2.3
6063
		 *
6064
		 * @param string $content_width Content Width value.
6065
		 */
6066
		return apply_filters( 'jetpack_content_width', $content_width );
6067
	}
6068
6069
	/**
6070
	 * Pings the WordPress.com Mirror Site for the specified options.
6071
	 *
6072
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6073
	 *
6074
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6075
	 */
6076
	public function get_cloud_site_options( $option_names ) {
6077
		$option_names = array_filter( (array) $option_names, 'is_string' );
6078
6079
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
6080
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6081
		if ( $xml->isError() ) {
6082
			return array(
6083
				'error_code' => $xml->getErrorCode(),
6084
				'error_msg'  => $xml->getErrorMessage(),
6085
			);
6086
		}
6087
		$cloud_site_options = $xml->getResponse();
6088
6089
		return $cloud_site_options;
6090
	}
6091
6092
	/**
6093
	 * Checks if the site is currently in an identity crisis.
6094
	 *
6095
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6096
	 */
6097
	public static function check_identity_crisis() {
6098
		if ( ! self::is_active() || ( new Status() )->is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6099
			return false;
6100
		}
6101
6102
		return Jetpack_Options::get_option( 'sync_error_idc' );
6103
	}
6104
6105
	/**
6106
	 * Checks whether the home and siteurl specifically are whitelisted
6107
	 * Written so that we don't have re-check $key and $value params every time
6108
	 * we want to check if this site is whitelisted, for example in footer.php
6109
	 *
6110
	 * @since  3.8.0
6111
	 * @return bool True = already whitelisted False = not whitelisted
6112
	 */
6113
	public static function is_staging_site() {
6114
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6115
		return ( new Status() )->is_staging_site();
6116
	}
6117
6118
	/**
6119
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6120
	 *
6121
	 * @since 4.4.0
6122
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6123
	 *
6124
	 * @return bool
6125
	 */
6126
	public static function validate_sync_error_idc_option() {
6127
		$is_valid = false;
6128
6129
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6130
		if ( false === $idc_allowed ) {
6131
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6132
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6133
				$json               = json_decode( wp_remote_retrieve_body( $response ) );
6134
				$idc_allowed        = isset( $json, $json->result ) && $json->result ? '1' : '0';
6135
				$transient_duration = HOUR_IN_SECONDS;
6136
			} else {
6137
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6138
				$idc_allowed        = '1';
6139
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6140
			}
6141
6142
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6143
		}
6144
6145
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6146
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6147
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6148
			$local_options = self::get_sync_error_idc_option();
6149
			// Ensure all values are set.
6150
			if ( isset( $sync_error['home'] ) && isset ( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6151
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6152
					$is_valid = true;
6153
				}
6154
			}
6155
6156
		}
6157
6158
		/**
6159
		 * Filters whether the sync_error_idc option is valid.
6160
		 *
6161
		 * @since 4.4.0
6162
		 *
6163
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6164
		 */
6165
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6166
6167
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6168
			// Since the option exists, and did not validate, delete it
6169
			Jetpack_Options::delete_option( 'sync_error_idc' );
6170
		}
6171
6172
		return $is_valid;
6173
	}
6174
6175
	/**
6176
	 * Normalizes a url by doing three things:
6177
	 *  - Strips protocol
6178
	 *  - Strips www
6179
	 *  - Adds a trailing slash
6180
	 *
6181
	 * @since 4.4.0
6182
	 * @param string $url
6183
	 * @return WP_Error|string
6184
	 */
6185
	public static function normalize_url_protocol_agnostic( $url ) {
6186
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6187
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6188
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6189
		}
6190
6191
		// Strip www and protocols
6192
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6193
		return $url;
6194
	}
6195
6196
	/**
6197
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6198
	 *
6199
	 * @since 4.4.0
6200
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6201
	 *
6202
	 * @param array $response
6203
	 * @return array Array of the local urls, wpcom urls, and error code
6204
	 */
6205
	public static function get_sync_error_idc_option( $response = array() ) {
6206
		// Since the local options will hit the database directly, store the values
6207
		// in a transient to allow for autoloading and caching on subsequent views.
6208
		$local_options = get_transient( 'jetpack_idc_local' );
6209
		if ( false === $local_options ) {
6210
			$local_options = array(
6211
				'home'    => Functions::home_url(),
6212
				'siteurl' => Functions::site_url(),
6213
			);
6214
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6215
		}
6216
6217
		$options = array_merge( $local_options, $response );
6218
6219
		$returned_values = array();
6220
		foreach ( $options as $key => $option ) {
6221
			if ( 'error_code' === $key ) {
6222
				$returned_values[ $key ] = $option;
6223
				continue;
6224
			}
6225
6226
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6227
				continue;
6228
			}
6229
6230
			$returned_values[ $key ] = $normalized_url;
6231
		}
6232
6233
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6234
6235
		return $returned_values;
6236
	}
6237
6238
	/**
6239
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6240
	 * If set to true, the site will be put into staging mode.
6241
	 *
6242
	 * @since 4.3.2
6243
	 * @return bool
6244
	 */
6245
	public static function sync_idc_optin() {
6246
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6247
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6248
		} else {
6249
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6250
		}
6251
6252
		/**
6253
		 * Allows sites to opt in to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6254
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6255
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6256
		 *
6257
		 * @since 4.3.2
6258
		 *
6259
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6260
		 */
6261
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6262
	}
6263
6264
	/**
6265
	 * Maybe Use a .min.css stylesheet, maybe not.
6266
	 *
6267
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6268
	 */
6269
	public static function maybe_min_asset( $url, $path, $plugin ) {
6270
		// Short out on things trying to find actual paths.
6271
		if ( ! $path || empty( $plugin ) ) {
6272
			return $url;
6273
		}
6274
6275
		$path = ltrim( $path, '/' );
6276
6277
		// Strip out the abspath.
6278
		$base = dirname( plugin_basename( $plugin ) );
6279
6280
		// Short out on non-Jetpack assets.
6281
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6282
			return $url;
6283
		}
6284
6285
		// File name parsing.
6286
		$file              = "{$base}/{$path}";
6287
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6288
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6289
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6290
		$extension         = array_shift( $file_name_parts_r );
6291
6292
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6293
			// Already pointing at the minified version.
6294
			if ( 'min' === $file_name_parts_r[0] ) {
6295
				return $url;
6296
			}
6297
6298
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6299
			if ( file_exists( $min_full_path ) ) {
6300
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6301
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6302
				if ( 'css' === $extension ) {
6303
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6304
					self::$min_assets[ $key ] = $path;
6305
				}
6306
			}
6307
		}
6308
6309
		return $url;
6310
	}
6311
6312
	/**
6313
	 * If the asset is minified, let's flag .min as the suffix.
6314
	 *
6315
	 * Attached to `style_loader_src` filter.
6316
	 *
6317
	 * @param string $tag The tag that would link to the external asset.
6318
	 * @param string $handle The registered handle of the script in question.
6319
	 * @param string $href The url of the asset in question.
6320
	 */
6321
	public static function set_suffix_on_min( $src, $handle ) {
6322
		if ( false === strpos( $src, '.min.css' ) ) {
6323
			return $src;
6324
		}
6325
6326
		if ( ! empty( self::$min_assets ) ) {
6327
			foreach ( self::$min_assets as $file => $path ) {
6328
				if ( false !== strpos( $src, $file ) ) {
6329
					wp_style_add_data( $handle, 'suffix', '.min' );
6330
					return $src;
6331
				}
6332
			}
6333
		}
6334
6335
		return $src;
6336
	}
6337
6338
	/**
6339
	 * Maybe inlines a stylesheet.
6340
	 *
6341
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6342
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6343
	 *
6344
	 * Attached to `style_loader_tag` filter.
6345
	 *
6346
	 * @param string $tag The tag that would link to the external asset.
6347
	 * @param string $handle The registered handle of the script in question.
6348
	 *
6349
	 * @return string
6350
	 */
6351
	public static function maybe_inline_style( $tag, $handle ) {
6352
		global $wp_styles;
6353
		$item = $wp_styles->registered[ $handle ];
6354
6355
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6356
			return $tag;
6357
		}
6358
6359
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6360
			$href = $matches[1];
6361
			// Strip off query string
6362
			if ( $pos = strpos( $href, '?' ) ) {
6363
				$href = substr( $href, 0, $pos );
6364
			}
6365
			// Strip off fragment
6366
			if ( $pos = strpos( $href, '#' ) ) {
6367
				$href = substr( $href, 0, $pos );
6368
			}
6369
		} else {
6370
			return $tag;
6371
		}
6372
6373
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6374
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6375
			return $tag;
6376
		}
6377
6378
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6379
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6380
			// And this isn't the pass that actually deals with the RTL version...
6381
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6382
				// Short out, as the RTL version will deal with it in a moment.
6383
				return $tag;
6384
			}
6385
		}
6386
6387
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6388
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6389
		if ( $css ) {
6390
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6391
			if ( empty( $item->extra['after'] ) ) {
6392
				wp_add_inline_style( $handle, $css );
6393
			} else {
6394
				array_unshift( $item->extra['after'], $css );
6395
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6396
			}
6397
		}
6398
6399
		return $tag;
6400
	}
6401
6402
	/**
6403
	 * Loads a view file from the views
6404
	 *
6405
	 * Data passed in with the $data parameter will be available in the
6406
	 * template file as $data['value']
6407
	 *
6408
	 * @param string $template - Template file to load
6409
	 * @param array  $data - Any data to pass along to the template
6410
	 * @return boolean - If template file was found
6411
	 **/
6412
	public function load_view( $template, $data = array() ) {
6413
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6414
6415
		if ( file_exists( $views_dir . $template ) ) {
6416
			require_once $views_dir . $template;
6417
			return true;
6418
		}
6419
6420
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6421
		return false;
6422
	}
6423
6424
	/**
6425
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6426
	 */
6427
	public function deprecated_hooks() {
6428
		global $wp_filter;
6429
6430
		/*
6431
		 * Format:
6432
		 * deprecated_filter_name => replacement_name
6433
		 *
6434
		 * If there is no replacement, use null for replacement_name
6435
		 */
6436
		$deprecated_list = array(
6437
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6438
			'wpl_sharing_2014_1'                           => null,
6439
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6440
			'jetpack_identity_crisis_options_to_check'     => null,
6441
			'update_option_jetpack_single_user_site'       => null,
6442
			'audio_player_default_colors'                  => null,
6443
			'add_option_jetpack_featured_images_enabled'   => null,
6444
			'add_option_jetpack_update_details'            => null,
6445
			'add_option_jetpack_updates'                   => null,
6446
			'add_option_jetpack_network_name'              => null,
6447
			'add_option_jetpack_network_allow_new_registrations' => null,
6448
			'add_option_jetpack_network_add_new_users'     => null,
6449
			'add_option_jetpack_network_site_upload_space' => null,
6450
			'add_option_jetpack_network_upload_file_types' => null,
6451
			'add_option_jetpack_network_enable_administration_menus' => null,
6452
			'add_option_jetpack_is_multi_site'             => null,
6453
			'add_option_jetpack_is_main_network'           => null,
6454
			'add_option_jetpack_main_network_site'         => null,
6455
			'jetpack_sync_all_registered_options'          => null,
6456
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6457
			'jetpack_is_post_mailable'                     => null,
6458
			'jetpack_seo_site_host'                        => null,
6459
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6460
			'jetpack_holiday_snow_option_name'             => null,
6461
			'jetpack_holiday_chance_of_snow'               => null,
6462
			'jetpack_holiday_snow_js_url'                  => null,
6463
			'jetpack_is_holiday_snow_season'               => null,
6464
			'jetpack_holiday_snow_option_updated'          => null,
6465
			'jetpack_holiday_snowing'                      => null,
6466
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6467
			'jetpack_cache_plans'                          => null,
6468
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6469
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6470
			'jetpack_enable_site_verification'             => null,
6471
			'can_display_jetpack_manage_notice'            => null,
6472
			// Removed in Jetpack 7.3.0
6473
			'atd_load_scripts'                             => null,
6474
			'atd_http_post_timeout'                        => null,
6475
			'atd_http_post_error'                          => null,
6476
			'atd_service_domain'                           => null,
6477
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6478
			// Removed in Jetpack 7.9.0
6479
			'jetpack_pwa_manifest'                         => null,
6480
			'jetpack_pwa_background_color'                 => null,
6481
			// Removed in Jetpack 8.3.0.
6482
			'jetpack_check_mobile'                         => null,
6483
			'jetpack_mobile_stylesheet'                    => null,
6484
			'jetpack_mobile_template'                      => null,
6485
			'mobile_reject_mobile'                         => null,
6486
			'mobile_force_mobile'                          => null,
6487
			'mobile_app_promo_download'                    => null,
6488
			'mobile_setup'                                 => null,
6489
			'jetpack_mobile_footer_before'                 => null,
6490
			'wp_mobile_theme_footer'                       => null,
6491
			'minileven_credits'                            => null,
6492
			'jetpack_mobile_header_before'                 => null,
6493
			'jetpack_mobile_header_after'                  => null,
6494
			'jetpack_mobile_theme_menu'                    => null,
6495
			'minileven_show_featured_images'               => null,
6496
			'minileven_attachment_size'                    => null,
6497
		);
6498
6499
		// This is a silly loop depth. Better way?
6500
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6501
			if ( has_action( $hook ) ) {
6502
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6503
					foreach ( $values as $hooked ) {
6504
						if ( is_callable( $hooked['function'] ) ) {
6505
							$function_name = 'an anonymous function';
6506
						} else {
6507
							$function_name = $hooked['function'];
6508
						}
6509
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6510
					}
6511
				}
6512
			}
6513
		}
6514
	}
6515
6516
	/**
6517
	 * Converts any url in a stylesheet, to the correct absolute url.
6518
	 *
6519
	 * Considerations:
6520
	 *  - Normal, relative URLs     `feh.png`
6521
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6522
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6523
	 *  - Absolute URLs             `http://domain.com/feh.png`
6524
	 *  - Domain root relative URLs `/feh.png`
6525
	 *
6526
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6527
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6528
	 *
6529
	 * @return mixed|string
6530
	 */
6531
	public static function absolutize_css_urls( $css, $css_file_url ) {
6532
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6533
		$css_dir = dirname( $css_file_url );
6534
		$p       = wp_parse_url( $css_dir );
6535
		$domain  = sprintf(
6536
			'%1$s//%2$s%3$s%4$s',
6537
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6538
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6539
			$p['host'],
6540
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6541
		);
6542
6543
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6544
			$find = $replace = array();
6545
			foreach ( $matches as $match ) {
6546
				$url = trim( $match['path'], "'\" \t" );
6547
6548
				// If this is a data url, we don't want to mess with it.
6549
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6550
					continue;
6551
				}
6552
6553
				// If this is an absolute or protocol-agnostic url,
6554
				// we don't want to mess with it.
6555
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6556
					continue;
6557
				}
6558
6559
				switch ( substr( $url, 0, 1 ) ) {
6560
					case '/':
6561
						$absolute = $domain . $url;
6562
						break;
6563
					default:
6564
						$absolute = $css_dir . '/' . $url;
6565
				}
6566
6567
				$find[]    = $match[0];
6568
				$replace[] = sprintf( 'url("%s")', $absolute );
6569
			}
6570
			$css = str_replace( $find, $replace, $css );
6571
		}
6572
6573
		return $css;
6574
	}
6575
6576
	/**
6577
	 * This methods removes all of the registered css files on the front end
6578
	 * from Jetpack in favor of using a single file. In effect "imploding"
6579
	 * all the files into one file.
6580
	 *
6581
	 * Pros:
6582
	 * - Uses only ONE css asset connection instead of 15
6583
	 * - Saves a minimum of 56k
6584
	 * - Reduces server load
6585
	 * - Reduces time to first painted byte
6586
	 *
6587
	 * Cons:
6588
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6589
	 *      should not cause any issues with themes.
6590
	 * - Plugins/themes dequeuing styles no longer do anything. See
6591
	 *      jetpack_implode_frontend_css filter for a workaround
6592
	 *
6593
	 * For some situations developers may wish to disable css imploding and
6594
	 * instead operate in legacy mode where each file loads seperately and
6595
	 * can be edited individually or dequeued. This can be accomplished with
6596
	 * the following line:
6597
	 *
6598
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6599
	 *
6600
	 * @since 3.2
6601
	 **/
6602
	public function implode_frontend_css( $travis_test = false ) {
6603
		$do_implode = true;
6604
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6605
			$do_implode = false;
6606
		}
6607
6608
		// Do not implode CSS when the page loads via the AMP plugin.
6609
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6610
			$do_implode = false;
6611
		}
6612
6613
		/**
6614
		 * Allow CSS to be concatenated into a single jetpack.css file.
6615
		 *
6616
		 * @since 3.2.0
6617
		 *
6618
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6619
		 */
6620
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6621
6622
		// Do not use the imploded file when default behavior was altered through the filter
6623
		if ( ! $do_implode ) {
6624
			return;
6625
		}
6626
6627
		// We do not want to use the imploded file in dev mode, or if not connected
6628
		if ( ( new Status() )->is_development_mode() || ! self::is_active() ) {
6629
			if ( ! $travis_test ) {
6630
				return;
6631
			}
6632
		}
6633
6634
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6635
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6636
			return;
6637
		}
6638
6639
		/*
6640
		 * Now we assume Jetpack is connected and able to serve the single
6641
		 * file.
6642
		 *
6643
		 * In the future there will be a check here to serve the file locally
6644
		 * or potentially from the Jetpack CDN
6645
		 *
6646
		 * For now:
6647
		 * - Enqueue a single imploded css file
6648
		 * - Zero out the style_loader_tag for the bundled ones
6649
		 * - Be happy, drink scotch
6650
		 */
6651
6652
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6653
6654
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6655
6656
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6657
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6658
	}
6659
6660
	function concat_remove_style_loader_tag( $tag, $handle ) {
6661
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6662
			$tag = '';
6663
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6664
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6665
			}
6666
		}
6667
6668
		return $tag;
6669
	}
6670
6671
	/**
6672
	 * Add an async attribute to scripts that can be loaded asynchronously.
6673
	 * https://www.w3schools.com/tags/att_script_async.asp
6674
	 *
6675
	 * @since 7.7.0
6676
	 *
6677
	 * @param string $tag    The <script> tag for the enqueued script.
6678
	 * @param string $handle The script's registered handle.
6679
	 * @param string $src    The script's source URL.
6680
	 */
6681
	public function script_add_async( $tag, $handle, $src ) {
6682
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6683
			return preg_replace( '/^<script /i', '<script async ', $tag );
6684
		}
6685
6686
		return $tag;
6687
	}
6688
6689
	/*
6690
	 * Check the heartbeat data
6691
	 *
6692
	 * Organizes the heartbeat data by severity.  For example, if the site
6693
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6694
	 *
6695
	 * Data will be added to "caution" array, if it either:
6696
	 *  - Out of date Jetpack version
6697
	 *  - Out of date WP version
6698
	 *  - Out of date PHP version
6699
	 *
6700
	 * $return array $filtered_data
6701
	 */
6702
	public static function jetpack_check_heartbeat_data() {
6703
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6704
6705
		$good    = array();
6706
		$caution = array();
6707
		$bad     = array();
6708
6709
		foreach ( $raw_data as $stat => $value ) {
6710
6711
			// Check jetpack version
6712
			if ( 'version' == $stat ) {
6713
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6714
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6715
					continue;
6716
				}
6717
			}
6718
6719
			// Check WP version
6720
			if ( 'wp-version' == $stat ) {
6721
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6722
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6723
					continue;
6724
				}
6725
			}
6726
6727
			// Check PHP version
6728
			if ( 'php-version' == $stat ) {
6729
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6730
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_PHP_VERSION;
6731
					continue;
6732
				}
6733
			}
6734
6735
			// Check ID crisis
6736
			if ( 'identitycrisis' == $stat ) {
6737
				if ( 'yes' == $value ) {
6738
					$bad[ $stat ] = $value;
6739
					continue;
6740
				}
6741
			}
6742
6743
			// The rest are good :)
6744
			$good[ $stat ] = $value;
6745
		}
6746
6747
		$filtered_data = array(
6748
			'good'    => $good,
6749
			'caution' => $caution,
6750
			'bad'     => $bad,
6751
		);
6752
6753
		return $filtered_data;
6754
	}
6755
6756
6757
	/*
6758
	 * This method is used to organize all options that can be reset
6759
	 * without disconnecting Jetpack.
6760
	 *
6761
	 * It is used in class.jetpack-cli.php to reset options
6762
	 *
6763
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6764
	 *
6765
	 * @return array of options to delete.
6766
	 */
6767
	public static function get_jetpack_options_for_reset() {
6768
		return Jetpack_Options::get_options_for_reset();
6769
	}
6770
6771
	/*
6772
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6773
	 * so we can bring them directly to their site in calypso.
6774
	 *
6775
	 * @param string | url
6776
	 * @return string | url without the guff
6777
	 */
6778
	public static function build_raw_urls( $url ) {
6779
		$strip_http = '/.*?:\/\//i';
6780
		$url        = preg_replace( $strip_http, '', $url );
6781
		$url        = str_replace( '/', '::', $url );
6782
		return $url;
6783
	}
6784
6785
	/**
6786
	 * Stores and prints out domains to prefetch for page speed optimization.
6787
	 *
6788
	 * @param mixed $new_urls
6789
	 */
6790
	public static function dns_prefetch( $new_urls = null ) {
6791
		static $prefetch_urls = array();
6792
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6793
			echo "\r\n";
6794
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6795
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6796
			}
6797
		} elseif ( ! empty( $new_urls ) ) {
6798
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6799
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6800
			}
6801
			foreach ( (array) $new_urls as $this_new_url ) {
6802
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6803
			}
6804
			$prefetch_urls = array_unique( $prefetch_urls );
6805
		}
6806
	}
6807
6808
	public function wp_dashboard_setup() {
6809
		if ( self::is_active() ) {
6810
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6811
		}
6812
6813
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6814
			$jetpack_logo = new Jetpack_Logo();
6815
			$widget_title = sprintf(
6816
				wp_kses(
6817
					/* translators: Placeholder is a Jetpack logo. */
6818
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6819
					array( 'span' => array() )
6820
				),
6821
				$jetpack_logo->get_jp_emblem( true )
6822
			);
6823
6824
			wp_add_dashboard_widget(
6825
				'jetpack_summary_widget',
6826
				$widget_title,
6827
				array( __CLASS__, 'dashboard_widget' )
6828
			);
6829
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6830
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6831
6832
			// If we're inactive and not in development mode, sort our box to the top.
6833
			if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
6834
				global $wp_meta_boxes;
6835
6836
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6837
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6838
6839
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6840
			}
6841
		}
6842
	}
6843
6844
	/**
6845
	 * @param mixed $result Value for the user's option
6846
	 * @return mixed
6847
	 */
6848
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6849
		if ( ! is_array( $sorted ) ) {
6850
			return $sorted;
6851
		}
6852
6853
		foreach ( $sorted as $box_context => $ids ) {
6854
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6855
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6856
				continue;
6857
			}
6858
6859
			$ids_array = explode( ',', $ids );
6860
			$key       = array_search( 'dashboard_stats', $ids_array );
6861
6862
			if ( false !== $key ) {
6863
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6864
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6865
				$sorted[ $box_context ] = implode( ',', $ids_array );
6866
				// We've found it, stop searching, and just return.
6867
				break;
6868
			}
6869
		}
6870
6871
		return $sorted;
6872
	}
6873
6874
	public static function dashboard_widget() {
6875
		/**
6876
		 * Fires when the dashboard is loaded.
6877
		 *
6878
		 * @since 3.4.0
6879
		 */
6880
		do_action( 'jetpack_dashboard_widget' );
6881
	}
6882
6883
	public static function dashboard_widget_footer() {
6884
		?>
6885
		<footer>
6886
6887
		<div class="protect">
6888
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6889
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6890
				<p class="blocked-count">
6891
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6892
				</p>
6893
				<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>
6894
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
6895
				<a href="
6896
				<?php
6897
				echo esc_url(
6898
					wp_nonce_url(
6899
						self::admin_url(
6900
							array(
6901
								'action' => 'activate',
6902
								'module' => 'protect',
6903
							)
6904
						),
6905
						'jetpack_activate-protect'
6906
					)
6907
				);
6908
				?>
6909
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6910
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
6911
				</a>
6912
			<?php else : ?>
6913
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
6914
			<?php endif; ?>
6915
		</div>
6916
6917
		<div class="akismet">
6918
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
6919
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6920
				<p class="blocked-count">
6921
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
6922
				</p>
6923
				<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>
6924
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6925
				<a href="
6926
				<?php
6927
				echo esc_url(
6928
					wp_nonce_url(
6929
						add_query_arg(
6930
							array(
6931
								'action' => 'activate',
6932
								'plugin' => 'akismet/akismet.php',
6933
							),
6934
							admin_url( 'plugins.php' )
6935
						),
6936
						'activate-plugin_akismet/akismet.php'
6937
					)
6938
				);
6939
				?>
6940
							" class="button button-jetpack">
6941
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
6942
				</a>
6943
			<?php else : ?>
6944
				<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>
6945
			<?php endif; ?>
6946
		</div>
6947
6948
		</footer>
6949
		<?php
6950
	}
6951
6952
	/*
6953
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6954
	 */
6955
	function jetpack_icon_user_connected( $columns ) {
6956
		$columns['user_jetpack'] = '';
6957
		return $columns;
6958
	}
6959
6960
	/*
6961
	 * Show Jetpack icon if the user is linked.
6962
	 */
6963
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6964
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
6965
			$jetpack_logo = new Jetpack_Logo();
6966
			$emblem_html  = sprintf(
6967
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6968
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6969
				$jetpack_logo->get_jp_emblem()
6970
			);
6971
			return $emblem_html;
6972
		}
6973
6974
		return $val;
6975
	}
6976
6977
	/*
6978
	 * Style the Jetpack user column
6979
	 */
6980
	function jetpack_user_col_style() {
6981
		global $current_screen;
6982
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
6983
			?>
6984
			<style>
6985
				.fixed .column-user_jetpack {
6986
					width: 21px;
6987
				}
6988
				.jp-emblem-user-admin svg {
6989
					width: 20px;
6990
					height: 20px;
6991
				}
6992
				.jp-emblem-user-admin path {
6993
					fill: #00BE28;
6994
				}
6995
			</style>
6996
			<?php
6997
		}
6998
	}
6999
7000
	/**
7001
	 * Checks if Akismet is active and working.
7002
	 *
7003
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7004
	 * that implied usage of methods present since more recent version.
7005
	 * See https://github.com/Automattic/jetpack/pull/9585
7006
	 *
7007
	 * @since  5.1.0
7008
	 *
7009
	 * @return bool True = Akismet available. False = Aksimet not available.
7010
	 */
7011
	public static function is_akismet_active() {
7012
		static $status = null;
7013
7014
		if ( ! is_null( $status ) ) {
7015
			return $status;
7016
		}
7017
7018
		// Check if a modern version of Akismet is active.
7019
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7020
			$status = false;
7021
			return $status;
7022
		}
7023
7024
		// Make sure there is a key known to Akismet at all before verifying key.
7025
		$akismet_key = Akismet::get_api_key();
7026
		if ( ! $akismet_key ) {
7027
			$status = false;
7028
			return $status;
7029
		}
7030
7031
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7032
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7033
7034
		// 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.
7035
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7036
		// We cache the result of the Akismet key verification for ten minutes.
7037
		if ( ! $akismet_key_state || $recheck ) {
7038
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7039
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7040
		}
7041
7042
		$status = 'valid' === $akismet_key_state;
7043
7044
		return $status;
7045
	}
7046
7047
	/**
7048
	 * @deprecated
7049
	 *
7050
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7051
	 */
7052
	public static function is_function_in_backtrace() {
7053
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7054
	}
7055
7056
	/**
7057
	 * Given a minified path, and a non-minified path, will return
7058
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7059
	 *
7060
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7061
	 * root Jetpack directory.
7062
	 *
7063
	 * @since 5.6.0
7064
	 *
7065
	 * @param string $min_path
7066
	 * @param string $non_min_path
7067
	 * @return string The URL to the file
7068
	 */
7069
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7070
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7071
	}
7072
7073
	/**
7074
	 * Checks for whether Jetpack Backup & Scan is enabled.
7075
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
7076
	 *
7077
	 * @return bool|int|mixed
7078
	 */
7079
	public static function is_rewind_enabled() {
7080
		if ( ! self::is_active() ) {
7081
			return false;
7082
		}
7083
7084
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7085
		if ( false === $rewind_enabled ) {
7086
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7087
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7088
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7089
				&& ! empty( $rewind_data['state'] )
7090
				&& 'active' === $rewind_data['state'] )
7091
				? 1
7092
				: 0;
7093
7094
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7095
		}
7096
		return $rewind_enabled;
7097
	}
7098
7099
	/**
7100
	 * Return Calypso environment value; used for developing Jetpack and pairing
7101
	 * it with different Calypso enrionments, such as localhost.
7102
	 *
7103
	 * @since 7.4.0
7104
	 *
7105
	 * @return string Calypso environment
7106
	 */
7107
	public static function get_calypso_env() {
7108
		if ( isset( $_GET['calypso_env'] ) ) {
7109
			return sanitize_key( $_GET['calypso_env'] );
7110
		}
7111
7112
		if ( getenv( 'CALYPSO_ENV' ) ) {
7113
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7114
		}
7115
7116
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7117
			return sanitize_key( CALYPSO_ENV );
7118
		}
7119
7120
		return '';
7121
	}
7122
7123
	/**
7124
	 * Checks whether or not TOS has been agreed upon.
7125
	 * Will return true if a user has clicked to register, or is already connected.
7126
	 */
7127
	public static function jetpack_tos_agreed() {
7128
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7129
7130
		$terms_of_service = new Terms_Of_Service();
7131
		return $terms_of_service->has_agreed();
7132
7133
	}
7134
7135
	/**
7136
	 * Handles activating default modules as well general cleanup for the new connection.
7137
	 *
7138
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7139
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7140
	 * @param boolean $send_state_messages          Whether to send state messages.
7141
	 * @return void
7142
	 */
7143
	public static function handle_post_authorization_actions(
7144
		$activate_sso = false,
7145
		$redirect_on_activation_error = false,
7146
		$send_state_messages = true
7147
	) {
7148
		$other_modules = $activate_sso
7149
			? array( 'sso' )
7150
			: array();
7151
7152
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7153
			self::delete_active_modules();
7154
7155
			self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
7156
		} else {
7157
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7158
		}
7159
7160
		// Since this is a fresh connection, be sure to clear out IDC options
7161
		Jetpack_IDC::clear_all_idc_options();
7162
7163
		if ( $send_state_messages ) {
7164
			self::state( 'message', 'authorized' );
7165
		}
7166
	}
7167
7168
	/**
7169
	 * Returns a boolean for whether backups UI should be displayed or not.
7170
	 *
7171
	 * @return bool Should backups UI be displayed?
7172
	 */
7173
	public static function show_backups_ui() {
7174
		/**
7175
		 * Whether UI for backups should be displayed.
7176
		 *
7177
		 * @since 6.5.0
7178
		 *
7179
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7180
		 */
7181
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7182
	}
7183
7184
	/*
7185
	 * Deprecated manage functions
7186
	 */
7187
	function prepare_manage_jetpack_notice() {
7188
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7189
	}
7190
	function manage_activate_screen() {
7191
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7192
	}
7193
	function admin_jetpack_manage_notice() {
7194
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7195
	}
7196
	function opt_out_jetpack_manage_url() {
7197
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7198
	}
7199
	function opt_in_jetpack_manage_url() {
7200
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7201
	}
7202
	function opt_in_jetpack_manage_notice() {
7203
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7204
	}
7205
	function can_display_jetpack_manage_notice() {
7206
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7207
	}
7208
7209
	/**
7210
	 * Clean leftoveruser meta.
7211
	 *
7212
	 * Delete Jetpack-related user meta when it is no longer needed.
7213
	 *
7214
	 * @since 7.3.0
7215
	 *
7216
	 * @param int $user_id User ID being updated.
7217
	 */
7218
	public static function user_meta_cleanup( $user_id ) {
7219
		$meta_keys = array(
7220
			// AtD removed from Jetpack 7.3
7221
			'AtD_options',
7222
			'AtD_check_when',
7223
			'AtD_guess_lang',
7224
			'AtD_ignored_phrases',
7225
		);
7226
7227
		foreach ( $meta_keys as $meta_key ) {
7228
			if ( get_user_meta( $user_id, $meta_key ) ) {
7229
				delete_user_meta( $user_id, $meta_key );
7230
			}
7231
		}
7232
	}
7233
7234
	/**
7235
	 * Checks if a Jetpack site is both active and not in development.
7236
	 *
7237
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7238
	 *
7239
	 * @return bool True if Jetpack is active and not in development.
7240
	 */
7241
	public static function is_active_and_not_development_mode() {
7242
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7243
			return false;
7244
		}
7245
		return true;
7246
	}
7247
}
7248