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