Completed
Push — fix/sync-empty-errors ( 53827c...ec13f3 )
by
unknown
89:12 queued 80:44
created

class.jetpack.php (1 issue)

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

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

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