Completed
Push — renovate/css-loader-3.x ( 28f4d8...69dcae )
by
unknown
51:11 queued 42:16
created

class.jetpack.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

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

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

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
5794
				if ( strlen( $v ) ) {
5795
					$state[ $k ] = $v;
5796
				}
5797
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5798
			}
5799
		}
5800
5801
		if ( $restate ) {
5802
			foreach ( $state as $k => $v ) {
5803
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5804
			}
5805
			return;
5806
		}
5807
5808
		// Get a state variable.
5809
		if ( isset( $key ) && ! isset( $value ) ) {
5810
			if ( array_key_exists( $key, $state ) ) {
5811
				return $state[ $key ];
5812
			}
5813
			return null;
5814
		}
5815
5816
		// Set a state variable.
5817
		if ( isset( $key ) && isset( $value ) ) {
5818
			if ( is_array( $value ) && isset( $value[0] ) ) {
5819
				$value = $value[0];
5820
			}
5821
			$state[ $key ] = $value;
5822
			if ( ! headers_sent() ) {
5823
				if ( self::should_set_cookie( $key ) ) {
5824
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5825
				}
5826
			}
5827
		}
5828
	}
5829
5830
	public static function restate() {
5831
		self::state( null, null, true );
5832
	}
5833
5834
	/**
5835
	 * Determines whether the jetpackState[$key] value should be added to the
5836
	 * cookie.
5837
	 *
5838
	 * @param string $key The state key.
5839
	 *
5840
	 * @return boolean Whether the value should be added to the cookie.
5841
	 */
5842
	public static function should_set_cookie( $key ) {
5843
		global $current_screen;
5844
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5845
5846
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5847
			return false;
5848
		}
5849
5850
		return true;
5851
	}
5852
5853
	public static function check_privacy( $file ) {
5854
		static $is_site_publicly_accessible = null;
5855
5856
		if ( is_null( $is_site_publicly_accessible ) ) {
5857
			$is_site_publicly_accessible = false;
5858
5859
			$rpc = new Jetpack_IXR_Client();
5860
5861
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5862
			if ( $success ) {
5863
				$response = $rpc->getResponse();
5864
				if ( $response ) {
5865
					$is_site_publicly_accessible = true;
5866
				}
5867
			}
5868
5869
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5870
		}
5871
5872
		if ( $is_site_publicly_accessible ) {
5873
			return;
5874
		}
5875
5876
		$module_slug = self::get_module_slug( $file );
5877
5878
		$privacy_checks = self::state( 'privacy_checks' );
5879
		if ( ! $privacy_checks ) {
5880
			$privacy_checks = $module_slug;
5881
		} else {
5882
			$privacy_checks .= ",$module_slug";
5883
		}
5884
5885
		self::state( 'privacy_checks', $privacy_checks );
5886
	}
5887
5888
	/**
5889
	 * Helper method for multicall XMLRPC.
5890
	 *
5891
	 * @param ...$args Args for the async_call.
5892
	 */
5893
	public static function xmlrpc_async_call( ...$args ) {
5894
		global $blog_id;
5895
		static $clients = array();
5896
5897
		$client_blog_id = is_multisite() ? $blog_id : 0;
5898
5899
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5900
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5901
			if ( function_exists( 'ignore_user_abort' ) ) {
5902
				ignore_user_abort( true );
5903
			}
5904
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5905
		}
5906
5907
		if ( ! empty( $args[0] ) ) {
5908
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5909
		} elseif ( is_multisite() ) {
5910
			foreach ( $clients as $client_blog_id => $client ) {
5911
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5912
					continue;
5913
				}
5914
5915
				$switch_success = switch_to_blog( $client_blog_id, true );
5916
				if ( ! $switch_success ) {
5917
					continue;
5918
				}
5919
5920
				flush();
5921
				$client->query();
5922
5923
				restore_current_blog();
5924
			}
5925
		} else {
5926
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5927
				flush();
5928
				$clients[0]->query();
5929
			}
5930
		}
5931
	}
5932
5933
	public static function staticize_subdomain( $url ) {
5934
5935
		// Extract hostname from URL
5936
		$host = wp_parse_url( $url, PHP_URL_HOST );
5937
5938
		// Explode hostname on '.'
5939
		$exploded_host = explode( '.', $host );
5940
5941
		// Retrieve the name and TLD
5942
		if ( count( $exploded_host ) > 1 ) {
5943
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5944
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5945
			// Rebuild domain excluding subdomains
5946
			$domain = $name . '.' . $tld;
5947
		} else {
5948
			$domain = $host;
5949
		}
5950
		// Array of Automattic domains.
5951
		$domains_allowed = array( 'wordpress.com', 'wp.com' );
5952
5953
		// Return $url if not an Automattic domain.
5954
		if ( ! in_array( $domain, $domains_allowed, true ) ) {
5955
			return $url;
5956
		}
5957
5958
		if ( is_ssl() ) {
5959
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5960
		}
5961
5962
		srand( crc32( basename( $url ) ) );
5963
		$static_counter = rand( 0, 2 );
5964
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5965
5966
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5967
	}
5968
5969
	/* JSON API Authorization */
5970
5971
	/**
5972
	 * Handles the login action for Authorizing the JSON API
5973
	 */
5974
	function login_form_json_api_authorization() {
5975
		$this->verify_json_api_authorization_request();
5976
5977
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5978
5979
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5980
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5981
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5982
	}
5983
5984
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5985
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5986
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5987
			return $url;
5988
		}
5989
5990
		$parsed_url = wp_parse_url( $url );
5991
		$url        = strtok( $url, '?' );
5992
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5993
		if ( ! empty( $parsed_url['query'] ) ) {
5994
			$url .= "&{$parsed_url['query']}";
5995
		}
5996
5997
		return $url;
5998
	}
5999
6000
	// Make sure the POSTed request is handled by the same action
6001
	function preserve_action_in_login_form_for_json_api_authorization() {
6002
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
6003
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
6004
	}
6005
6006
	// If someone logs in to approve API access, store the Access Code in usermeta
6007
	function store_json_api_authorization_token( $user_login, $user ) {
6008
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
6009
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
6010
		$token = wp_generate_password( 32, false );
6011
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
6012
	}
6013
6014
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
6015
	function allow_wpcom_public_api_domain( $domains ) {
6016
		$domains[] = 'public-api.wordpress.com';
6017
		return $domains;
6018
	}
6019
6020
	static function is_redirect_encoded( $redirect_url ) {
6021
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
6022
	}
6023
6024
	// Add all wordpress.com environments to the safe redirect allowed list.
6025
	function allow_wpcom_environments( $domains ) {
6026
		$domains[] = 'wordpress.com';
6027
		$domains[] = 'wpcalypso.wordpress.com';
6028
		$domains[] = 'horizon.wordpress.com';
6029
		$domains[] = 'calypso.localhost';
6030
		return $domains;
6031
	}
6032
6033
	// Add the Access Code details to the public-api.wordpress.com redirect
6034
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
6035
		return add_query_arg(
6036
			urlencode_deep(
6037
				array(
6038
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6039
					'jetpack-user-id' => (int) $user->ID,
6040
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6041
				)
6042
			),
6043
			$redirect_to
6044
		);
6045
	}
6046
6047
6048
	/**
6049
	 * Verifies the request by checking the signature
6050
	 *
6051
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6052
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6053
	 *
6054
	 * @param null|array $environment
6055
	 */
6056
	function verify_json_api_authorization_request( $environment = null ) {
6057
		$environment = is_null( $environment )
6058
			? $_REQUEST
6059
			: $environment;
6060
6061
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
6062
		$token                                     = Jetpack_Data::get_access_token( $envUserId, $envToken );
6063
		if ( ! $token || empty( $token->secret ) ) {
6064
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6065
		}
6066
6067
		$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' );
6068
6069
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6070
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6071
			/**
6072
			 * Jetpack authorisation request Error.
6073
			 *
6074
			 * @since 7.5.0
6075
			 */
6076
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6077
			$die_error = sprintf(
6078
				/* translators: %s is a URL */
6079
				__( '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' ),
6080
				Redirect::get_url( 'jetpack-support-double-encoding' )
6081
			);
6082
		}
6083
6084
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6085
6086
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6087
			$signature = $jetpack_signature->sign_request(
6088
				$environment['token'],
6089
				$environment['timestamp'],
6090
				$environment['nonce'],
6091
				'',
6092
				'GET',
6093
				$environment['jetpack_json_api_original_query'],
6094
				null,
6095
				true
6096
			);
6097
		} else {
6098
			$signature = $jetpack_signature->sign_current_request(
6099
				array(
6100
					'body'   => null,
6101
					'method' => 'GET',
6102
				)
6103
			);
6104
		}
6105
6106
		if ( ! $signature ) {
6107
			wp_die( $die_error );
6108
		} elseif ( is_wp_error( $signature ) ) {
6109
			wp_die( $die_error );
6110
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6111
			if ( is_ssl() ) {
6112
				// 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
6113
				$signature = $jetpack_signature->sign_current_request(
6114
					array(
6115
						'scheme' => 'http',
6116
						'body'   => null,
6117
						'method' => 'GET',
6118
					)
6119
				);
6120
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6121
					wp_die( $die_error );
6122
				}
6123
			} else {
6124
				wp_die( $die_error );
6125
			}
6126
		}
6127
6128
		$timestamp = (int) $environment['timestamp'];
6129
		$nonce     = stripslashes( (string) $environment['nonce'] );
6130
6131
		if ( ! $this->connection_manager ) {
6132
			$this->connection_manager = new Connection_Manager();
6133
		}
6134
6135
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
6136
			// De-nonce the nonce, at least for 5 minutes.
6137
			// 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)
6138
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6139
			if ( $old_nonce_time < time() - 300 ) {
6140
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6141
			}
6142
		}
6143
6144
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6145
		$data_filters = array(
6146
			'state'        => 'opaque',
6147
			'client_id'    => 'int',
6148
			'client_title' => 'string',
6149
			'client_image' => 'url',
6150
		);
6151
6152
		foreach ( $data_filters as $key => $sanitation ) {
6153
			if ( ! isset( $data->$key ) ) {
6154
				wp_die( $die_error );
6155
			}
6156
6157
			switch ( $sanitation ) {
6158
				case 'int':
6159
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6160
					break;
6161
				case 'opaque':
6162
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6163
					break;
6164
				case 'string':
6165
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6166
					break;
6167
				case 'url':
6168
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6169
					break;
6170
			}
6171
		}
6172
6173
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6174
			wp_die( $die_error );
6175
		}
6176
	}
6177
6178
	function login_message_json_api_authorization( $message ) {
6179
		return '<p class="message">' . sprintf(
6180
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6181
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6182
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6183
	}
6184
6185
	/**
6186
	 * Get $content_width, but with a <s>twist</s> filter.
6187
	 */
6188
	public static function get_content_width() {
6189
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6190
			? $GLOBALS['content_width']
6191
			: false;
6192
		/**
6193
		 * Filter the Content Width value.
6194
		 *
6195
		 * @since 2.2.3
6196
		 *
6197
		 * @param string $content_width Content Width value.
6198
		 */
6199
		return apply_filters( 'jetpack_content_width', $content_width );
6200
	}
6201
6202
	/**
6203
	 * Pings the WordPress.com Mirror Site for the specified options.
6204
	 *
6205
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6206
	 *
6207
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6208
	 */
6209
	public function get_cloud_site_options( $option_names ) {
6210
		$option_names = array_filter( (array) $option_names, 'is_string' );
6211
6212
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
6213
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6214
		if ( $xml->isError() ) {
6215
			return array(
6216
				'error_code' => $xml->getErrorCode(),
6217
				'error_msg'  => $xml->getErrorMessage(),
6218
			);
6219
		}
6220
		$cloud_site_options = $xml->getResponse();
6221
6222
		return $cloud_site_options;
6223
	}
6224
6225
	/**
6226
	 * Checks if the site is currently in an identity crisis.
6227
	 *
6228
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6229
	 */
6230
	public static function check_identity_crisis() {
6231
		if ( ! self::is_active() || ( new Status() )->is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6232
			return false;
6233
		}
6234
6235
		return Jetpack_Options::get_option( 'sync_error_idc' );
6236
	}
6237
6238
	/**
6239
	 * Checks whether the home and siteurl specifically are allowed.
6240
	 * Written so that we don't have re-check $key and $value params every time
6241
	 * we want to check if this site is allowed, for example in footer.php
6242
	 *
6243
	 * @since  3.8.0
6244
	 * @return bool True = already allowed False = not on the allowed list.
6245
	 */
6246
	public static function is_staging_site() {
6247
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6248
		return ( new Status() )->is_staging_site();
6249
	}
6250
6251
	/**
6252
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6253
	 *
6254
	 * @since 4.4.0
6255
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6256
	 *
6257
	 * @return bool
6258
	 */
6259
	public static function validate_sync_error_idc_option() {
6260
		$is_valid = false;
6261
6262
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6263
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6264
		if ( $sync_error && self::sync_idc_optin() ) {
6265
			$local_options = self::get_sync_error_idc_option();
6266
			// Ensure all values are set.
6267
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6268
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6269
					$is_valid = true;
6270
				}
6271
			}
6272
		}
6273
6274
		/**
6275
		 * Filters whether the sync_error_idc option is valid.
6276
		 *
6277
		 * @since 4.4.0
6278
		 *
6279
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6280
		 */
6281
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6282
6283
		if ( ! $is_valid && $sync_error ) {
6284
			// Since the option exists, and did not validate, delete it
6285
			Jetpack_Options::delete_option( 'sync_error_idc' );
6286
		}
6287
6288
		return $is_valid;
6289
	}
6290
6291
	/**
6292
	 * Normalizes a url by doing three things:
6293
	 *  - Strips protocol
6294
	 *  - Strips www
6295
	 *  - Adds a trailing slash
6296
	 *
6297
	 * @since 4.4.0
6298
	 * @param string $url
6299
	 * @return WP_Error|string
6300
	 */
6301
	public static function normalize_url_protocol_agnostic( $url ) {
6302
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6303
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6304
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6305
		}
6306
6307
		// Strip www and protocols
6308
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6309
		return $url;
6310
	}
6311
6312
	/**
6313
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6314
	 *
6315
	 * @since 4.4.0
6316
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6317
	 *
6318
	 * @param array $response
6319
	 * @return array Array of the local urls, wpcom urls, and error code
6320
	 */
6321
	public static function get_sync_error_idc_option( $response = array() ) {
6322
		// Since the local options will hit the database directly, store the values
6323
		// in a transient to allow for autoloading and caching on subsequent views.
6324
		$local_options = get_transient( 'jetpack_idc_local' );
6325
		if ( false === $local_options ) {
6326
			$local_options = array(
6327
				'home'    => Functions::home_url(),
6328
				'siteurl' => Functions::site_url(),
6329
			);
6330
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6331
		}
6332
6333
		$options = array_merge( $local_options, $response );
6334
6335
		$returned_values = array();
6336
		foreach ( $options as $key => $option ) {
6337
			if ( 'error_code' === $key ) {
6338
				$returned_values[ $key ] = $option;
6339
				continue;
6340
			}
6341
6342
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6343
				continue;
6344
			}
6345
6346
			$returned_values[ $key ] = $normalized_url;
6347
		}
6348
6349
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6350
6351
		return $returned_values;
6352
	}
6353
6354
	/**
6355
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6356
	 * If set to true, the site will be put into staging mode.
6357
	 *
6358
	 * @since 4.3.2
6359
	 * @return bool
6360
	 */
6361
	public static function sync_idc_optin() {
6362
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6363
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6364
		} else {
6365
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6366
		}
6367
6368
		/**
6369
		 * Allows sites to opt in to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6370
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6371
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6372
		 *
6373
		 * @since 4.3.2
6374
		 *
6375
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6376
		 */
6377
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6378
	}
6379
6380
	/**
6381
	 * Maybe Use a .min.css stylesheet, maybe not.
6382
	 *
6383
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6384
	 */
6385
	public static function maybe_min_asset( $url, $path, $plugin ) {
6386
		// Short out on things trying to find actual paths.
6387
		if ( ! $path || empty( $plugin ) ) {
6388
			return $url;
6389
		}
6390
6391
		$path = ltrim( $path, '/' );
6392
6393
		// Strip out the abspath.
6394
		$base = dirname( plugin_basename( $plugin ) );
6395
6396
		// Short out on non-Jetpack assets.
6397
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6398
			return $url;
6399
		}
6400
6401
		// File name parsing.
6402
		$file              = "{$base}/{$path}";
6403
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6404
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6405
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6406
		$extension         = array_shift( $file_name_parts_r );
6407
6408
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6409
			// Already pointing at the minified version.
6410
			if ( 'min' === $file_name_parts_r[0] ) {
6411
				return $url;
6412
			}
6413
6414
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6415
			if ( file_exists( $min_full_path ) ) {
6416
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6417
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6418
				if ( 'css' === $extension ) {
6419
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6420
					self::$min_assets[ $key ] = $path;
6421
				}
6422
			}
6423
		}
6424
6425
		return $url;
6426
	}
6427
6428
	/**
6429
	 * If the asset is minified, let's flag .min as the suffix.
6430
	 *
6431
	 * Attached to `style_loader_src` filter.
6432
	 *
6433
	 * @param string $tag The tag that would link to the external asset.
6434
	 * @param string $handle The registered handle of the script in question.
6435
	 * @param string $href The url of the asset in question.
6436
	 */
6437
	public static function set_suffix_on_min( $src, $handle ) {
6438
		if ( false === strpos( $src, '.min.css' ) ) {
6439
			return $src;
6440
		}
6441
6442
		if ( ! empty( self::$min_assets ) ) {
6443
			foreach ( self::$min_assets as $file => $path ) {
6444
				if ( false !== strpos( $src, $file ) ) {
6445
					wp_style_add_data( $handle, 'suffix', '.min' );
6446
					return $src;
6447
				}
6448
			}
6449
		}
6450
6451
		return $src;
6452
	}
6453
6454
	/**
6455
	 * Maybe inlines a stylesheet.
6456
	 *
6457
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6458
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6459
	 *
6460
	 * Attached to `style_loader_tag` filter.
6461
	 *
6462
	 * @param string $tag The tag that would link to the external asset.
6463
	 * @param string $handle The registered handle of the script in question.
6464
	 *
6465
	 * @return string
6466
	 */
6467
	public static function maybe_inline_style( $tag, $handle ) {
6468
		global $wp_styles;
6469
		$item = $wp_styles->registered[ $handle ];
6470
6471
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6472
			return $tag;
6473
		}
6474
6475
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6476
			$href = $matches[1];
6477
			// Strip off query string
6478
			if ( $pos = strpos( $href, '?' ) ) {
6479
				$href = substr( $href, 0, $pos );
6480
			}
6481
			// Strip off fragment
6482
			if ( $pos = strpos( $href, '#' ) ) {
6483
				$href = substr( $href, 0, $pos );
6484
			}
6485
		} else {
6486
			return $tag;
6487
		}
6488
6489
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6490
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6491
			return $tag;
6492
		}
6493
6494
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6495
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6496
			// And this isn't the pass that actually deals with the RTL version...
6497
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6498
				// Short out, as the RTL version will deal with it in a moment.
6499
				return $tag;
6500
			}
6501
		}
6502
6503
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6504
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6505
		if ( $css ) {
6506
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6507
			if ( empty( $item->extra['after'] ) ) {
6508
				wp_add_inline_style( $handle, $css );
6509
			} else {
6510
				array_unshift( $item->extra['after'], $css );
6511
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6512
			}
6513
		}
6514
6515
		return $tag;
6516
	}
6517
6518
	/**
6519
	 * Loads a view file from the views
6520
	 *
6521
	 * Data passed in with the $data parameter will be available in the
6522
	 * template file as $data['value']
6523
	 *
6524
	 * @param string $template - Template file to load
6525
	 * @param array  $data - Any data to pass along to the template
6526
	 * @return boolean - If template file was found
6527
	 **/
6528
	public function load_view( $template, $data = array() ) {
6529
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6530
6531
		if ( file_exists( $views_dir . $template ) ) {
6532
			require_once $views_dir . $template;
6533
			return true;
6534
		}
6535
6536
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6537
		return false;
6538
	}
6539
6540
	/**
6541
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6542
	 */
6543
	public function deprecated_hooks() {
6544
		global $wp_filter;
6545
6546
		/*
6547
		 * Format:
6548
		 * deprecated_filter_name => replacement_name
6549
		 *
6550
		 * If there is no replacement, use null for replacement_name
6551
		 */
6552
		$deprecated_list = array(
6553
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6554
			'wpl_sharing_2014_1'                           => null,
6555
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6556
			'jetpack_identity_crisis_options_to_check'     => null,
6557
			'update_option_jetpack_single_user_site'       => null,
6558
			'audio_player_default_colors'                  => null,
6559
			'add_option_jetpack_featured_images_enabled'   => null,
6560
			'add_option_jetpack_update_details'            => null,
6561
			'add_option_jetpack_updates'                   => null,
6562
			'add_option_jetpack_network_name'              => null,
6563
			'add_option_jetpack_network_allow_new_registrations' => null,
6564
			'add_option_jetpack_network_add_new_users'     => null,
6565
			'add_option_jetpack_network_site_upload_space' => null,
6566
			'add_option_jetpack_network_upload_file_types' => null,
6567
			'add_option_jetpack_network_enable_administration_menus' => null,
6568
			'add_option_jetpack_is_multi_site'             => null,
6569
			'add_option_jetpack_is_main_network'           => null,
6570
			'add_option_jetpack_main_network_site'         => null,
6571
			'jetpack_sync_all_registered_options'          => null,
6572
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6573
			'jetpack_is_post_mailable'                     => null,
6574
			'jetpack_seo_site_host'                        => null,
6575
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6576
			'jetpack_holiday_snow_option_name'             => null,
6577
			'jetpack_holiday_chance_of_snow'               => null,
6578
			'jetpack_holiday_snow_js_url'                  => null,
6579
			'jetpack_is_holiday_snow_season'               => null,
6580
			'jetpack_holiday_snow_option_updated'          => null,
6581
			'jetpack_holiday_snowing'                      => null,
6582
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6583
			'jetpack_cache_plans'                          => null,
6584
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6585
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6586
			'jetpack_enable_site_verification'             => null,
6587
			'can_display_jetpack_manage_notice'            => null,
6588
			// Removed in Jetpack 7.3.0
6589
			'atd_load_scripts'                             => null,
6590
			'atd_http_post_timeout'                        => null,
6591
			'atd_http_post_error'                          => null,
6592
			'atd_service_domain'                           => null,
6593
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6594
			// Removed in Jetpack 7.9.0
6595
			'jetpack_pwa_manifest'                         => null,
6596
			'jetpack_pwa_background_color'                 => null,
6597
			// Removed in Jetpack 8.3.0.
6598
			'jetpack_check_mobile'                         => null,
6599
			'jetpack_mobile_stylesheet'                    => null,
6600
			'jetpack_mobile_template'                      => null,
6601
			'mobile_reject_mobile'                         => null,
6602
			'mobile_force_mobile'                          => null,
6603
			'mobile_app_promo_download'                    => null,
6604
			'mobile_setup'                                 => null,
6605
			'jetpack_mobile_footer_before'                 => null,
6606
			'wp_mobile_theme_footer'                       => null,
6607
			'minileven_credits'                            => null,
6608
			'jetpack_mobile_header_before'                 => null,
6609
			'jetpack_mobile_header_after'                  => null,
6610
			'jetpack_mobile_theme_menu'                    => null,
6611
			'minileven_show_featured_images'               => null,
6612
			'minileven_attachment_size'                    => null,
6613
		);
6614
6615
		// This is a silly loop depth. Better way?
6616
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6617
			if ( has_action( $hook ) ) {
6618
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6619
					foreach ( $values as $hooked ) {
6620
						if ( is_callable( $hooked['function'] ) ) {
6621
							$function_name = $hooked['function'];
6622
						} else {
6623
							$function_name = 'an anonymous function';
6624
						}
6625
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6626
					}
6627
				}
6628
			}
6629
		}
6630
	}
6631
6632
	/**
6633
	 * Converts any url in a stylesheet, to the correct absolute url.
6634
	 *
6635
	 * Considerations:
6636
	 *  - Normal, relative URLs     `feh.png`
6637
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6638
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6639
	 *  - Absolute URLs             `http://domain.com/feh.png`
6640
	 *  - Domain root relative URLs `/feh.png`
6641
	 *
6642
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6643
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6644
	 *
6645
	 * @return mixed|string
6646
	 */
6647
	public static function absolutize_css_urls( $css, $css_file_url ) {
6648
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6649
		$css_dir = dirname( $css_file_url );
6650
		$p       = wp_parse_url( $css_dir );
6651
		$domain  = sprintf(
6652
			'%1$s//%2$s%3$s%4$s',
6653
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6654
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6655
			$p['host'],
6656
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6657
		);
6658
6659
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6660
			$find = $replace = array();
6661
			foreach ( $matches as $match ) {
6662
				$url = trim( $match['path'], "'\" \t" );
6663
6664
				// If this is a data url, we don't want to mess with it.
6665
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6666
					continue;
6667
				}
6668
6669
				// If this is an absolute or protocol-agnostic url,
6670
				// we don't want to mess with it.
6671
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6672
					continue;
6673
				}
6674
6675
				switch ( substr( $url, 0, 1 ) ) {
6676
					case '/':
6677
						$absolute = $domain . $url;
6678
						break;
6679
					default:
6680
						$absolute = $css_dir . '/' . $url;
6681
				}
6682
6683
				$find[]    = $match[0];
6684
				$replace[] = sprintf( 'url("%s")', $absolute );
6685
			}
6686
			$css = str_replace( $find, $replace, $css );
6687
		}
6688
6689
		return $css;
6690
	}
6691
6692
	/**
6693
	 * This methods removes all of the registered css files on the front end
6694
	 * from Jetpack in favor of using a single file. In effect "imploding"
6695
	 * all the files into one file.
6696
	 *
6697
	 * Pros:
6698
	 * - Uses only ONE css asset connection instead of 15
6699
	 * - Saves a minimum of 56k
6700
	 * - Reduces server load
6701
	 * - Reduces time to first painted byte
6702
	 *
6703
	 * Cons:
6704
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6705
	 *      should not cause any issues with themes.
6706
	 * - Plugins/themes dequeuing styles no longer do anything. See
6707
	 *      jetpack_implode_frontend_css filter for a workaround
6708
	 *
6709
	 * For some situations developers may wish to disable css imploding and
6710
	 * instead operate in legacy mode where each file loads seperately and
6711
	 * can be edited individually or dequeued. This can be accomplished with
6712
	 * the following line:
6713
	 *
6714
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6715
	 *
6716
	 * @since 3.2
6717
	 **/
6718
	public function implode_frontend_css( $travis_test = false ) {
6719
		$do_implode = true;
6720
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6721
			$do_implode = false;
6722
		}
6723
6724
		// Do not implode CSS when the page loads via the AMP plugin.
6725
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6726
			$do_implode = false;
6727
		}
6728
6729
		/**
6730
		 * Allow CSS to be concatenated into a single jetpack.css file.
6731
		 *
6732
		 * @since 3.2.0
6733
		 *
6734
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6735
		 */
6736
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6737
6738
		// Do not use the imploded file when default behavior was altered through the filter
6739
		if ( ! $do_implode ) {
6740
			return;
6741
		}
6742
6743
		// We do not want to use the imploded file in dev mode, or if not connected
6744
		if ( ( new Status() )->is_development_mode() || ! self::is_active() ) {
6745
			if ( ! $travis_test ) {
6746
				return;
6747
			}
6748
		}
6749
6750
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6751
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6752
			return;
6753
		}
6754
6755
		/*
6756
		 * Now we assume Jetpack is connected and able to serve the single
6757
		 * file.
6758
		 *
6759
		 * In the future there will be a check here to serve the file locally
6760
		 * or potentially from the Jetpack CDN
6761
		 *
6762
		 * For now:
6763
		 * - Enqueue a single imploded css file
6764
		 * - Zero out the style_loader_tag for the bundled ones
6765
		 * - Be happy, drink scotch
6766
		 */
6767
6768
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6769
6770
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6771
6772
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6773
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6774
	}
6775
6776
	function concat_remove_style_loader_tag( $tag, $handle ) {
6777
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6778
			$tag = '';
6779
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6780
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6781
			}
6782
		}
6783
6784
		return $tag;
6785
	}
6786
6787
	/**
6788
	 * @deprecated
6789
	 * @see Automattic\Jetpack\Assets\add_aync_script
6790
	 */
6791
	public function script_add_async( $tag, $handle, $src ) {
6792
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6793
	}
6794
6795
	/*
6796
	 * Check the heartbeat data
6797
	 *
6798
	 * Organizes the heartbeat data by severity.  For example, if the site
6799
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6800
	 *
6801
	 * Data will be added to "caution" array, if it either:
6802
	 *  - Out of date Jetpack version
6803
	 *  - Out of date WP version
6804
	 *  - Out of date PHP version
6805
	 *
6806
	 * $return array $filtered_data
6807
	 */
6808
	public static function jetpack_check_heartbeat_data() {
6809
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6810
6811
		$good    = array();
6812
		$caution = array();
6813
		$bad     = array();
6814
6815
		foreach ( $raw_data as $stat => $value ) {
6816
6817
			// Check jetpack version
6818
			if ( 'version' == $stat ) {
6819
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6820
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6821
					continue;
6822
				}
6823
			}
6824
6825
			// Check WP version
6826
			if ( 'wp-version' == $stat ) {
6827
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6828
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6829
					continue;
6830
				}
6831
			}
6832
6833
			// Check PHP version
6834
			if ( 'php-version' == $stat ) {
6835
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6836
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6837
					continue;
6838
				}
6839
			}
6840
6841
			// Check ID crisis
6842
			if ( 'identitycrisis' == $stat ) {
6843
				if ( 'yes' == $value ) {
6844
					$bad[ $stat ] = $value;
6845
					continue;
6846
				}
6847
			}
6848
6849
			// The rest are good :)
6850
			$good[ $stat ] = $value;
6851
		}
6852
6853
		$filtered_data = array(
6854
			'good'    => $good,
6855
			'caution' => $caution,
6856
			'bad'     => $bad,
6857
		);
6858
6859
		return $filtered_data;
6860
	}
6861
6862
6863
	/*
6864
	 * This method is used to organize all options that can be reset
6865
	 * without disconnecting Jetpack.
6866
	 *
6867
	 * It is used in class.jetpack-cli.php to reset options
6868
	 *
6869
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6870
	 *
6871
	 * @return array of options to delete.
6872
	 */
6873
	public static function get_jetpack_options_for_reset() {
6874
		return Jetpack_Options::get_options_for_reset();
6875
	}
6876
6877
	/*
6878
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6879
	 * so we can bring them directly to their site in calypso.
6880
	 *
6881
	 * @param string | url
6882
	 * @return string | url without the guff
6883
	 */
6884 View Code Duplication
	public static function build_raw_urls( $url ) {
6885
		$strip_http = '/.*?:\/\//i';
6886
		$url        = preg_replace( $strip_http, '', $url );
6887
		$url        = str_replace( '/', '::', $url );
6888
		return $url;
6889
	}
6890
6891
	/**
6892
	 * Stores and prints out domains to prefetch for page speed optimization.
6893
	 *
6894
	 * @param mixed $new_urls
6895
	 */
6896
	public static function dns_prefetch( $new_urls = null ) {
6897
		static $prefetch_urls = array();
6898
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6899
			echo "\r\n";
6900
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6901
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6902
			}
6903
		} elseif ( ! empty( $new_urls ) ) {
6904
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6905
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6906
			}
6907
			foreach ( (array) $new_urls as $this_new_url ) {
6908
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6909
			}
6910
			$prefetch_urls = array_unique( $prefetch_urls );
6911
		}
6912
	}
6913
6914
	public function wp_dashboard_setup() {
6915
		if ( self::is_active() ) {
6916
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6917
		}
6918
6919
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6920
			$jetpack_logo = new Jetpack_Logo();
6921
			$widget_title = sprintf(
6922
				wp_kses(
6923
					/* translators: Placeholder is a Jetpack logo. */
6924
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6925
					array( 'span' => array() )
6926
				),
6927
				$jetpack_logo->get_jp_emblem( true )
6928
			);
6929
6930
			wp_add_dashboard_widget(
6931
				'jetpack_summary_widget',
6932
				$widget_title,
6933
				array( __CLASS__, 'dashboard_widget' )
6934
			);
6935
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6936
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6937
6938
			// If we're inactive and not in development mode, sort our box to the top.
6939
			if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
6940
				global $wp_meta_boxes;
6941
6942
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6943
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6944
6945
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6946
			}
6947
		}
6948
	}
6949
6950
	/**
6951
	 * @param mixed $result Value for the user's option
6952
	 * @return mixed
6953
	 */
6954
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6955
		if ( ! is_array( $sorted ) ) {
6956
			return $sorted;
6957
		}
6958
6959
		foreach ( $sorted as $box_context => $ids ) {
6960
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6961
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6962
				continue;
6963
			}
6964
6965
			$ids_array = explode( ',', $ids );
6966
			$key       = array_search( 'dashboard_stats', $ids_array );
6967
6968
			if ( false !== $key ) {
6969
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6970
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6971
				$sorted[ $box_context ] = implode( ',', $ids_array );
6972
				// We've found it, stop searching, and just return.
6973
				break;
6974
			}
6975
		}
6976
6977
		return $sorted;
6978
	}
6979
6980
	public static function dashboard_widget() {
6981
		/**
6982
		 * Fires when the dashboard is loaded.
6983
		 *
6984
		 * @since 3.4.0
6985
		 */
6986
		do_action( 'jetpack_dashboard_widget' );
6987
	}
6988
6989
	public static function dashboard_widget_footer() {
6990
		?>
6991
		<footer>
6992
6993
		<div class="protect">
6994
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6995
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6996
				<p class="blocked-count">
6997
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6998
				</p>
6999
				<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>
7000
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
7001
				<a href="
7002
				<?php
7003
				echo esc_url(
7004
					wp_nonce_url(
7005
						self::admin_url(
7006
							array(
7007
								'action' => 'activate',
7008
								'module' => 'protect',
7009
							)
7010
						),
7011
						'jetpack_activate-protect'
7012
					)
7013
				);
7014
				?>
7015
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7016
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7017
				</a>
7018
			<?php else : ?>
7019
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7020
			<?php endif; ?>
7021
		</div>
7022
7023
		<div class="akismet">
7024
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7025
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7026
				<p class="blocked-count">
7027
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7028
				</p>
7029
				<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>
7030
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7031
				<a href="
7032
				<?php
7033
				echo esc_url(
7034
					wp_nonce_url(
7035
						add_query_arg(
7036
							array(
7037
								'action' => 'activate',
7038
								'plugin' => 'akismet/akismet.php',
7039
							),
7040
							admin_url( 'plugins.php' )
7041
						),
7042
						'activate-plugin_akismet/akismet.php'
7043
					)
7044
				);
7045
				?>
7046
							" class="button button-jetpack">
7047
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7048
				</a>
7049
			<?php else : ?>
7050
				<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>
7051
			<?php endif; ?>
7052
		</div>
7053
7054
		</footer>
7055
		<?php
7056
	}
7057
7058
	/*
7059
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7060
	 */
7061
	function jetpack_icon_user_connected( $columns ) {
7062
		$columns['user_jetpack'] = '';
7063
		return $columns;
7064
	}
7065
7066
	/*
7067
	 * Show Jetpack icon if the user is linked.
7068
	 */
7069
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7070
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
7071
			$jetpack_logo = new Jetpack_Logo();
7072
			$emblem_html  = sprintf(
7073
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7074
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7075
				$jetpack_logo->get_jp_emblem()
7076
			);
7077
			return $emblem_html;
7078
		}
7079
7080
		return $val;
7081
	}
7082
7083
	/*
7084
	 * Style the Jetpack user column
7085
	 */
7086
	function jetpack_user_col_style() {
7087
		global $current_screen;
7088
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7089
			?>
7090
			<style>
7091
				.fixed .column-user_jetpack {
7092
					width: 21px;
7093
				}
7094
				.jp-emblem-user-admin svg {
7095
					width: 20px;
7096
					height: 20px;
7097
				}
7098
				.jp-emblem-user-admin path {
7099
					fill: #00BE28;
7100
				}
7101
			</style>
7102
			<?php
7103
		}
7104
	}
7105
7106
	/**
7107
	 * Checks if Akismet is active and working.
7108
	 *
7109
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7110
	 * that implied usage of methods present since more recent version.
7111
	 * See https://github.com/Automattic/jetpack/pull/9585
7112
	 *
7113
	 * @since  5.1.0
7114
	 *
7115
	 * @return bool True = Akismet available. False = Aksimet not available.
7116
	 */
7117
	public static function is_akismet_active() {
7118
		static $status = null;
7119
7120
		if ( ! is_null( $status ) ) {
7121
			return $status;
7122
		}
7123
7124
		// Check if a modern version of Akismet is active.
7125
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7126
			$status = false;
7127
			return $status;
7128
		}
7129
7130
		// Make sure there is a key known to Akismet at all before verifying key.
7131
		$akismet_key = Akismet::get_api_key();
7132
		if ( ! $akismet_key ) {
7133
			$status = false;
7134
			return $status;
7135
		}
7136
7137
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7138
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7139
7140
		// 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.
7141
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7142
		// We cache the result of the Akismet key verification for ten minutes.
7143
		if ( ! $akismet_key_state || $recheck ) {
7144
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7145
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7146
		}
7147
7148
		$status = 'valid' === $akismet_key_state;
7149
7150
		return $status;
7151
	}
7152
7153
	/**
7154
	 * @deprecated
7155
	 *
7156
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7157
	 */
7158
	public static function is_function_in_backtrace() {
7159
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7160
	}
7161
7162
	/**
7163
	 * Given a minified path, and a non-minified path, will return
7164
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7165
	 *
7166
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7167
	 * root Jetpack directory.
7168
	 *
7169
	 * @since 5.6.0
7170
	 *
7171
	 * @param string $min_path
7172
	 * @param string $non_min_path
7173
	 * @return string The URL to the file
7174
	 */
7175
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7176
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7177
	}
7178
7179
	/**
7180
	 * Checks for whether Jetpack Backup is enabled.
7181
	 * Will return true if the state of Backup is anything except "unavailable".
7182
	 *
7183
	 * @return bool|int|mixed
7184
	 */
7185
	public static function is_rewind_enabled() {
7186
		if ( ! self::is_active() ) {
7187
			return false;
7188
		}
7189
7190
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7191
		if ( false === $rewind_enabled ) {
7192
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7193
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7194
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7195
				&& ! empty( $rewind_data['state'] )
7196
				&& 'active' === $rewind_data['state'] )
7197
				? 1
7198
				: 0;
7199
7200
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7201
		}
7202
		return $rewind_enabled;
7203
	}
7204
7205
	/**
7206
	 * Return Calypso environment value; used for developing Jetpack and pairing
7207
	 * it with different Calypso enrionments, such as localhost.
7208
	 *
7209
	 * @since 7.4.0
7210
	 *
7211
	 * @return string Calypso environment
7212
	 */
7213
	public static function get_calypso_env() {
7214
		if ( isset( $_GET['calypso_env'] ) ) {
7215
			return sanitize_key( $_GET['calypso_env'] );
7216
		}
7217
7218
		if ( getenv( 'CALYPSO_ENV' ) ) {
7219
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7220
		}
7221
7222
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7223
			return sanitize_key( CALYPSO_ENV );
7224
		}
7225
7226
		return '';
7227
	}
7228
7229
	/**
7230
	 * Returns the hostname with protocol for Calypso.
7231
	 * Used for developing Jetpack with Calypso.
7232
	 *
7233
	 * @since 8.4.0
7234
	 *
7235
	 * @return string Calypso host.
7236
	 */
7237
	public static function get_calypso_host() {
7238
		$calypso_env = self::get_calypso_env();
7239
		switch ( $calypso_env ) {
7240
			case 'development':
7241
				return 'http://calypso.localhost:3000/';
7242
			case 'wpcalypso':
7243
				return 'https://wpcalypso.wordpress.com/';
7244
			case 'horizon':
7245
				return 'https://horizon.wordpress.com/';
7246
			default:
7247
				return 'https://wordpress.com/';
7248
		}
7249
	}
7250
7251
	/**
7252
	 * Checks whether or not TOS has been agreed upon.
7253
	 * Will return true if a user has clicked to register, or is already connected.
7254
	 */
7255
	public static function jetpack_tos_agreed() {
7256
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7257
7258
		$terms_of_service = new Terms_Of_Service();
7259
		return $terms_of_service->has_agreed();
7260
7261
	}
7262
7263
	/**
7264
	 * Handles activating default modules as well general cleanup for the new connection.
7265
	 *
7266
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7267
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7268
	 * @param boolean $send_state_messages          Whether to send state messages.
7269
	 * @return void
7270
	 */
7271
	public static function handle_post_authorization_actions(
7272
		$activate_sso = false,
7273
		$redirect_on_activation_error = false,
7274
		$send_state_messages = true
7275
	) {
7276
		$other_modules = $activate_sso
7277
			? array( 'sso' )
7278
			: array();
7279
7280
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7281
			self::delete_active_modules();
7282
7283
			self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
7284
		} else {
7285
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7286
		}
7287
7288
		// Since this is a fresh connection, be sure to clear out IDC options
7289
		Jetpack_IDC::clear_all_idc_options();
7290
7291
		if ( $send_state_messages ) {
7292
			self::state( 'message', 'authorized' );
7293
		}
7294
	}
7295
7296
	/**
7297
	 * Returns a boolean for whether backups UI should be displayed or not.
7298
	 *
7299
	 * @return bool Should backups UI be displayed?
7300
	 */
7301
	public static function show_backups_ui() {
7302
		/**
7303
		 * Whether UI for backups should be displayed.
7304
		 *
7305
		 * @since 6.5.0
7306
		 *
7307
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7308
		 */
7309
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7310
	}
7311
7312
	/*
7313
	 * Deprecated manage functions
7314
	 */
7315
	function prepare_manage_jetpack_notice() {
7316
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7317
	}
7318
	function manage_activate_screen() {
7319
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7320
	}
7321
	function admin_jetpack_manage_notice() {
7322
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7323
	}
7324
	function opt_out_jetpack_manage_url() {
7325
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7326
	}
7327
	function opt_in_jetpack_manage_url() {
7328
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7329
	}
7330
	function opt_in_jetpack_manage_notice() {
7331
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7332
	}
7333
	function can_display_jetpack_manage_notice() {
7334
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7335
	}
7336
7337
	/**
7338
	 * Clean leftoveruser meta.
7339
	 *
7340
	 * Delete Jetpack-related user meta when it is no longer needed.
7341
	 *
7342
	 * @since 7.3.0
7343
	 *
7344
	 * @param int $user_id User ID being updated.
7345
	 */
7346
	public static function user_meta_cleanup( $user_id ) {
7347
		$meta_keys = array(
7348
			// AtD removed from Jetpack 7.3
7349
			'AtD_options',
7350
			'AtD_check_when',
7351
			'AtD_guess_lang',
7352
			'AtD_ignored_phrases',
7353
		);
7354
7355
		foreach ( $meta_keys as $meta_key ) {
7356
			if ( get_user_meta( $user_id, $meta_key ) ) {
7357
				delete_user_meta( $user_id, $meta_key );
7358
			}
7359
		}
7360
	}
7361
7362
	/**
7363
	 * Checks if a Jetpack site is both active and not in development.
7364
	 *
7365
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7366
	 *
7367
	 * @return bool True if Jetpack is active and not in development.
7368
	 */
7369
	public static function is_active_and_not_development_mode() {
7370
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7371
			return false;
7372
		}
7373
		return true;
7374
	}
7375
7376
	/**
7377
	 * Returns the list of products that we have available for purchase.
7378
	 */
7379
	public static function get_products_for_purchase() {
7380
		$products = array();
7381
		if ( ! is_multisite() ) {
7382
			$products[] = array(
7383
				'key'               => 'backup',
7384
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7385
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7386
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7387
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7388
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7389
				'options'           => array(
7390
					array(
7391
						'type'        => 'daily',
7392
						'slug'        => 'jetpack-backup-daily',
7393
						'key'         => 'jetpack_backup_daily',
7394
						'name'        => __( 'Daily Backups', 'jetpack' ),
7395
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7396
					),
7397
					array(
7398
						'type'        => 'realtime',
7399
						'slug'        => 'jetpack-backup-realtime',
7400
						'key'         => 'jetpack_backup_realtime',
7401
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7402
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7403
					),
7404
				),
7405
				'default_option'    => 'realtime',
7406
				'show_promotion'    => true,
7407
				'discount_percent'  => 70,
7408
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7409
			);
7410
7411
			$products[] = array(
7412
				'key'               => 'scan',
7413
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7414
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7415
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7416
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7417
				'show_promotion'    => true,
7418
				'discount_percent'  => 30,
7419
				'options'           => array(
7420
					array(
7421
						'type'      => 'scan',
7422
						'slug'      => 'jetpack-scan',
7423
						'key'       => 'jetpack_scan',
7424
						'name'      => __( 'Daily Scan', 'jetpack' ),
7425
					),
7426
				),
7427
				'default_option'    => 'scan',
7428
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7429
			);
7430
		}
7431
7432
		$products[] = array(
7433
			'key'               => 'search',
7434
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7435
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7436
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7437
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7438
			'label_popup'  		=> __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.' ),
7439
			'options'           => array(
7440
				array(
7441
					'type'      => 'search',
7442
					'slug'      => 'jetpack-search',
7443
					'key'       => 'jetpack_search',
7444
					'name'      => __( 'Search', 'jetpack' ),
7445
				),
7446
			),
7447
			'tears'             => array(),
7448
			'default_option'    => 'search',
7449
			'show_promotion'    => false,
7450
			'included_in_plans' => array( 'search-plan' ),
7451
		);
7452
7453
		return $products;
7454
	}
7455
}
7456