Completed
Push — fusion-sync/sergiomdgomes/r217... ( 6d8cea...0e26fe )
by
unknown
15:51 queued 07:02
created

class.jetpack.php (1 issue)

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\Plugin_Storage as Connection_Plugin_Storage;
8
use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
9
use Automattic\Jetpack\Connection\Utils as Connection_Utils;
10
use Automattic\Jetpack\Constants;
11
use Automattic\Jetpack\Device_Detection\User_Agent_Info;
12
use Automattic\Jetpack\Licensing;
13
use Automattic\Jetpack\Partner;
14
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
15
use Automattic\Jetpack\Redirect;
16
use Automattic\Jetpack\Roles;
17
use Automattic\Jetpack\Status;
18
use Automattic\Jetpack\Sync\Functions;
19
use Automattic\Jetpack\Sync\Health;
20
use Automattic\Jetpack\Sync\Sender;
21
use Automattic\Jetpack\Sync\Users;
22
use Automattic\Jetpack\Terms_Of_Service;
23
use Automattic\Jetpack\Tracking;
24
25
/*
26
Options:
27
jetpack_options (array)
28
	An array of options.
29
	@see Jetpack_Options::get_option_names()
30
31
jetpack_register (string)
32
	Temporary verification secrets.
33
34
jetpack_activated (int)
35
	1: the plugin was activated normally
36
	2: the plugin was activated on this site because of a network-wide activation
37
	3: the plugin was auto-installed
38
	4: the plugin was manually disconnected (but is still installed)
39
40
jetpack_active_modules (array)
41
	Array of active module slugs.
42
43
jetpack_do_activate (bool)
44
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
45
*/
46
47
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
48
49
class Jetpack {
50
	public $xmlrpc_server = null;
51
52
	/**
53
	 * @var array The handles of styles that are concatenated into jetpack.css.
54
	 *
55
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
56
	 */
57
	public $concatenated_style_handles = array(
58
		'jetpack-carousel',
59
		'grunion.css',
60
		'the-neverending-homepage',
61
		'jetpack_likes',
62
		'jetpack_related-posts',
63
		'sharedaddy',
64
		'jetpack-slideshow',
65
		'presentations',
66
		'quiz',
67
		'jetpack-subscriptions',
68
		'jetpack-responsive-videos-style',
69
		'jetpack-social-menu',
70
		'tiled-gallery',
71
		'jetpack_display_posts_widget',
72
		'gravatar-profile-widget',
73
		'goodreads-widget',
74
		'jetpack_social_media_icons_widget',
75
		'jetpack-top-posts-widget',
76
		'jetpack_image_widget',
77
		'jetpack-my-community-widget',
78
		'jetpack-authors-widget',
79
		'wordads',
80
		'eu-cookie-law-style',
81
		'flickr-widget-style',
82
		'jetpack-search-widget',
83
		'jetpack-simple-payments-widget-style',
84
		'jetpack-widget-social-icons-styles',
85
		'wpcom_instagram_widget',
86
	);
87
88
	/**
89
	 * Contains all assets that have had their URL rewritten to minified versions.
90
	 *
91
	 * @var array
92
	 */
93
	static $min_assets = array();
94
95
	public $plugins_to_deactivate = array(
96
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
97
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
98
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
99
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
100
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
101
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
102
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
103
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
104
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
105
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
106
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
107
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
108
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
109
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
110
	);
111
112
	/**
113
	 * Map of roles we care about, and their corresponding minimum capabilities.
114
	 *
115
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
116
	 *
117
	 * @access public
118
	 * @static
119
	 *
120
	 * @var array
121
	 */
122
	public static $capability_translations = array(
123
		'administrator' => 'manage_options',
124
		'editor'        => 'edit_others_posts',
125
		'author'        => 'publish_posts',
126
		'contributor'   => 'edit_posts',
127
		'subscriber'    => 'read',
128
	);
129
130
	/**
131
	 * Map of modules that have conflicts with plugins and should not be auto-activated
132
	 * if the plugins are active.  Used by filter_default_modules
133
	 *
134
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
135
	 * change `module-slug` and add this to your plugin:
136
	 *
137
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
138
	 * function my_jetpack_get_default_modules( $modules ) {
139
	 *     return array_diff( $modules, array( 'module-slug' ) );
140
	 * }
141
	 *
142
	 * @var array
143
	 */
144
	private $conflicting_plugins = array(
145
		'comments'           => array(
146
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
147
			'Disqus'                         => 'disqus-comment-system/disqus.php',
148
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
149
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
150
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
151
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
152
		),
153
		'comment-likes'      => array(
154
			'Epoch' => 'epoch/plugincore.php',
155
		),
156
		'contact-form'       => array(
157
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
158
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
159
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
160
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
161
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
162
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
163
		),
164
		'latex'              => array(
165
			'LaTeX for WordPress'     => 'latex/latex.php',
166
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
167
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
168
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
169
			'Enable Latex'            => 'enable-latex/enable-latex.php',
170
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
171
		),
172
		'protect'            => array(
173
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
174
			'Captcha'                           => 'captcha/captcha.php',
175
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
176
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
177
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
178
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
179
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
180
			'Security-protection'               => 'security-protection/security-protection.php',
181
			'Login Security'                    => 'login-security/login-security.php',
182
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
183
			'Wordfence Security'                => 'wordfence/wordfence.php',
184
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
185
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
186
		),
187
		'random-redirect'    => array(
188
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
189
		),
190
		'related-posts'      => array(
191
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
192
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
193
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
194
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
195
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
196
			'outbrain'                    => 'outbrain/outbrain.php',
197
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
198
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
199
		),
200
		'sharedaddy'         => array(
201
			'AddThis'     => 'addthis/addthis_social_widget.php',
202
			'Add To Any'  => 'add-to-any/add-to-any.php',
203
			'ShareThis'   => 'share-this/sharethis.php',
204
			'Shareaholic' => 'shareaholic/shareaholic.php',
205
		),
206
		'seo-tools'          => array(
207
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
208
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
209
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
210
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
211
			'The SEO Framework'              => 'autodescription/autodescription.php',
212
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
213
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
214
		),
215
		'verification-tools' => array(
216
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
217
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
218
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
219
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
220
			'The SEO Framework'              => 'autodescription/autodescription.php',
221
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
222
			'Slim SEO'                       => 'slim-seo/slim-seo.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
			'Slim SEO'                             => 'slim-seo/slim-seo.php',
246
		),
247
		'lazy-images'        => array(
248
			'Lazy Load'              => 'lazy-load/lazy-load.php',
249
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
250
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
251
		),
252
	);
253
254
	/**
255
	 * Plugins for which we turn off our Facebook OG Tags implementation.
256
	 *
257
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
258
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
259
	 *
260
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
261
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
262
	 */
263
	private $open_graph_conflicting_plugins = array(
264
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
265
		// 2 Click Social Media Buttons
266
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
267
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
268
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
269
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
270
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
271
		// Open Graph Meta Tags by Heateor
272
		'facebook/facebook.php',                                 // Facebook (official plugin)
273
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
274
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
275
		// Facebook Featured Image & OG Meta Tags
276
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
277
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
278
		// Facebook Open Graph Meta Tags for WordPress
279
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
280
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
281
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
282
		// Fedmich's Facebook Open Graph Meta
283
		'network-publisher/networkpub.php',                      // Network Publisher
284
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
285
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
286
		// NextScripts SNAP
287
		'og-tags/og-tags.php',                                   // OG Tags
288
		'opengraph/opengraph.php',                               // Open Graph
289
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
290
		// Open Graph Protocol Framework
291
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
292
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
293
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
294
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
295
		'sharepress/sharepress.php',                             // SharePress
296
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
297
		'social-discussions/social-discussions.php',             // Social Discussions
298
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
299
		'socialize/socialize.php',                               // Socialize
300
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
301
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
302
		// Tweet, Like, Google +1 and Share
303
		'wordbooker/wordbooker.php',                             // Wordbooker
304
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
305
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
306
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
307
		// WP Facebook Like Send & Open Graph Meta
308
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
309
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
310
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
311
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
312
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
313
		'seo-by-rank-math/rank-math.php',                        // Rank Math.
314
		'slim-seo/slim-seo.php',                                 // Slim SEO
315
	);
316
317
	/**
318
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
319
	 */
320
	private $twitter_cards_conflicting_plugins = array(
321
		// 'twitter/twitter.php',                       // The official one handles this on its own.
322
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
323
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
324
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
325
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
326
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
327
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
328
		'twitter-cards/twitter-cards.php',           // Twitter Cards
329
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
330
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
331
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
332
		'seo-by-rank-math/rank-math.php',            // Rank Math.
333
		'slim-seo/slim-seo.php',                     // Slim SEO
334
	);
335
336
	/**
337
	 * Message to display in admin_notice
338
	 *
339
	 * @var string
340
	 */
341
	public $message = '';
342
343
	/**
344
	 * Error to display in admin_notice
345
	 *
346
	 * @var string
347
	 */
348
	public $error = '';
349
350
	/**
351
	 * Modules that need more privacy description.
352
	 *
353
	 * @var string
354
	 */
355
	public $privacy_checks = '';
356
357
	/**
358
	 * Stats to record once the page loads
359
	 *
360
	 * @var array
361
	 */
362
	public $stats = array();
363
364
	/**
365
	 * Jetpack_Sync object
366
	 */
367
	public $sync;
368
369
	/**
370
	 * Verified data for JSON authorization request
371
	 */
372
	public $json_api_authorization_request = array();
373
374
	/**
375
	 * @var Automattic\Jetpack\Connection\Manager
376
	 */
377
	protected $connection_manager;
378
379
	/**
380
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
381
	 */
382
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
383
384
	/**
385
	 * Holds an instance of Automattic\Jetpack\A8c_Mc_Stats
386
	 *
387
	 * @var Automattic\Jetpack\A8c_Mc_Stats
388
	 */
389
	public $a8c_mc_stats_instance;
390
391
	/**
392
	 * Constant for login redirect key.
393
	 *
394
	 * @var string
395
	 * @since 8.4.0
396
	 */
397
	public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
398
399
	/**
400
	 * Holds the singleton instance of this class
401
	 *
402
	 * @since 2.3.3
403
	 * @var Jetpack
404
	 */
405
	static $instance = false;
406
407
	/**
408
	 * Singleton
409
	 *
410
	 * @static
411
	 */
412
	public static function init() {
413
		if ( ! self::$instance ) {
414
			self::$instance = new Jetpack();
415
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
416
		}
417
418
		return self::$instance;
419
	}
420
421
	/**
422
	 * Must never be called statically
423
	 */
424
	function plugin_upgrade() {
425
		if ( self::is_active() ) {
426
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
427
			if ( JETPACK__VERSION != $version ) {
428
				// Prevent multiple upgrades at once - only a single process should trigger
429
				// an upgrade to avoid stampedes
430
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
431
					return;
432
				}
433
434
				// Set a short lock to prevent multiple instances of the upgrade
435
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
436
437
				// check which active modules actually exist and remove others from active_modules list
438
				$unfiltered_modules = self::get_active_modules();
439
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
440
				if ( array_diff( $unfiltered_modules, $modules ) ) {
441
					self::update_active_modules( $modules );
442
				}
443
444
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
445
446
				// Upgrade to 4.3.0
447
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
448
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
449
				}
450
451
				// Make sure Markdown for posts gets turned back on
452
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
453
					update_option( 'wpcom_publish_posts_with_markdown', true );
454
				}
455
456
				/*
457
				 * Minileven deprecation. 8.3.0.
458
				 * Only delete options if not using
459
				 * the replacement standalone Minileven plugin.
460
				 */
461
				if (
462
					! self::is_plugin_active( 'minileven-master/minileven.php' )
463
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
464
				) {
465
					if ( get_option( 'wp_mobile_custom_css' ) ) {
466
						delete_option( 'wp_mobile_custom_css' );
467
					}
468
					if ( get_option( 'wp_mobile_excerpt' ) ) {
469
						delete_option( 'wp_mobile_excerpt' );
470
					}
471
					if ( get_option( 'wp_mobile_featured_images' ) ) {
472
						delete_option( 'wp_mobile_featured_images' );
473
					}
474
					if ( get_option( 'wp_mobile_app_promos' ) ) {
475
						delete_option( 'wp_mobile_app_promos' );
476
					}
477
				}
478
479
				// Upgrade to 8.4.0.
480
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
481
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
482
				}
483
484
				// Update to 8.8.x (WordPress 5.5 Compatibility).
485
				if ( Jetpack_Options::get_option( 'autoupdate_plugins' ) ) {
486
					$updated = update_site_option(
487
						'auto_update_plugins',
488
						array_unique(
489
							array_merge(
490
								(array) Jetpack_Options::get_option( 'autoupdate_plugins', array() ),
491
								(array) get_site_option( 'auto_update_plugins', array() )
492
							)
493
						)
494
					);
495
496
					if ( $updated ) {
497
						Jetpack_Options::delete_option( 'autoupdate_plugins' );
498
					} // Should we have some type of fallback if something fails here?
499
				}
500
501
				if ( did_action( 'wp_loaded' ) ) {
502
					self::upgrade_on_load();
503
				} else {
504
					add_action(
505
						'wp_loaded',
506
						array( __CLASS__, 'upgrade_on_load' )
507
					);
508
				}
509
			}
510
		}
511
	}
512
513
	/**
514
	 * Runs upgrade routines that need to have modules loaded.
515
	 */
516
	static function upgrade_on_load() {
517
518
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
519
		// This can happen in case Jetpack has been just upgraded and is
520
		// being initialized late during the page load. In this case we wait
521
		// until the next proper admin page load with Jetpack active.
522
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
523
			delete_transient( self::$plugin_upgrade_lock_key );
524
525
			return;
526
		}
527
528
		self::maybe_set_version_option();
529
530
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
531
			Jetpack_Widget_Conditions::migrate_post_type_rules();
532
		}
533
534
		if (
535
			class_exists( 'Jetpack_Sitemap_Manager' )
536
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
537
		) {
538
			do_action( 'jetpack_sitemaps_purge_data' );
539
		}
540
541
		// Delete old stats cache
542
		delete_option( 'jetpack_restapi_stats_cache' );
543
544
		delete_transient( self::$plugin_upgrade_lock_key );
545
	}
546
547
	/**
548
	 * Saves all the currently active modules to options.
549
	 * Also fires Action hooks for each newly activated and deactivated module.
550
	 *
551
	 * @param $modules Array Array of active modules to be saved in options.
552
	 *
553
	 * @return $success bool true for success, false for failure.
554
	 */
555
	static function update_active_modules( $modules ) {
556
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
557
		$active_modules       = self::get_active_modules();
558
		$new_active_modules   = array_diff( $modules, $current_modules );
559
		$new_inactive_modules = array_diff( $active_modules, $modules );
560
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
561
		$reindexed_modules    = array_values( $new_current_modules );
562
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
563
564
		foreach ( $new_active_modules as $module ) {
565
			/**
566
			 * Fires when a specific module is activated.
567
			 *
568
			 * @since 1.9.0
569
			 *
570
			 * @param string $module Module slug.
571
			 * @param boolean $success whether the module was activated. @since 4.2
572
			 */
573
			do_action( 'jetpack_activate_module', $module, $success );
574
			/**
575
			 * Fires when a module is activated.
576
			 * The dynamic part of the filter, $module, is the module slug.
577
			 *
578
			 * @since 1.9.0
579
			 *
580
			 * @param string $module Module slug.
581
			 */
582
			do_action( "jetpack_activate_module_$module", $module );
583
		}
584
585
		foreach ( $new_inactive_modules as $module ) {
586
			/**
587
			 * Fired after a module has been deactivated.
588
			 *
589
			 * @since 4.2.0
590
			 *
591
			 * @param string $module Module slug.
592
			 * @param boolean $success whether the module was deactivated.
593
			 */
594
			do_action( 'jetpack_deactivate_module', $module, $success );
595
			/**
596
			 * Fires when a module is deactivated.
597
			 * The dynamic part of the filter, $module, is the module slug.
598
			 *
599
			 * @since 1.9.0
600
			 *
601
			 * @param string $module Module slug.
602
			 */
603
			do_action( "jetpack_deactivate_module_$module", $module );
604
		}
605
606
		return $success;
607
	}
608
609
	static function delete_active_modules() {
610
		self::update_active_modules( array() );
611
	}
612
613
	/**
614
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
615
	 * available.
616
	 */
617
	public function add_configure_hook() {
618
		global $wp_filter;
619
620
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
621
		if ( false !== $current_priority ) {
622
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
623
		}
624
625
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
626
		sort( $taken_priorities );
627
628
		$first_priority = array_shift( $taken_priorities );
629
630
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
631
			$new_priority = - PHP_INT_MAX;
632
		} else {
633
			$new_priority = $first_priority - 1;
634
		}
635
636
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
637
	}
638
639
	/**
640
	 * Constructor.  Initializes WordPress hooks
641
	 */
642
	private function __construct() {
643
		/*
644
		 * Check for and alert any deprecated hooks
645
		 */
646
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
647
648
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
649
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
650
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
651
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
652
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
653
654
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
655
656
		add_filter(
657
			'jetpack_signature_check_token',
658
			array( __CLASS__, 'verify_onboarding_token' ),
659
			10,
660
			3
661
		);
662
663
		/**
664
		 * Prepare Gutenberg Editor functionality
665
		 */
666
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
667
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
668
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
669
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_extended_blocks' ), 9 );
670
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
671
672
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
673
674
		// Unlink user before deleting the user from WP.com.
675
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
676
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
677
678
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
679
680
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
681
		add_action( 'login_init', array( $this, 'login_init' ) );
682
683
		// Set up the REST authentication hooks.
684
		Connection_Rest_Authentication::init();
685
686
		add_action( 'admin_init', array( $this, 'admin_init' ) );
687
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
688
689
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
690
691
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
692
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
693
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
694
695
		// returns HTTPS support status
696
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
697
698
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
699
700
		add_action( 'wp_ajax_jetpack_wizard_banner', array( 'Jetpack_Wizard_Banner', 'ajax_callback' ) );
701
702
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
703
704
		/**
705
		 * These actions run checks to load additional files.
706
		 * They check for external files or plugins, so they need to run as late as possible.
707
		 */
708
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
709
		add_action( 'web_stories_story_head', array( $this, 'check_open_graph' ), 1 );
710
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
711
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
712
713
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
714
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
715
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
716
717
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
718
719
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
720
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
721
722
		// A filter to control all just in time messages
723
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
724
725
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
726
727
		/*
728
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
729
		 * We should make sure to only do this for front end links.
730
		 */
731
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
732
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
733
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
734
735
			/*
736
			 * We'll shortcircuit wp_notify_postauthor and wp_notify_moderator pluggable functions
737
			 * so they point moderation links on emails to Calypso.
738
			 */
739
			jetpack_require_lib( 'functions.wp-notify' );
740
			add_filter( 'comment_notification_recipients', 'jetpack_notify_postauthor', 1, 2 );
741
			add_filter( 'notify_moderator', 'jetpack_notify_moderator', 1, 2 );
742
		}
743
744
		add_action(
745
			'plugins_loaded',
746
			function () {
747
				if ( User_Agent_Info::is_mobile_app() ) {
748
					add_filter( 'get_edit_post_link', '__return_empty_string' );
749
				}
750
			}
751
		);
752
753
		// Update the site's Jetpack plan and products from API on heartbeats.
754
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
755
756
		/**
757
		 * This is the hack to concatenate all css files into one.
758
		 * For description and reasoning see the implode_frontend_css method.
759
		 *
760
		 * Super late priority so we catch all the registered styles.
761
		 */
762
		if ( ! is_admin() ) {
763
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
764
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
765
		}
766
767
		/**
768
		 * These are sync actions that we need to keep track of for jitms
769
		 */
770
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
771
772
		// Actually push the stats on shutdown.
773
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
774
			add_action( 'shutdown', array( $this, 'push_stats' ) );
775
		}
776
777
		// Actions for Manager::authorize().
778
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
779
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
780
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
781
782
		// Filters for the Manager::get_token() urls and request body.
783
		add_filter( 'jetpack_token_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
784
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
785
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
786
787
		// Actions for successful reconnect.
788
		add_action( 'jetpack_reconnection_completed', array( $this, 'reconnection_completed' ) );
789
790
		// Actions for licensing.
791
		Licensing::instance()->initialize();
792
	}
793
794
	/**
795
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
796
	 * Config object.
797
	 */
798
	public function configure() {
799
		$config = new Config();
800
801
		foreach (
802
			array(
803
				'sync',
804
			)
805
			as $feature
806
		) {
807
			$config->ensure( $feature );
808
		}
809
810
		$config->ensure(
811
			'connection',
812
			array(
813
				'slug' => 'jetpack',
814
				'name' => 'Jetpack',
815
			)
816
		);
817
818
		if ( is_admin() ) {
819
			$config->ensure( 'jitm' );
820
		}
821
822
		if ( ! $this->connection_manager ) {
823
			$this->connection_manager = new Connection_Manager( 'jetpack' );
824
		}
825
826
		/*
827
		 * Load things that should only be in Network Admin.
828
		 *
829
		 * For now blow away everything else until a more full
830
		 * understanding of what is needed at the network level is
831
		 * available
832
		 */
833
		if ( is_multisite() ) {
834
			$network = Jetpack_Network::init();
835
			$network->set_connection( $this->connection_manager );
836
		}
837
838
		if ( $this->connection_manager->is_active() ) {
839
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
840
841
			Jetpack_Heartbeat::init();
842
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
843
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
844
				Jetpack_Search_Performance_Logger::init();
845
			}
846
		}
847
848
		// Initialize remote file upload request handlers.
849
		$this->add_remote_request_handlers();
850
851
		/*
852
		 * Enable enhanced handling of previewing sites in Calypso
853
		 */
854
		if ( self::is_active() ) {
855
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
856
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
857
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
858
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
859
		}
860
861
		if ( ( new Tracking( $this->connection_manager ) )->should_enable_tracking( new Terms_Of_Service(), new Status() ) ) {
862
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
863
		} else {
864
			/**
865
			 * Initialize tracking right after the user agrees to the terms of service.
866
			 */
867
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
868
		}
869
	}
870
871
	/**
872
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
873
	 * initialization code.
874
	 *
875
	 * @action plugins_loaded
876
	 */
877
	public function late_initialization() {
878
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
879
880
		Partner::init();
881
882
		/**
883
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
884
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
885
		 *
886
		 * @since 8.1.0
887
		 *
888
		 * @param Jetpack $jetpack the main plugin class object.
889
		 */
890
		do_action( 'jetpack_loaded', $this );
891
892
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
893
	}
894
895
	/**
896
	 * Sets up the XMLRPC request handlers.
897
	 *
898
	 * @deprecated since 7.7.0
899
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
900
	 *
901
	 * @param array                 $request_params Incoming request parameters.
902
	 * @param Boolean               $is_active      Whether the connection is currently active.
903
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
904
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
905
	 */
906 View Code Duplication
	public function setup_xmlrpc_handlers(
907
		$request_params,
908
		$is_active,
909
		$is_signed,
910
		Jetpack_XMLRPC_Server $xmlrpc_server = null
911
	) {
912
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
913
914
		if ( ! $this->connection_manager ) {
915
			$this->connection_manager = new Connection_Manager();
916
		}
917
918
		return $this->connection_manager->setup_xmlrpc_handlers(
919
			$request_params,
920
			$is_active,
921
			$is_signed,
922
			$xmlrpc_server
923
		);
924
	}
925
926
	/**
927
	 * Initialize REST API registration connector.
928
	 *
929
	 * @deprecated since 7.7.0
930
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
931
	 */
932 View Code Duplication
	public function initialize_rest_api_registration_connector() {
933
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
934
935
		if ( ! $this->connection_manager ) {
936
			$this->connection_manager = new Connection_Manager();
937
		}
938
939
		$this->connection_manager->initialize_rest_api_registration_connector();
940
	}
941
942
	/**
943
	 * This is ported over from the manage module, which has been deprecated and baked in here.
944
	 *
945
	 * @param $domains
946
	 */
947
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
948
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
949
	}
950
951
	/**
952
	 * Return $domains, with 'wordpress.com' appended.
953
	 * This is ported over from the manage module, which has been deprecated and baked in here.
954
	 *
955
	 * @param $domains
956
	 * @return array
957
	 */
958
	function allow_wpcom_domain( $domains ) {
959
		if ( empty( $domains ) ) {
960
			$domains = array();
961
		}
962
		$domains[] = 'wordpress.com';
963
		return array_unique( $domains );
964
	}
965
966
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
967
		$post = get_post( $post_id );
968
969
		if ( empty( $post ) ) {
970
			return $default_url;
971
		}
972
973
		$post_type = $post->post_type;
974
975
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
976
		// https://en.support.wordpress.com/custom-post-types/
977
		$allowed_post_types = array(
978
			'post',
979
			'page',
980
			'jetpack-portfolio',
981
			'jetpack-testimonial',
982
		);
983
984
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
985
			return $default_url;
986
		}
987
988
		return Redirect::get_url(
989
			'calypso-edit-' . $post_type,
990
			array(
991
				'path' => $post_id,
992
			)
993
		);
994
	}
995
996
	function point_edit_comment_links_to_calypso( $url ) {
997
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
998
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
999
1000
		return Redirect::get_url(
1001
			'calypso-edit-comment',
1002
			array(
1003
				'path' => $query_args['amp;c'],
1004
			)
1005
		);
1006
1007
	}
1008
1009
	function jetpack_track_last_sync_callback( $params ) {
1010
		/**
1011
		 * Filter to turn off jitm caching
1012
		 *
1013
		 * @since 5.4.0
1014
		 *
1015
		 * @param bool false Whether to cache just in time messages
1016
		 */
1017
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
1018
			return $params;
1019
		}
1020
1021
		if ( is_array( $params ) && isset( $params[0] ) ) {
1022
			$option = $params[0];
1023
			if ( 'active_plugins' === $option ) {
1024
				// use the cache if we can, but not terribly important if it gets evicted
1025
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
1026
			}
1027
		}
1028
1029
		return $params;
1030
	}
1031
1032
	function jetpack_connection_banner_callback() {
1033
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1034
1035
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1036
		if (
1037
			isset( $_REQUEST['dismissBanner'] ) &&
1038
			! Jetpack_Connection_Banner::force_display()
1039
		) {
1040
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1041
			wp_send_json_success();
1042
		}
1043
1044
		wp_die();
1045
	}
1046
1047
	/**
1048
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1049
	 * Only used in our alternate XML-RPC endpoint, where we want to
1050
	 * ensure that Core and other plugins' methods are not exposed.
1051
	 *
1052
	 * @deprecated since 7.7.0
1053
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1054
	 *
1055
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1056
	 * @return array Filtered $methods
1057
	 */
1058 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1059
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1060
1061
		if ( ! $this->connection_manager ) {
1062
			$this->connection_manager = new Connection_Manager();
1063
		}
1064
1065
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1066
	}
1067
1068
	/**
1069
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1070
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1071
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1072
	 * which is accessible via a different URI. Most of the below is copied directly
1073
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1074
	 *
1075
	 * @deprecated since 7.7.0
1076
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1077
	 */
1078 View Code Duplication
	public function alternate_xmlrpc() {
1079
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1080
1081
		if ( ! $this->connection_manager ) {
1082
			$this->connection_manager = new Connection_Manager();
1083
		}
1084
1085
		$this->connection_manager->alternate_xmlrpc();
1086
	}
1087
1088
	/**
1089
	 * The callback for the JITM ajax requests.
1090
	 *
1091
	 * @deprecated since 7.9.0
1092
	 */
1093
	function jetpack_jitm_ajax_callback() {
1094
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1095
	}
1096
1097
	/**
1098
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1099
	 */
1100
	function push_stats() {
1101
		if ( ! empty( $this->stats ) ) {
1102
			$this->do_stats( 'server_side' );
1103
		}
1104
	}
1105
1106
	/**
1107
	 * Sets the Jetpack custom capabilities.
1108
	 *
1109
	 * @param string[] $caps    Array of the user's capabilities.
1110
	 * @param string   $cap     Capability name.
1111
	 * @param int      $user_id The user ID.
1112
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1113
	 */
1114
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1115
		$is_offline_mode = ( new Status() )->is_offline_mode();
1116
		switch ( $cap ) {
1117
			case 'jetpack_manage_modules':
1118
			case 'jetpack_activate_modules':
1119
			case 'jetpack_deactivate_modules':
1120
				$caps = array( 'manage_options' );
1121
				break;
1122
			case 'jetpack_configure_modules':
1123
				$caps = array( 'manage_options' );
1124
				break;
1125
			case 'jetpack_manage_autoupdates':
1126
				$caps = array(
1127
					'manage_options',
1128
					'update_plugins',
1129
				);
1130
				break;
1131
			case 'jetpack_network_admin_page':
1132
			case 'jetpack_network_settings_page':
1133
				$caps = array( 'manage_network_plugins' );
1134
				break;
1135
			case 'jetpack_network_sites_page':
1136
				$caps = array( 'manage_sites' );
1137
				break;
1138
			case 'jetpack_admin_page':
1139
				if ( $is_offline_mode ) {
1140
					$caps = array( 'manage_options' );
1141
					break;
1142
				} else {
1143
					$caps = array( 'read' );
1144
				}
1145
				break;
1146
		}
1147
		return $caps;
1148
	}
1149
1150
	/**
1151
	 * Require a Jetpack authentication.
1152
	 *
1153
	 * @deprecated since 7.7.0
1154
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1155
	 */
1156 View Code Duplication
	public function require_jetpack_authentication() {
1157
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1158
1159
		if ( ! $this->connection_manager ) {
1160
			$this->connection_manager = new Connection_Manager();
1161
		}
1162
1163
		$this->connection_manager->require_jetpack_authentication();
1164
	}
1165
1166
	/**
1167
	 * Register assets for use in various modules and the Jetpack admin page.
1168
	 *
1169
	 * @uses wp_script_is, wp_register_script, plugins_url
1170
	 * @action wp_loaded
1171
	 * @return null
1172
	 */
1173
	public function register_assets() {
1174 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1175
			wp_register_script(
1176
				'jetpack-gallery-settings',
1177
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1178
				array( 'media-views' ),
1179
				'20121225'
1180
			);
1181
		}
1182
1183
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1184
			wp_register_script(
1185
				'jetpack-twitter-timeline',
1186
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1187
				array( 'jquery' ),
1188
				'4.0.0',
1189
				true
1190
			);
1191
		}
1192
1193
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1194
			wp_register_script(
1195
				'jetpack-facebook-embed',
1196
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1197
				array(),
1198
				null,
1199
				true
1200
			);
1201
1202
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1203
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1204
			if ( ! is_numeric( $fb_app_id ) ) {
1205
				$fb_app_id = '';
1206
			}
1207
			wp_localize_script(
1208
				'jetpack-facebook-embed',
1209
				'jpfbembed',
1210
				array(
1211
					'appid'  => $fb_app_id,
1212
					'locale' => $this->get_locale(),
1213
				)
1214
			);
1215
		}
1216
1217
		/**
1218
		 * As jetpack_register_genericons is by default fired off a hook,
1219
		 * the hook may have already fired by this point.
1220
		 * So, let's just trigger it manually.
1221
		 */
1222
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1223
		jetpack_register_genericons();
1224
1225
		/**
1226
		 * Register the social logos
1227
		 */
1228
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1229
		jetpack_register_social_logos();
1230
1231 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1232
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1233
		}
1234
	}
1235
1236
	/**
1237
	 * Guess locale from language code.
1238
	 *
1239
	 * @param string $lang Language code.
1240
	 * @return string|bool
1241
	 */
1242 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1243
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1244
			return 'en_US';
1245
		}
1246
1247
		if ( ! class_exists( 'GP_Locales' ) ) {
1248
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1249
				return false;
1250
			}
1251
1252
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1253
		}
1254
1255
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1256
			// WP.com: get_locale() returns 'it'
1257
			$locale = GP_Locales::by_slug( $lang );
1258
		} else {
1259
			// Jetpack: get_locale() returns 'it_IT';
1260
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1261
		}
1262
1263
		if ( ! $locale ) {
1264
			return false;
1265
		}
1266
1267
		if ( empty( $locale->facebook_locale ) ) {
1268
			if ( empty( $locale->wp_locale ) ) {
1269
				return false;
1270
			} else {
1271
				// Facebook SDK is smart enough to fall back to en_US if a
1272
				// locale isn't supported. Since supported Facebook locales
1273
				// can fall out of sync, we'll attempt to use the known
1274
				// wp_locale value and rely on said fallback.
1275
				return $locale->wp_locale;
1276
			}
1277
		}
1278
1279
		return $locale->facebook_locale;
1280
	}
1281
1282
	/**
1283
	 * Get the locale.
1284
	 *
1285
	 * @return string|bool
1286
	 */
1287
	function get_locale() {
1288
		$locale = $this->guess_locale_from_lang( get_locale() );
1289
1290
		if ( ! $locale ) {
1291
			$locale = 'en_US';
1292
		}
1293
1294
		return $locale;
1295
	}
1296
1297
	/**
1298
	 * Return the network_site_url so that .com knows what network this site is a part of.
1299
	 *
1300
	 * @param  bool $option
1301
	 * @return string
1302
	 */
1303
	public function jetpack_main_network_site_option( $option ) {
1304
		return network_site_url();
1305
	}
1306
	/**
1307
	 * Network Name.
1308
	 */
1309
	static function network_name( $option = null ) {
1310
		global $current_site;
1311
		return $current_site->site_name;
1312
	}
1313
	/**
1314
	 * Does the network allow new user and site registrations.
1315
	 *
1316
	 * @return string
1317
	 */
1318
	static function network_allow_new_registrations( $option = null ) {
1319
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1320
	}
1321
	/**
1322
	 * Does the network allow admins to add new users.
1323
	 *
1324
	 * @return boolian
1325
	 */
1326
	static function network_add_new_users( $option = null ) {
1327
		return (bool) get_site_option( 'add_new_users' );
1328
	}
1329
	/**
1330
	 * File upload psace left per site in MB.
1331
	 *  -1 means NO LIMIT.
1332
	 *
1333
	 * @return number
1334
	 */
1335
	static function network_site_upload_space( $option = null ) {
1336
		// value in MB
1337
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1338
	}
1339
1340
	/**
1341
	 * Network allowed file types.
1342
	 *
1343
	 * @return string
1344
	 */
1345
	static function network_upload_file_types( $option = null ) {
1346
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1347
	}
1348
1349
	/**
1350
	 * Maximum file upload size set by the network.
1351
	 *
1352
	 * @return number
1353
	 */
1354
	static function network_max_upload_file_size( $option = null ) {
1355
		// value in KB
1356
		return get_site_option( 'fileupload_maxk', 300 );
1357
	}
1358
1359
	/**
1360
	 * Lets us know if a site allows admins to manage the network.
1361
	 *
1362
	 * @return array
1363
	 */
1364
	static function network_enable_administration_menus( $option = null ) {
1365
		return get_site_option( 'menu_items' );
1366
	}
1367
1368
	/**
1369
	 * If a user has been promoted to or demoted from admin, we need to clear the
1370
	 * jetpack_other_linked_admins transient.
1371
	 *
1372
	 * @since 4.3.2
1373
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1374
	 *
1375
	 * @param int    $user_id   The user ID whose role changed.
1376
	 * @param string $role      The new role.
1377
	 * @param array  $old_roles An array of the user's previous roles.
1378
	 */
1379
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1380
		if ( 'administrator' == $role
1381
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1382
			|| is_null( $old_roles )
1383
		) {
1384
			delete_transient( 'jetpack_other_linked_admins' );
1385
		}
1386
	}
1387
1388
	/**
1389
	 * Checks to see if there are any other users available to become primary
1390
	 * Users must both:
1391
	 * - Be linked to wpcom
1392
	 * - Be an admin
1393
	 *
1394
	 * @return mixed False if no other users are linked, Int if there are.
1395
	 */
1396
	static function get_other_linked_admins() {
1397
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1398
1399
		if ( false === $other_linked_users ) {
1400
			$admins = get_users( array( 'role' => 'administrator' ) );
1401
			if ( count( $admins ) > 1 ) {
1402
				$available = array();
1403
				foreach ( $admins as $admin ) {
1404
					if ( self::is_user_connected( $admin->ID ) ) {
1405
						$available[] = $admin->ID;
1406
					}
1407
				}
1408
1409
				$count_connected_admins = count( $available );
1410
				if ( count( $available ) > 1 ) {
1411
					$other_linked_users = $count_connected_admins;
1412
				} else {
1413
					$other_linked_users = 0;
1414
				}
1415
			} else {
1416
				$other_linked_users = 0;
1417
			}
1418
1419
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1420
		}
1421
1422
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1423
	}
1424
1425
	/**
1426
	 * Return whether we are dealing with a multi network setup or not.
1427
	 * The reason we are type casting this is because we want to avoid the situation where
1428
	 * the result is false since when is_main_network_option return false it cases
1429
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1430
	 * database which could be set to anything as opposed to what this function returns.
1431
	 *
1432
	 * @param  bool $option
1433
	 *
1434
	 * @return boolean
1435
	 */
1436
	public function is_main_network_option( $option ) {
1437
		// return '1' or ''
1438
		return (string) (bool) self::is_multi_network();
1439
	}
1440
1441
	/**
1442
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1443
	 *
1444
	 * @param  string $option
1445
	 * @return boolean
1446
	 */
1447
	public function is_multisite( $option ) {
1448
		return (string) (bool) is_multisite();
1449
	}
1450
1451
	/**
1452
	 * Implemented since there is no core is multi network function
1453
	 * Right now there is no way to tell if we which network is the dominant network on the system
1454
	 *
1455
	 * @since  3.3
1456
	 * @return boolean
1457
	 */
1458 View Code Duplication
	public static function is_multi_network() {
1459
		global  $wpdb;
1460
1461
		// if we don't have a multi site setup no need to do any more
1462
		if ( ! is_multisite() ) {
1463
			return false;
1464
		}
1465
1466
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1467
		if ( $num_sites > 1 ) {
1468
			return true;
1469
		} else {
1470
			return false;
1471
		}
1472
	}
1473
1474
	/**
1475
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1476
	 *
1477
	 * @return null
1478
	 */
1479
	function update_jetpack_main_network_site_option() {
1480
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1481
	}
1482
	/**
1483
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1484
	 */
1485
	function update_jetpack_network_settings() {
1486
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1487
		// Only sync this info for the main network site.
1488
	}
1489
1490
	/**
1491
	 * Get back if the current site is single user site.
1492
	 *
1493
	 * @return bool
1494
	 */
1495 View Code Duplication
	public static function is_single_user_site() {
1496
		global $wpdb;
1497
1498
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1499
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1500
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1501
		}
1502
		return 1 === (int) $some_users;
1503
	}
1504
1505
	/**
1506
	 * Returns true if the site has file write access false otherwise.
1507
	 *
1508
	 * @return string ( '1' | '0' )
1509
	 **/
1510
	public static function file_system_write_access() {
1511
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1512
			require_once ABSPATH . 'wp-admin/includes/file.php';
1513
		}
1514
1515
		require_once ABSPATH . 'wp-admin/includes/template.php';
1516
1517
		$filesystem_method = get_filesystem_method();
1518
		if ( $filesystem_method === 'direct' ) {
1519
			return 1;
1520
		}
1521
1522
		ob_start();
1523
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1524
		ob_end_clean();
1525
		if ( $filesystem_credentials_are_stored ) {
1526
			return 1;
1527
		}
1528
		return 0;
1529
	}
1530
1531
	/**
1532
	 * Finds out if a site is using a version control system.
1533
	 *
1534
	 * @return string ( '1' | '0' )
1535
	 **/
1536
	public static function is_version_controlled() {
1537
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1538
		return (string) (int) Functions::is_version_controlled();
1539
	}
1540
1541
	/**
1542
	 * Determines whether the current theme supports featured images or not.
1543
	 *
1544
	 * @return string ( '1' | '0' )
1545
	 */
1546
	public static function featured_images_enabled() {
1547
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1548
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1549
	}
1550
1551
	/**
1552
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1553
	 *
1554
	 * @deprecated 4.7 use get_avatar_url instead.
1555
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1556
	 * @param int               $size Size of the avatar image
1557
	 * @param string            $default URL to a default image to use if no avatar is available
1558
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1559
	 *
1560
	 * @return array
1561
	 */
1562
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1563
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1564
		return get_avatar_url(
1565
			$id_or_email,
1566
			array(
1567
				'size'          => $size,
1568
				'default'       => $default,
1569
				'force_default' => $force_display,
1570
			)
1571
		);
1572
	}
1573
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1574
	/**
1575
	 * jetpack_updates is saved in the following schema:
1576
	 *
1577
	 * array (
1578
	 *      'plugins'                       => (int) Number of plugin updates available.
1579
	 *      'themes'                        => (int) Number of theme updates available.
1580
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1581
	 *      'translations'                  => (int) Number of translation updates available.
1582
	 *      'total'                         => (int) Total of all available updates.
1583
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1584
	 * )
1585
	 *
1586
	 * @return array
1587
	 */
1588
	public static function get_updates() {
1589
		$update_data = wp_get_update_data();
1590
1591
		// Stores the individual update counts as well as the total count.
1592
		if ( isset( $update_data['counts'] ) ) {
1593
			$updates = $update_data['counts'];
1594
		}
1595
1596
		// If we need to update WordPress core, let's find the latest version number.
1597 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1598
			$cur = get_preferred_from_update_core();
1599
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1600
				$updates['wp_update_version'] = $cur->current;
1601
			}
1602
		}
1603
		return isset( $updates ) ? $updates : array();
1604
	}
1605
	// phpcs:enable
1606
1607
	public static function get_update_details() {
1608
		$update_details = array(
1609
			'update_core'    => get_site_transient( 'update_core' ),
1610
			'update_plugins' => get_site_transient( 'update_plugins' ),
1611
			'update_themes'  => get_site_transient( 'update_themes' ),
1612
		);
1613
		return $update_details;
1614
	}
1615
1616
	public static function refresh_update_data() {
1617
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1618
1619
	}
1620
1621
	public static function refresh_theme_data() {
1622
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1623
	}
1624
1625
	/**
1626
	 * Is Jetpack active?
1627
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1628
	 *
1629
	 * @return bool
1630
	 */
1631
	public static function is_active() {
1632
		return self::connection()->is_active();
1633
	}
1634
1635
	/**
1636
	 * Make an API call to WordPress.com for plan status
1637
	 *
1638
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1639
	 *
1640
	 * @return bool True if plan is updated, false if no update
1641
	 */
1642
	public static function refresh_active_plan_from_wpcom() {
1643
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1644
		return Jetpack_Plan::refresh_from_wpcom();
1645
	}
1646
1647
	/**
1648
	 * Get the plan that this Jetpack site is currently using
1649
	 *
1650
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1651
	 * @return array Active Jetpack plan details.
1652
	 */
1653
	public static function get_active_plan() {
1654
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1655
		return Jetpack_Plan::get();
1656
	}
1657
1658
	/**
1659
	 * Determine whether the active plan supports a particular feature
1660
	 *
1661
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1662
	 * @return bool True if plan supports feature, false if not.
1663
	 */
1664
	public static function active_plan_supports( $feature ) {
1665
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1666
		return Jetpack_Plan::supports( $feature );
1667
	}
1668
1669
	/**
1670
	 * Deprecated: Is Jetpack in development (offline) mode?
1671
	 *
1672
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1673
	 * and themes still use it, and we do not want to flood them with notices.
1674
	 *
1675
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1676
	 *
1677
	 * @deprecated since 8.0.
1678
	 */
1679
	public static function is_development_mode() {
1680
		return ( new Status() )->is_offline_mode();
1681
	}
1682
1683
	/**
1684
	 * Whether the site is currently onboarding or not.
1685
	 * A site is considered as being onboarded if it currently has an onboarding token.
1686
	 *
1687
	 * @since 5.8
1688
	 *
1689
	 * @access public
1690
	 * @static
1691
	 *
1692
	 * @return bool True if the site is currently onboarding, false otherwise
1693
	 */
1694
	public static function is_onboarding() {
1695
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1696
	}
1697
1698
	/**
1699
	 * Determines reason for Jetpack offline mode.
1700
	 */
1701
	public static function development_mode_trigger_text() {
1702
		$status = new Status();
1703
1704
		if ( ! $status->is_offline_mode() ) {
1705
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1706
		}
1707
1708
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1709
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1710
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1711
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1712
		} elseif ( $status->is_local_site() ) {
1713
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1714
			/** This filter is documented in packages/status/src/class-status.php */
1715
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1716
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1717
		} else {
1718
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1719
		}
1720
1721
		return $notice;
1722
1723
	}
1724
	/**
1725
	 * Get Jetpack offline mode notice text and notice class.
1726
	 *
1727
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1728
	 */
1729
	public static function show_development_mode_notice() {
1730 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1731
			$notice = sprintf(
1732
				/* translators: %s is a URL */
1733
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1734
				Redirect::get_url( 'jetpack-support-development-mode' )
1735
			);
1736
1737
			$notice .= ' ' . self::development_mode_trigger_text();
1738
1739
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1740
		}
1741
1742
		// Throw up a notice if using a development version and as for feedback.
1743
		if ( self::is_development_version() ) {
1744
			/* translators: %s is a URL */
1745
			$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' ) );
1746
1747
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1748
		}
1749
		// Throw up a notice if using staging mode
1750 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1751
			/* translators: %s is a URL */
1752
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1753
1754
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1755
		}
1756
	}
1757
1758
	/**
1759
	 * Whether Jetpack's version maps to a public release, or a development version.
1760
	 */
1761
	public static function is_development_version() {
1762
		/**
1763
		 * Allows filtering whether this is a development version of Jetpack.
1764
		 *
1765
		 * This filter is especially useful for tests.
1766
		 *
1767
		 * @since 4.3.0
1768
		 *
1769
		 * @param bool $development_version Is this a develoment version of Jetpack?
1770
		 */
1771
		return (bool) apply_filters(
1772
			'jetpack_development_version',
1773
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1774
		);
1775
	}
1776
1777
	/**
1778
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1779
	 */
1780
	public static function is_user_connected( $user_id = false ) {
1781
		return self::connection()->is_user_connected( $user_id );
0 ignored issues
show
$user_id is of type boolean, but the function expects a false|integer.

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...
1782
	}
1783
1784
	/**
1785
	 * Get the wpcom user data of the current|specified connected user.
1786
	 */
1787 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1788
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1789
		if ( ! $user_id ) {
1790
			$user_id = get_current_user_id();
1791
		}
1792
1793
		$transient_key = "jetpack_connected_user_data_$user_id";
1794
1795
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1796
			return $cached_user_data;
1797
		}
1798
1799
		$xml = new Jetpack_IXR_Client(
1800
			array(
1801
				'user_id' => $user_id,
1802
			)
1803
		);
1804
		$xml->query( 'wpcom.getUser' );
1805
		if ( ! $xml->isError() ) {
1806
			$user_data = $xml->getResponse();
1807
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1808
			return $user_data;
1809
		}
1810
1811
		return false;
1812
	}
1813
1814
	/**
1815
	 * Get the wpcom email of the current|specified connected user.
1816
	 */
1817
	public static function get_connected_user_email( $user_id = null ) {
1818
		if ( ! $user_id ) {
1819
			$user_id = get_current_user_id();
1820
		}
1821
1822
		$xml = new Jetpack_IXR_Client(
1823
			array(
1824
				'user_id' => $user_id,
1825
			)
1826
		);
1827
		$xml->query( 'wpcom.getUserEmail' );
1828
		if ( ! $xml->isError() ) {
1829
			return $xml->getResponse();
1830
		}
1831
		return false;
1832
	}
1833
1834
	/**
1835
	 * Get the wpcom email of the master user.
1836
	 */
1837
	public static function get_master_user_email() {
1838
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1839
		if ( $master_user_id ) {
1840
			return self::get_connected_user_email( $master_user_id );
1841
		}
1842
		return '';
1843
	}
1844
1845
	/**
1846
	 * Whether the current user is the connection owner.
1847
	 *
1848
	 * @deprecated since 7.7
1849
	 *
1850
	 * @return bool Whether the current user is the connection owner.
1851
	 */
1852
	public function current_user_is_connection_owner() {
1853
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1854
		return self::connection()->is_connection_owner();
1855
	}
1856
1857
	/**
1858
	 * Gets current user IP address.
1859
	 *
1860
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1861
	 *
1862
	 * @return string                  Current user IP address.
1863
	 */
1864
	public static function current_user_ip( $check_all_headers = false ) {
1865
		if ( $check_all_headers ) {
1866
			foreach ( array(
1867
				'HTTP_CF_CONNECTING_IP',
1868
				'HTTP_CLIENT_IP',
1869
				'HTTP_X_FORWARDED_FOR',
1870
				'HTTP_X_FORWARDED',
1871
				'HTTP_X_CLUSTER_CLIENT_IP',
1872
				'HTTP_FORWARDED_FOR',
1873
				'HTTP_FORWARDED',
1874
				'HTTP_VIA',
1875
			) as $key ) {
1876
				if ( ! empty( $_SERVER[ $key ] ) ) {
1877
					return $_SERVER[ $key ];
1878
				}
1879
			}
1880
		}
1881
1882
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1883
	}
1884
1885
	/**
1886
	 * Synchronize connected user role changes
1887
	 */
1888
	function user_role_change( $user_id ) {
1889
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1890
		Users::user_role_change( $user_id );
1891
	}
1892
1893
	/**
1894
	 * Loads the currently active modules.
1895
	 */
1896
	public static function load_modules() {
1897
		$is_offline_mode = ( new Status() )->is_offline_mode();
1898
		if (
1899
			! self::is_active()
1900
			&& ! $is_offline_mode
1901
			&& ! self::is_onboarding()
1902
			&& (
1903
				! is_multisite()
1904
				|| ! get_site_option( 'jetpack_protect_active' )
1905
			)
1906
		) {
1907
			return;
1908
		}
1909
1910
		$version = Jetpack_Options::get_option( 'version' );
1911 View Code Duplication
		if ( ! $version ) {
1912
			$version = $old_version = JETPACK__VERSION . ':' . time();
1913
			/** This action is documented in class.jetpack.php */
1914
			do_action( 'updating_jetpack_version', $version, false );
1915
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1916
		}
1917
		list( $version ) = explode( ':', $version );
1918
1919
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1920
1921
		$modules_data = array();
1922
1923
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1924
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1925
			$updated_modules = array();
1926
			foreach ( $modules as $module ) {
1927
				$modules_data[ $module ] = self::get_module( $module );
1928
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1929
					continue;
1930
				}
1931
1932
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1933
					continue;
1934
				}
1935
1936
				$updated_modules[] = $module;
1937
			}
1938
1939
			$modules = array_diff( $modules, $updated_modules );
1940
		}
1941
1942
		foreach ( $modules as $index => $module ) {
1943
			// If we're in offline mode, disable modules requiring a connection.
1944
			if ( $is_offline_mode ) {
1945
				// Prime the pump if we need to
1946
				if ( empty( $modules_data[ $module ] ) ) {
1947
					$modules_data[ $module ] = self::get_module( $module );
1948
				}
1949
				// If the module requires a connection, but we're in local mode, don't include it.
1950
				if ( $modules_data[ $module ]['requires_connection'] ) {
1951
					continue;
1952
				}
1953
			}
1954
1955
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1956
				continue;
1957
			}
1958
1959
			if ( ! include_once self::get_module_path( $module ) ) {
1960
				unset( $modules[ $index ] );
1961
				self::update_active_modules( array_values( $modules ) );
1962
				continue;
1963
			}
1964
1965
			/**
1966
			 * Fires when a specific module is loaded.
1967
			 * The dynamic part of the hook, $module, is the module slug.
1968
			 *
1969
			 * @since 1.1.0
1970
			 */
1971
			do_action( 'jetpack_module_loaded_' . $module );
1972
		}
1973
1974
		/**
1975
		 * Fires when all the modules are loaded.
1976
		 *
1977
		 * @since 1.1.0
1978
		 */
1979
		do_action( 'jetpack_modules_loaded' );
1980
1981
		// 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.
1982
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1983
	}
1984
1985
	/**
1986
	 * Check if Jetpack's REST API compat file should be included
1987
	 *
1988
	 * @action plugins_loaded
1989
	 * @return null
1990
	 */
1991
	public function check_rest_api_compat() {
1992
		/**
1993
		 * Filters the list of REST API compat files to be included.
1994
		 *
1995
		 * @since 2.2.5
1996
		 *
1997
		 * @param array $args Array of REST API compat files to include.
1998
		 */
1999
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2000
2001
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2002
			require_once $_jetpack_rest_api_compat_include;
2003
		}
2004
	}
2005
2006
	/**
2007
	 * Gets all plugins currently active in values, regardless of whether they're
2008
	 * traditionally activated or network activated.
2009
	 *
2010
	 * @todo Store the result in core's object cache maybe?
2011
	 */
2012
	public static function get_active_plugins() {
2013
		$active_plugins = (array) get_option( 'active_plugins', array() );
2014
2015
		if ( is_multisite() ) {
2016
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2017
			// whereas active_plugins stores them in the values.
2018
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2019
			if ( $network_plugins ) {
2020
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2021
			}
2022
		}
2023
2024
		sort( $active_plugins );
2025
2026
		return array_unique( $active_plugins );
2027
	}
2028
2029
	/**
2030
	 * Gets and parses additional plugin data to send with the heartbeat data
2031
	 *
2032
	 * @since 3.8.1
2033
	 *
2034
	 * @return array Array of plugin data
2035
	 */
2036
	public static function get_parsed_plugin_data() {
2037
		if ( ! function_exists( 'get_plugins' ) ) {
2038
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2039
		}
2040
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2041
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2042
		$active_plugins = self::get_active_plugins();
2043
2044
		$plugins = array();
2045
		foreach ( $all_plugins as $path => $plugin_data ) {
2046
			$plugins[ $path ] = array(
2047
				'is_active' => in_array( $path, $active_plugins ),
2048
				'file'      => $path,
2049
				'name'      => $plugin_data['Name'],
2050
				'version'   => $plugin_data['Version'],
2051
				'author'    => $plugin_data['Author'],
2052
			);
2053
		}
2054
2055
		return $plugins;
2056
	}
2057
2058
	/**
2059
	 * Gets and parses theme data to send with the heartbeat data
2060
	 *
2061
	 * @since 3.8.1
2062
	 *
2063
	 * @return array Array of theme data
2064
	 */
2065
	public static function get_parsed_theme_data() {
2066
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2067
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2068
2069
		$themes = array();
2070
		foreach ( $all_themes as $slug => $theme_data ) {
2071
			$theme_headers = array();
2072
			foreach ( $header_keys as $header_key ) {
2073
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2074
			}
2075
2076
			$themes[ $slug ] = array(
2077
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2078
				'slug'            => $slug,
2079
				'theme_root'      => $theme_data->get_theme_root_uri(),
2080
				'parent'          => $theme_data->parent(),
2081
				'headers'         => $theme_headers,
2082
			);
2083
		}
2084
2085
		return $themes;
2086
	}
2087
2088
	/**
2089
	 * Checks whether a specific plugin is active.
2090
	 *
2091
	 * We don't want to store these in a static variable, in case
2092
	 * there are switch_to_blog() calls involved.
2093
	 */
2094
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2095
		return in_array( $plugin, self::get_active_plugins() );
2096
	}
2097
2098
	/**
2099
	 * Check if Jetpack's Open Graph tags should be used.
2100
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2101
	 *
2102
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2103
	 * @action plugins_loaded
2104
	 * @return null
2105
	 */
2106
	public function check_open_graph() {
2107
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2108
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2109
		}
2110
2111
		$active_plugins = self::get_active_plugins();
2112
2113
		if ( ! empty( $active_plugins ) ) {
2114
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2115
				if ( in_array( $plugin, $active_plugins ) ) {
2116
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2117
					break;
2118
				}
2119
			}
2120
		}
2121
2122
		/**
2123
		 * Allow the addition of Open Graph Meta Tags to all pages.
2124
		 *
2125
		 * @since 2.0.3
2126
		 *
2127
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2128
		 */
2129
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2130
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2131
		}
2132
	}
2133
2134
	/**
2135
	 * Check if Jetpack's Twitter tags should be used.
2136
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2137
	 *
2138
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2139
	 * @action plugins_loaded
2140
	 * @return null
2141
	 */
2142
	public function check_twitter_tags() {
2143
2144
		$active_plugins = self::get_active_plugins();
2145
2146
		if ( ! empty( $active_plugins ) ) {
2147
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2148
				if ( in_array( $plugin, $active_plugins ) ) {
2149
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2150
					break;
2151
				}
2152
			}
2153
		}
2154
2155
		/**
2156
		 * Allow Twitter Card Meta tags to be disabled.
2157
		 *
2158
		 * @since 2.6.0
2159
		 *
2160
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2161
		 */
2162
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2163
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2164
		}
2165
	}
2166
2167
	/**
2168
	 * Allows plugins to submit security reports.
2169
	 *
2170
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2171
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2172
	 * @param array  $args         See definitions above
2173
	 */
2174
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2175
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2176
	}
2177
2178
	/* Jetpack Options API */
2179
2180
	public static function get_option_names( $type = 'compact' ) {
2181
		return Jetpack_Options::get_option_names( $type );
2182
	}
2183
2184
	/**
2185
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2186
	 *
2187
	 * @param string $name    Option name
2188
	 * @param mixed  $default (optional)
2189
	 */
2190
	public static function get_option( $name, $default = false ) {
2191
		return Jetpack_Options::get_option( $name, $default );
2192
	}
2193
2194
	/**
2195
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2196
	 *
2197
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2198
	 * @param string $name  Option name
2199
	 * @param mixed  $value Option value
2200
	 */
2201
	public static function update_option( $name, $value ) {
2202
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2203
		return Jetpack_Options::update_option( $name, $value );
2204
	}
2205
2206
	/**
2207
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2208
	 *
2209
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2210
	 * @param array $array array( option name => option value, ... )
2211
	 */
2212
	public static function update_options( $array ) {
2213
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2214
		return Jetpack_Options::update_options( $array );
2215
	}
2216
2217
	/**
2218
	 * Deletes the given option.  May be passed multiple option names as an array.
2219
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2220
	 *
2221
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2222
	 * @param string|array $names
2223
	 */
2224
	public static function delete_option( $names ) {
2225
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2226
		return Jetpack_Options::delete_option( $names );
2227
	}
2228
2229
	/**
2230
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2231
	 *
2232
	 * Enters a user token into the user_tokens option
2233
	 *
2234
	 * @param int    $user_id The user id.
2235
	 * @param string $token The user token.
2236
	 * @param bool   $is_master_user Whether the user is the master user.
2237
	 * @return bool
2238
	 */
2239
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2240
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2241
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2242
	}
2243
2244
	/**
2245
	 * Returns an array of all PHP files in the specified absolute path.
2246
	 * Equivalent to glob( "$absolute_path/*.php" ).
2247
	 *
2248
	 * @param string $absolute_path The absolute path of the directory to search.
2249
	 * @return array Array of absolute paths to the PHP files.
2250
	 */
2251
	public static function glob_php( $absolute_path ) {
2252
		if ( function_exists( 'glob' ) ) {
2253
			return glob( "$absolute_path/*.php" );
2254
		}
2255
2256
		$absolute_path = untrailingslashit( $absolute_path );
2257
		$files         = array();
2258
		if ( ! $dir = @opendir( $absolute_path ) ) {
2259
			return $files;
2260
		}
2261
2262
		while ( false !== $file = readdir( $dir ) ) {
2263
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2264
				continue;
2265
			}
2266
2267
			$file = "$absolute_path/$file";
2268
2269
			if ( ! is_file( $file ) ) {
2270
				continue;
2271
			}
2272
2273
			$files[] = $file;
2274
		}
2275
2276
		closedir( $dir );
2277
2278
		return $files;
2279
	}
2280
2281
	public static function activate_new_modules( $redirect = false ) {
2282
		if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
2283
			return;
2284
		}
2285
2286
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2287 View Code Duplication
		if ( ! $jetpack_old_version ) {
2288
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2289
			/** This action is documented in class.jetpack.php */
2290
			do_action( 'updating_jetpack_version', $version, false );
2291
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2292
		}
2293
2294
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2295
2296
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2297
			return;
2298
		}
2299
2300
		$active_modules     = self::get_active_modules();
2301
		$reactivate_modules = array();
2302
		foreach ( $active_modules as $active_module ) {
2303
			$module = self::get_module( $active_module );
2304
			if ( ! isset( $module['changed'] ) ) {
2305
				continue;
2306
			}
2307
2308
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2309
				continue;
2310
			}
2311
2312
			$reactivate_modules[] = $active_module;
2313
			self::deactivate_module( $active_module );
2314
		}
2315
2316
		$new_version = JETPACK__VERSION . ':' . time();
2317
		/** This action is documented in class.jetpack.php */
2318
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2319
		Jetpack_Options::update_options(
2320
			array(
2321
				'version'     => $new_version,
2322
				'old_version' => $jetpack_old_version,
2323
			)
2324
		);
2325
2326
		self::state( 'message', 'modules_activated' );
2327
2328
		self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
2329
2330
		if ( $redirect ) {
2331
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2332
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2333
				$page = $_GET['page'];
2334
			}
2335
2336
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2337
			exit;
2338
		}
2339
	}
2340
2341
	/**
2342
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2343
	 * Make sure to tuck away module "library" files in a sub-directory.
2344
	 */
2345
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2346
		static $modules = null;
2347
2348
		if ( ! isset( $modules ) ) {
2349
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2350
			// Use the cache if we're on the front-end and it's available...
2351
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2352
				$modules = $available_modules_option[ JETPACK__VERSION ];
2353
			} else {
2354
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2355
2356
				$modules = array();
2357
2358
				foreach ( $files as $file ) {
2359
					if ( ! $headers = self::get_module( $file ) ) {
2360
						continue;
2361
					}
2362
2363
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2364
				}
2365
2366
				Jetpack_Options::update_option(
2367
					'available_modules',
2368
					array(
2369
						JETPACK__VERSION => $modules,
2370
					)
2371
				);
2372
			}
2373
		}
2374
2375
		/**
2376
		 * Filters the array of modules available to be activated.
2377
		 *
2378
		 * @since 2.4.0
2379
		 *
2380
		 * @param array $modules Array of available modules.
2381
		 * @param string $min_version Minimum version number required to use modules.
2382
		 * @param string $max_version Maximum version number required to use modules.
2383
		 */
2384
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2385
2386
		if ( ! $min_version && ! $max_version ) {
2387
			return array_keys( $mods );
2388
		}
2389
2390
		$r = array();
2391
		foreach ( $mods as $slug => $introduced ) {
2392
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2393
				continue;
2394
			}
2395
2396
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2397
				continue;
2398
			}
2399
2400
			$r[] = $slug;
2401
		}
2402
2403
		return $r;
2404
	}
2405
2406
	/**
2407
	 * Default modules loaded on activation.
2408
	 */
2409
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2410
		$return = array();
2411
2412
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2413
			$module_data = self::get_module( $module );
2414
2415
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2416
				case 'yes':
2417
					$return[] = $module;
2418
					break;
2419
				case 'public':
2420
					if ( Jetpack_Options::get_option( 'public' ) ) {
2421
						$return[] = $module;
2422
					}
2423
					break;
2424
				case 'no':
2425
				default:
2426
					break;
2427
			}
2428
		}
2429
		/**
2430
		 * Filters the array of default modules.
2431
		 *
2432
		 * @since 2.5.0
2433
		 *
2434
		 * @param array $return Array of default modules.
2435
		 * @param string $min_version Minimum version number required to use modules.
2436
		 * @param string $max_version Maximum version number required to use modules.
2437
		 */
2438
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2439
	}
2440
2441
	/**
2442
	 * Checks activated modules during auto-activation to determine
2443
	 * if any of those modules are being deprecated.  If so, close
2444
	 * them out, and add any replacement modules.
2445
	 *
2446
	 * Runs at priority 99 by default.
2447
	 *
2448
	 * This is run late, so that it can still activate a module if
2449
	 * the new module is a replacement for another that the user
2450
	 * currently has active, even if something at the normal priority
2451
	 * would kibosh everything.
2452
	 *
2453
	 * @since 2.6
2454
	 * @uses jetpack_get_default_modules filter
2455
	 * @param array $modules
2456
	 * @return array
2457
	 */
2458
	function handle_deprecated_modules( $modules ) {
2459
		$deprecated_modules = array(
2460
			'debug'            => null,  // Closed out and moved to the debugger library.
2461
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2462
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2463
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2464
		);
2465
2466
		// Don't activate SSO if they never completed activating WPCC.
2467
		if ( self::is_module_active( 'wpcc' ) ) {
2468
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2469
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2470
				$deprecated_modules['wpcc'] = null;
2471
			}
2472
		}
2473
2474
		foreach ( $deprecated_modules as $module => $replacement ) {
2475
			if ( self::is_module_active( $module ) ) {
2476
				self::deactivate_module( $module );
2477
				if ( $replacement ) {
2478
					$modules[] = $replacement;
2479
				}
2480
			}
2481
		}
2482
2483
		return array_unique( $modules );
2484
	}
2485
2486
	/**
2487
	 * Checks activated plugins during auto-activation to determine
2488
	 * if any of those plugins are in the list with a corresponding module
2489
	 * that is not compatible with the plugin. The module will not be allowed
2490
	 * to auto-activate.
2491
	 *
2492
	 * @since 2.6
2493
	 * @uses jetpack_get_default_modules filter
2494
	 * @param array $modules
2495
	 * @return array
2496
	 */
2497
	function filter_default_modules( $modules ) {
2498
2499
		$active_plugins = self::get_active_plugins();
2500
2501
		if ( ! empty( $active_plugins ) ) {
2502
2503
			// For each module we'd like to auto-activate...
2504
			foreach ( $modules as $key => $module ) {
2505
				// If there are potential conflicts for it...
2506
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2507
					// For each potential conflict...
2508
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2509
						// If that conflicting plugin is active...
2510
						if ( in_array( $plugin, $active_plugins ) ) {
2511
							// Remove that item from being auto-activated.
2512
							unset( $modules[ $key ] );
2513
						}
2514
					}
2515
				}
2516
			}
2517
		}
2518
2519
		return $modules;
2520
	}
2521
2522
	/**
2523
	 * Extract a module's slug from its full path.
2524
	 */
2525
	public static function get_module_slug( $file ) {
2526
		return str_replace( '.php', '', basename( $file ) );
2527
	}
2528
2529
	/**
2530
	 * Generate a module's path from its slug.
2531
	 */
2532
	public static function get_module_path( $slug ) {
2533
		/**
2534
		 * Filters the path of a modules.
2535
		 *
2536
		 * @since 7.4.0
2537
		 *
2538
		 * @param array $return The absolute path to a module's root php file
2539
		 * @param string $slug The module slug
2540
		 */
2541
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2542
	}
2543
2544
	/**
2545
	 * Load module data from module file. Headers differ from WordPress
2546
	 * plugin headers to avoid them being identified as standalone
2547
	 * plugins on the WordPress plugins page.
2548
	 */
2549
	public static function get_module( $module ) {
2550
		$headers = array(
2551
			'name'                      => 'Module Name',
2552
			'description'               => 'Module Description',
2553
			'sort'                      => 'Sort Order',
2554
			'recommendation_order'      => 'Recommendation Order',
2555
			'introduced'                => 'First Introduced',
2556
			'changed'                   => 'Major Changes In',
2557
			'deactivate'                => 'Deactivate',
2558
			'free'                      => 'Free',
2559
			'requires_connection'       => 'Requires Connection',
2560
			'auto_activate'             => 'Auto Activate',
2561
			'module_tags'               => 'Module Tags',
2562
			'feature'                   => 'Feature',
2563
			'additional_search_queries' => 'Additional Search Queries',
2564
			'plan_classes'              => 'Plans',
2565
		);
2566
2567
		$file = self::get_module_path( self::get_module_slug( $module ) );
2568
2569
		$mod = self::get_file_data( $file, $headers );
2570
		if ( empty( $mod['name'] ) ) {
2571
			return false;
2572
		}
2573
2574
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2575
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2576
		$mod['deactivate']           = empty( $mod['deactivate'] );
2577
		$mod['free']                 = empty( $mod['free'] );
2578
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2579
2580
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2581
			$mod['auto_activate'] = 'No';
2582
		} else {
2583
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2584
		}
2585
2586
		if ( $mod['module_tags'] ) {
2587
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2588
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2589
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2590
		} else {
2591
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2592
		}
2593
2594 View Code Duplication
		if ( $mod['plan_classes'] ) {
2595
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2596
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2597
		} else {
2598
			$mod['plan_classes'] = array( 'free' );
2599
		}
2600
2601 View Code Duplication
		if ( $mod['feature'] ) {
2602
			$mod['feature'] = explode( ',', $mod['feature'] );
2603
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2604
		} else {
2605
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2606
		}
2607
2608
		/**
2609
		 * Filters the feature array on a module.
2610
		 *
2611
		 * This filter allows you to control where each module is filtered: Recommended,
2612
		 * and the default "Other" listing.
2613
		 *
2614
		 * @since 3.5.0
2615
		 *
2616
		 * @param array   $mod['feature'] The areas to feature this module:
2617
		 *     'Recommended' shows on the main Jetpack admin screen.
2618
		 *     'Other' should be the default if no other value is in the array.
2619
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2620
		 * @param array   $mod All the currently assembled module data.
2621
		 */
2622
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2623
2624
		/**
2625
		 * Filter the returned data about a module.
2626
		 *
2627
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2628
		 * so please be careful.
2629
		 *
2630
		 * @since 3.6.0
2631
		 *
2632
		 * @param array   $mod    The details of the requested module.
2633
		 * @param string  $module The slug of the module, e.g. sharedaddy
2634
		 * @param string  $file   The path to the module source file.
2635
		 */
2636
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2637
	}
2638
2639
	/**
2640
	 * Like core's get_file_data implementation, but caches the result.
2641
	 */
2642
	public static function get_file_data( $file, $headers ) {
2643
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2644
		$file_name = basename( $file );
2645
2646
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2647
2648
		$file_data_option = get_transient( $cache_key );
2649
2650
		if ( ! is_array( $file_data_option ) ) {
2651
			delete_transient( $cache_key );
2652
			$file_data_option = false;
2653
		}
2654
2655
		if ( false === $file_data_option ) {
2656
			$file_data_option = array();
2657
		}
2658
2659
		$key           = md5( $file_name . serialize( $headers ) );
2660
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2661
2662
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2663
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2664
			return $file_data_option[ $key ];
2665
		}
2666
2667
		$data = get_file_data( $file, $headers );
2668
2669
		$file_data_option[ $key ] = $data;
2670
2671
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2672
2673
		return $data;
2674
	}
2675
2676
	/**
2677
	 * Return translated module tag.
2678
	 *
2679
	 * @param string $tag Tag as it appears in each module heading.
2680
	 *
2681
	 * @return mixed
2682
	 */
2683
	public static function translate_module_tag( $tag ) {
2684
		return jetpack_get_module_i18n_tag( $tag );
2685
	}
2686
2687
	/**
2688
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2689
	 *
2690
	 * @since 3.9.2
2691
	 *
2692
	 * @param array $modules
2693
	 *
2694
	 * @return string|void
2695
	 */
2696
	public static function get_translated_modules( $modules ) {
2697
		foreach ( $modules as $index => $module ) {
2698
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2699
			if ( isset( $module['name'] ) ) {
2700
				$modules[ $index ]['name'] = $i18n_module['name'];
2701
			}
2702
			if ( isset( $module['description'] ) ) {
2703
				$modules[ $index ]['description']       = $i18n_module['description'];
2704
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2705
			}
2706
		}
2707
		return $modules;
2708
	}
2709
2710
	/**
2711
	 * Get a list of activated modules as an array of module slugs.
2712
	 */
2713
	public static function get_active_modules() {
2714
		$active = Jetpack_Options::get_option( 'active_modules' );
2715
2716
		if ( ! is_array( $active ) ) {
2717
			$active = array();
2718
		}
2719
2720
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2721
			$active[] = 'vaultpress';
2722
		} else {
2723
			$active = array_diff( $active, array( 'vaultpress' ) );
2724
		}
2725
2726
		// If protect is active on the main site of a multisite, it should be active on all sites.
2727
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2728
			$active[] = 'protect';
2729
		}
2730
2731
		/**
2732
		 * Allow filtering of the active modules.
2733
		 *
2734
		 * Gives theme and plugin developers the power to alter the modules that
2735
		 * are activated on the fly.
2736
		 *
2737
		 * @since 5.8.0
2738
		 *
2739
		 * @param array $active Array of active module slugs.
2740
		 */
2741
		$active = apply_filters( 'jetpack_active_modules', $active );
2742
2743
		return array_unique( $active );
2744
	}
2745
2746
	/**
2747
	 * Check whether or not a Jetpack module is active.
2748
	 *
2749
	 * @param string $module The slug of a Jetpack module.
2750
	 * @return bool
2751
	 *
2752
	 * @static
2753
	 */
2754
	public static function is_module_active( $module ) {
2755
		return in_array( $module, self::get_active_modules() );
2756
	}
2757
2758
	public static function is_module( $module ) {
2759
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2760
	}
2761
2762
	/**
2763
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2764
	 *
2765
	 * @param bool $catch True to start catching, False to stop.
2766
	 *
2767
	 * @static
2768
	 */
2769
	public static function catch_errors( $catch ) {
2770
		static $display_errors, $error_reporting;
2771
2772
		if ( $catch ) {
2773
			$display_errors  = @ini_set( 'display_errors', 1 );
2774
			$error_reporting = @error_reporting( E_ALL );
2775
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2776
		} else {
2777
			@ini_set( 'display_errors', $display_errors );
2778
			@error_reporting( $error_reporting );
2779
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2780
		}
2781
	}
2782
2783
	/**
2784
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2785
	 */
2786
	public static function catch_errors_on_shutdown() {
2787
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2788
	}
2789
2790
	/**
2791
	 * Rewrite any string to make paths easier to read.
2792
	 *
2793
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2794
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2795
	 *
2796
	 * @param $string
2797
	 * @return mixed
2798
	 */
2799
	public static function alias_directories( $string ) {
2800
		// ABSPATH has a trailing slash.
2801
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2802
		// WP_CONTENT_DIR does not have a trailing slash.
2803
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2804
2805
		return $string;
2806
	}
2807
2808
	public static function activate_default_modules(
2809
		$min_version = false,
2810
		$max_version = false,
2811
		$other_modules = array(),
2812
		$redirect = null,
2813
		$send_state_messages = null
2814
	) {
2815
		$jetpack = self::init();
2816
2817
		if ( is_null( $redirect ) ) {
2818
			if (
2819
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2820
			||
2821
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2822
			||
2823
				( defined( 'WP_CLI' ) && WP_CLI )
2824
			||
2825
				( defined( 'DOING_CRON' ) && DOING_CRON )
2826
			||
2827
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2828
			) {
2829
				$redirect = false;
2830
			} elseif ( is_admin() ) {
2831
				$redirect = true;
2832
			} else {
2833
				$redirect = false;
2834
			}
2835
		}
2836
2837
		if ( is_null( $send_state_messages ) ) {
2838
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2839
		}
2840
2841
		$modules = self::get_default_modules( $min_version, $max_version );
2842
		$modules = array_merge( $other_modules, $modules );
2843
2844
		// Look for standalone plugins and disable if active.
2845
2846
		$to_deactivate = array();
2847
		foreach ( $modules as $module ) {
2848
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2849
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2850
			}
2851
		}
2852
2853
		$deactivated = array();
2854
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2855
			list( $probable_file, $probable_title ) = $deactivate_me;
2856
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2857
				$deactivated[] = $module;
2858
			}
2859
		}
2860
2861
		if ( $deactivated ) {
2862
			if ( $send_state_messages ) {
2863
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2864
			}
2865
2866
			if ( $redirect ) {
2867
				$url = add_query_arg(
2868
					array(
2869
						'action'   => 'activate_default_modules',
2870
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2871
					),
2872
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2873
				);
2874
				wp_safe_redirect( $url );
2875
				exit;
2876
			}
2877
		}
2878
2879
		/**
2880
		 * Fires before default modules are activated.
2881
		 *
2882
		 * @since 1.9.0
2883
		 *
2884
		 * @param string $min_version Minimum version number required to use modules.
2885
		 * @param string $max_version Maximum version number required to use modules.
2886
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2887
		 */
2888
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2889
2890
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2891
		if ( $send_state_messages ) {
2892
			self::restate();
2893
			self::catch_errors( true );
2894
		}
2895
2896
		$active = self::get_active_modules();
2897
2898
		foreach ( $modules as $module ) {
2899
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2900
				$active[] = $module;
2901
				self::update_active_modules( $active );
2902
				continue;
2903
			}
2904
2905
			if ( $send_state_messages && in_array( $module, $active ) ) {
2906
				$module_info = self::get_module( $module );
2907 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2908
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2909
					if ( $active_state = self::state( $state ) ) {
2910
						$active_state = explode( ',', $active_state );
2911
					} else {
2912
						$active_state = array();
2913
					}
2914
					$active_state[] = $module;
2915
					self::state( $state, implode( ',', $active_state ) );
2916
				}
2917
				continue;
2918
			}
2919
2920
			$file = self::get_module_path( $module );
2921
			if ( ! file_exists( $file ) ) {
2922
				continue;
2923
			}
2924
2925
			// we'll override this later if the plugin can be included without fatal error
2926
			if ( $redirect ) {
2927
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2928
			}
2929
2930
			if ( $send_state_messages ) {
2931
				self::state( 'error', 'module_activation_failed' );
2932
				self::state( 'module', $module );
2933
			}
2934
2935
			ob_start();
2936
			require_once $file;
2937
2938
			$active[] = $module;
2939
2940 View Code Duplication
			if ( $send_state_messages ) {
2941
2942
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2943
				if ( $active_state = self::state( $state ) ) {
2944
					$active_state = explode( ',', $active_state );
2945
				} else {
2946
					$active_state = array();
2947
				}
2948
				$active_state[] = $module;
2949
				self::state( $state, implode( ',', $active_state ) );
2950
			}
2951
2952
			self::update_active_modules( $active );
2953
2954
			ob_end_clean();
2955
		}
2956
2957
		if ( $send_state_messages ) {
2958
			self::state( 'error', false );
2959
			self::state( 'module', false );
2960
		}
2961
2962
		self::catch_errors( false );
2963
		/**
2964
		 * Fires when default modules are activated.
2965
		 *
2966
		 * @since 1.9.0
2967
		 *
2968
		 * @param string $min_version Minimum version number required to use modules.
2969
		 * @param string $max_version Maximum version number required to use modules.
2970
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2971
		 */
2972
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2973
	}
2974
2975
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2976
		/**
2977
		 * Fires before a module is activated.
2978
		 *
2979
		 * @since 2.6.0
2980
		 *
2981
		 * @param string $module Module slug.
2982
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2983
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2984
		 */
2985
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2986
2987
		$jetpack = self::init();
2988
2989
		if ( ! strlen( $module ) ) {
2990
			return false;
2991
		}
2992
2993
		if ( ! self::is_module( $module ) ) {
2994
			return false;
2995
		}
2996
2997
		// If it's already active, then don't do it again
2998
		$active = self::get_active_modules();
2999
		foreach ( $active as $act ) {
3000
			if ( $act == $module ) {
3001
				return true;
3002
			}
3003
		}
3004
3005
		$module_data = self::get_module( $module );
3006
3007
		$is_offline_mode = ( new Status() )->is_offline_mode();
3008
		if ( ! self::is_active() ) {
3009
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3010
				return false;
3011
			}
3012
3013
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3014
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3015
				return false;
3016
			}
3017
		}
3018
3019
		// Check and see if the old plugin is active
3020
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3021
			// Deactivate the old plugin
3022
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3023
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3024
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3025
				self::state( 'deactivated_plugins', $module );
3026
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3027
				exit;
3028
			}
3029
		}
3030
3031
		// Protect won't work with mis-configured IPs
3032
		if ( 'protect' === $module ) {
3033
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3034
			if ( ! jetpack_protect_get_ip() ) {
3035
				self::state( 'message', 'protect_misconfigured_ip' );
3036
				return false;
3037
			}
3038
		}
3039
3040
		if ( ! Jetpack_Plan::supports( $module ) ) {
3041
			return false;
3042
		}
3043
3044
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3045
		self::state( 'module', $module );
3046
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3047
3048
		self::catch_errors( true );
3049
		ob_start();
3050
		require self::get_module_path( $module );
3051
		/** This action is documented in class.jetpack.php */
3052
		do_action( 'jetpack_activate_module', $module );
3053
		$active[] = $module;
3054
		self::update_active_modules( $active );
3055
3056
		self::state( 'error', false ); // the override
3057
		ob_end_clean();
3058
		self::catch_errors( false );
3059
3060
		if ( $redirect ) {
3061
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3062
		}
3063
		if ( $exit ) {
3064
			exit;
3065
		}
3066
		return true;
3067
	}
3068
3069
	function activate_module_actions( $module ) {
3070
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3071
	}
3072
3073
	public static function deactivate_module( $module ) {
3074
		/**
3075
		 * Fires when a module is deactivated.
3076
		 *
3077
		 * @since 1.9.0
3078
		 *
3079
		 * @param string $module Module slug.
3080
		 */
3081
		do_action( 'jetpack_pre_deactivate_module', $module );
3082
3083
		$jetpack = self::init();
3084
3085
		$active = self::get_active_modules();
3086
		$new    = array_filter( array_diff( $active, (array) $module ) );
3087
3088
		return self::update_active_modules( $new );
3089
	}
3090
3091
	public static function enable_module_configurable( $module ) {
3092
		$module = self::get_module_slug( $module );
3093
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3094
	}
3095
3096
	/**
3097
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3098
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3099
	 *
3100
	 * @param string $module Module slug
3101
	 * @return string $url module configuration URL
3102
	 */
3103
	public static function module_configuration_url( $module ) {
3104
		$module      = self::get_module_slug( $module );
3105
		$default_url = self::admin_url() . "#/settings?term=$module";
3106
		/**
3107
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3108
		 *
3109
		 * @since 6.9.0
3110
		 *
3111
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3112
		 */
3113
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3114
3115
		return $url;
3116
	}
3117
3118
	/* Installation */
3119
	public static function bail_on_activation( $message, $deactivate = true ) {
3120
		?>
3121
<!doctype html>
3122
<html>
3123
<head>
3124
<meta charset="<?php bloginfo( 'charset' ); ?>">
3125
<style>
3126
* {
3127
	text-align: center;
3128
	margin: 0;
3129
	padding: 0;
3130
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3131
}
3132
p {
3133
	margin-top: 1em;
3134
	font-size: 18px;
3135
}
3136
</style>
3137
<body>
3138
<p><?php echo esc_html( $message ); ?></p>
3139
</body>
3140
</html>
3141
		<?php
3142
		if ( $deactivate ) {
3143
			$plugins = get_option( 'active_plugins' );
3144
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3145
			$update  = false;
3146
			foreach ( $plugins as $i => $plugin ) {
3147
				if ( $plugin === $jetpack ) {
3148
					$plugins[ $i ] = false;
3149
					$update        = true;
3150
				}
3151
			}
3152
3153
			if ( $update ) {
3154
				update_option( 'active_plugins', array_filter( $plugins ) );
3155
			}
3156
		}
3157
		exit;
3158
	}
3159
3160
	/**
3161
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3162
	 *
3163
	 * @static
3164
	 */
3165
	public static function plugin_activation( $network_wide ) {
3166
		Jetpack_Options::update_option( 'activated', 1 );
3167
3168
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3169
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3170
		}
3171
3172
		if ( $network_wide ) {
3173
			self::state( 'network_nag', true );
3174
		}
3175
3176
		// For firing one-off events (notices) immediately after activation
3177
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3178
3179
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3180
3181
		Health::on_jetpack_activated();
3182
3183
		self::plugin_initialize();
3184
	}
3185
3186
	public static function get_activation_source( $referer_url ) {
3187
3188
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3189
			return array( 'wp-cli', null );
3190
		}
3191
3192
		$referer = wp_parse_url( $referer_url );
3193
3194
		$source_type  = 'unknown';
3195
		$source_query = null;
3196
3197
		if ( ! is_array( $referer ) ) {
3198
			return array( $source_type, $source_query );
3199
		}
3200
3201
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3202
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3203
3204
		if ( isset( $referer['query'] ) ) {
3205
			parse_str( $referer['query'], $query_parts );
3206
		} else {
3207
			$query_parts = array();
3208
		}
3209
3210
		if ( $plugins_path === $referer['path'] ) {
3211
			$source_type = 'list';
3212
		} elseif ( $plugins_install_path === $referer['path'] ) {
3213
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3214
			switch ( $tab ) {
3215
				case 'popular':
3216
					$source_type = 'popular';
3217
					break;
3218
				case 'recommended':
3219
					$source_type = 'recommended';
3220
					break;
3221
				case 'favorites':
3222
					$source_type = 'favorites';
3223
					break;
3224
				case 'search':
3225
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3226
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3227
					break;
3228
				default:
3229
					$source_type = 'featured';
3230
			}
3231
		}
3232
3233
		return array( $source_type, $source_query );
3234
	}
3235
3236
	/**
3237
	 * Runs before bumping version numbers up to a new version
3238
	 *
3239
	 * @param string $version    Version:timestamp.
3240
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3241
	 */
3242
	public static function do_version_bump( $version, $old_version ) {
3243
		if ( $old_version ) { // For existing Jetpack installations.
3244
3245
			// If a front end page is visited after the update, the 'wp' action will fire.
3246
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3247
3248
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3249
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3250
		}
3251
	}
3252
3253
	/**
3254
	 * Sets the display_update_modal state.
3255
	 */
3256
	public static function set_update_modal_display() {
3257
		self::state( 'display_update_modal', true );
3258
	}
3259
3260
	/**
3261
	 * Sets the internal version number and activation state.
3262
	 *
3263
	 * @static
3264
	 */
3265
	public static function plugin_initialize() {
3266
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3267
			Jetpack_Options::update_option( 'activated', 2 );
3268
		}
3269
3270 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3271
			$version = $old_version = JETPACK__VERSION . ':' . time();
3272
			/** This action is documented in class.jetpack.php */
3273
			do_action( 'updating_jetpack_version', $version, false );
3274
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3275
		}
3276
3277
		self::load_modules();
3278
3279
		Jetpack_Options::delete_option( 'do_activate' );
3280
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3281
	}
3282
3283
	/**
3284
	 * Removes all connection options
3285
	 *
3286
	 * @static
3287
	 */
3288
	public static function plugin_deactivation() {
3289
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3290
		$tracking = new Tracking();
3291
		$tracking->record_user_event( 'deactivate_plugin', array() );
3292
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3293
			Jetpack_Network::init()->deactivate();
3294
		} else {
3295
			self::disconnect( false );
3296
			// Jetpack_Heartbeat::init()->deactivate();
3297
		}
3298
	}
3299
3300
	/**
3301
	 * Disconnects from the Jetpack servers.
3302
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3303
	 *
3304
	 * @static
3305
	 */
3306
	public static function disconnect( $update_activated_state = true ) {
3307
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3308
3309
		$connection = self::connection();
3310
		$connection->clean_nonces( true );
3311
3312
		// If the site is in an IDC because sync is not allowed,
3313
		// let's make sure to not disconnect the production site.
3314
		if ( ! self::validate_sync_error_idc_option() ) {
3315
			$tracking = new Tracking();
3316
			$tracking->record_user_event( 'disconnect_site', array() );
3317
3318
			$connection->disconnect_site_wpcom( true );
3319
		}
3320
3321
		$connection->delete_all_connection_tokens( true );
3322
		Jetpack_IDC::clear_all_idc_options();
3323
3324
		if ( $update_activated_state ) {
3325
			Jetpack_Options::update_option( 'activated', 4 );
3326
		}
3327
3328
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3329
			// Check then record unique disconnection if site has never been disconnected previously
3330
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3331
				$jetpack_unique_connection['disconnected'] = 1;
3332
			} else {
3333
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3334
					// track unique disconnect
3335
					$jetpack = self::init();
3336
3337
					$jetpack->stat( 'connections', 'unique-disconnect' );
3338
					$jetpack->do_stats( 'server_side' );
3339
				}
3340
				// increment number of times disconnected
3341
				$jetpack_unique_connection['disconnected'] += 1;
3342
			}
3343
3344
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3345
		}
3346
3347
		// Delete all the sync related data. Since it could be taking up space.
3348
		Sender::get_instance()->uninstall();
3349
3350
	}
3351
3352
	/**
3353
	 * Unlinks the current user from the linked WordPress.com user.
3354
	 *
3355
	 * @deprecated since 7.7
3356
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3357
	 *
3358
	 * @param Integer $user_id the user identifier.
3359
	 * @return Boolean Whether the disconnection of the user was successful.
3360
	 */
3361
	public static function unlink_user( $user_id = null ) {
3362
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3363
		return Connection_Manager::disconnect_user( $user_id );
3364
	}
3365
3366
	/**
3367
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3368
	 */
3369
	public static function try_registration() {
3370
		$terms_of_service = new Terms_Of_Service();
3371
		// The user has agreed to the TOS at some point by now.
3372
		$terms_of_service->agree();
3373
3374
		// Let's get some testing in beta versions and such.
3375
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3376
			// Before attempting to connect, let's make sure that the domains are viable.
3377
			$domains_to_check = array_unique(
3378
				array(
3379
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3380
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3381
				)
3382
			);
3383
			foreach ( $domains_to_check as $domain ) {
3384
				$result = self::connection()->is_usable_domain( $domain );
3385
				if ( is_wp_error( $result ) ) {
3386
					return $result;
3387
				}
3388
			}
3389
		}
3390
3391
		$result = self::register();
3392
3393
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3394
		if ( ! $result || is_wp_error( $result ) ) {
3395
			return $result;
3396
		} else {
3397
			return true;
3398
		}
3399
	}
3400
3401
	/**
3402
	 * Tracking an internal event log. Try not to put too much chaff in here.
3403
	 *
3404
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3405
	 */
3406
	public static function log( $code, $data = null ) {
3407
		// only grab the latest 200 entries
3408
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3409
3410
		// Append our event to the log
3411
		$log_entry = array(
3412
			'time'    => time(),
3413
			'user_id' => get_current_user_id(),
3414
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3415
			'code'    => $code,
3416
		);
3417
		// Don't bother storing it unless we've got some.
3418
		if ( ! is_null( $data ) ) {
3419
			$log_entry['data'] = $data;
3420
		}
3421
		$log[] = $log_entry;
3422
3423
		// Try add_option first, to make sure it's not autoloaded.
3424
		// @todo: Add an add_option method to Jetpack_Options
3425
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3426
			Jetpack_Options::update_option( 'log', $log );
3427
		}
3428
3429
		/**
3430
		 * Fires when Jetpack logs an internal event.
3431
		 *
3432
		 * @since 3.0.0
3433
		 *
3434
		 * @param array $log_entry {
3435
		 *  Array of details about the log entry.
3436
		 *
3437
		 *  @param string time Time of the event.
3438
		 *  @param int user_id ID of the user who trigerred the event.
3439
		 *  @param int blog_id Jetpack Blog ID.
3440
		 *  @param string code Unique name for the event.
3441
		 *  @param string data Data about the event.
3442
		 * }
3443
		 */
3444
		do_action( 'jetpack_log_entry', $log_entry );
3445
	}
3446
3447
	/**
3448
	 * Get the internal event log.
3449
	 *
3450
	 * @param $event (string) - only return the specific log events
3451
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3452
	 *
3453
	 * @return array of log events || WP_Error for invalid params
3454
	 */
3455
	public static function get_log( $event = false, $num = false ) {
3456
		if ( $event && ! is_string( $event ) ) {
3457
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3458
		}
3459
3460
		if ( $num && ! is_numeric( $num ) ) {
3461
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3462
		}
3463
3464
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3465
3466
		// If nothing set - act as it did before, otherwise let's start customizing the output
3467
		if ( ! $num && ! $event ) {
3468
			return $entire_log;
3469
		} else {
3470
			$entire_log = array_reverse( $entire_log );
3471
		}
3472
3473
		$custom_log_output = array();
3474
3475
		if ( $event ) {
3476
			foreach ( $entire_log as $log_event ) {
3477
				if ( $event == $log_event['code'] ) {
3478
					$custom_log_output[] = $log_event;
3479
				}
3480
			}
3481
		} else {
3482
			$custom_log_output = $entire_log;
3483
		}
3484
3485
		if ( $num ) {
3486
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3487
		}
3488
3489
		return $custom_log_output;
3490
	}
3491
3492
	/**
3493
	 * Log modification of important settings.
3494
	 */
3495
	public static function log_settings_change( $option, $old_value, $value ) {
3496
		switch ( $option ) {
3497
			case 'jetpack_sync_non_public_post_stati':
3498
				self::log( $option, $value );
3499
				break;
3500
		}
3501
	}
3502
3503
	/**
3504
	 * Return stat data for WPCOM sync
3505
	 */
3506
	public static function get_stat_data( $encode = true, $extended = true ) {
3507
		$data = Jetpack_Heartbeat::generate_stats_array();
3508
3509
		if ( $extended ) {
3510
			$additional_data = self::get_additional_stat_data();
3511
			$data            = array_merge( $data, $additional_data );
3512
		}
3513
3514
		if ( $encode ) {
3515
			return json_encode( $data );
3516
		}
3517
3518
		return $data;
3519
	}
3520
3521
	/**
3522
	 * Get additional stat data to sync to WPCOM
3523
	 */
3524
	public static function get_additional_stat_data( $prefix = '' ) {
3525
		$return[ "{$prefix}themes" ]        = self::get_parsed_theme_data();
3526
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3527
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3528
		$return[ "{$prefix}site-count" ]    = 0;
3529
3530
		if ( function_exists( 'get_blog_count' ) ) {
3531
			$return[ "{$prefix}site-count" ] = get_blog_count();
3532
		}
3533
		return $return;
3534
	}
3535
3536
	private static function get_site_user_count() {
3537
		global $wpdb;
3538
3539
		if ( function_exists( 'wp_is_large_network' ) ) {
3540
			if ( wp_is_large_network( 'users' ) ) {
3541
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3542
			}
3543
		}
3544
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3545
			// It wasn't there, so regenerate the data and save the transient
3546
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3547
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3548
		}
3549
		return $user_count;
3550
	}
3551
3552
	/* Admin Pages */
3553
3554
	function admin_init() {
3555
		// If the plugin is not connected, display a connect message.
3556
		if (
3557
			// the plugin was auto-activated and needs its candy
3558
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3559
		||
3560
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3561
			! Jetpack_Options::get_option( 'activated' )
3562
		) {
3563
			self::plugin_initialize();
3564
		}
3565
3566
		$is_offline_mode = ( new Status() )->is_offline_mode();
3567
		if ( ! self::is_active() && ! $is_offline_mode ) {
3568
			Jetpack_Connection_Banner::init();
3569
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3570
			// Upgrade: 1.1 -> 1.1.1
3571
			// Check and see if host can verify the Jetpack servers' SSL certificate
3572
			$args = array();
3573
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3574
		}
3575
3576
		Jetpack_Wizard_Banner::init();
3577
3578
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3579
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3580
		}
3581
3582
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3583
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3584
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3585
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3586
3587
		if ( self::is_active() || $is_offline_mode ) {
3588
			// Artificially throw errors in certain specific cases during plugin activation.
3589
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3590
		}
3591
3592
		// Add custom column in wp-admin/users.php to show whether user is linked.
3593
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3594
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3595
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3596
	}
3597
3598
	function admin_body_class( $admin_body_class = '' ) {
3599
		$classes = explode( ' ', trim( $admin_body_class ) );
3600
3601
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3602
3603
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3604
		return " $admin_body_class ";
3605
	}
3606
3607
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3608
		return $admin_body_class . ' jetpack-pagestyles ';
3609
	}
3610
3611
	/**
3612
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3613
	 * This function artificially throws errors for such cases (per a specific list).
3614
	 *
3615
	 * @param string $plugin The activated plugin.
3616
	 */
3617
	function throw_error_on_activate_plugin( $plugin ) {
3618
		$active_modules = self::get_active_modules();
3619
3620
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3621
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3622
			$throw = false;
3623
3624
			// Try and make sure it really was the stats plugin
3625
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3626
				if ( 'stats.php' == basename( $plugin ) ) {
3627
					$throw = true;
3628
				}
3629
			} else {
3630
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3631
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3632
					$throw = true;
3633
				}
3634
			}
3635
3636
			if ( $throw ) {
3637
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3638
			}
3639
		}
3640
	}
3641
3642
	function intercept_plugin_error_scrape_init() {
3643
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3644
	}
3645
3646
	function intercept_plugin_error_scrape( $action, $result ) {
3647
		if ( ! $result ) {
3648
			return;
3649
		}
3650
3651
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3652
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3653
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3654
			}
3655
		}
3656
	}
3657
3658
	/**
3659
	 * Register the remote file upload request handlers, if needed.
3660
	 *
3661
	 * @access public
3662
	 */
3663
	public function add_remote_request_handlers() {
3664
		// Remote file uploads are allowed only via AJAX requests.
3665
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3666
			return;
3667
		}
3668
3669
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3670
		$remote_request_actions = array(
3671
			'jetpack_upload_file',
3672
			'jetpack_update_file',
3673
		);
3674
3675
		// phpcs:ignore WordPress.Security.NonceVerification
3676
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3677
			return;
3678
		}
3679
3680
		// Require Jetpack authentication for the remote file upload AJAX requests.
3681
		if ( ! $this->connection_manager ) {
3682
			$this->connection_manager = new Connection_Manager();
3683
		}
3684
3685
		$this->connection_manager->require_jetpack_authentication();
3686
3687
		// Register the remote file upload AJAX handlers.
3688
		foreach ( $remote_request_actions as $action ) {
3689
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3690
		}
3691
	}
3692
3693
	/**
3694
	 * Handler for Jetpack remote file uploads.
3695
	 *
3696
	 * @access public
3697
	 */
3698
	public function remote_request_handlers() {
3699
		$action = current_filter();
3700
3701
		switch ( current_filter() ) {
3702
			case 'wp_ajax_nopriv_jetpack_upload_file':
3703
				$response = $this->upload_handler();
3704
				break;
3705
3706
			case 'wp_ajax_nopriv_jetpack_update_file':
3707
				$response = $this->upload_handler( true );
3708
				break;
3709
			default:
3710
				$response = new WP_Error( 'unknown_handler', 'Unknown Handler', 400 );
3711
				break;
3712
		}
3713
3714
		if ( ! $response ) {
3715
			$response = new WP_Error( 'unknown_error', 'Unknown Error', 400 );
3716
		}
3717
3718
		if ( is_wp_error( $response ) ) {
3719
			$status_code       = $response->get_error_data();
3720
			$error             = $response->get_error_code();
3721
			$error_description = $response->get_error_message();
3722
3723
			if ( ! is_int( $status_code ) ) {
3724
				$status_code = 400;
3725
			}
3726
3727
			status_header( $status_code );
3728
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3729
		}
3730
3731
		status_header( 200 );
3732
		if ( true === $response ) {
3733
			exit;
3734
		}
3735
3736
		die( json_encode( (object) $response ) );
3737
	}
3738
3739
	/**
3740
	 * Uploads a file gotten from the global $_FILES.
3741
	 * If `$update_media_item` is true and `post_id` is defined
3742
	 * the attachment file of the media item (gotten through of the post_id)
3743
	 * will be updated instead of add a new one.
3744
	 *
3745
	 * @param  boolean $update_media_item - update media attachment
3746
	 * @return array - An array describing the uploadind files process
3747
	 */
3748
	function upload_handler( $update_media_item = false ) {
3749
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3750
			return new WP_Error( 405, get_status_header_desc( 405 ), 405 );
3751
		}
3752
3753
		$user = wp_authenticate( '', '' );
3754
		if ( ! $user || is_wp_error( $user ) ) {
3755
			return new WP_Error( 403, get_status_header_desc( 403 ), 403 );
3756
		}
3757
3758
		wp_set_current_user( $user->ID );
3759
3760
		if ( ! current_user_can( 'upload_files' ) ) {
3761
			return new WP_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3762
		}
3763
3764
		if ( empty( $_FILES ) ) {
3765
			return new WP_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3766
		}
3767
3768
		foreach ( array_keys( $_FILES ) as $files_key ) {
3769
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3770
				return new WP_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3771
			}
3772
		}
3773
3774
		$media_keys = array_keys( $_FILES['media'] );
3775
3776
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3777
		if ( ! $token || is_wp_error( $token ) ) {
3778
			return new WP_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3779
		}
3780
3781
		$uploaded_files = array();
3782
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3783
		unset( $GLOBALS['post'] );
3784
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3785
			$file = array();
3786
			foreach ( $media_keys as $media_key ) {
3787
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3788
			}
3789
3790
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3791
3792
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3793
			if ( $hmac_provided !== $hmac_file ) {
3794
				$uploaded_files[ $index ] = (object) array(
3795
					'error'             => 'invalid_hmac',
3796
					'error_description' => 'The corresponding HMAC for this file does not match',
3797
				);
3798
				continue;
3799
			}
3800
3801
			$_FILES['.jetpack.upload.'] = $file;
3802
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3803
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3804
				$post_id = 0;
3805
			}
3806
3807
			if ( $update_media_item ) {
3808
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3809
					return new WP_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3810
				}
3811
3812
				$media_array = $_FILES['media'];
3813
3814
				$file_array['name']     = $media_array['name'][0];
3815
				$file_array['type']     = $media_array['type'][0];
3816
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3817
				$file_array['error']    = $media_array['error'][0];
3818
				$file_array['size']     = $media_array['size'][0];
3819
3820
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3821
3822
				if ( is_wp_error( $edited_media_item ) ) {
3823
					return $edited_media_item;
3824
				}
3825
3826
				$response = (object) array(
3827
					'id'   => (string) $post_id,
3828
					'file' => (string) $edited_media_item->post_title,
3829
					'url'  => (string) wp_get_attachment_url( $post_id ),
3830
					'type' => (string) $edited_media_item->post_mime_type,
3831
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3832
				);
3833
3834
				return (array) array( $response );
3835
			}
3836
3837
			$attachment_id = media_handle_upload(
3838
				'.jetpack.upload.',
3839
				$post_id,
3840
				array(),
3841
				array(
3842
					'action' => 'jetpack_upload_file',
3843
				)
3844
			);
3845
3846
			if ( ! $attachment_id ) {
3847
				$uploaded_files[ $index ] = (object) array(
3848
					'error'             => 'unknown',
3849
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3850
				);
3851
			} elseif ( is_wp_error( $attachment_id ) ) {
3852
				$uploaded_files[ $index ] = (object) array(
3853
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3854
					'error_description' => $attachment_id->get_error_message(),
3855
				);
3856
			} else {
3857
				$attachment               = get_post( $attachment_id );
3858
				$uploaded_files[ $index ] = (object) array(
3859
					'id'   => (string) $attachment_id,
3860
					'file' => $attachment->post_title,
3861
					'url'  => wp_get_attachment_url( $attachment_id ),
3862
					'type' => $attachment->post_mime_type,
3863
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3864
				);
3865
				// Zip files uploads are not supported unless they are done for installation purposed
3866
				// lets delete them in case something goes wrong in this whole process
3867
				if ( 'application/zip' === $attachment->post_mime_type ) {
3868
					// Schedule a cleanup for 2 hours from now in case of failed install.
3869
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3870
				}
3871
			}
3872
		}
3873
		if ( ! is_null( $global_post ) ) {
3874
			$GLOBALS['post'] = $global_post;
3875
		}
3876
3877
		return $uploaded_files;
3878
	}
3879
3880
	/**
3881
	 * Add help to the Jetpack page
3882
	 *
3883
	 * @since Jetpack (1.2.3)
3884
	 * @return false if not the Jetpack page
3885
	 */
3886
	function admin_help() {
3887
		$current_screen = get_current_screen();
3888
3889
		// Overview
3890
		$current_screen->add_help_tab(
3891
			array(
3892
				'id'      => 'home',
3893
				'title'   => __( 'Home', 'jetpack' ),
3894
				'content' =>
3895
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3896
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3897
					'<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>',
3898
			)
3899
		);
3900
3901
		// Screen Content
3902
		if ( current_user_can( 'manage_options' ) ) {
3903
			$current_screen->add_help_tab(
3904
				array(
3905
					'id'      => 'settings',
3906
					'title'   => __( 'Settings', 'jetpack' ),
3907
					'content' =>
3908
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3909
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3910
						'<ol>' .
3911
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3912
							'<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>' .
3913
						'</ol>' .
3914
						'<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>',
3915
				)
3916
			);
3917
		}
3918
3919
		// Help Sidebar
3920
		$support_url = Redirect::get_url( 'jetpack-support' );
3921
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3922
		$current_screen->set_help_sidebar(
3923
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3924
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3925
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3926
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3927
		);
3928
	}
3929
3930
	function admin_menu_css() {
3931
		wp_enqueue_style( 'jetpack-icons' );
3932
	}
3933
3934
	function admin_menu_order() {
3935
		return true;
3936
	}
3937
3938
	function jetpack_menu_order( $menu_order ) {
3939
		$jp_menu_order = array();
3940
3941
		foreach ( $menu_order as $index => $item ) {
3942
			if ( $item != 'jetpack' ) {
3943
				$jp_menu_order[] = $item;
3944
			}
3945
3946
			if ( $index == 0 ) {
3947
				$jp_menu_order[] = 'jetpack';
3948
			}
3949
		}
3950
3951
		return $jp_menu_order;
3952
	}
3953
3954
	function admin_banner_styles() {
3955
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3956
3957 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3958
			wp_register_style(
3959
				'jetpack-dops-style',
3960
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3961
				array(),
3962
				JETPACK__VERSION
3963
			);
3964
		}
3965
3966
		wp_enqueue_style(
3967
			'jetpack',
3968
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3969
			array( 'jetpack-dops-style' ),
3970
			JETPACK__VERSION . '-20121016'
3971
		);
3972
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3973
		wp_style_add_data( 'jetpack', 'suffix', $min );
3974
	}
3975
3976
	function plugin_action_links( $actions ) {
3977
3978
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3979
3980
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_offline_mode() ) ) {
3981
			return array_merge(
3982
				$jetpack_home,
3983
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3984
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
3985
				$actions
3986
			);
3987
		}
3988
3989
		return array_merge( $jetpack_home, $actions );
3990
	}
3991
3992
	/**
3993
	 * Adds the deactivation warning modal if there are other active plugins using the connection
3994
	 *
3995
	 * @param string $hook The current admin page.
3996
	 *
3997
	 * @return void
3998
	 */
3999
	public function deactivate_dialog( $hook ) {
4000
		if (
4001
			'plugins.php' === $hook
4002
			&& self::is_active()
4003
		) {
4004
4005
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4006
4007
			if ( count( $active_plugins_using_connection ) > 1 ) {
4008
4009
				add_thickbox();
4010
4011
				wp_register_script(
4012
					'jp-tracks',
4013
					'//stats.wp.com/w.js',
4014
					array(),
4015
					gmdate( 'YW' ),
4016
					true
4017
				);
4018
4019
				wp_register_script(
4020
					'jp-tracks-functions',
4021
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4022
					array( 'jp-tracks' ),
4023
					JETPACK__VERSION,
4024
					false
4025
				);
4026
4027
				wp_enqueue_script(
4028
					'jetpack-deactivate-dialog-js',
4029
					Assets::get_file_url_for_environment(
4030
						'_inc/build/jetpack-deactivate-dialog.min.js',
4031
						'_inc/jetpack-deactivate-dialog.js'
4032
					),
4033
					array( 'jquery', 'jp-tracks-functions' ),
4034
					JETPACK__VERSION,
4035
					true
4036
				);
4037
4038
				wp_localize_script(
4039
					'jetpack-deactivate-dialog-js',
4040
					'deactivate_dialog',
4041
					array(
4042
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4043
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4044
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4045
					)
4046
				);
4047
4048
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4049
4050
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4051
			}
4052
		}
4053
	}
4054
4055
	/**
4056
	 * Outputs the content of the deactivation modal
4057
	 *
4058
	 * @return void
4059
	 */
4060
	public function deactivate_dialog_content() {
4061
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4062
		unset( $active_plugins_using_connection['jetpack'] );
4063
		$this->load_view( 'admin/deactivation-dialog.php', $active_plugins_using_connection );
4064
	}
4065
4066
	/**
4067
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4068
	 *
4069
	 * @param string $login_url The wp-login URL.
4070
	 * @param string $redirect  URL to redirect users after logging in.
4071
	 * @since Jetpack 8.4
4072
	 * @return string
4073
	 */
4074
	public function login_url( $login_url, $redirect ) {
4075
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4076
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4077
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4078
		}
4079
		return $login_url;
4080
	}
4081
4082
	/**
4083
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4084
	 *
4085
	 * @since Jetpack 8.4
4086
	 */
4087
	public function login_init() {
4088
		// phpcs:ignore WordPress.Security.NonceVerification
4089
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4090
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4091
			wp_safe_redirect(
4092
				add_query_arg(
4093
					array(
4094
						'forceInstall' => 1,
4095
						'url'          => rawurlencode( get_site_url() ),
4096
					),
4097
					// @todo provide way to go to specific calypso env.
4098
					self::get_calypso_host() . 'jetpack/connect'
4099
				)
4100
			);
4101
			exit;
4102
		}
4103
	}
4104
4105
	/*
4106
	 * Registration flow:
4107
	 * 1 - ::admin_page_load() action=register
4108
	 * 2 - ::try_registration()
4109
	 * 3 - ::register()
4110
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4111
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4112
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4113
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4114
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4115
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4116
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4117
	 *       jetpack_id, jetpack_secret, jetpack_public
4118
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4119
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4120
	 * 5 - user logs in with WP.com account
4121
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4122
	 *		- Manager::authorize()
4123
	 *		- Manager::get_token()
4124
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4125
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4126
	 *			- which responds with access_token, token_type, scope
4127
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4128
	 *		- Jetpack::activate_default_modules()
4129
	 *     		- Deactivates deprecated plugins
4130
	 *     		- Activates all default modules
4131
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4132
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4133
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4134
	 *     Done!
4135
	 */
4136
4137
	/**
4138
	 * Handles the page load events for the Jetpack admin page
4139
	 */
4140
	function admin_page_load() {
4141
		$error = false;
4142
4143
		// Make sure we have the right body class to hook stylings for subpages off of.
4144
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4145
4146
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4147
			// Should only be used in intermediate redirects to preserve state across redirects
4148
			self::restate();
4149
		}
4150
4151
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4152
			// @todo: Add validation against a known allowed list.
4153
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4154
			// User clicked in the iframe to link their accounts
4155
			if ( ! self::is_user_connected() ) {
4156
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4157
4158
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4159
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4160
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4161
4162
				if ( isset( $_GET['notes_iframe'] ) ) {
4163
					$connect_url .= '&notes_iframe';
4164
				}
4165
				wp_redirect( $connect_url );
4166
				exit;
4167
			} else {
4168
				if ( ! isset( $_GET['calypso_env'] ) ) {
4169
					self::state( 'message', 'already_authorized' );
4170
					wp_safe_redirect( self::admin_url() );
4171
					exit;
4172
				} else {
4173
					$connect_url  = $this->build_connect_url( true, false, $from );
4174
					$connect_url .= '&already_authorized=true';
4175
					wp_redirect( $connect_url );
4176
					exit;
4177
				}
4178
			}
4179
		}
4180
4181
		if ( isset( $_GET['action'] ) ) {
4182
			switch ( $_GET['action'] ) {
4183
				case 'authorize':
4184
					if ( self::is_active() && self::is_user_connected() ) {
4185
						self::state( 'message', 'already_authorized' );
4186
						wp_safe_redirect( self::admin_url() );
4187
						exit;
4188
					}
4189
					self::log( 'authorize' );
4190
					$client_server = new Jetpack_Client_Server();
4191
					$client_server->client_authorize();
4192
					exit;
4193
				case 'register':
4194
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4195
						$error = 'cheatin';
4196
						break;
4197
					}
4198
					check_admin_referer( 'jetpack-register' );
4199
					self::log( 'register' );
4200
					self::maybe_set_version_option();
4201
					$registered = self::try_registration();
4202 View Code Duplication
					if ( is_wp_error( $registered ) ) {
4203
						$error = $registered->get_error_code();
4204
						self::state( 'error', $error );
4205
						self::state( 'error', $registered->get_error_message() );
4206
4207
						/**
4208
						 * Jetpack registration Error.
4209
						 *
4210
						 * @since 7.5.0
4211
						 *
4212
						 * @param string|int $error The error code.
4213
						 * @param \WP_Error $registered The error object.
4214
						 */
4215
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4216
						break;
4217
					}
4218
4219
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4220
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4221
4222
					/**
4223
					 * Jetpack registration Success.
4224
					 *
4225
					 * @since 7.5.0
4226
					 *
4227
					 * @param string $from 'from' GET parameter;
4228
					 */
4229
					do_action( 'jetpack_connection_register_success', $from );
4230
4231
					$url = $this->build_connect_url( true, $redirect, $from );
4232
4233
					if ( ! empty( $_GET['onboarding'] ) ) {
4234
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4235
					}
4236
4237
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4238
						$url = add_query_arg( 'auth_approved', 'true', $url );
4239
					}
4240
4241
					wp_redirect( $url );
4242
					exit;
4243
				case 'activate':
4244
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4245
						$error = 'cheatin';
4246
						break;
4247
					}
4248
4249
					$module = stripslashes( $_GET['module'] );
4250
					check_admin_referer( "jetpack_activate-$module" );
4251
					self::log( 'activate', $module );
4252
					if ( ! self::activate_module( $module ) ) {
4253
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4254
					}
4255
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4256
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4257
					exit;
4258
				case 'activate_default_modules':
4259
					check_admin_referer( 'activate_default_modules' );
4260
					self::log( 'activate_default_modules' );
4261
					self::restate();
4262
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4263
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4264
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4265
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4266
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4267
					exit;
4268
				case 'disconnect':
4269
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4270
						$error = 'cheatin';
4271
						break;
4272
					}
4273
4274
					check_admin_referer( 'jetpack-disconnect' );
4275
					self::log( 'disconnect' );
4276
					self::disconnect();
4277
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4278
					exit;
4279
				case 'reconnect':
4280
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4281
						$error = 'cheatin';
4282
						break;
4283
					}
4284
4285
					check_admin_referer( 'jetpack-reconnect' );
4286
					self::log( 'reconnect' );
4287
					$this->disconnect();
4288
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4289
					exit;
4290 View Code Duplication
				case 'deactivate':
4291
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4292
						$error = 'cheatin';
4293
						break;
4294
					}
4295
4296
					$modules = stripslashes( $_GET['module'] );
4297
					check_admin_referer( "jetpack_deactivate-$modules" );
4298
					foreach ( explode( ',', $modules ) as $module ) {
4299
						self::log( 'deactivate', $module );
4300
						self::deactivate_module( $module );
4301
						self::state( 'message', 'module_deactivated' );
4302
					}
4303
					self::state( 'module', $modules );
4304
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4305
					exit;
4306
				case 'unlink':
4307
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4308
					check_admin_referer( 'jetpack-unlink' );
4309
					self::log( 'unlink' );
4310
					Connection_Manager::disconnect_user();
4311
					self::state( 'message', 'unlinked' );
4312
					if ( 'sub-unlink' == $redirect ) {
4313
						wp_safe_redirect( admin_url() );
4314
					} else {
4315
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4316
					}
4317
					exit;
4318
				case 'onboard':
4319
					if ( ! current_user_can( 'manage_options' ) ) {
4320
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4321
					} else {
4322
						self::create_onboarding_token();
4323
						$url = $this->build_connect_url( true );
4324
4325
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4326
							$url = add_query_arg( 'onboarding', $token, $url );
4327
						}
4328
4329
						$calypso_env = $this->get_calypso_env();
4330
						if ( ! empty( $calypso_env ) ) {
4331
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4332
						}
4333
4334
						wp_redirect( $url );
4335
						exit;
4336
					}
4337
					exit;
4338
				default:
4339
					/**
4340
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4341
					 *
4342
					 * @since 2.6.0
4343
					 *
4344
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4345
					 */
4346
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4347
			}
4348
		}
4349
4350
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4351
			self::activate_new_modules( true );
4352
		}
4353
4354
		$message_code = self::state( 'message' );
4355
		if ( self::state( 'optin-manage' ) ) {
4356
			$activated_manage = $message_code;
4357
			$message_code     = 'jetpack-manage';
4358
		}
4359
4360
		switch ( $message_code ) {
4361
			case 'jetpack-manage':
4362
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4363
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4364
				$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>';
4365
				if ( $activated_manage ) {
4366
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4367
				}
4368
				break;
4369
4370
		}
4371
4372
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4373
4374
		if ( ! empty( $deactivated_plugins ) ) {
4375
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4376
			$deactivated_titles  = array();
4377
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4378
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4379
					continue;
4380
				}
4381
4382
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4383
			}
4384
4385
			if ( $deactivated_titles ) {
4386
				if ( $this->message ) {
4387
					$this->message .= "<br /><br />\n";
4388
				}
4389
4390
				$this->message .= wp_sprintf(
4391
					_n(
4392
						'Jetpack contains the most recent version of the old %l plugin.',
4393
						'Jetpack contains the most recent versions of the old %l plugins.',
4394
						count( $deactivated_titles ),
4395
						'jetpack'
4396
					),
4397
					$deactivated_titles
4398
				);
4399
4400
				$this->message .= "<br />\n";
4401
4402
				$this->message .= _n(
4403
					'The old version has been deactivated and can be removed from your site.',
4404
					'The old versions have been deactivated and can be removed from your site.',
4405
					count( $deactivated_titles ),
4406
					'jetpack'
4407
				);
4408
			}
4409
		}
4410
4411
		$this->privacy_checks = self::state( 'privacy_checks' );
4412
4413
		if ( $this->message || $this->error || $this->privacy_checks ) {
4414
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4415
		}
4416
4417
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4418
	}
4419
4420
	function admin_notices() {
4421
4422
		if ( $this->error ) {
4423
			?>
4424
<div id="message" class="jetpack-message jetpack-err">
4425
	<div class="squeezer">
4426
		<h2>
4427
			<?php
4428
			echo wp_kses(
4429
				$this->error,
4430
				array(
4431
					'a'      => array( 'href' => array() ),
4432
					'small'  => true,
4433
					'code'   => true,
4434
					'strong' => true,
4435
					'br'     => true,
4436
					'b'      => true,
4437
				)
4438
			);
4439
			?>
4440
			</h2>
4441
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4442
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4443
<?php	endif; ?>
4444
	</div>
4445
</div>
4446
			<?php
4447
		}
4448
4449
		if ( $this->message ) {
4450
			?>
4451
<div id="message" class="jetpack-message">
4452
	<div class="squeezer">
4453
		<h2>
4454
			<?php
4455
			echo wp_kses(
4456
				$this->message,
4457
				array(
4458
					'strong' => array(),
4459
					'a'      => array( 'href' => true ),
4460
					'br'     => true,
4461
				)
4462
			);
4463
			?>
4464
			</h2>
4465
	</div>
4466
</div>
4467
			<?php
4468
		}
4469
4470
		if ( $this->privacy_checks ) :
4471
			$module_names = $module_slugs = array();
4472
4473
			$privacy_checks = explode( ',', $this->privacy_checks );
4474
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4475
			foreach ( $privacy_checks as $module_slug ) {
4476
				$module = self::get_module( $module_slug );
4477
				if ( ! $module ) {
4478
					continue;
4479
				}
4480
4481
				$module_slugs[] = $module_slug;
4482
				$module_names[] = "<strong>{$module['name']}</strong>";
4483
			}
4484
4485
			$module_slugs = join( ',', $module_slugs );
4486
			?>
4487
<div id="message" class="jetpack-message jetpack-err">
4488
	<div class="squeezer">
4489
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4490
		<p>
4491
			<?php
4492
			echo wp_kses(
4493
				wptexturize(
4494
					wp_sprintf(
4495
						_nx(
4496
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4497
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4498
							count( $privacy_checks ),
4499
							'%l = list of Jetpack module/feature names',
4500
							'jetpack'
4501
						),
4502
						$module_names
4503
					)
4504
				),
4505
				array( 'strong' => true )
4506
			);
4507
4508
			echo "\n<br />\n";
4509
4510
			echo wp_kses(
4511
				sprintf(
4512
					_nx(
4513
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4514
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4515
						count( $privacy_checks ),
4516
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4517
						'jetpack'
4518
					),
4519
					wp_nonce_url(
4520
						self::admin_url(
4521
							array(
4522
								'page'   => 'jetpack',
4523
								'action' => 'deactivate',
4524
								'module' => urlencode( $module_slugs ),
4525
							)
4526
						),
4527
						"jetpack_deactivate-$module_slugs"
4528
					),
4529
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4530
				),
4531
				array(
4532
					'a' => array(
4533
						'href'  => true,
4534
						'title' => true,
4535
					),
4536
				)
4537
			);
4538
			?>
4539
		</p>
4540
	</div>
4541
</div>
4542
			<?php
4543
endif;
4544
	}
4545
4546
	/**
4547
	 * We can't always respond to a signed XML-RPC request with a
4548
	 * helpful error message. In some circumstances, doing so could
4549
	 * leak information.
4550
	 *
4551
	 * Instead, track that the error occurred via a Jetpack_Option,
4552
	 * and send that data back in the heartbeat.
4553
	 * All this does is increment a number, but it's enough to find
4554
	 * trends.
4555
	 *
4556
	 * @param WP_Error $xmlrpc_error The error produced during
4557
	 *                               signature validation.
4558
	 */
4559
	function track_xmlrpc_error( $xmlrpc_error ) {
4560
		$code = is_wp_error( $xmlrpc_error )
4561
			? $xmlrpc_error->get_error_code()
4562
			: 'should-not-happen';
4563
4564
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4565
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4566
			// No need to update the option if we already have
4567
			// this code stored.
4568
			return;
4569
		}
4570
		$xmlrpc_errors[ $code ] = true;
4571
4572
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
4573
	}
4574
4575
	/**
4576
	 * Initialize the jetpack stats instance only when needed
4577
	 *
4578
	 * @return void
4579
	 */
4580
	private function initialize_stats() {
4581
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4582
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4583
		}
4584
	}
4585
4586
	/**
4587
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4588
	 */
4589
	function stat( $group, $detail ) {
4590
		$this->initialize_stats();
4591
		$this->a8c_mc_stats_instance->add( $group, $detail );
4592
4593
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4594
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4595
	}
4596
4597
	/**
4598
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4599
	 */
4600
	function do_stats( $method = '' ) {
4601
		$this->initialize_stats();
4602
		if ( 'server_side' === $method ) {
4603
			$this->a8c_mc_stats_instance->do_server_side_stats();
4604
		} else {
4605
			$this->a8c_mc_stats_instance->do_stats();
4606
		}
4607
4608
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4609
		$this->stats = array();
4610
	}
4611
4612
	/**
4613
	 * Runs stats code for a one-off, server-side.
4614
	 *
4615
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4616
	 *
4617
	 * @return bool If it worked.
4618
	 */
4619
	static function do_server_side_stat( $args ) {
4620
		$url                   = self::build_stats_url( $args );
4621
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4622
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4623
	}
4624
4625
	/**
4626
	 * Builds the stats url.
4627
	 *
4628
	 * @param $args array|string The arguments to append to the URL.
4629
	 *
4630
	 * @return string The URL to be pinged.
4631
	 */
4632
	static function build_stats_url( $args ) {
4633
4634
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4635
		return $a8c_mc_stats_instance->build_stats_url( $args );
4636
4637
	}
4638
4639
	/**
4640
	 * Get the role of the current user.
4641
	 *
4642
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4643
	 *
4644
	 * @access public
4645
	 * @static
4646
	 *
4647
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4648
	 */
4649
	public static function translate_current_user_to_role() {
4650
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4651
4652
		$roles = new Roles();
4653
		return $roles->translate_current_user_to_role();
4654
	}
4655
4656
	/**
4657
	 * Get the role of a particular user.
4658
	 *
4659
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4660
	 *
4661
	 * @access public
4662
	 * @static
4663
	 *
4664
	 * @param \WP_User $user User object.
4665
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4666
	 */
4667
	public static function translate_user_to_role( $user ) {
4668
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4669
4670
		$roles = new Roles();
4671
		return $roles->translate_user_to_role( $user );
4672
	}
4673
4674
	/**
4675
	 * Get the minimum capability for a role.
4676
	 *
4677
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4678
	 *
4679
	 * @access public
4680
	 * @static
4681
	 *
4682
	 * @param string $role Role name.
4683
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4684
	 */
4685
	public static function translate_role_to_cap( $role ) {
4686
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4687
4688
		$roles = new Roles();
4689
		return $roles->translate_role_to_cap( $role );
4690
	}
4691
4692
	/**
4693
	 * Sign a user role with the master access token.
4694
	 * If not specified, will default to the current user.
4695
	 *
4696
	 * @deprecated since 7.7
4697
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4698
	 *
4699
	 * @access public
4700
	 * @static
4701
	 *
4702
	 * @param string $role    User role.
4703
	 * @param int    $user_id ID of the user.
4704
	 * @return string Signed user role.
4705
	 */
4706
	public static function sign_role( $role, $user_id = null ) {
4707
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4708
		return self::connection()->sign_role( $role, $user_id );
4709
	}
4710
4711
	/**
4712
	 * Builds a URL to the Jetpack connection auth page
4713
	 *
4714
	 * @since 3.9.5
4715
	 *
4716
	 * @param bool        $raw If true, URL will not be escaped.
4717
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4718
	 *                              If string, will be a custom redirect.
4719
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4720
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4721
	 *
4722
	 * @return string Connect URL
4723
	 */
4724
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4725
		$site_id    = Jetpack_Options::get_option( 'id' );
4726
		$blog_token = Jetpack_Data::get_access_token();
4727
4728
		if ( $register || ! $blog_token || ! $site_id ) {
4729
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4730
4731
			if ( ! empty( $redirect ) ) {
4732
				$url = add_query_arg(
4733
					'redirect',
4734
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4735
					$url
4736
				);
4737
			}
4738
4739
			if ( is_network_admin() ) {
4740
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4741
			}
4742
4743
			$calypso_env = self::get_calypso_env();
4744
4745
			if ( ! empty( $calypso_env ) ) {
4746
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4747
			}
4748
		} else {
4749
4750
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4751
			// because otherwise this logic can get us in to a loop.
4752
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4753
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4754
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4755
4756
				$response = Client::wpcom_json_api_request_as_blog(
4757
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4758
					'1.1'
4759
				);
4760
4761
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4762
4763
					// Generating a register URL instead to refresh the existing token
4764
					return $this->build_connect_url( $raw, $redirect, $from, true );
4765
				}
4766
			}
4767
4768
			$url = $this->build_authorize_url( $redirect );
4769
		}
4770
4771
		if ( $from ) {
4772
			$url = add_query_arg( 'from', $from, $url );
4773
		}
4774
4775
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4776
		/**
4777
		 * Filter the URL used when connecting a user to a WordPress.com account.
4778
		 *
4779
		 * @since 8.1.0
4780
		 *
4781
		 * @param string $url Connection URL.
4782
		 * @param bool   $raw If true, URL will not be escaped.
4783
		 */
4784
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
4785
	}
4786
4787
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4788
4789
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4790
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4791
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4792
4793
		if ( $iframe ) {
4794
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4795
		}
4796
4797
		$c8n = self::connection();
4798
		$url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
4799
4800
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4801
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4802
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4803
4804
		if ( $iframe ) {
4805
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4806
		}
4807
4808
		/**
4809
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4810
		 *
4811
		 * @since 8.9.0
4812
		 *
4813
		 * @param string $url Connection URL.
4814
		 */
4815
		return apply_filters( 'jetpack_build_authorize_url', $url );
4816
	}
4817
4818
	/**
4819
	 * Filters the connection URL parameter array.
4820
	 *
4821
	 * @param array $args default URL parameters used by the package.
4822
	 * @return array the modified URL arguments array.
4823
	 */
4824
	public static function filter_connect_request_body( $args ) {
4825
		if (
4826
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4827
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4828
		) {
4829
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4830
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4831
				? $gp_locale->slug
4832
				: '';
4833
		}
4834
4835
		$tracking        = new Tracking();
4836
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4837
4838
		$args = array_merge(
4839
			$args,
4840
			array(
4841
				'_ui' => $tracks_identity['_ui'],
4842
				'_ut' => $tracks_identity['_ut'],
4843
			)
4844
		);
4845
4846
		$calypso_env = self::get_calypso_env();
4847
4848
		if ( ! empty( $calypso_env ) ) {
4849
			$args['calypso_env'] = $calypso_env;
4850
		}
4851
4852
		return $args;
4853
	}
4854
4855
	/**
4856
	 * Filters the URL that will process the connection data. It can be different from the URL
4857
	 * that we send the user to after everything is done.
4858
	 *
4859
	 * @param String $processing_url the default redirect URL used by the package.
4860
	 * @return String the modified URL.
4861
	 */
4862
	public static function filter_connect_processing_url( $processing_url ) {
4863
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4864
		return $processing_url;
4865
	}
4866
4867
	/**
4868
	 * Filters the redirection URL that is used for connect requests. The redirect
4869
	 * URL should return the user back to the Jetpack console.
4870
	 *
4871
	 * @param String $redirect the default redirect URL used by the package.
4872
	 * @return String the modified URL.
4873
	 */
4874
	public static function filter_connect_redirect_url( $redirect ) {
4875
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4876
		$redirect           = $redirect
4877
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4878
			: $jetpack_admin_page;
4879
4880
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4881
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4882
		}
4883
4884
		return $redirect;
4885
	}
4886
4887
	/**
4888
	 * This action fires at the beginning of the Manager::authorize method.
4889
	 */
4890
	public static function authorize_starting() {
4891
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4892
		// Checking if site has been active/connected previously before recording unique connection.
4893
		if ( ! $jetpack_unique_connection ) {
4894
			// jetpack_unique_connection option has never been set.
4895
			$jetpack_unique_connection = array(
4896
				'connected'    => 0,
4897
				'disconnected' => 0,
4898
				'version'      => '3.6.1',
4899
			);
4900
4901
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4902
4903
			// Track unique connection.
4904
			$jetpack = self::init();
4905
4906
			$jetpack->stat( 'connections', 'unique-connection' );
4907
			$jetpack->do_stats( 'server_side' );
4908
		}
4909
4910
		// Increment number of times connected.
4911
		$jetpack_unique_connection['connected'] += 1;
4912
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4913
	}
4914
4915
	/**
4916
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4917
	 * linked.
4918
	 */
4919
	public static function authorize_ending_linked() {
4920
		// Don't activate anything since we are just connecting a user.
4921
		self::state( 'message', 'linked' );
4922
	}
4923
4924
	/**
4925
	 * This action fires at the end of the Manager::authorize method when the master user is
4926
	 * authorized.
4927
	 *
4928
	 * @param array $data The request data.
4929
	 */
4930
	public static function authorize_ending_authorized( $data ) {
4931
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4932
		self::invalidate_onboarding_token();
4933
4934
		// If redirect_uri is SSO, ensure SSO module is enabled.
4935
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4936
4937
		/** This filter is documented in class.jetpack-cli.php */
4938
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4939
4940
		$activate_sso = (
4941
			isset( $redirect_options['action'] ) &&
4942
			'jetpack-sso' === $redirect_options['action'] &&
4943
			$jetpack_start_enable_sso
4944
		);
4945
4946
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4947
4948
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4949
	}
4950
4951
	/**
4952
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
4953
	 * reconnect process is completed.
4954
	 * Note that this currently only happens when we don't need the user to re-authorize
4955
	 * their WP.com account, eg in cases where we are restoring a connection with
4956
	 * unhealthy blog token.
4957
	 */
4958
	public static function reconnection_completed() {
4959
		self::state( 'message', 'reconnection_completed' );
4960
	}
4961
4962
	/**
4963
	 * Get our assumed site creation date.
4964
	 * Calculated based on the earlier date of either:
4965
	 * - Earliest admin user registration date.
4966
	 * - Earliest date of post of any post type.
4967
	 *
4968
	 * @since 7.2.0
4969
	 * @deprecated since 7.8.0
4970
	 *
4971
	 * @return string Assumed site creation date and time.
4972
	 */
4973
	public static function get_assumed_site_creation_date() {
4974
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4975
		return self::connection()->get_assumed_site_creation_date();
4976
	}
4977
4978 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4979
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4980
4981
		if ( $activation_source_name ) {
4982
			$args['_as'] = urlencode( $activation_source_name );
4983
		}
4984
4985
		if ( $activation_source_keyword ) {
4986
			$args['_ak'] = urlencode( $activation_source_keyword );
4987
		}
4988
	}
4989
4990
	function build_reconnect_url( $raw = false ) {
4991
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4992
		return $raw ? $url : esc_url( $url );
4993
	}
4994
4995
	public static function admin_url( $args = null ) {
4996
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4997
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4998
		return $url;
4999
	}
5000
5001
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5002
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5003
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5004
	}
5005
5006
	function dismiss_jetpack_notice() {
5007
5008
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5009
			return;
5010
		}
5011
5012
		switch ( $_GET['jetpack-notice'] ) {
5013
			case 'dismiss':
5014
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5015
5016
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5017
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5018
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5019
				}
5020
				break;
5021
		}
5022
	}
5023
5024
	public static function sort_modules( $a, $b ) {
5025
		if ( $a['sort'] == $b['sort'] ) {
5026
			return 0;
5027
		}
5028
5029
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5030
	}
5031
5032
	function ajax_recheck_ssl() {
5033
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5034
		$result = self::permit_ssl( true );
5035
		wp_send_json(
5036
			array(
5037
				'enabled' => $result,
5038
				'message' => get_transient( 'jetpack_https_test_message' ),
5039
			)
5040
		);
5041
	}
5042
5043
	/* Client API */
5044
5045
	/**
5046
	 * Returns the requested Jetpack API URL
5047
	 *
5048
	 * @deprecated since 7.7
5049
	 * @return string
5050
	 */
5051
	public static function api_url( $relative_url ) {
5052
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5053
		$connection = self::connection();
5054
		return $connection->api_url( $relative_url );
5055
	}
5056
5057
	/**
5058
	 * @deprecated 8.0
5059
	 *
5060
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5061
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5062
	 */
5063
	public static function fix_url_for_bad_hosts( $url ) {
5064
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5065
		return $url;
5066
	}
5067
5068
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5069
		// Default to a blog token.
5070
		$token_type = 'blog';
5071
5072
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5073
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5074
			if ( ! empty( $_GET['onboarding'] ) ) {
5075
				$jpo = $_GET;
5076
			} else {
5077
				$jpo = json_decode( $request_data, true );
5078
			}
5079
5080
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5081
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5082
5083
			if (
5084
				isset( $jpo_user )
5085
				&& isset( $jpo_token )
5086
				&& is_email( $jpo_user )
5087
				&& ctype_alnum( $jpo_token )
5088
				&& isset( $_GET['rest_route'] )
5089
				&& self::validate_onboarding_token_action(
5090
					$jpo_token,
5091
					$_GET['rest_route']
5092
				)
5093
			) {
5094
				$jp_user = get_user_by( 'email', $jpo_user );
5095
				if ( is_a( $jp_user, 'WP_User' ) ) {
5096
					wp_set_current_user( $jp_user->ID );
5097
					$user_can = is_multisite()
5098
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5099
						: current_user_can( 'manage_options' );
5100
					if ( $user_can ) {
5101
						$token_type              = 'user';
5102
						$token->external_user_id = $jp_user->ID;
5103
					}
5104
				}
5105
			}
5106
5107
			$token_data['type']    = $token_type;
5108
			$token_data['user_id'] = $token->external_user_id;
5109
		}
5110
5111
		return $token_data;
5112
	}
5113
5114
	/**
5115
	 * Create a random secret for validating onboarding payload
5116
	 *
5117
	 * @return string Secret token
5118
	 */
5119
	public static function create_onboarding_token() {
5120
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5121
			$token = wp_generate_password( 32, false );
5122
			Jetpack_Options::update_option( 'onboarding', $token );
5123
		}
5124
5125
		return $token;
5126
	}
5127
5128
	/**
5129
	 * Remove the onboarding token
5130
	 *
5131
	 * @return bool True on success, false on failure
5132
	 */
5133
	public static function invalidate_onboarding_token() {
5134
		return Jetpack_Options::delete_option( 'onboarding' );
5135
	}
5136
5137
	/**
5138
	 * Validate an onboarding token for a specific action
5139
	 *
5140
	 * @return boolean True if token/action pair is accepted, false if not
5141
	 */
5142
	public static function validate_onboarding_token_action( $token, $action ) {
5143
		// Compare tokens, bail if tokens do not match
5144
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5145
			return false;
5146
		}
5147
5148
		// List of valid actions we can take
5149
		$valid_actions = array(
5150
			'/jetpack/v4/settings',
5151
		);
5152
5153
		// Only allow valid actions.
5154
		if ( ! in_array( $action, $valid_actions ) ) {
5155
			return false;
5156
		}
5157
5158
		return true;
5159
	}
5160
5161
	/**
5162
	 * Checks to see if the URL is using SSL to connect with Jetpack
5163
	 *
5164
	 * @since 2.3.3
5165
	 * @return boolean
5166
	 */
5167
	public static function permit_ssl( $force_recheck = false ) {
5168
		// Do some fancy tests to see if ssl is being supported
5169
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5170
			$message = '';
5171
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5172
				$ssl = 0;
5173
			} else {
5174
				$ssl = 1;
5175
5176
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5177
					$ssl     = 0;
5178
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5179
				} else {
5180
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5181
					if ( is_wp_error( $response ) ) {
5182
						$ssl     = 0;
5183
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5184
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5185
						$ssl     = 0;
5186
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5187
					}
5188
				}
5189
			}
5190
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5191
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5192
		}
5193
5194
		return (bool) $ssl;
5195
	}
5196
5197
	/*
5198
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5199
	 */
5200
	public function alert_auto_ssl_fail() {
5201
		if ( ! current_user_can( 'manage_options' ) ) {
5202
			return;
5203
		}
5204
5205
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5206
		?>
5207
5208
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5209
			<div class="jp-banner__content">
5210
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5211
				<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>
5212
				<p>
5213
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5214
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5215
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5216
				</p>
5217
				<p>
5218
					<?php
5219
					printf(
5220
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5221
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5222
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5223
					);
5224
					?>
5225
				</p>
5226
			</div>
5227
		</div>
5228
		<style>
5229
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5230
		</style>
5231
		<script type="text/javascript">
5232
			jQuery( document ).ready( function( $ ) {
5233
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5234
					var $this = $( this );
5235
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5236
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5237
					e.preventDefault();
5238
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5239
					$.post( ajaxurl, data )
5240
					  .done( function( response ) {
5241
						  if ( response.enabled ) {
5242
							  $( '#jetpack-ssl-warning' ).hide();
5243
						  } else {
5244
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5245
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5246
						  }
5247
					  }.bind( $this ) );
5248
				} );
5249
			} );
5250
		</script>
5251
5252
		<?php
5253
	}
5254
5255
	/**
5256
	 * Returns the Jetpack XML-RPC API
5257
	 *
5258
	 * @deprecated 8.0 Use Connection_Manager instead.
5259
	 * @return string
5260
	 */
5261
	public static function xmlrpc_api_url() {
5262
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5263
		return self::connection()->xmlrpc_api_url();
5264
	}
5265
5266
	/**
5267
	 * Returns the connection manager object.
5268
	 *
5269
	 * @return Automattic\Jetpack\Connection\Manager
5270
	 */
5271
	public static function connection() {
5272
		$jetpack = static::init();
5273
5274
		// If the connection manager hasn't been instantiated, do that now.
5275
		if ( ! $jetpack->connection_manager ) {
5276
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5277
		}
5278
5279
		return $jetpack->connection_manager;
5280
	}
5281
5282
	/**
5283
	 * Creates two secret tokens and the end of life timestamp for them.
5284
	 *
5285
	 * Note these tokens are unique per call, NOT static per site for connecting.
5286
	 *
5287
	 * @since 2.6
5288
	 * @param String  $action  The action name.
5289
	 * @param Integer $user_id The user identifier.
5290
	 * @param Integer $exp     Expiration time in seconds.
5291
	 * @return array
5292
	 */
5293
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5294
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5295
	}
5296
5297
	public static function get_secrets( $action, $user_id ) {
5298
		$secrets = self::connection()->get_secrets( $action, $user_id );
5299
5300
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5301
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
5302
		}
5303
5304
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5305
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
5306
		}
5307
5308
		return $secrets;
5309
	}
5310
5311
	/**
5312
	 * @deprecated 7.5 Use Connection_Manager instead.
5313
	 *
5314
	 * @param $action
5315
	 * @param $user_id
5316
	 */
5317
	public static function delete_secrets( $action, $user_id ) {
5318
		return self::connection()->delete_secrets( $action, $user_id );
5319
	}
5320
5321
	/**
5322
	 * Builds the timeout limit for queries talking with the wpcom servers.
5323
	 *
5324
	 * Based on local php max_execution_time in php.ini
5325
	 *
5326
	 * @since 2.6
5327
	 * @return int
5328
	 * @deprecated
5329
	 **/
5330
	public function get_remote_query_timeout_limit() {
5331
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5332
		return self::get_max_execution_time();
5333
	}
5334
5335
	/**
5336
	 * Builds the timeout limit for queries talking with the wpcom servers.
5337
	 *
5338
	 * Based on local php max_execution_time in php.ini
5339
	 *
5340
	 * @since 5.4
5341
	 * @return int
5342
	 **/
5343
	public static function get_max_execution_time() {
5344
		$timeout = (int) ini_get( 'max_execution_time' );
5345
5346
		// Ensure exec time set in php.ini
5347
		if ( ! $timeout ) {
5348
			$timeout = 30;
5349
		}
5350
		return $timeout;
5351
	}
5352
5353
	/**
5354
	 * Sets a minimum request timeout, and returns the current timeout
5355
	 *
5356
	 * @since 5.4
5357
	 **/
5358 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5359
		$timeout = self::get_max_execution_time();
5360
		if ( $timeout < $min_timeout ) {
5361
			$timeout = $min_timeout;
5362
			set_time_limit( $timeout );
5363
		}
5364
		return $timeout;
5365
	}
5366
5367
	/**
5368
	 * Takes the response from the Jetpack register new site endpoint and
5369
	 * verifies it worked properly.
5370
	 *
5371
	 * @since 2.6
5372
	 * @deprecated since 7.7.0
5373
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5374
	 **/
5375
	public function validate_remote_register_response() {
5376
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5377
	}
5378
5379
	/**
5380
	 * @return bool|WP_Error
5381
	 */
5382
	public static function register() {
5383
		$tracking = new Tracking();
5384
		$tracking->record_user_event( 'jpc_register_begin' );
5385
5386
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5387
5388
		$connection   = self::connection();
5389
		$registration = $connection->register();
5390
5391
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5392
5393
		if ( ! $registration || is_wp_error( $registration ) ) {
5394
			return $registration;
5395
		}
5396
5397
		return true;
5398
	}
5399
5400
	/**
5401
	 * Filters the registration request body to include tracking properties.
5402
	 *
5403
	 * @param array $properties
5404
	 * @return array amended properties.
5405
	 */
5406 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5407
		$tracking        = new Tracking();
5408
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5409
5410
		return array_merge(
5411
			$properties,
5412
			array(
5413
				'_ui' => $tracks_identity['_ui'],
5414
				'_ut' => $tracks_identity['_ut'],
5415
			)
5416
		);
5417
	}
5418
5419
	/**
5420
	 * Filters the token request body to include tracking properties.
5421
	 *
5422
	 * @param array $properties
5423
	 * @return array amended properties.
5424
	 */
5425 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5426
		$tracking        = new Tracking();
5427
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5428
5429
		return array_merge(
5430
			$properties,
5431
			array(
5432
				'_ui' => $tracks_identity['_ui'],
5433
				'_ut' => $tracks_identity['_ut'],
5434
			)
5435
		);
5436
	}
5437
5438
	/**
5439
	 * If the db version is showing something other that what we've got now, bump it to current.
5440
	 *
5441
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5442
	 */
5443
	public static function maybe_set_version_option() {
5444
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5445
		if ( JETPACK__VERSION != $version ) {
5446
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5447
5448
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5449
				/** This action is documented in class.jetpack.php */
5450
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5451
			}
5452
5453
			return true;
5454
		}
5455
		return false;
5456
	}
5457
5458
	/* Client Server API */
5459
5460
	/**
5461
	 * Loads the Jetpack XML-RPC client.
5462
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5463
	 *
5464
	 * @deprecated since 7.7.0
5465
	 */
5466
	public static function load_xml_rpc_client() {
5467
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5468
	}
5469
5470
	/**
5471
	 * Resets the saved authentication state in between testing requests.
5472
	 *
5473
	 * @deprecated since 8.9.0
5474
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5475
	 */
5476
	public function reset_saved_auth_state() {
5477
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5478
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5479
	}
5480
5481
	/**
5482
	 * Verifies the signature of the current request.
5483
	 *
5484
	 * @deprecated since 7.7.0
5485
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5486
	 *
5487
	 * @return false|array
5488
	 */
5489
	public function verify_xml_rpc_signature() {
5490
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5491
		return self::connection()->verify_xml_rpc_signature();
5492
	}
5493
5494
	/**
5495
	 * Verifies the signature of the current request.
5496
	 *
5497
	 * This function has side effects and should not be used. Instead,
5498
	 * use the memoized version `->verify_xml_rpc_signature()`.
5499
	 *
5500
	 * @deprecated since 7.7.0
5501
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5502
	 * @internal
5503
	 */
5504
	private function internal_verify_xml_rpc_signature() {
5505
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5506
	}
5507
5508
	/**
5509
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5510
	 *
5511
	 * @deprecated since 7.7.0
5512
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5513
	 *
5514
	 * @param \WP_User|mixed $user     User object if authenticated.
5515
	 * @param string         $username Username.
5516
	 * @param string         $password Password string.
5517
	 * @return \WP_User|mixed Authenticated user or error.
5518
	 */
5519 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5520
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5521
5522
		if ( ! $this->connection_manager ) {
5523
			$this->connection_manager = new Connection_Manager();
5524
		}
5525
5526
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5527
	}
5528
5529
	/**
5530
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5531
	 * Uses the existing XMLRPC request signing implementation.
5532
	 *
5533
	 * @deprecated since 8.9.0
5534
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5535
	 */
5536
	function wp_rest_authenticate( $user ) {
5537
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5538
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5539
	}
5540
5541
	/**
5542
	 * Report authentication status to the WP REST API.
5543
	 *
5544
	 * @deprecated since 8.9.0
5545
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5546
	 *
5547
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5548
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5549
	 */
5550
	public function wp_rest_authentication_errors( $value ) {
5551
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5552
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5553
	}
5554
5555
	/**
5556
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5557
	 * Capture it here so we can verify the signature later.
5558
	 *
5559
	 * @deprecated since 7.7.0
5560
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5561
	 *
5562
	 * @param array $methods XMLRPC methods.
5563
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5564
	 */
5565 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5566
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5567
5568
		if ( ! $this->connection_manager ) {
5569
			$this->connection_manager = new Connection_Manager();
5570
		}
5571
5572
		return $this->connection_manager->xmlrpc_methods( $methods );
5573
	}
5574
5575
	/**
5576
	 * Register additional public XMLRPC methods.
5577
	 *
5578
	 * @deprecated since 7.7.0
5579
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5580
	 *
5581
	 * @param array $methods Public XMLRPC methods.
5582
	 * @return array Public XMLRPC methods, with the getOptions one.
5583
	 */
5584 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5585
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5586
5587
		if ( ! $this->connection_manager ) {
5588
			$this->connection_manager = new Connection_Manager();
5589
		}
5590
5591
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5592
	}
5593
5594
	/**
5595
	 * Handles a getOptions XMLRPC method call.
5596
	 *
5597
	 * @deprecated since 7.7.0
5598
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5599
	 *
5600
	 * @param array $args method call arguments.
5601
	 * @return array an amended XMLRPC server options array.
5602
	 */
5603 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5604
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5605
5606
		if ( ! $this->connection_manager ) {
5607
			$this->connection_manager = new Connection_Manager();
5608
		}
5609
5610
		return $this->connection_manager->jetpack_getOptions( $args );
5611
	}
5612
5613
	/**
5614
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5615
	 *
5616
	 * @deprecated since 7.7.0
5617
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5618
	 *
5619
	 * @param array $options Standard Core options.
5620
	 * @return array Amended options.
5621
	 */
5622 View Code Duplication
	public function xmlrpc_options( $options ) {
5623
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5624
5625
		if ( ! $this->connection_manager ) {
5626
			$this->connection_manager = new Connection_Manager();
5627
		}
5628
5629
		return $this->connection_manager->xmlrpc_options( $options );
5630
	}
5631
5632
	/**
5633
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5634
	 * SET: state( $key, $value );
5635
	 * GET: $value = state( $key );
5636
	 *
5637
	 * @param string $key
5638
	 * @param string $value
5639
	 * @param bool   $restate private
5640
	 */
5641
	public static function state( $key = null, $value = null, $restate = false ) {
5642
		static $state = array();
5643
		static $path, $domain;
5644
		if ( ! isset( $path ) ) {
5645
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5646
			$admin_url = self::admin_url();
5647
			$bits      = wp_parse_url( $admin_url );
5648
5649
			if ( is_array( $bits ) ) {
5650
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5651
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5652
			} else {
5653
				$path = $domain = null;
5654
			}
5655
		}
5656
5657
		// Extract state from cookies and delete cookies
5658
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5659
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5660
			unset( $_COOKIE['jetpackState'] );
5661
			foreach ( $yum as $k => $v ) {
5662
				if ( strlen( $v ) ) {
5663
					$state[ $k ] = $v;
5664
				}
5665
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5666
			}
5667
		}
5668
5669
		if ( $restate ) {
5670
			foreach ( $state as $k => $v ) {
5671
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5672
			}
5673
			return;
5674
		}
5675
5676
		// Get a state variable.
5677
		if ( isset( $key ) && ! isset( $value ) ) {
5678
			if ( array_key_exists( $key, $state ) ) {
5679
				return $state[ $key ];
5680
			}
5681
			return null;
5682
		}
5683
5684
		// Set a state variable.
5685
		if ( isset( $key ) && isset( $value ) ) {
5686
			if ( is_array( $value ) && isset( $value[0] ) ) {
5687
				$value = $value[0];
5688
			}
5689
			$state[ $key ] = $value;
5690
			if ( ! headers_sent() ) {
5691
				if ( self::should_set_cookie( $key ) ) {
5692
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5693
				}
5694
			}
5695
		}
5696
	}
5697
5698
	public static function restate() {
5699
		self::state( null, null, true );
5700
	}
5701
5702
	/**
5703
	 * Determines whether the jetpackState[$key] value should be added to the
5704
	 * cookie.
5705
	 *
5706
	 * @param string $key The state key.
5707
	 *
5708
	 * @return boolean Whether the value should be added to the cookie.
5709
	 */
5710
	public static function should_set_cookie( $key ) {
5711
		global $current_screen;
5712
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5713
5714
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5715
			return false;
5716
		}
5717
5718
		return true;
5719
	}
5720
5721
	public static function check_privacy( $file ) {
5722
		static $is_site_publicly_accessible = null;
5723
5724
		if ( is_null( $is_site_publicly_accessible ) ) {
5725
			$is_site_publicly_accessible = false;
5726
5727
			$rpc = new Jetpack_IXR_Client();
5728
5729
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5730
			if ( $success ) {
5731
				$response = $rpc->getResponse();
5732
				if ( $response ) {
5733
					$is_site_publicly_accessible = true;
5734
				}
5735
			}
5736
5737
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5738
		}
5739
5740
		if ( $is_site_publicly_accessible ) {
5741
			return;
5742
		}
5743
5744
		$module_slug = self::get_module_slug( $file );
5745
5746
		$privacy_checks = self::state( 'privacy_checks' );
5747
		if ( ! $privacy_checks ) {
5748
			$privacy_checks = $module_slug;
5749
		} else {
5750
			$privacy_checks .= ",$module_slug";
5751
		}
5752
5753
		self::state( 'privacy_checks', $privacy_checks );
5754
	}
5755
5756
	/**
5757
	 * Helper method for multicall XMLRPC.
5758
	 *
5759
	 * @deprecated since 8.9.0
5760
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5761
	 *
5762
	 * @param ...$args Args for the async_call.
5763
	 */
5764
	public static function xmlrpc_async_call( ...$args ) {
5765
5766
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5767
5768
		global $blog_id;
5769
		static $clients = array();
5770
5771
		$client_blog_id = is_multisite() ? $blog_id : 0;
5772
5773
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5774
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => Connection_Manager::CONNECTION_OWNER ) );
5775
			if ( function_exists( 'ignore_user_abort' ) ) {
5776
				ignore_user_abort( true );
5777
			}
5778
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5779
		}
5780
5781
		if ( ! empty( $args[0] ) ) {
5782
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5783
		} elseif ( is_multisite() ) {
5784
			foreach ( $clients as $client_blog_id => $client ) {
5785
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5786
					continue;
5787
				}
5788
5789
				$switch_success = switch_to_blog( $client_blog_id, true );
5790
				if ( ! $switch_success ) {
5791
					continue;
5792
				}
5793
5794
				flush();
5795
				$client->query();
5796
5797
				restore_current_blog();
5798
			}
5799
		} else {
5800
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5801
				flush();
5802
				$clients[0]->query();
5803
			}
5804
		}
5805
	}
5806
5807
	public static function staticize_subdomain( $url ) {
5808
5809
		// Extract hostname from URL
5810
		$host = wp_parse_url( $url, PHP_URL_HOST );
5811
5812
		// Explode hostname on '.'
5813
		$exploded_host = explode( '.', $host );
5814
5815
		// Retrieve the name and TLD
5816
		if ( count( $exploded_host ) > 1 ) {
5817
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5818
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5819
			// Rebuild domain excluding subdomains
5820
			$domain = $name . '.' . $tld;
5821
		} else {
5822
			$domain = $host;
5823
		}
5824
		// Array of Automattic domains.
5825
		$domains_allowed = array( 'wordpress.com', 'wp.com' );
5826
5827
		// Return $url if not an Automattic domain.
5828
		if ( ! in_array( $domain, $domains_allowed, true ) ) {
5829
			return $url;
5830
		}
5831
5832
		if ( is_ssl() ) {
5833
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5834
		}
5835
5836
		srand( crc32( basename( $url ) ) );
5837
		$static_counter = rand( 0, 2 );
5838
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5839
5840
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5841
	}
5842
5843
	/* JSON API Authorization */
5844
5845
	/**
5846
	 * Handles the login action for Authorizing the JSON API
5847
	 */
5848
	function login_form_json_api_authorization() {
5849
		$this->verify_json_api_authorization_request();
5850
5851
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5852
5853
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5854
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5855
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5856
	}
5857
5858
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5859
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5860
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5861
			return $url;
5862
		}
5863
5864
		$parsed_url = wp_parse_url( $url );
5865
		$url        = strtok( $url, '?' );
5866
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5867
		if ( ! empty( $parsed_url['query'] ) ) {
5868
			$url .= "&{$parsed_url['query']}";
5869
		}
5870
5871
		return $url;
5872
	}
5873
5874
	// Make sure the POSTed request is handled by the same action
5875
	function preserve_action_in_login_form_for_json_api_authorization() {
5876
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5877
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5878
	}
5879
5880
	// If someone logs in to approve API access, store the Access Code in usermeta
5881
	function store_json_api_authorization_token( $user_login, $user ) {
5882
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5883
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5884
		$token = wp_generate_password( 32, false );
5885
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5886
	}
5887
5888
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5889
	function allow_wpcom_public_api_domain( $domains ) {
5890
		$domains[] = 'public-api.wordpress.com';
5891
		return $domains;
5892
	}
5893
5894
	static function is_redirect_encoded( $redirect_url ) {
5895
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5896
	}
5897
5898
	// Add all wordpress.com environments to the safe redirect allowed list.
5899
	function allow_wpcom_environments( $domains ) {
5900
		$domains[] = 'wordpress.com';
5901
		$domains[] = 'wpcalypso.wordpress.com';
5902
		$domains[] = 'horizon.wordpress.com';
5903
		$domains[] = 'calypso.localhost';
5904
		return $domains;
5905
	}
5906
5907
	// Add the Access Code details to the public-api.wordpress.com redirect
5908
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5909
		return add_query_arg(
5910
			urlencode_deep(
5911
				array(
5912
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5913
					'jetpack-user-id' => (int) $user->ID,
5914
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5915
				)
5916
			),
5917
			$redirect_to
5918
		);
5919
	}
5920
5921
	/**
5922
	 * Verifies the request by checking the signature
5923
	 *
5924
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5925
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5926
	 *
5927
	 * @param null|array $environment
5928
	 */
5929
	function verify_json_api_authorization_request( $environment = null ) {
5930
		$environment = is_null( $environment )
5931
			? $_REQUEST
5932
			: $environment;
5933
5934
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
5935
		$token                                     = Jetpack_Data::get_access_token( $envUserId, $envToken );
5936
		if ( ! $token || empty( $token->secret ) ) {
5937
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5938
		}
5939
5940
		$die_error = __( 'Someone may be trying to trick you into giving them access to your site.  Or it could be you just encountered a bug :).  Either way, please close this window.', 'jetpack' );
5941
5942
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5943
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5944
			/**
5945
			 * Jetpack authorisation request Error.
5946
			 *
5947
			 * @since 7.5.0
5948
			 */
5949
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5950
			$die_error = sprintf(
5951
				/* translators: %s is a URL */
5952
				__( 'Your site is incorrectly double-encoding redirects from http to https. This is preventing Jetpack from authenticating your connection. Please visit our <a href="%s">support page</a> for details about how to resolve this.', 'jetpack' ),
5953
				Redirect::get_url( 'jetpack-support-double-encoding' )
5954
			);
5955
		}
5956
5957
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5958
5959
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5960
			$signature = $jetpack_signature->sign_request(
5961
				$environment['token'],
5962
				$environment['timestamp'],
5963
				$environment['nonce'],
5964
				'',
5965
				'GET',
5966
				$environment['jetpack_json_api_original_query'],
5967
				null,
5968
				true
5969
			);
5970
		} else {
5971
			$signature = $jetpack_signature->sign_current_request(
5972
				array(
5973
					'body'   => null,
5974
					'method' => 'GET',
5975
				)
5976
			);
5977
		}
5978
5979
		if ( ! $signature ) {
5980
			wp_die( $die_error );
5981
		} elseif ( is_wp_error( $signature ) ) {
5982
			wp_die( $die_error );
5983
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5984
			if ( is_ssl() ) {
5985
				// If we signed an HTTP request on the Jetpack Servers, but got redirected to HTTPS by the local blog, check the HTTP signature as well
5986
				$signature = $jetpack_signature->sign_current_request(
5987
					array(
5988
						'scheme' => 'http',
5989
						'body'   => null,
5990
						'method' => 'GET',
5991
					)
5992
				);
5993
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5994
					wp_die( $die_error );
5995
				}
5996
			} else {
5997
				wp_die( $die_error );
5998
			}
5999
		}
6000
6001
		$timestamp = (int) $environment['timestamp'];
6002
		$nonce     = stripslashes( (string) $environment['nonce'] );
6003
6004
		if ( ! $this->connection_manager ) {
6005
			$this->connection_manager = new Connection_Manager();
6006
		}
6007
6008
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
6009
			// De-nonce the nonce, at least for 5 minutes.
6010
			// We have to reuse this nonce at least once (used the first time when the initial request is made, used a second time when the login form is POSTed)
6011
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6012
			if ( $old_nonce_time < time() - 300 ) {
6013
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6014
			}
6015
		}
6016
6017
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6018
		$data_filters = array(
6019
			'state'        => 'opaque',
6020
			'client_id'    => 'int',
6021
			'client_title' => 'string',
6022
			'client_image' => 'url',
6023
		);
6024
6025
		foreach ( $data_filters as $key => $sanitation ) {
6026
			if ( ! isset( $data->$key ) ) {
6027
				wp_die( $die_error );
6028
			}
6029
6030
			switch ( $sanitation ) {
6031
				case 'int':
6032
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6033
					break;
6034
				case 'opaque':
6035
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6036
					break;
6037
				case 'string':
6038
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6039
					break;
6040
				case 'url':
6041
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6042
					break;
6043
			}
6044
		}
6045
6046
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6047
			wp_die( $die_error );
6048
		}
6049
	}
6050
6051
	function login_message_json_api_authorization( $message ) {
6052
		return '<p class="message">' . sprintf(
6053
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6054
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6055
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6056
	}
6057
6058
	/**
6059
	 * Get $content_width, but with a <s>twist</s> filter.
6060
	 */
6061
	public static function get_content_width() {
6062
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6063
			? $GLOBALS['content_width']
6064
			: false;
6065
		/**
6066
		 * Filter the Content Width value.
6067
		 *
6068
		 * @since 2.2.3
6069
		 *
6070
		 * @param string $content_width Content Width value.
6071
		 */
6072
		return apply_filters( 'jetpack_content_width', $content_width );
6073
	}
6074
6075
	/**
6076
	 * Pings the WordPress.com Mirror Site for the specified options.
6077
	 *
6078
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6079
	 *
6080
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6081
	 */
6082
	public function get_cloud_site_options( $option_names ) {
6083
		$option_names = array_filter( (array) $option_names, 'is_string' );
6084
6085
		$xml = new Jetpack_IXR_Client();
6086
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6087
		if ( $xml->isError() ) {
6088
			return array(
6089
				'error_code' => $xml->getErrorCode(),
6090
				'error_msg'  => $xml->getErrorMessage(),
6091
			);
6092
		}
6093
		$cloud_site_options = $xml->getResponse();
6094
6095
		return $cloud_site_options;
6096
	}
6097
6098
	/**
6099
	 * Checks if the site is currently in an identity crisis.
6100
	 *
6101
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6102
	 */
6103
	public static function check_identity_crisis() {
6104
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
6105
			return false;
6106
		}
6107
6108
		return Jetpack_Options::get_option( 'sync_error_idc' );
6109
	}
6110
6111
	/**
6112
	 * Checks whether the home and siteurl specifically are allowed.
6113
	 * Written so that we don't have re-check $key and $value params every time
6114
	 * we want to check if this site is allowed, for example in footer.php
6115
	 *
6116
	 * @since  3.8.0
6117
	 * @return bool True = already allowed False = not on the allowed list.
6118
	 */
6119
	public static function is_staging_site() {
6120
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6121
		return ( new Status() )->is_staging_site();
6122
	}
6123
6124
	/**
6125
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6126
	 *
6127
	 * @since 4.4.0
6128
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6129
	 *
6130
	 * @return bool
6131
	 */
6132
	public static function validate_sync_error_idc_option() {
6133
		$is_valid = false;
6134
6135
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6136
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6137
		if ( $sync_error && self::sync_idc_optin() ) {
6138
			$local_options = self::get_sync_error_idc_option();
6139
			// Ensure all values are set.
6140
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6141
6142
				// If the WP.com expected home and siteurl match local home and siteurl it is not valid IDC.
6143
				if (
6144
						isset( $sync_error['wpcom_home'] ) &&
6145
						isset( $sync_error['wpcom_siteurl'] ) &&
6146
						$sync_error['wpcom_home'] === $local_options['home'] &&
6147
						$sync_error['wpcom_siteurl'] === $local_options['siteurl']
6148
				) {
6149
					$is_valid = false;
6150
					// Enable migrate_for_idc so that sync actions are accepted.
6151
					Jetpack_Options::update_option( 'migrate_for_idc', true );
6152
				} elseif ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6153
					$is_valid = true;
6154
				}
6155
			}
6156
		}
6157
6158
		/**
6159
		 * Filters whether the sync_error_idc option is valid.
6160
		 *
6161
		 * @since 4.4.0
6162
		 *
6163
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6164
		 */
6165
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6166
6167
		if ( ! $is_valid && $sync_error ) {
6168
			// Since the option exists, and did not validate, delete it
6169
			Jetpack_Options::delete_option( 'sync_error_idc' );
6170
		}
6171
6172
		return $is_valid;
6173
	}
6174
6175
	/**
6176
	 * Normalizes a url by doing three things:
6177
	 *  - Strips protocol
6178
	 *  - Strips www
6179
	 *  - Adds a trailing slash
6180
	 *
6181
	 * @since 4.4.0
6182
	 * @param string $url
6183
	 * @return WP_Error|string
6184
	 */
6185
	public static function normalize_url_protocol_agnostic( $url ) {
6186
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6187 View Code Duplication
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6188
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6189
		}
6190
6191
		// Strip www and protocols
6192
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6193
		return $url;
6194
	}
6195
6196
	/**
6197
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6198
	 *
6199
	 * @since 4.4.0
6200
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6201
	 *
6202
	 * @param array $response
6203
	 * @return array Array of the local urls, wpcom urls, and error code
6204
	 */
6205
	public static function get_sync_error_idc_option( $response = array() ) {
6206
		// Since the local options will hit the database directly, store the values
6207
		// in a transient to allow for autoloading and caching on subsequent views.
6208
		$local_options = get_transient( 'jetpack_idc_local' );
6209
		if ( false === $local_options ) {
6210
			$local_options = array(
6211
				'home'    => Functions::home_url(),
6212
				'siteurl' => Functions::site_url(),
6213
			);
6214
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6215
		}
6216
6217
		$options = array_merge( $local_options, $response );
6218
6219
		$returned_values = array();
6220
		foreach ( $options as $key => $option ) {
6221
			if ( 'error_code' === $key ) {
6222
				$returned_values[ $key ] = $option;
6223
				continue;
6224
			}
6225
6226
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6227
				continue;
6228
			}
6229
6230
			$returned_values[ $key ] = $normalized_url;
6231
		}
6232
6233
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6234
6235
		return $returned_values;
6236
	}
6237
6238
	/**
6239
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6240
	 * If set to true, the site will be put into staging mode.
6241
	 *
6242
	 * @since 4.3.2
6243
	 * @return bool
6244
	 */
6245
	public static function sync_idc_optin() {
6246
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6247
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6248
		} else {
6249
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6250
		}
6251
6252
		/**
6253
		 * Allows sites to opt in for IDC mitigation which blocks the site from syncing to WordPress.com when the home
6254
		 * URL or site URL do not match what WordPress.com expects. The default value is either true, or the value of
6255
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6256
		 *
6257
		 * @since 4.3.2
6258
		 *
6259
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6260
		 */
6261
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6262
	}
6263
6264
	/**
6265
	 * Maybe Use a .min.css stylesheet, maybe not.
6266
	 *
6267
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6268
	 */
6269
	public static function maybe_min_asset( $url, $path, $plugin ) {
6270
		// Short out on things trying to find actual paths.
6271
		if ( ! $path || empty( $plugin ) ) {
6272
			return $url;
6273
		}
6274
6275
		$path = ltrim( $path, '/' );
6276
6277
		// Strip out the abspath.
6278
		$base = dirname( plugin_basename( $plugin ) );
6279
6280
		// Short out on non-Jetpack assets.
6281
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6282
			return $url;
6283
		}
6284
6285
		// File name parsing.
6286
		$file              = "{$base}/{$path}";
6287
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6288
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6289
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6290
		$extension         = array_shift( $file_name_parts_r );
6291
6292
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6293
			// Already pointing at the minified version.
6294
			if ( 'min' === $file_name_parts_r[0] ) {
6295
				return $url;
6296
			}
6297
6298
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6299
			if ( file_exists( $min_full_path ) ) {
6300
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6301
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6302
				if ( 'css' === $extension ) {
6303
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6304
					self::$min_assets[ $key ] = $path;
6305
				}
6306
			}
6307
		}
6308
6309
		return $url;
6310
	}
6311
6312
	/**
6313
	 * If the asset is minified, let's flag .min as the suffix.
6314
	 *
6315
	 * Attached to `style_loader_src` filter.
6316
	 *
6317
	 * @param string $tag The tag that would link to the external asset.
6318
	 * @param string $handle The registered handle of the script in question.
6319
	 * @param string $href The url of the asset in question.
6320
	 */
6321
	public static function set_suffix_on_min( $src, $handle ) {
6322
		if ( false === strpos( $src, '.min.css' ) ) {
6323
			return $src;
6324
		}
6325
6326
		if ( ! empty( self::$min_assets ) ) {
6327
			foreach ( self::$min_assets as $file => $path ) {
6328
				if ( false !== strpos( $src, $file ) ) {
6329
					wp_style_add_data( $handle, 'suffix', '.min' );
6330
					return $src;
6331
				}
6332
			}
6333
		}
6334
6335
		return $src;
6336
	}
6337
6338
	/**
6339
	 * Maybe inlines a stylesheet.
6340
	 *
6341
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6342
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6343
	 *
6344
	 * Attached to `style_loader_tag` filter.
6345
	 *
6346
	 * @param string $tag The tag that would link to the external asset.
6347
	 * @param string $handle The registered handle of the script in question.
6348
	 *
6349
	 * @return string
6350
	 */
6351
	public static function maybe_inline_style( $tag, $handle ) {
6352
		global $wp_styles;
6353
		$item = $wp_styles->registered[ $handle ];
6354
6355
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6356
			return $tag;
6357
		}
6358
6359
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6360
			$href = $matches[1];
6361
			// Strip off query string
6362
			if ( $pos = strpos( $href, '?' ) ) {
6363
				$href = substr( $href, 0, $pos );
6364
			}
6365
			// Strip off fragment
6366
			if ( $pos = strpos( $href, '#' ) ) {
6367
				$href = substr( $href, 0, $pos );
6368
			}
6369
		} else {
6370
			return $tag;
6371
		}
6372
6373
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6374
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6375
			return $tag;
6376
		}
6377
6378
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6379
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6380
			// And this isn't the pass that actually deals with the RTL version...
6381
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6382
				// Short out, as the RTL version will deal with it in a moment.
6383
				return $tag;
6384
			}
6385
		}
6386
6387
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6388
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6389
		if ( $css ) {
6390
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6391
			if ( empty( $item->extra['after'] ) ) {
6392
				wp_add_inline_style( $handle, $css );
6393
			} else {
6394
				array_unshift( $item->extra['after'], $css );
6395
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6396
			}
6397
		}
6398
6399
		return $tag;
6400
	}
6401
6402
	/**
6403
	 * Loads a view file from the views
6404
	 *
6405
	 * Data passed in with the $data parameter will be available in the
6406
	 * template file as $data['value']
6407
	 *
6408
	 * @param string $template - Template file to load
6409
	 * @param array  $data - Any data to pass along to the template
6410
	 * @return boolean - If template file was found
6411
	 **/
6412
	public function load_view( $template, $data = array() ) {
6413
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6414
6415
		if ( file_exists( $views_dir . $template ) ) {
6416
			require_once $views_dir . $template;
6417
			return true;
6418
		}
6419
6420
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6421
		return false;
6422
	}
6423
6424
	/**
6425
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6426
	 */
6427
	public function deprecated_hooks() {
6428
		$filter_deprecated_list = array(
6429
			'jetpack_bail_on_shortcode'                    => array(
6430
				'replacement' => 'jetpack_shortcodes_to_include',
6431
				'version'     => 'jetpack-3.1.0',
6432
			),
6433
			'wpl_sharing_2014_1'                           => array(
6434
				'replacement' => null,
6435
				'version'     => 'jetpack-3.6.0',
6436
			),
6437
			'jetpack-tools-to-include'                     => array(
6438
				'replacement' => 'jetpack_tools_to_include',
6439
				'version'     => 'jetpack-3.9.0',
6440
			),
6441
			'jetpack_identity_crisis_options_to_check'     => array(
6442
				'replacement' => null,
6443
				'version'     => 'jetpack-4.0.0',
6444
			),
6445
			'update_option_jetpack_single_user_site'       => array(
6446
				'replacement' => null,
6447
				'version'     => 'jetpack-4.3.0',
6448
			),
6449
			'audio_player_default_colors'                  => array(
6450
				'replacement' => null,
6451
				'version'     => 'jetpack-4.3.0',
6452
			),
6453
			'add_option_jetpack_featured_images_enabled'   => array(
6454
				'replacement' => null,
6455
				'version'     => 'jetpack-4.3.0',
6456
			),
6457
			'add_option_jetpack_update_details'            => array(
6458
				'replacement' => null,
6459
				'version'     => 'jetpack-4.3.0',
6460
			),
6461
			'add_option_jetpack_updates'                   => array(
6462
				'replacement' => null,
6463
				'version'     => 'jetpack-4.3.0',
6464
			),
6465
			'add_option_jetpack_network_name'              => array(
6466
				'replacement' => null,
6467
				'version'     => 'jetpack-4.3.0',
6468
			),
6469
			'add_option_jetpack_network_allow_new_registrations' => array(
6470
				'replacement' => null,
6471
				'version'     => 'jetpack-4.3.0',
6472
			),
6473
			'add_option_jetpack_network_add_new_users'     => array(
6474
				'replacement' => null,
6475
				'version'     => 'jetpack-4.3.0',
6476
			),
6477
			'add_option_jetpack_network_site_upload_space' => array(
6478
				'replacement' => null,
6479
				'version'     => 'jetpack-4.3.0',
6480
			),
6481
			'add_option_jetpack_network_upload_file_types' => array(
6482
				'replacement' => null,
6483
				'version'     => 'jetpack-4.3.0',
6484
			),
6485
			'add_option_jetpack_network_enable_administration_menus' => array(
6486
				'replacement' => null,
6487
				'version'     => 'jetpack-4.3.0',
6488
			),
6489
			'add_option_jetpack_is_multi_site'             => array(
6490
				'replacement' => null,
6491
				'version'     => 'jetpack-4.3.0',
6492
			),
6493
			'add_option_jetpack_is_main_network'           => array(
6494
				'replacement' => null,
6495
				'version'     => 'jetpack-4.3.0',
6496
			),
6497
			'add_option_jetpack_main_network_site'         => array(
6498
				'replacement' => null,
6499
				'version'     => 'jetpack-4.3.0',
6500
			),
6501
			'jetpack_sync_all_registered_options'          => array(
6502
				'replacement' => null,
6503
				'version'     => 'jetpack-4.3.0',
6504
			),
6505
			'jetpack_has_identity_crisis'                  => array(
6506
				'replacement' => 'jetpack_sync_error_idc_validation',
6507
				'version'     => 'jetpack-4.4.0',
6508
			),
6509
			'jetpack_is_post_mailable'                     => array(
6510
				'replacement' => null,
6511
				'version'     => 'jetpack-4.4.0',
6512
			),
6513
			'jetpack_seo_site_host'                        => array(
6514
				'replacement' => null,
6515
				'version'     => 'jetpack-5.1.0',
6516
			),
6517
			'jetpack_installed_plugin'                     => array(
6518
				'replacement' => 'jetpack_plugin_installed',
6519
				'version'     => 'jetpack-6.0.0',
6520
			),
6521
			'jetpack_holiday_snow_option_name'             => array(
6522
				'replacement' => null,
6523
				'version'     => 'jetpack-6.0.0',
6524
			),
6525
			'jetpack_holiday_chance_of_snow'               => array(
6526
				'replacement' => null,
6527
				'version'     => 'jetpack-6.0.0',
6528
			),
6529
			'jetpack_holiday_snow_js_url'                  => array(
6530
				'replacement' => null,
6531
				'version'     => 'jetpack-6.0.0',
6532
			),
6533
			'jetpack_is_holiday_snow_season'               => array(
6534
				'replacement' => null,
6535
				'version'     => 'jetpack-6.0.0',
6536
			),
6537
			'jetpack_holiday_snow_option_updated'          => array(
6538
				'replacement' => null,
6539
				'version'     => 'jetpack-6.0.0',
6540
			),
6541
			'jetpack_holiday_snowing'                      => array(
6542
				'replacement' => null,
6543
				'version'     => 'jetpack-6.0.0',
6544
			),
6545
			'jetpack_sso_auth_cookie_expirtation'          => array(
6546
				'replacement' => 'jetpack_sso_auth_cookie_expiration',
6547
				'version'     => 'jetpack-6.1.0',
6548
			),
6549
			'jetpack_cache_plans'                          => array(
6550
				'replacement' => null,
6551
				'version'     => 'jetpack-6.1.0',
6552
			),
6553
6554
			'jetpack_lazy_images_skip_image_with_atttributes' => array(
6555
				'replacement' => 'jetpack_lazy_images_skip_image_with_attributes',
6556
				'version'     => 'jetpack-6.5.0',
6557
			),
6558
			'jetpack_enable_site_verification'             => array(
6559
				'replacement' => null,
6560
				'version'     => 'jetpack-6.5.0',
6561
			),
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
			'jetpack_widget_authors_exclude'               => array(
6579
				'replacement' => 'jetpack_widget_authors_params',
6580
				'version'     => 'jetpack-7.7.0',
6581
			),
6582
			// Removed in Jetpack 7.9.0
6583
			'jetpack_pwa_manifest'                         => array(
6584
				'replacement' => null,
6585
				'version'     => 'jetpack-7.9.0',
6586
			),
6587
			'jetpack_pwa_background_color'                 => array(
6588
				'replacement' => null,
6589
				'version'     => 'jetpack-7.9.0',
6590
			),
6591
			'jetpack_check_mobile'                         => array(
6592
				'replacement' => null,
6593
				'version'     => 'jetpack-8.3.0',
6594
			),
6595
			'jetpack_mobile_stylesheet'                    => array(
6596
				'replacement' => null,
6597
				'version'     => 'jetpack-8.3.0',
6598
			),
6599
			'jetpack_mobile_template'                      => array(
6600
				'replacement' => null,
6601
				'version'     => 'jetpack-8.3.0',
6602
			),
6603
			'jetpack_mobile_theme_menu'                    => array(
6604
				'replacement' => null,
6605
				'version'     => 'jetpack-8.3.0',
6606
			),
6607
			'minileven_show_featured_images'               => array(
6608
				'replacement' => null,
6609
				'version'     => 'jetpack-8.3.0',
6610
			),
6611
			'minileven_attachment_size'                    => array(
6612
				'replacement' => null,
6613
				'version'     => 'jetpack-8.3.0',
6614
			),
6615
			'instagram_cache_oembed_api_response_body'     => array(
6616
				'replacement' => null,
6617
				'version'     => 'jetpack-9.1.0',
6618
			),
6619
			'jetpack_can_make_outbound_https'              => array(
6620
				'replacement' => null,
6621
				'version'     => 'jetpack-9.1.0',
6622
			),
6623
		);
6624
6625
		foreach ( $filter_deprecated_list as $tag => $args ) {
6626
			if ( has_filter( $tag ) ) {
6627
				apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
6628
			}
6629
		}
6630
6631
		$action_deprecated_list = array(
6632
			'jetpack_updated_theme'        => array(
6633
				'replacement' => 'jetpack_updated_themes',
6634
				'version'     => 'jetpack-6.2.0',
6635
			),
6636
			'atd_http_post_error'          => array(
6637
				'replacement' => null,
6638
				'version'     => 'jetpack-7.3.0',
6639
			),
6640
			'mobile_reject_mobile'         => array(
6641
				'replacement' => null,
6642
				'version'     => 'jetpack-8.3.0',
6643
			),
6644
			'mobile_force_mobile'          => array(
6645
				'replacement' => null,
6646
				'version'     => 'jetpack-8.3.0',
6647
			),
6648
			'mobile_app_promo_download'    => array(
6649
				'replacement' => null,
6650
				'version'     => 'jetpack-8.3.0',
6651
			),
6652
			'mobile_setup'                 => array(
6653
				'replacement' => null,
6654
				'version'     => 'jetpack-8.3.0',
6655
			),
6656
			'jetpack_mobile_footer_before' => array(
6657
				'replacement' => null,
6658
				'version'     => 'jetpack-8.3.0',
6659
			),
6660
			'wp_mobile_theme_footer'       => array(
6661
				'replacement' => null,
6662
				'version'     => 'jetpack-8.3.0',
6663
			),
6664
			'minileven_credits'            => array(
6665
				'replacement' => null,
6666
				'version'     => 'jetpack-8.3.0',
6667
			),
6668
			'jetpack_mobile_header_before' => array(
6669
				'replacement' => null,
6670
				'version'     => 'jetpack-8.3.0',
6671
			),
6672
			'jetpack_mobile_header_after'  => array(
6673
				'replacement' => null,
6674
				'version'     => 'jetpack-8.3.0',
6675
			),
6676
		);
6677
6678
		foreach ( $action_deprecated_list as $tag => $args ) {
6679
			if ( has_action( $tag ) ) {
6680
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6681
			}
6682
		}
6683
	}
6684
6685
	/**
6686
	 * Converts any url in a stylesheet, to the correct absolute url.
6687
	 *
6688
	 * Considerations:
6689
	 *  - Normal, relative URLs     `feh.png`
6690
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6691
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6692
	 *  - Absolute URLs             `http://domain.com/feh.png`
6693
	 *  - Domain root relative URLs `/feh.png`
6694
	 *
6695
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6696
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6697
	 *
6698
	 * @return mixed|string
6699
	 */
6700
	public static function absolutize_css_urls( $css, $css_file_url ) {
6701
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6702
		$css_dir = dirname( $css_file_url );
6703
		$p       = wp_parse_url( $css_dir );
6704
		$domain  = sprintf(
6705
			'%1$s//%2$s%3$s%4$s',
6706
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6707
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6708
			$p['host'],
6709
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6710
		);
6711
6712
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6713
			$find = $replace = array();
6714
			foreach ( $matches as $match ) {
6715
				$url = trim( $match['path'], "'\" \t" );
6716
6717
				// If this is a data url, we don't want to mess with it.
6718
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6719
					continue;
6720
				}
6721
6722
				// If this is an absolute or protocol-agnostic url,
6723
				// we don't want to mess with it.
6724
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6725
					continue;
6726
				}
6727
6728
				switch ( substr( $url, 0, 1 ) ) {
6729
					case '/':
6730
						$absolute = $domain . $url;
6731
						break;
6732
					default:
6733
						$absolute = $css_dir . '/' . $url;
6734
				}
6735
6736
				$find[]    = $match[0];
6737
				$replace[] = sprintf( 'url("%s")', $absolute );
6738
			}
6739
			$css = str_replace( $find, $replace, $css );
6740
		}
6741
6742
		return $css;
6743
	}
6744
6745
	/**
6746
	 * This methods removes all of the registered css files on the front end
6747
	 * from Jetpack in favor of using a single file. In effect "imploding"
6748
	 * all the files into one file.
6749
	 *
6750
	 * Pros:
6751
	 * - Uses only ONE css asset connection instead of 15
6752
	 * - Saves a minimum of 56k
6753
	 * - Reduces server load
6754
	 * - Reduces time to first painted byte
6755
	 *
6756
	 * Cons:
6757
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6758
	 *      should not cause any issues with themes.
6759
	 * - Plugins/themes dequeuing styles no longer do anything. See
6760
	 *      jetpack_implode_frontend_css filter for a workaround
6761
	 *
6762
	 * For some situations developers may wish to disable css imploding and
6763
	 * instead operate in legacy mode where each file loads seperately and
6764
	 * can be edited individually or dequeued. This can be accomplished with
6765
	 * the following line:
6766
	 *
6767
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6768
	 *
6769
	 * @since 3.2
6770
	 **/
6771
	public function implode_frontend_css( $travis_test = false ) {
6772
		$do_implode = true;
6773
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6774
			$do_implode = false;
6775
		}
6776
6777
		// Do not implode CSS when the page loads via the AMP plugin.
6778
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6779
			$do_implode = false;
6780
		}
6781
6782
		/**
6783
		 * Allow CSS to be concatenated into a single jetpack.css file.
6784
		 *
6785
		 * @since 3.2.0
6786
		 *
6787
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6788
		 */
6789
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6790
6791
		// Do not use the imploded file when default behavior was altered through the filter
6792
		if ( ! $do_implode ) {
6793
			return;
6794
		}
6795
6796
		// We do not want to use the imploded file in dev mode, or if not connected
6797
		if ( ( new Status() )->is_offline_mode() || ! self::is_active() ) {
6798
			if ( ! $travis_test ) {
6799
				return;
6800
			}
6801
		}
6802
6803
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6804
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6805
			return;
6806
		}
6807
6808
		/*
6809
		 * Now we assume Jetpack is connected and able to serve the single
6810
		 * file.
6811
		 *
6812
		 * In the future there will be a check here to serve the file locally
6813
		 * or potentially from the Jetpack CDN
6814
		 *
6815
		 * For now:
6816
		 * - Enqueue a single imploded css file
6817
		 * - Zero out the style_loader_tag for the bundled ones
6818
		 * - Be happy, drink scotch
6819
		 */
6820
6821
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6822
6823
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6824
6825
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6826
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6827
	}
6828
6829
	function concat_remove_style_loader_tag( $tag, $handle ) {
6830
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6831
			$tag = '';
6832
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6833
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6834
			}
6835
		}
6836
6837
		return $tag;
6838
	}
6839
6840
	/**
6841
	 * @deprecated
6842
	 * @see Automattic\Jetpack\Assets\add_aync_script
6843
	 */
6844
	public function script_add_async( $tag, $handle, $src ) {
6845
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6846
	}
6847
6848
	/*
6849
	 * Check the heartbeat data
6850
	 *
6851
	 * Organizes the heartbeat data by severity.  For example, if the site
6852
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6853
	 *
6854
	 * Data will be added to "caution" array, if it either:
6855
	 *  - Out of date Jetpack version
6856
	 *  - Out of date WP version
6857
	 *  - Out of date PHP version
6858
	 *
6859
	 * $return array $filtered_data
6860
	 */
6861
	public static function jetpack_check_heartbeat_data() {
6862
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6863
6864
		$good    = array();
6865
		$caution = array();
6866
		$bad     = array();
6867
6868
		foreach ( $raw_data as $stat => $value ) {
6869
6870
			// Check jetpack version
6871
			if ( 'version' == $stat ) {
6872
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6873
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6874
					continue;
6875
				}
6876
			}
6877
6878
			// Check WP version
6879
			if ( 'wp-version' == $stat ) {
6880
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6881
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6882
					continue;
6883
				}
6884
			}
6885
6886
			// Check PHP version
6887
			if ( 'php-version' == $stat ) {
6888
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6889
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6890
					continue;
6891
				}
6892
			}
6893
6894
			// Check ID crisis
6895
			if ( 'identitycrisis' == $stat ) {
6896
				if ( 'yes' == $value ) {
6897
					$bad[ $stat ] = $value;
6898
					continue;
6899
				}
6900
			}
6901
6902
			// The rest are good :)
6903
			$good[ $stat ] = $value;
6904
		}
6905
6906
		$filtered_data = array(
6907
			'good'    => $good,
6908
			'caution' => $caution,
6909
			'bad'     => $bad,
6910
		);
6911
6912
		return $filtered_data;
6913
	}
6914
6915
	/*
6916
	 * This method is used to organize all options that can be reset
6917
	 * without disconnecting Jetpack.
6918
	 *
6919
	 * It is used in class.jetpack-cli.php to reset options
6920
	 *
6921
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6922
	 *
6923
	 * @return array of options to delete.
6924
	 */
6925
	public static function get_jetpack_options_for_reset() {
6926
		return Jetpack_Options::get_options_for_reset();
6927
	}
6928
6929
	/*
6930
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6931
	 * so we can bring them directly to their site in calypso.
6932
	 *
6933
	 * @deprecated 9.2.0 Use Automattic\Jetpack\Status::get_site_suffix
6934
	 *
6935
	 * @param string | url
6936
	 * @return string | url without the guff
6937
	 */
6938
	public static function build_raw_urls( $url ) {
6939
		_deprecated_function( __METHOD__, 'jetpack-9.2.0', 'Automattic\Jetpack\Status::get_site_suffix' );
6940
6941
		return ( new Status() )->get_site_suffix( $url );
6942
	}
6943
6944
	/**
6945
	 * Stores and prints out domains to prefetch for page speed optimization.
6946
	 *
6947
	 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
6948
	 *
6949
	 * @param string|array $urls URLs to hint.
6950
	 */
6951
	public static function dns_prefetch( $urls = null ) {
6952
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
6953
		if ( $urls ) {
6954
			Assets::add_resource_hint( $urls );
6955
		}
6956
	}
6957
6958
	public function wp_dashboard_setup() {
6959
		if ( self::is_active() ) {
6960
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6961
		}
6962
6963
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6964
			$jetpack_logo = new Jetpack_Logo();
6965
			$widget_title = sprintf(
6966
				wp_kses(
6967
					/* translators: Placeholder is a Jetpack logo. */
6968
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6969
					array( 'span' => array() )
6970
				),
6971
				$jetpack_logo->get_jp_emblem( true )
6972
			);
6973
6974
			wp_add_dashboard_widget(
6975
				'jetpack_summary_widget',
6976
				$widget_title,
6977
				array( __CLASS__, 'dashboard_widget' )
6978
			);
6979
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6980
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6981
6982
			// If we're inactive and not in offline mode, sort our box to the top.
6983
			if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
6984
				global $wp_meta_boxes;
6985
6986
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6987
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6988
6989
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6990
			}
6991
		}
6992
	}
6993
6994
	/**
6995
	 * @param mixed $result Value for the user's option
6996
	 * @return mixed
6997
	 */
6998
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6999
		if ( ! is_array( $sorted ) ) {
7000
			return $sorted;
7001
		}
7002
7003
		foreach ( $sorted as $box_context => $ids ) {
7004
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
7005
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
7006
				continue;
7007
			}
7008
7009
			$ids_array = explode( ',', $ids );
7010
			$key       = array_search( 'dashboard_stats', $ids_array );
7011
7012
			if ( false !== $key ) {
7013
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
7014
				$ids_array[ $key ]      = 'jetpack_summary_widget';
7015
				$sorted[ $box_context ] = implode( ',', $ids_array );
7016
				// We've found it, stop searching, and just return.
7017
				break;
7018
			}
7019
		}
7020
7021
		return $sorted;
7022
	}
7023
7024
	public static function dashboard_widget() {
7025
		/**
7026
		 * Fires when the dashboard is loaded.
7027
		 *
7028
		 * @since 3.4.0
7029
		 */
7030
		do_action( 'jetpack_dashboard_widget' );
7031
	}
7032
7033
	public static function dashboard_widget_footer() {
7034
		?>
7035
		<footer>
7036
7037
		<div class="protect">
7038
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
7039
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
7040
				<p class="blocked-count">
7041
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
7042
				</p>
7043
				<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>
7044
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
7045
				<a href="
7046
				<?php
7047
				echo esc_url(
7048
					wp_nonce_url(
7049
						self::admin_url(
7050
							array(
7051
								'action' => 'activate',
7052
								'module' => 'protect',
7053
							)
7054
						),
7055
						'jetpack_activate-protect'
7056
					)
7057
				);
7058
				?>
7059
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7060
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7061
				</a>
7062
			<?php else : ?>
7063
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7064
			<?php endif; ?>
7065
		</div>
7066
7067
		<div class="akismet">
7068
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7069
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7070
				<p class="blocked-count">
7071
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7072
				</p>
7073
				<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>
7074
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7075
				<a href="
7076
				<?php
7077
				echo esc_url(
7078
					wp_nonce_url(
7079
						add_query_arg(
7080
							array(
7081
								'action' => 'activate',
7082
								'plugin' => 'akismet/akismet.php',
7083
							),
7084
							admin_url( 'plugins.php' )
7085
						),
7086
						'activate-plugin_akismet/akismet.php'
7087
					)
7088
				);
7089
				?>
7090
							" class="button button-jetpack">
7091
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7092
				</a>
7093
			<?php else : ?>
7094
				<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>
7095
			<?php endif; ?>
7096
		</div>
7097
7098
		</footer>
7099
		<?php
7100
	}
7101
7102
	/*
7103
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7104
	 */
7105
	function jetpack_icon_user_connected( $columns ) {
7106
		$columns['user_jetpack'] = '';
7107
		return $columns;
7108
	}
7109
7110
	/*
7111
	 * Show Jetpack icon if the user is linked.
7112
	 */
7113
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7114
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
7115
			$jetpack_logo = new Jetpack_Logo();
7116
			$emblem_html  = sprintf(
7117
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7118
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7119
				$jetpack_logo->get_jp_emblem()
7120
			);
7121
			return $emblem_html;
7122
		}
7123
7124
		return $val;
7125
	}
7126
7127
	/*
7128
	 * Style the Jetpack user column
7129
	 */
7130
	function jetpack_user_col_style() {
7131
		global $current_screen;
7132
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7133
			?>
7134
			<style>
7135
				.fixed .column-user_jetpack {
7136
					width: 21px;
7137
				}
7138
				.jp-emblem-user-admin svg {
7139
					width: 20px;
7140
					height: 20px;
7141
				}
7142
				.jp-emblem-user-admin path {
7143
					fill: #00BE28;
7144
				}
7145
			</style>
7146
			<?php
7147
		}
7148
	}
7149
7150
	/**
7151
	 * Checks if Akismet is active and working.
7152
	 *
7153
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7154
	 * that implied usage of methods present since more recent version.
7155
	 * See https://github.com/Automattic/jetpack/pull/9585
7156
	 *
7157
	 * @since  5.1.0
7158
	 *
7159
	 * @return bool True = Akismet available. False = Aksimet not available.
7160
	 */
7161
	public static function is_akismet_active() {
7162
		static $status = null;
7163
7164
		if ( ! is_null( $status ) ) {
7165
			return $status;
7166
		}
7167
7168
		// Check if a modern version of Akismet is active.
7169
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7170
			$status = false;
7171
			return $status;
7172
		}
7173
7174
		// Make sure there is a key known to Akismet at all before verifying key.
7175
		$akismet_key = Akismet::get_api_key();
7176
		if ( ! $akismet_key ) {
7177
			$status = false;
7178
			return $status;
7179
		}
7180
7181
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7182
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7183
7184
		// 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.
7185
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7186
		// We cache the result of the Akismet key verification for ten minutes.
7187
		if ( ! $akismet_key_state || $recheck ) {
7188
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7189
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7190
		}
7191
7192
		$status = 'valid' === $akismet_key_state;
7193
7194
		return $status;
7195
	}
7196
7197
	/**
7198
	 * @deprecated
7199
	 *
7200
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7201
	 */
7202
	public static function is_function_in_backtrace() {
7203
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7204
	}
7205
7206
	/**
7207
	 * Given a minified path, and a non-minified path, will return
7208
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7209
	 *
7210
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7211
	 * root Jetpack directory.
7212
	 *
7213
	 * @since 5.6.0
7214
	 *
7215
	 * @param string $min_path
7216
	 * @param string $non_min_path
7217
	 * @return string The URL to the file
7218
	 */
7219
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7220
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7221
	}
7222
7223
	/**
7224
	 * Checks for whether Jetpack Backup is enabled.
7225
	 * Will return true if the state of Backup is anything except "unavailable".
7226
	 *
7227
	 * @return bool|int|mixed
7228
	 */
7229
	public static function is_rewind_enabled() {
7230
		if ( ! self::is_active() ) {
7231
			return false;
7232
		}
7233
7234
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7235
		if ( false === $rewind_enabled ) {
7236
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7237
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7238
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7239
				&& ! empty( $rewind_data['state'] )
7240
				&& 'active' === $rewind_data['state'] )
7241
				? 1
7242
				: 0;
7243
7244
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7245
		}
7246
		return $rewind_enabled;
7247
	}
7248
7249
	/**
7250
	 * Return Calypso environment value; used for developing Jetpack and pairing
7251
	 * it with different Calypso enrionments, such as localhost.
7252
	 *
7253
	 * @since 7.4.0
7254
	 *
7255
	 * @return string Calypso environment
7256
	 */
7257
	public static function get_calypso_env() {
7258
		if ( isset( $_GET['calypso_env'] ) ) {
7259
			return sanitize_key( $_GET['calypso_env'] );
7260
		}
7261
7262
		if ( getenv( 'CALYPSO_ENV' ) ) {
7263
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7264
		}
7265
7266
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7267
			return sanitize_key( CALYPSO_ENV );
7268
		}
7269
7270
		return '';
7271
	}
7272
7273
	/**
7274
	 * Returns the hostname with protocol for Calypso.
7275
	 * Used for developing Jetpack with Calypso.
7276
	 *
7277
	 * @since 8.4.0
7278
	 *
7279
	 * @return string Calypso host.
7280
	 */
7281
	public static function get_calypso_host() {
7282
		$calypso_env = self::get_calypso_env();
7283
		switch ( $calypso_env ) {
7284
			case 'development':
7285
				return 'http://calypso.localhost:3000/';
7286
			case 'wpcalypso':
7287
				return 'https://wpcalypso.wordpress.com/';
7288
			case 'horizon':
7289
				return 'https://horizon.wordpress.com/';
7290
			default:
7291
				return 'https://wordpress.com/';
7292
		}
7293
	}
7294
7295
	/**
7296
	 * Handles activating default modules as well general cleanup for the new connection.
7297
	 *
7298
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7299
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7300
	 * @param boolean $send_state_messages          Whether to send state messages.
7301
	 * @return void
7302
	 */
7303
	public static function handle_post_authorization_actions(
7304
		$activate_sso = false,
7305
		$redirect_on_activation_error = false,
7306
		$send_state_messages = true
7307
	) {
7308
		$other_modules = $activate_sso
7309
			? array( 'sso' )
7310
			: array();
7311
7312
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7313
			self::delete_active_modules();
7314
7315
			self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
7316
		} else {
7317
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7318
		}
7319
7320
		// Since this is a fresh connection, be sure to clear out IDC options
7321
		Jetpack_IDC::clear_all_idc_options();
7322
7323
		if ( $send_state_messages ) {
7324
			self::state( 'message', 'authorized' );
7325
		}
7326
	}
7327
7328
	/**
7329
	 * Returns a boolean for whether backups UI should be displayed or not.
7330
	 *
7331
	 * @return bool Should backups UI be displayed?
7332
	 */
7333
	public static function show_backups_ui() {
7334
		/**
7335
		 * Whether UI for backups should be displayed.
7336
		 *
7337
		 * @since 6.5.0
7338
		 *
7339
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7340
		 */
7341
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7342
	}
7343
7344
	/*
7345
	 * Deprecated manage functions
7346
	 */
7347
	function prepare_manage_jetpack_notice() {
7348
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7349
	}
7350
	function manage_activate_screen() {
7351
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7352
	}
7353
	function admin_jetpack_manage_notice() {
7354
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7355
	}
7356
	function opt_out_jetpack_manage_url() {
7357
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7358
	}
7359
	function opt_in_jetpack_manage_url() {
7360
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7361
	}
7362
	function opt_in_jetpack_manage_notice() {
7363
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7364
	}
7365
	function can_display_jetpack_manage_notice() {
7366
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7367
	}
7368
7369
	/**
7370
	 * Clean leftoveruser meta.
7371
	 *
7372
	 * Delete Jetpack-related user meta when it is no longer needed.
7373
	 *
7374
	 * @since 7.3.0
7375
	 *
7376
	 * @param int $user_id User ID being updated.
7377
	 */
7378
	public static function user_meta_cleanup( $user_id ) {
7379
		$meta_keys = array(
7380
			// AtD removed from Jetpack 7.3
7381
			'AtD_options',
7382
			'AtD_check_when',
7383
			'AtD_guess_lang',
7384
			'AtD_ignored_phrases',
7385
		);
7386
7387
		foreach ( $meta_keys as $meta_key ) {
7388
			if ( get_user_meta( $user_id, $meta_key ) ) {
7389
				delete_user_meta( $user_id, $meta_key );
7390
			}
7391
		}
7392
	}
7393
7394
	/**
7395
	 * Checks if a Jetpack site is both active and not in offline mode.
7396
	 *
7397
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7398
	 *
7399
	 * @deprecated 8.8.0
7400
	 *
7401
	 * @return bool True if Jetpack is active and not in offline mode.
7402
	 */
7403
	public static function is_active_and_not_development_mode() {
7404
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7405
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7406
			return false;
7407
		}
7408
		return true;
7409
	}
7410
7411
	/**
7412
	 * Checks if a Jetpack site is both active and not in offline mode.
7413
	 *
7414
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7415
	 *
7416
	 * @since 8.8.0
7417
	 *
7418
	 * @return bool True if Jetpack is active and not in offline mode.
7419
	 */
7420
	public static function is_active_and_not_offline_mode() {
7421
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7422
			return false;
7423
		}
7424
		return true;
7425
	}
7426
7427
	/**
7428
	 * Returns the list of products that we have available for purchase.
7429
	 */
7430
	public static function get_products_for_purchase() {
7431
		$products = array();
7432
		if ( ! is_multisite() ) {
7433
			$products[] = array(
7434
				'key'               => 'backup',
7435
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7436
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7437
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7438
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7439
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7440
				'options'           => array(
7441
					array(
7442
						'type'        => 'daily',
7443
						'slug'        => 'jetpack-backup-daily',
7444
						'key'         => 'jetpack_backup_daily',
7445
						'name'        => __( 'Daily Backups', 'jetpack' ),
7446
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7447
					),
7448
					array(
7449
						'type'        => 'realtime',
7450
						'slug'        => 'jetpack-backup-realtime',
7451
						'key'         => 'jetpack_backup_realtime',
7452
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7453
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7454
					),
7455
				),
7456
				'default_option'    => 'realtime',
7457
				'show_promotion'    => true,
7458
				'discount_percent'  => 70,
7459
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7460
			);
7461
7462
			$products[] = array(
7463
				'key'               => 'scan',
7464
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7465
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7466
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7467
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7468
				'show_promotion'    => true,
7469
				'discount_percent'  => 30,
7470
				'options'           => array(
7471
					array(
7472
						'type' => 'scan',
7473
						'slug' => 'jetpack-scan',
7474
						'key'  => 'jetpack_scan',
7475
						'name' => __( 'Daily Scan', 'jetpack' ),
7476
					),
7477
				),
7478
				'default_option'    => 'scan',
7479
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7480
			);
7481
		}
7482
7483
		$products[] = array(
7484
			'key'               => 'search',
7485
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7486
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7487
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7488
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7489
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
7490
			'options'           => array(
7491
				array(
7492
					'type' => 'search',
7493
					'slug' => 'jetpack-search',
7494
					'key'  => 'jetpack_search',
7495
					'name' => __( 'Search', 'jetpack' ),
7496
				),
7497
			),
7498
			'tears'             => array(),
7499
			'default_option'    => 'search',
7500
			'show_promotion'    => false,
7501
			'included_in_plans' => array( 'search-plan' ),
7502
		);
7503
7504
		$products[] = array(
7505
			'key'               => 'anti-spam',
7506
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7507
			'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' ),
7508
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7509
			'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' ),
7510
			'options'           => array(
7511
				array(
7512
					'type' => 'anti-spam',
7513
					'slug' => 'jetpack-anti-spam',
7514
					'key'  => 'jetpack_anti_spam',
7515
					'name' => __( 'Anti-Spam', 'jetpack' ),
7516
				),
7517
			),
7518
			'default_option'    => 'anti-spam',
7519
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7520
		);
7521
7522
		return $products;
7523
	}
7524
}
7525