Completed
Push — add/plan-radio-button ( 8fbc2b...bc5e3f )
by
unknown
75:28 queued 69:08
created

class.jetpack.php (1 issue)

Upgrade to new PHP Analysis Engine

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

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

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
5043
	 * @param Integer $exp     Expiration time in seconds.
5044
	 * @return array
5045
	 */
5046
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5047
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5048
	}
5049
5050
	public static function get_secrets( $action, $user_id ) {
5051
		$secrets = self::connection()->get_secrets( $action, $user_id );
5052
5053
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5054
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
5055
		}
5056
5057
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5058
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
5059
		}
5060
5061
		return $secrets;
5062
	}
5063
5064
	/**
5065
	 * @deprecated 7.5 Use Connection_Manager instead.
5066
	 *
5067
	 * @param $action
5068
	 * @param $user_id
5069
	 */
5070
	public static function delete_secrets( $action, $user_id ) {
5071
		return self::connection()->delete_secrets( $action, $user_id );
5072
	}
5073
5074
	/**
5075
	 * Builds the timeout limit for queries talking with the wpcom servers.
5076
	 *
5077
	 * Based on local php max_execution_time in php.ini
5078
	 *
5079
	 * @since 2.6
5080
	 * @return int
5081
	 * @deprecated
5082
	 **/
5083
	public function get_remote_query_timeout_limit() {
5084
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5085
		return self::get_max_execution_time();
5086
	}
5087
5088
	/**
5089
	 * Builds the timeout limit for queries talking with the wpcom servers.
5090
	 *
5091
	 * Based on local php max_execution_time in php.ini
5092
	 *
5093
	 * @since 5.4
5094
	 * @return int
5095
	 **/
5096
	public static function get_max_execution_time() {
5097
		$timeout = (int) ini_get( 'max_execution_time' );
5098
5099
		// Ensure exec time set in php.ini
5100
		if ( ! $timeout ) {
5101
			$timeout = 30;
5102
		}
5103
		return $timeout;
5104
	}
5105
5106
	/**
5107
	 * Sets a minimum request timeout, and returns the current timeout
5108
	 *
5109
	 * @since 5.4
5110
	 **/
5111 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5112
		$timeout = self::get_max_execution_time();
5113
		if ( $timeout < $min_timeout ) {
5114
			$timeout = $min_timeout;
5115
			set_time_limit( $timeout );
5116
		}
5117
		return $timeout;
5118
	}
5119
5120
	/**
5121
	 * Takes the response from the Jetpack register new site endpoint and
5122
	 * verifies it worked properly.
5123
	 *
5124
	 * @since 2.6
5125
	 * @deprecated since 7.7.0
5126
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5127
	 **/
5128
	public function validate_remote_register_response() {
5129
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5130
	}
5131
5132
	/**
5133
	 * @return bool|WP_Error
5134
	 */
5135
	public static function register() {
5136
		$tracking = new Tracking();
5137
		$tracking->record_user_event( 'jpc_register_begin' );
5138
5139
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5140
5141
		$connection   = self::connection();
5142
		$registration = $connection->register();
5143
5144
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5145
5146
		if ( ! $registration || is_wp_error( $registration ) ) {
5147
			return $registration;
5148
		}
5149
5150
		return true;
5151
	}
5152
5153
	/**
5154
	 * Filters the registration request body to include tracking properties.
5155
	 *
5156
	 * @param Array $properties
5157
	 * @return Array amended properties.
5158
	 */
5159
	public static function filter_register_request_body( $properties ) {
5160
		$tracking        = new Tracking();
5161
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5162
5163
		return array_merge(
5164
			$properties,
5165
			array(
5166
				'_ui' => $tracks_identity['_ui'],
5167
				'_ut' => $tracks_identity['_ut'],
5168
			)
5169
		);
5170
	}
5171
5172
	/**
5173
	 * If the db version is showing something other that what we've got now, bump it to current.
5174
	 *
5175
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5176
	 */
5177
	public static function maybe_set_version_option() {
5178
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5179
		if ( JETPACK__VERSION != $version ) {
5180
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5181
5182
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5183
				/** This action is documented in class.jetpack.php */
5184
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5185
			}
5186
5187
			return true;
5188
		}
5189
		return false;
5190
	}
5191
5192
	/* Client Server API */
5193
5194
	/**
5195
	 * Loads the Jetpack XML-RPC client.
5196
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5197
	 *
5198
	 * @deprecated since 7.7.0
5199
	 */
5200
	public static function load_xml_rpc_client() {
5201
		// Removed the php notice that shows up in order to give time to Akismet and VaultPress time to update.
5202
		// _deprecated_function( __METHOD__, 'jetpack-7.7' );
5203
	}
5204
5205
	/**
5206
	 * Resets the saved authentication state in between testing requests.
5207
	 */
5208
	public function reset_saved_auth_state() {
5209
		$this->rest_authentication_status = null;
5210
		$this->connection_manager->reset_saved_auth_state();
5211
	}
5212
5213
	/**
5214
	 * Verifies the signature of the current request.
5215
	 *
5216
	 * @deprecated since 7.7.0
5217
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5218
	 *
5219
	 * @return false|array
5220
	 */
5221
	public function verify_xml_rpc_signature() {
5222
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5223
		return self::connection()->verify_xml_rpc_signature();
5224
	}
5225
5226
	/**
5227
	 * Verifies the signature of the current request.
5228
	 *
5229
	 * This function has side effects and should not be used. Instead,
5230
	 * use the memoized version `->verify_xml_rpc_signature()`.
5231
	 *
5232
	 * @deprecated since 7.7.0
5233
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5234
	 * @internal
5235
	 */
5236
	private function internal_verify_xml_rpc_signature() {
5237
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5238
	}
5239
5240
	/**
5241
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5242
	 *
5243
	 * @deprecated since 7.7.0
5244
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5245
	 *
5246
	 * @param \WP_User|mixed $user     User object if authenticated.
5247
	 * @param string         $username Username.
5248
	 * @param string         $password Password string.
5249
	 * @return \WP_User|mixed Authenticated user or error.
5250
	 */
5251
	public function authenticate_jetpack( $user, $username, $password ) {
5252
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5253
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5254
	}
5255
5256
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5257
	// Uses the existing XMLRPC request signing implementation.
5258
	function wp_rest_authenticate( $user ) {
5259
		if ( ! empty( $user ) ) {
5260
			// Another authentication method is in effect.
5261
			return $user;
5262
		}
5263
5264
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5265
			// Nothing to do for this authentication method.
5266
			return null;
5267
		}
5268
5269
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5270
			// Nothing to do for this authentication method.
5271
			return null;
5272
		}
5273
5274
		// Ensure that we always have the request body available.  At this
5275
		// point, the WP REST API code to determine the request body has not
5276
		// run yet.  That code may try to read from 'php://input' later, but
5277
		// this can only be done once per request in PHP versions prior to 5.6.
5278
		// So we will go ahead and perform this read now if needed, and save
5279
		// the request body where both the Jetpack signature verification code
5280
		// and the WP REST API code can see it.
5281
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5282
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5283
		}
5284
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5285
5286
		// Only support specific request parameters that have been tested and
5287
		// are known to work with signature verification.  A different method
5288
		// can be passed to the WP REST API via the '?_method=' parameter if
5289
		// needed.
5290
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5291
			$this->rest_authentication_status = new WP_Error(
5292
				'rest_invalid_request',
5293
				__( 'This request method is not supported.', 'jetpack' ),
5294
				array( 'status' => 400 )
5295
			);
5296
			return null;
5297
		}
5298
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5299
			$this->rest_authentication_status = new WP_Error(
5300
				'rest_invalid_request',
5301
				__( 'This request method does not support body parameters.', 'jetpack' ),
5302
				array( 'status' => 400 )
5303
			);
5304
			return null;
5305
		}
5306
5307
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5308
5309
		if (
5310
			$verified &&
5311
			isset( $verified['type'] ) &&
5312
			'user' === $verified['type'] &&
5313
			! empty( $verified['user_id'] )
5314
		) {
5315
			// Authentication successful.
5316
			$this->rest_authentication_status = true;
5317
			return $verified['user_id'];
5318
		}
5319
5320
		// Something else went wrong.  Probably a signature error.
5321
		$this->rest_authentication_status = new WP_Error(
5322
			'rest_invalid_signature',
5323
			__( 'The request is not signed correctly.', 'jetpack' ),
5324
			array( 'status' => 400 )
5325
		);
5326
		return null;
5327
	}
5328
5329
	/**
5330
	 * Report authentication status to the WP REST API.
5331
	 *
5332
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5333
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5334
	 */
5335
	public function wp_rest_authentication_errors( $value ) {
5336
		if ( $value !== null ) {
5337
			return $value;
5338
		}
5339
		return $this->rest_authentication_status;
5340
	}
5341
5342
	/**
5343
	 * Add our nonce to this request.
5344
	 *
5345
	 * @deprecated since 7.7.0
5346
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5347
	 *
5348
	 * @param int    $timestamp Timestamp of the request.
5349
	 * @param string $nonce     Nonce string.
5350
	 */
5351
	public function add_nonce( $timestamp, $nonce ) {
5352
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5353
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5354
	}
5355
5356
	/**
5357
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5358
	 * Capture it here so we can verify the signature later.
5359
	 *
5360
	 * @deprecated since 7.7.0
5361
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5362
	 *
5363
	 * @param array $methods XMLRPC methods.
5364
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5365
	 */
5366
	public function xmlrpc_methods( $methods ) {
5367
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5368
		return $this->connection_manager->xmlrpc_methods( $methods );
5369
	}
5370
5371
	/**
5372
	 * Register additional public XMLRPC methods.
5373
	 *
5374
	 * @deprecated since 7.7.0
5375
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5376
	 *
5377
	 * @param array $methods Public XMLRPC methods.
5378
	 * @return array Public XMLRPC methods, with the getOptions one.
5379
	 */
5380
	public function public_xmlrpc_methods( $methods ) {
5381
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5382
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5383
	}
5384
5385
	/**
5386
	 * Handles a getOptions XMLRPC method call.
5387
	 *
5388
	 * @deprecated since 7.7.0
5389
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5390
	 *
5391
	 * @param array $args method call arguments.
5392
	 * @return array an amended XMLRPC server options array.
5393
	 */
5394
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5395
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5396
		return $this->connection_manager->jetpack_getOptions( $args );
5397
	}
5398
5399
	/**
5400
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5401
	 *
5402
	 * @deprecated since 7.7.0
5403
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5404
	 *
5405
	 * @param array $options Standard Core options.
5406
	 * @return array Amended options.
5407
	 */
5408
	public function xmlrpc_options( $options ) {
5409
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5410
		return $this->connection_manager->xmlrpc_options( $options );
5411
	}
5412
5413
	/**
5414
	 * Cleans nonces that were saved when calling ::add_nonce.
5415
	 *
5416
	 * @deprecated since 7.7.0
5417
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5418
	 *
5419
	 * @param bool $all whether to clean even non-expired nonces.
5420
	 */
5421
	public static function clean_nonces( $all = false ) {
5422
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5423
		return self::connection()->clean_nonces( $all );
5424
	}
5425
5426
	/**
5427
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5428
	 * SET: state( $key, $value );
5429
	 * GET: $value = state( $key );
5430
	 *
5431
	 * @param string $key
5432
	 * @param string $value
5433
	 * @param bool   $restate private
5434
	 */
5435
	public static function state( $key = null, $value = null, $restate = false ) {
5436
		static $state = array();
5437
		static $path, $domain;
5438
		if ( ! isset( $path ) ) {
5439
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5440
			$admin_url = self::admin_url();
5441
			$bits      = wp_parse_url( $admin_url );
5442
5443
			if ( is_array( $bits ) ) {
5444
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5445
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5446
			} else {
5447
				$path = $domain = null;
5448
			}
5449
		}
5450
5451
		// Extract state from cookies and delete cookies
5452
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5453
			$yum = $_COOKIE['jetpackState'];
5454
			unset( $_COOKIE['jetpackState'] );
5455
			foreach ( $yum as $k => $v ) {
5456
				if ( strlen( $v ) ) {
5457
					$state[ $k ] = $v;
5458
				}
5459
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5460
			}
5461
		}
5462
5463
		if ( $restate ) {
5464
			foreach ( $state as $k => $v ) {
5465
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5466
			}
5467
			return;
5468
		}
5469
5470
		// Get a state variable
5471
		if ( isset( $key ) && ! isset( $value ) ) {
5472
			if ( array_key_exists( $key, $state ) ) {
5473
				return $state[ $key ];
5474
			}
5475
			return null;
5476
		}
5477
5478
		// Set a state variable
5479
		if ( isset( $key ) && isset( $value ) ) {
5480
			if ( is_array( $value ) && isset( $value[0] ) ) {
5481
				$value = $value[0];
5482
			}
5483
			$state[ $key ] = $value;
5484
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5485
		}
5486
	}
5487
5488
	public static function restate() {
5489
		self::state( null, null, true );
5490
	}
5491
5492
	public static function check_privacy( $file ) {
5493
		static $is_site_publicly_accessible = null;
5494
5495
		if ( is_null( $is_site_publicly_accessible ) ) {
5496
			$is_site_publicly_accessible = false;
5497
5498
			$rpc = new Jetpack_IXR_Client();
5499
5500
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5501
			if ( $success ) {
5502
				$response = $rpc->getResponse();
5503
				if ( $response ) {
5504
					$is_site_publicly_accessible = true;
5505
				}
5506
			}
5507
5508
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5509
		}
5510
5511
		if ( $is_site_publicly_accessible ) {
5512
			return;
5513
		}
5514
5515
		$module_slug = self::get_module_slug( $file );
5516
5517
		$privacy_checks = self::state( 'privacy_checks' );
5518
		if ( ! $privacy_checks ) {
5519
			$privacy_checks = $module_slug;
5520
		} else {
5521
			$privacy_checks .= ",$module_slug";
5522
		}
5523
5524
		self::state( 'privacy_checks', $privacy_checks );
5525
	}
5526
5527
	/**
5528
	 * Helper method for multicall XMLRPC.
5529
	 *
5530
	 * @param ...$args Args for the async_call.
5531
	 */
5532
	public static function xmlrpc_async_call( ...$args ) {
5533
		global $blog_id;
5534
		static $clients = array();
5535
5536
		$client_blog_id = is_multisite() ? $blog_id : 0;
5537
5538
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5539
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5540
			if ( function_exists( 'ignore_user_abort' ) ) {
5541
				ignore_user_abort( true );
5542
			}
5543
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5544
		}
5545
5546
		if ( ! empty( $args[0] ) ) {
5547
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5548
		} elseif ( is_multisite() ) {
5549
			foreach ( $clients as $client_blog_id => $client ) {
5550
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5551
					continue;
5552
				}
5553
5554
				$switch_success = switch_to_blog( $client_blog_id, true );
5555
				if ( ! $switch_success ) {
5556
					continue;
5557
				}
5558
5559
				flush();
5560
				$client->query();
5561
5562
				restore_current_blog();
5563
			}
5564
		} else {
5565
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5566
				flush();
5567
				$clients[0]->query();
5568
			}
5569
		}
5570
	}
5571
5572
	public static function staticize_subdomain( $url ) {
5573
5574
		// Extract hostname from URL
5575
		$host = wp_parse_url( $url, PHP_URL_HOST );
5576
5577
		// Explode hostname on '.'
5578
		$exploded_host = explode( '.', $host );
5579
5580
		// Retrieve the name and TLD
5581
		if ( count( $exploded_host ) > 1 ) {
5582
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5583
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5584
			// Rebuild domain excluding subdomains
5585
			$domain = $name . '.' . $tld;
5586
		} else {
5587
			$domain = $host;
5588
		}
5589
		// Array of Automattic domains
5590
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5591
5592
		// Return $url if not an Automattic domain
5593
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5594
			return $url;
5595
		}
5596
5597
		if ( is_ssl() ) {
5598
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5599
		}
5600
5601
		srand( crc32( basename( $url ) ) );
5602
		$static_counter = rand( 0, 2 );
5603
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5604
5605
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5606
	}
5607
5608
	/* JSON API Authorization */
5609
5610
	/**
5611
	 * Handles the login action for Authorizing the JSON API
5612
	 */
5613
	function login_form_json_api_authorization() {
5614
		$this->verify_json_api_authorization_request();
5615
5616
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5617
5618
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5619
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5620
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5621
	}
5622
5623
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5624
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5625
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5626
			return $url;
5627
		}
5628
5629
		$parsed_url = wp_parse_url( $url );
5630
		$url        = strtok( $url, '?' );
5631
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5632
		if ( ! empty( $parsed_url['query'] ) ) {
5633
			$url .= "&{$parsed_url['query']}";
5634
		}
5635
5636
		return $url;
5637
	}
5638
5639
	// Make sure the POSTed request is handled by the same action
5640
	function preserve_action_in_login_form_for_json_api_authorization() {
5641
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5642
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5643
	}
5644
5645
	// If someone logs in to approve API access, store the Access Code in usermeta
5646
	function store_json_api_authorization_token( $user_login, $user ) {
5647
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5648
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5649
		$token = wp_generate_password( 32, false );
5650
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5651
	}
5652
5653
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5654
	function allow_wpcom_public_api_domain( $domains ) {
5655
		$domains[] = 'public-api.wordpress.com';
5656
		return $domains;
5657
	}
5658
5659
	static function is_redirect_encoded( $redirect_url ) {
5660
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5661
	}
5662
5663
	// Add all wordpress.com environments to the safe redirect whitelist
5664
	function allow_wpcom_environments( $domains ) {
5665
		$domains[] = 'wordpress.com';
5666
		$domains[] = 'wpcalypso.wordpress.com';
5667
		$domains[] = 'horizon.wordpress.com';
5668
		$domains[] = 'calypso.localhost';
5669
		return $domains;
5670
	}
5671
5672
	// Add the Access Code details to the public-api.wordpress.com redirect
5673
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5674
		return add_query_arg(
5675
			urlencode_deep(
5676
				array(
5677
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5678
					'jetpack-user-id' => (int) $user->ID,
5679
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5680
				)
5681
			),
5682
			$redirect_to
5683
		);
5684
	}
5685
5686
5687
	/**
5688
	 * Verifies the request by checking the signature
5689
	 *
5690
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5691
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5692
	 *
5693
	 * @param null|array $environment
5694
	 */
5695
	function verify_json_api_authorization_request( $environment = null ) {
5696
		$environment = is_null( $environment )
5697
			? $_REQUEST
5698
			: $environment;
5699
5700
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
5701
		$token                                     = Jetpack_Data::get_access_token( $envUserId, $envToken );
5702
		if ( ! $token || empty( $token->secret ) ) {
5703
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5704
		}
5705
5706
		$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' );
5707
5708
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5709
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5710
			/**
5711
			 * Jetpack authorisation request Error.
5712
			 *
5713
			 * @since 7.5.0
5714
			 */
5715
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5716
			$die_error = sprintf(
5717
				/* translators: %s is a URL */
5718
				__( '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' ),
5719
				'https://jetpack.com/support/double-encoding/'
5720
			);
5721
		}
5722
5723
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5724
5725
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5726
			$signature = $jetpack_signature->sign_request(
5727
				$environment['token'],
5728
				$environment['timestamp'],
5729
				$environment['nonce'],
5730
				'',
5731
				'GET',
5732
				$environment['jetpack_json_api_original_query'],
5733
				null,
5734
				true
5735
			);
5736
		} else {
5737
			$signature = $jetpack_signature->sign_current_request(
5738
				array(
5739
					'body'   => null,
5740
					'method' => 'GET',
5741
				)
5742
			);
5743
		}
5744
5745
		if ( ! $signature ) {
5746
			wp_die( $die_error );
5747
		} elseif ( is_wp_error( $signature ) ) {
5748
			wp_die( $die_error );
5749
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5750
			if ( is_ssl() ) {
5751
				// 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
5752
				$signature = $jetpack_signature->sign_current_request(
5753
					array(
5754
						'scheme' => 'http',
5755
						'body'   => null,
5756
						'method' => 'GET',
5757
					)
5758
				);
5759
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5760
					wp_die( $die_error );
5761
				}
5762
			} else {
5763
				wp_die( $die_error );
5764
			}
5765
		}
5766
5767
		$timestamp = (int) $environment['timestamp'];
5768
		$nonce     = stripslashes( (string) $environment['nonce'] );
5769
5770
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
5771
			// De-nonce the nonce, at least for 5 minutes.
5772
			// 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)
5773
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5774
			if ( $old_nonce_time < time() - 300 ) {
5775
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
5776
			}
5777
		}
5778
5779
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5780
		$data_filters = array(
5781
			'state'        => 'opaque',
5782
			'client_id'    => 'int',
5783
			'client_title' => 'string',
5784
			'client_image' => 'url',
5785
		);
5786
5787
		foreach ( $data_filters as $key => $sanitation ) {
5788
			if ( ! isset( $data->$key ) ) {
5789
				wp_die( $die_error );
5790
			}
5791
5792
			switch ( $sanitation ) {
5793
				case 'int':
5794
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
5795
					break;
5796
				case 'opaque':
5797
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
5798
					break;
5799
				case 'string':
5800
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
5801
					break;
5802
				case 'url':
5803
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
5804
					break;
5805
			}
5806
		}
5807
5808
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5809
			wp_die( $die_error );
5810
		}
5811
	}
5812
5813
	function login_message_json_api_authorization( $message ) {
5814
		return '<p class="message">' . sprintf(
5815
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
5816
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5817
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5818
	}
5819
5820
	/**
5821
	 * Get $content_width, but with a <s>twist</s> filter.
5822
	 */
5823
	public static function get_content_width() {
5824
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5825
			? $GLOBALS['content_width']
5826
			: false;
5827
		/**
5828
		 * Filter the Content Width value.
5829
		 *
5830
		 * @since 2.2.3
5831
		 *
5832
		 * @param string $content_width Content Width value.
5833
		 */
5834
		return apply_filters( 'jetpack_content_width', $content_width );
5835
	}
5836
5837
	/**
5838
	 * Pings the WordPress.com Mirror Site for the specified options.
5839
	 *
5840
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5841
	 *
5842
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5843
	 */
5844
	public function get_cloud_site_options( $option_names ) {
5845
		$option_names = array_filter( (array) $option_names, 'is_string' );
5846
5847
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
5848
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5849
		if ( $xml->isError() ) {
5850
			return array(
5851
				'error_code' => $xml->getErrorCode(),
5852
				'error_msg'  => $xml->getErrorMessage(),
5853
			);
5854
		}
5855
		$cloud_site_options = $xml->getResponse();
5856
5857
		return $cloud_site_options;
5858
	}
5859
5860
	/**
5861
	 * Checks if the site is currently in an identity crisis.
5862
	 *
5863
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5864
	 */
5865
	public static function check_identity_crisis() {
5866
		if ( ! self::is_active() || ( new Status() )->is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5867
			return false;
5868
		}
5869
5870
		return Jetpack_Options::get_option( 'sync_error_idc' );
5871
	}
5872
5873
	/**
5874
	 * Checks whether the home and siteurl specifically are whitelisted
5875
	 * Written so that we don't have re-check $key and $value params every time
5876
	 * we want to check if this site is whitelisted, for example in footer.php
5877
	 *
5878
	 * @since  3.8.0
5879
	 * @return bool True = already whitelisted False = not whitelisted
5880
	 */
5881
	public static function is_staging_site() {
5882
		$is_staging = false;
5883
5884
		$known_staging = array(
5885
			'urls'      => array(
5886
				'#\.staging\.wpengine\.com$#i', // WP Engine
5887
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5888
				'#\.stage\.site$#i',            // DreamPress
5889
			),
5890
			'constants' => array(
5891
				'IS_WPE_SNAPSHOT',      // WP Engine
5892
				'KINSTA_DEV_ENV',       // Kinsta.com
5893
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5894
				'JETPACK_STAGING_MODE', // Generic
5895
			),
5896
		);
5897
		/**
5898
		 * Filters the flags of known staging sites.
5899
		 *
5900
		 * @since 3.9.0
5901
		 *
5902
		 * @param array $known_staging {
5903
		 *     An array of arrays that each are used to check if the current site is staging.
5904
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5905
		 *     @type array $constants PHP constants of known staging/developement environments.
5906
		 *  }
5907
		 */
5908
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5909
5910
		if ( isset( $known_staging['urls'] ) ) {
5911
			foreach ( $known_staging['urls'] as $url ) {
5912
				if ( preg_match( $url, site_url() ) ) {
5913
					$is_staging = true;
5914
					break;
5915
				}
5916
			}
5917
		}
5918
5919
		if ( isset( $known_staging['constants'] ) ) {
5920
			foreach ( $known_staging['constants'] as $constant ) {
5921
				if ( defined( $constant ) && constant( $constant ) ) {
5922
					$is_staging = true;
5923
				}
5924
			}
5925
		}
5926
5927
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5928
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5929
			$is_staging = true;
5930
		}
5931
5932
		/**
5933
		 * Filters is_staging_site check.
5934
		 *
5935
		 * @since 3.9.0
5936
		 *
5937
		 * @param bool $is_staging If the current site is a staging site.
5938
		 */
5939
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5940
	}
5941
5942
	/**
5943
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5944
	 *
5945
	 * @since 4.4.0
5946
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
5947
	 *
5948
	 * @return bool
5949
	 */
5950
	public static function validate_sync_error_idc_option() {
5951
		$is_valid = false;
5952
5953
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5954
		if ( false === $idc_allowed ) {
5955
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5956
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5957
				$json               = json_decode( wp_remote_retrieve_body( $response ) );
5958
				$idc_allowed        = isset( $json, $json->result ) && $json->result ? '1' : '0';
5959
				$transient_duration = HOUR_IN_SECONDS;
5960
			} else {
5961
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5962
				$idc_allowed        = '1';
5963
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5964
			}
5965
5966
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5967
		}
5968
5969
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5970
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5971
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5972
			$local_options = self::get_sync_error_idc_option();
5973
			// Ensure all values are set.
5974
			if ( isset( $sync_error['home'] ) && isset ( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
5975
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5976
					$is_valid = true;
5977
				}
5978
			}
5979
5980
		}
5981
5982
		/**
5983
		 * Filters whether the sync_error_idc option is valid.
5984
		 *
5985
		 * @since 4.4.0
5986
		 *
5987
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5988
		 */
5989
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5990
5991
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5992
			// Since the option exists, and did not validate, delete it
5993
			Jetpack_Options::delete_option( 'sync_error_idc' );
5994
		}
5995
5996
		return $is_valid;
5997
	}
5998
5999
	/**
6000
	 * Normalizes a url by doing three things:
6001
	 *  - Strips protocol
6002
	 *  - Strips www
6003
	 *  - Adds a trailing slash
6004
	 *
6005
	 * @since 4.4.0
6006
	 * @param string $url
6007
	 * @return WP_Error|string
6008
	 */
6009
	public static function normalize_url_protocol_agnostic( $url ) {
6010
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6011
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6012
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6013
		}
6014
6015
		// Strip www and protocols
6016
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6017
		return $url;
6018
	}
6019
6020
	/**
6021
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6022
	 *
6023
	 * @since 4.4.0
6024
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6025
	 *
6026
	 * @param array $response
6027
	 * @return array Array of the local urls, wpcom urls, and error code
6028
	 */
6029
	public static function get_sync_error_idc_option( $response = array() ) {
6030
		// Since the local options will hit the database directly, store the values
6031
		// in a transient to allow for autoloading and caching on subsequent views.
6032
		$local_options = get_transient( 'jetpack_idc_local' );
6033
		if ( false === $local_options ) {
6034
			$local_options = array(
6035
				'home'    => Functions::home_url(),
6036
				'siteurl' => Functions::site_url(),
6037
			);
6038
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6039
		}
6040
6041
		$options = array_merge( $local_options, $response );
6042
6043
		$returned_values = array();
6044
		foreach ( $options as $key => $option ) {
6045
			if ( 'error_code' === $key ) {
6046
				$returned_values[ $key ] = $option;
6047
				continue;
6048
			}
6049
6050
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6051
				continue;
6052
			}
6053
6054
			$returned_values[ $key ] = $normalized_url;
6055
		}
6056
6057
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6058
6059
		return $returned_values;
6060
	}
6061
6062
	/**
6063
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6064
	 * If set to true, the site will be put into staging mode.
6065
	 *
6066
	 * @since 4.3.2
6067
	 * @return bool
6068
	 */
6069
	public static function sync_idc_optin() {
6070
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6071
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6072
		} else {
6073
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6074
		}
6075
6076
		/**
6077
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6078
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6079
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6080
		 *
6081
		 * @since 4.3.2
6082
		 *
6083
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6084
		 */
6085
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6086
	}
6087
6088
	/**
6089
	 * Maybe Use a .min.css stylesheet, maybe not.
6090
	 *
6091
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6092
	 */
6093
	public static function maybe_min_asset( $url, $path, $plugin ) {
6094
		// Short out on things trying to find actual paths.
6095
		if ( ! $path || empty( $plugin ) ) {
6096
			return $url;
6097
		}
6098
6099
		$path = ltrim( $path, '/' );
6100
6101
		// Strip out the abspath.
6102
		$base = dirname( plugin_basename( $plugin ) );
6103
6104
		// Short out on non-Jetpack assets.
6105
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6106
			return $url;
6107
		}
6108
6109
		// File name parsing.
6110
		$file              = "{$base}/{$path}";
6111
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6112
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6113
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6114
		$extension         = array_shift( $file_name_parts_r );
6115
6116
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6117
			// Already pointing at the minified version.
6118
			if ( 'min' === $file_name_parts_r[0] ) {
6119
				return $url;
6120
			}
6121
6122
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6123
			if ( file_exists( $min_full_path ) ) {
6124
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6125
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6126
				if ( 'css' === $extension ) {
6127
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6128
					self::$min_assets[ $key ] = $path;
6129
				}
6130
			}
6131
		}
6132
6133
		return $url;
6134
	}
6135
6136
	/**
6137
	 * If the asset is minified, let's flag .min as the suffix.
6138
	 *
6139
	 * Attached to `style_loader_src` filter.
6140
	 *
6141
	 * @param string $tag The tag that would link to the external asset.
6142
	 * @param string $handle The registered handle of the script in question.
6143
	 * @param string $href The url of the asset in question.
6144
	 */
6145
	public static function set_suffix_on_min( $src, $handle ) {
6146
		if ( false === strpos( $src, '.min.css' ) ) {
6147
			return $src;
6148
		}
6149
6150
		if ( ! empty( self::$min_assets ) ) {
6151
			foreach ( self::$min_assets as $file => $path ) {
6152
				if ( false !== strpos( $src, $file ) ) {
6153
					wp_style_add_data( $handle, 'suffix', '.min' );
6154
					return $src;
6155
				}
6156
			}
6157
		}
6158
6159
		return $src;
6160
	}
6161
6162
	/**
6163
	 * Maybe inlines a stylesheet.
6164
	 *
6165
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6166
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6167
	 *
6168
	 * Attached to `style_loader_tag` filter.
6169
	 *
6170
	 * @param string $tag The tag that would link to the external asset.
6171
	 * @param string $handle The registered handle of the script in question.
6172
	 *
6173
	 * @return string
6174
	 */
6175
	public static function maybe_inline_style( $tag, $handle ) {
6176
		global $wp_styles;
6177
		$item = $wp_styles->registered[ $handle ];
6178
6179
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6180
			return $tag;
6181
		}
6182
6183
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6184
			$href = $matches[1];
6185
			// Strip off query string
6186
			if ( $pos = strpos( $href, '?' ) ) {
6187
				$href = substr( $href, 0, $pos );
6188
			}
6189
			// Strip off fragment
6190
			if ( $pos = strpos( $href, '#' ) ) {
6191
				$href = substr( $href, 0, $pos );
6192
			}
6193
		} else {
6194
			return $tag;
6195
		}
6196
6197
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6198
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6199
			return $tag;
6200
		}
6201
6202
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6203
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6204
			// And this isn't the pass that actually deals with the RTL version...
6205
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6206
				// Short out, as the RTL version will deal with it in a moment.
6207
				return $tag;
6208
			}
6209
		}
6210
6211
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6212
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6213
		if ( $css ) {
6214
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6215
			if ( empty( $item->extra['after'] ) ) {
6216
				wp_add_inline_style( $handle, $css );
6217
			} else {
6218
				array_unshift( $item->extra['after'], $css );
6219
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6220
			}
6221
		}
6222
6223
		return $tag;
6224
	}
6225
6226
	/**
6227
	 * Loads a view file from the views
6228
	 *
6229
	 * Data passed in with the $data parameter will be available in the
6230
	 * template file as $data['value']
6231
	 *
6232
	 * @param string $template - Template file to load
6233
	 * @param array  $data - Any data to pass along to the template
6234
	 * @return boolean - If template file was found
6235
	 **/
6236
	public function load_view( $template, $data = array() ) {
6237
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6238
6239
		if ( file_exists( $views_dir . $template ) ) {
6240
			require_once $views_dir . $template;
6241
			return true;
6242
		}
6243
6244
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6245
		return false;
6246
	}
6247
6248
	/**
6249
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6250
	 */
6251
	public function deprecated_hooks() {
6252
		global $wp_filter;
6253
6254
		/*
6255
		 * Format:
6256
		 * deprecated_filter_name => replacement_name
6257
		 *
6258
		 * If there is no replacement, use null for replacement_name
6259
		 */
6260
		$deprecated_list = array(
6261
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6262
			'wpl_sharing_2014_1'                           => null,
6263
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6264
			'jetpack_identity_crisis_options_to_check'     => null,
6265
			'update_option_jetpack_single_user_site'       => null,
6266
			'audio_player_default_colors'                  => null,
6267
			'add_option_jetpack_featured_images_enabled'   => null,
6268
			'add_option_jetpack_update_details'            => null,
6269
			'add_option_jetpack_updates'                   => null,
6270
			'add_option_jetpack_network_name'              => null,
6271
			'add_option_jetpack_network_allow_new_registrations' => null,
6272
			'add_option_jetpack_network_add_new_users'     => null,
6273
			'add_option_jetpack_network_site_upload_space' => null,
6274
			'add_option_jetpack_network_upload_file_types' => null,
6275
			'add_option_jetpack_network_enable_administration_menus' => null,
6276
			'add_option_jetpack_is_multi_site'             => null,
6277
			'add_option_jetpack_is_main_network'           => null,
6278
			'add_option_jetpack_main_network_site'         => null,
6279
			'jetpack_sync_all_registered_options'          => null,
6280
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6281
			'jetpack_is_post_mailable'                     => null,
6282
			'jetpack_seo_site_host'                        => null,
6283
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6284
			'jetpack_holiday_snow_option_name'             => null,
6285
			'jetpack_holiday_chance_of_snow'               => null,
6286
			'jetpack_holiday_snow_js_url'                  => null,
6287
			'jetpack_is_holiday_snow_season'               => null,
6288
			'jetpack_holiday_snow_option_updated'          => null,
6289
			'jetpack_holiday_snowing'                      => null,
6290
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6291
			'jetpack_cache_plans'                          => null,
6292
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6293
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6294
			'jetpack_enable_site_verification'             => null,
6295
			'can_display_jetpack_manage_notice'            => null,
6296
			// Removed in Jetpack 7.3.0
6297
			'atd_load_scripts'                             => null,
6298
			'atd_http_post_timeout'                        => null,
6299
			'atd_http_post_error'                          => null,
6300
			'atd_service_domain'                           => null,
6301
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6302
			// Removed in Jetpack 7.9.0
6303
			'jetpack_pwa_manifest'                         => null,
6304
			'jetpack_pwa_background_color'                 => null,
6305
		);
6306
6307
		// This is a silly loop depth. Better way?
6308
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6309
			if ( has_action( $hook ) ) {
6310
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6311
					foreach ( $values as $hooked ) {
6312
						if ( is_callable( $hooked['function'] ) ) {
6313
							$function_name = 'an anonymous function';
6314
						} else {
6315
							$function_name = $hooked['function'];
6316
						}
6317
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6318
					}
6319
				}
6320
			}
6321
		}
6322
	}
6323
6324
	/**
6325
	 * Converts any url in a stylesheet, to the correct absolute url.
6326
	 *
6327
	 * Considerations:
6328
	 *  - Normal, relative URLs     `feh.png`
6329
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6330
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6331
	 *  - Absolute URLs             `http://domain.com/feh.png`
6332
	 *  - Domain root relative URLs `/feh.png`
6333
	 *
6334
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6335
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6336
	 *
6337
	 * @return mixed|string
6338
	 */
6339
	public static function absolutize_css_urls( $css, $css_file_url ) {
6340
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6341
		$css_dir = dirname( $css_file_url );
6342
		$p       = wp_parse_url( $css_dir );
6343
		$domain  = sprintf(
6344
			'%1$s//%2$s%3$s%4$s',
6345
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6346
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6347
			$p['host'],
6348
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6349
		);
6350
6351
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6352
			$find = $replace = array();
6353
			foreach ( $matches as $match ) {
6354
				$url = trim( $match['path'], "'\" \t" );
6355
6356
				// If this is a data url, we don't want to mess with it.
6357
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6358
					continue;
6359
				}
6360
6361
				// If this is an absolute or protocol-agnostic url,
6362
				// we don't want to mess with it.
6363
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6364
					continue;
6365
				}
6366
6367
				switch ( substr( $url, 0, 1 ) ) {
6368
					case '/':
6369
						$absolute = $domain . $url;
6370
						break;
6371
					default:
6372
						$absolute = $css_dir . '/' . $url;
6373
				}
6374
6375
				$find[]    = $match[0];
6376
				$replace[] = sprintf( 'url("%s")', $absolute );
6377
			}
6378
			$css = str_replace( $find, $replace, $css );
6379
		}
6380
6381
		return $css;
6382
	}
6383
6384
	/**
6385
	 * This methods removes all of the registered css files on the front end
6386
	 * from Jetpack in favor of using a single file. In effect "imploding"
6387
	 * all the files into one file.
6388
	 *
6389
	 * Pros:
6390
	 * - Uses only ONE css asset connection instead of 15
6391
	 * - Saves a minimum of 56k
6392
	 * - Reduces server load
6393
	 * - Reduces time to first painted byte
6394
	 *
6395
	 * Cons:
6396
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6397
	 *      should not cause any issues with themes.
6398
	 * - Plugins/themes dequeuing styles no longer do anything. See
6399
	 *      jetpack_implode_frontend_css filter for a workaround
6400
	 *
6401
	 * For some situations developers may wish to disable css imploding and
6402
	 * instead operate in legacy mode where each file loads seperately and
6403
	 * can be edited individually or dequeued. This can be accomplished with
6404
	 * the following line:
6405
	 *
6406
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6407
	 *
6408
	 * @since 3.2
6409
	 **/
6410
	public function implode_frontend_css( $travis_test = false ) {
6411
		$do_implode = true;
6412
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6413
			$do_implode = false;
6414
		}
6415
6416
		// Do not implode CSS when the page loads via the AMP plugin.
6417
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6418
			$do_implode = false;
6419
		}
6420
6421
		/**
6422
		 * Allow CSS to be concatenated into a single jetpack.css file.
6423
		 *
6424
		 * @since 3.2.0
6425
		 *
6426
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6427
		 */
6428
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6429
6430
		// Do not use the imploded file when default behavior was altered through the filter
6431
		if ( ! $do_implode ) {
6432
			return;
6433
		}
6434
6435
		// We do not want to use the imploded file in dev mode, or if not connected
6436
		if ( ( new Status() )->is_development_mode() || ! self::is_active() ) {
6437
			if ( ! $travis_test ) {
6438
				return;
6439
			}
6440
		}
6441
6442
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6443
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6444
			return;
6445
		}
6446
6447
		/*
6448
		 * Now we assume Jetpack is connected and able to serve the single
6449
		 * file.
6450
		 *
6451
		 * In the future there will be a check here to serve the file locally
6452
		 * or potentially from the Jetpack CDN
6453
		 *
6454
		 * For now:
6455
		 * - Enqueue a single imploded css file
6456
		 * - Zero out the style_loader_tag for the bundled ones
6457
		 * - Be happy, drink scotch
6458
		 */
6459
6460
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6461
6462
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6463
6464
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6465
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6466
	}
6467
6468
	function concat_remove_style_loader_tag( $tag, $handle ) {
6469
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6470
			$tag = '';
6471
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6472
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6473
			}
6474
		}
6475
6476
		return $tag;
6477
	}
6478
6479
	/**
6480
	 * Add an async attribute to scripts that can be loaded asynchronously.
6481
	 * https://www.w3schools.com/tags/att_script_async.asp
6482
	 *
6483
	 * @since 7.7.0
6484
	 *
6485
	 * @param string $tag    The <script> tag for the enqueued script.
6486
	 * @param string $handle The script's registered handle.
6487
	 * @param string $src    The script's source URL.
6488
	 */
6489
	public function script_add_async( $tag, $handle, $src ) {
6490
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6491
			return preg_replace( '/^<script /i', '<script async ', $tag );
6492
		}
6493
6494
		return $tag;
6495
	}
6496
6497
	/*
6498
	 * Check the heartbeat data
6499
	 *
6500
	 * Organizes the heartbeat data by severity.  For example, if the site
6501
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6502
	 *
6503
	 * Data will be added to "caution" array, if it either:
6504
	 *  - Out of date Jetpack version
6505
	 *  - Out of date WP version
6506
	 *  - Out of date PHP version
6507
	 *
6508
	 * $return array $filtered_data
6509
	 */
6510
	public static function jetpack_check_heartbeat_data() {
6511
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6512
6513
		$good    = array();
6514
		$caution = array();
6515
		$bad     = array();
6516
6517
		foreach ( $raw_data as $stat => $value ) {
6518
6519
			// Check jetpack version
6520
			if ( 'version' == $stat ) {
6521
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6522
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6523
					continue;
6524
				}
6525
			}
6526
6527
			// Check WP version
6528
			if ( 'wp-version' == $stat ) {
6529
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6530
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6531
					continue;
6532
				}
6533
			}
6534
6535
			// Check PHP version
6536
			if ( 'php-version' == $stat ) {
6537
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6538
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_PHP_VERSION;
6539
					continue;
6540
				}
6541
			}
6542
6543
			// Check ID crisis
6544
			if ( 'identitycrisis' == $stat ) {
6545
				if ( 'yes' == $value ) {
6546
					$bad[ $stat ] = $value;
6547
					continue;
6548
				}
6549
			}
6550
6551
			// The rest are good :)
6552
			$good[ $stat ] = $value;
6553
		}
6554
6555
		$filtered_data = array(
6556
			'good'    => $good,
6557
			'caution' => $caution,
6558
			'bad'     => $bad,
6559
		);
6560
6561
		return $filtered_data;
6562
	}
6563
6564
6565
	/*
6566
	 * This method is used to organize all options that can be reset
6567
	 * without disconnecting Jetpack.
6568
	 *
6569
	 * It is used in class.jetpack-cli.php to reset options
6570
	 *
6571
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6572
	 *
6573
	 * @return array of options to delete.
6574
	 */
6575
	public static function get_jetpack_options_for_reset() {
6576
		return Jetpack_Options::get_options_for_reset();
6577
	}
6578
6579
	/*
6580
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6581
	 * so we can bring them directly to their site in calypso.
6582
	 *
6583
	 * @param string | url
6584
	 * @return string | url without the guff
6585
	 */
6586
	public static function build_raw_urls( $url ) {
6587
		$strip_http = '/.*?:\/\//i';
6588
		$url        = preg_replace( $strip_http, '', $url );
6589
		$url        = str_replace( '/', '::', $url );
6590
		return $url;
6591
	}
6592
6593
	/**
6594
	 * Stores and prints out domains to prefetch for page speed optimization.
6595
	 *
6596
	 * @param mixed $new_urls
6597
	 */
6598
	public static function dns_prefetch( $new_urls = null ) {
6599
		static $prefetch_urls = array();
6600
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6601
			echo "\r\n";
6602
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6603
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6604
			}
6605
		} elseif ( ! empty( $new_urls ) ) {
6606
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6607
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6608
			}
6609
			foreach ( (array) $new_urls as $this_new_url ) {
6610
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6611
			}
6612
			$prefetch_urls = array_unique( $prefetch_urls );
6613
		}
6614
	}
6615
6616
	public function wp_dashboard_setup() {
6617
		if ( self::is_active() ) {
6618
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6619
		}
6620
6621
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6622
			$jetpack_logo = new Jetpack_Logo();
6623
			$widget_title = sprintf(
6624
				wp_kses(
6625
					/* translators: Placeholder is a Jetpack logo. */
6626
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6627
					array( 'span' => array() )
6628
				),
6629
				$jetpack_logo->get_jp_emblem( true )
6630
			);
6631
6632
			wp_add_dashboard_widget(
6633
				'jetpack_summary_widget',
6634
				$widget_title,
6635
				array( __CLASS__, 'dashboard_widget' )
6636
			);
6637
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6638
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6639
6640
			// If we're inactive and not in development mode, sort our box to the top.
6641
			if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
6642
				global $wp_meta_boxes;
6643
6644
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6645
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6646
6647
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6648
			}
6649
		}
6650
	}
6651
6652
	/**
6653
	 * @param mixed $result Value for the user's option
6654
	 * @return mixed
6655
	 */
6656
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6657
		if ( ! is_array( $sorted ) ) {
6658
			return $sorted;
6659
		}
6660
6661
		foreach ( $sorted as $box_context => $ids ) {
6662
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6663
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6664
				continue;
6665
			}
6666
6667
			$ids_array = explode( ',', $ids );
6668
			$key       = array_search( 'dashboard_stats', $ids_array );
6669
6670
			if ( false !== $key ) {
6671
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6672
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6673
				$sorted[ $box_context ] = implode( ',', $ids_array );
6674
				// We've found it, stop searching, and just return.
6675
				break;
6676
			}
6677
		}
6678
6679
		return $sorted;
6680
	}
6681
6682
	public static function dashboard_widget() {
6683
		/**
6684
		 * Fires when the dashboard is loaded.
6685
		 *
6686
		 * @since 3.4.0
6687
		 */
6688
		do_action( 'jetpack_dashboard_widget' );
6689
	}
6690
6691
	public static function dashboard_widget_footer() {
6692
		?>
6693
		<footer>
6694
6695
		<div class="protect">
6696
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6697
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6698
				<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>
6699
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
6700
				<a href="
6701
				<?php
6702
				echo esc_url(
6703
					wp_nonce_url(
6704
						self::admin_url(
6705
							array(
6706
								'action' => 'activate',
6707
								'module' => 'protect',
6708
							)
6709
						),
6710
						'jetpack_activate-protect'
6711
					)
6712
				);
6713
				?>
6714
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6715
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6716
				</a>
6717
			<?php else : ?>
6718
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6719
			<?php endif; ?>
6720
		</div>
6721
6722
		<div class="akismet">
6723
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6724
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6725
				<p><?php echo esc_html_x( 'Spam comments blocked by Akismet.', '{#} Spam comments blocked by Akismet -- number is on a prior line, text is a caption.', 'jetpack' ); ?></p>
6726
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6727
				<a href="
6728
				<?php
6729
				echo esc_url(
6730
					wp_nonce_url(
6731
						add_query_arg(
6732
							array(
6733
								'action' => 'activate',
6734
								'plugin' => 'akismet/akismet.php',
6735
							),
6736
							admin_url( 'plugins.php' )
6737
						),
6738
						'activate-plugin_akismet/akismet.php'
6739
					)
6740
				);
6741
				?>
6742
							" class="button button-jetpack">
6743
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6744
				</a>
6745
			<?php else : ?>
6746
				<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( 'Akismet can help to keep your blog safe from spam!', 'jetpack' ); ?></a></p>
6747
			<?php endif; ?>
6748
		</div>
6749
6750
		</footer>
6751
		<?php
6752
	}
6753
6754
	/*
6755
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6756
	 */
6757
	function jetpack_icon_user_connected( $columns ) {
6758
		$columns['user_jetpack'] = '';
6759
		return $columns;
6760
	}
6761
6762
	/*
6763
	 * Show Jetpack icon if the user is linked.
6764
	 */
6765
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6766
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
6767
			$jetpack_logo = new Jetpack_Logo();
6768
			$emblem_html  = sprintf(
6769
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6770
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6771
				$jetpack_logo->get_jp_emblem()
6772
			);
6773
			return $emblem_html;
6774
		}
6775
6776
		return $val;
6777
	}
6778
6779
	/*
6780
	 * Style the Jetpack user column
6781
	 */
6782
	function jetpack_user_col_style() {
6783
		global $current_screen;
6784
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
6785
			?>
6786
			<style>
6787
				.fixed .column-user_jetpack {
6788
					width: 21px;
6789
				}
6790
				.jp-emblem-user-admin svg {
6791
					width: 20px;
6792
					height: 20px;
6793
				}
6794
				.jp-emblem-user-admin path {
6795
					fill: #00BE28;
6796
				}
6797
			</style>
6798
			<?php
6799
		}
6800
	}
6801
6802
	/**
6803
	 * Checks if Akismet is active and working.
6804
	 *
6805
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6806
	 * that implied usage of methods present since more recent version.
6807
	 * See https://github.com/Automattic/jetpack/pull/9585
6808
	 *
6809
	 * @since  5.1.0
6810
	 *
6811
	 * @return bool True = Akismet available. False = Aksimet not available.
6812
	 */
6813
	public static function is_akismet_active() {
6814
		static $status = null;
6815
6816
		if ( ! is_null( $status ) ) {
6817
			return $status;
6818
		}
6819
6820
		// Check if a modern version of Akismet is active.
6821
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6822
			$status = false;
6823
			return $status;
6824
		}
6825
6826
		// Make sure there is a key known to Akismet at all before verifying key.
6827
		$akismet_key = Akismet::get_api_key();
6828
		if ( ! $akismet_key ) {
6829
			$status = false;
6830
			return $status;
6831
		}
6832
6833
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6834
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6835
6836
		// 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.
6837
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6838
		// We cache the result of the Akismet key verification for ten minutes.
6839
		if ( ! $akismet_key_state || $recheck ) {
6840
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6841
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6842
		}
6843
6844
		$status = 'valid' === $akismet_key_state;
6845
6846
		return $status;
6847
	}
6848
6849
	/**
6850
	 * @deprecated
6851
	 *
6852
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
6853
	 */
6854
	public static function is_function_in_backtrace() {
6855
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
6856
	}
6857
6858
	/**
6859
	 * Given a minified path, and a non-minified path, will return
6860
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6861
	 *
6862
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6863
	 * root Jetpack directory.
6864
	 *
6865
	 * @since 5.6.0
6866
	 *
6867
	 * @param string $min_path
6868
	 * @param string $non_min_path
6869
	 * @return string The URL to the file
6870
	 */
6871
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6872
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6873
	}
6874
6875
	/**
6876
	 * Checks for whether Jetpack Backup & Scan is enabled.
6877
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6878
	 *
6879
	 * @return bool|int|mixed
6880
	 */
6881
	public static function is_rewind_enabled() {
6882
		if ( ! self::is_active() ) {
6883
			return false;
6884
		}
6885
6886
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6887
		if ( false === $rewind_enabled ) {
6888
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6889
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6890
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6891
				&& ! empty( $rewind_data['state'] )
6892
				&& 'active' === $rewind_data['state'] )
6893
				? 1
6894
				: 0;
6895
6896
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6897
		}
6898
		return $rewind_enabled;
6899
	}
6900
6901
	/**
6902
	 * Return Calypso environment value; used for developing Jetpack and pairing
6903
	 * it with different Calypso enrionments, such as localhost.
6904
	 *
6905
	 * @since 7.4.0
6906
	 *
6907
	 * @return string Calypso environment
6908
	 */
6909
	public static function get_calypso_env() {
6910
		if ( isset( $_GET['calypso_env'] ) ) {
6911
			return sanitize_key( $_GET['calypso_env'] );
6912
		}
6913
6914
		if ( getenv( 'CALYPSO_ENV' ) ) {
6915
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6916
		}
6917
6918
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
6919
			return sanitize_key( CALYPSO_ENV );
6920
		}
6921
6922
		return '';
6923
	}
6924
6925
	/**
6926
	 * Checks whether or not TOS has been agreed upon.
6927
	 * Will return true if a user has clicked to register, or is already connected.
6928
	 */
6929
	public static function jetpack_tos_agreed() {
6930
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
6931
6932
		$terms_of_service = new Terms_Of_Service();
6933
		return $terms_of_service->has_agreed();
6934
6935
	}
6936
6937
	/**
6938
	 * Handles activating default modules as well general cleanup for the new connection.
6939
	 *
6940
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
6941
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
6942
	 * @param boolean $send_state_messages          Whether to send state messages.
6943
	 * @return void
6944
	 */
6945
	public static function handle_post_authorization_actions(
6946
		$activate_sso = false,
6947
		$redirect_on_activation_error = false,
6948
		$send_state_messages = true
6949
	) {
6950
		$other_modules = $activate_sso
6951
			? array( 'sso' )
6952
			: array();
6953
6954
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
6955
			self::delete_active_modules();
6956
6957
			self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
6958
		} else {
6959
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
6960
		}
6961
6962
		// Since this is a fresh connection, be sure to clear out IDC options
6963
		Jetpack_IDC::clear_all_idc_options();
6964
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
6965
6966
		// Start nonce cleaner
6967
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
6968
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
6969
6970
		if ( $send_state_messages ) {
6971
			self::state( 'message', 'authorized' );
6972
		}
6973
	}
6974
6975
	/**
6976
	 * Returns a boolean for whether backups UI should be displayed or not.
6977
	 *
6978
	 * @return bool Should backups UI be displayed?
6979
	 */
6980
	public static function show_backups_ui() {
6981
		/**
6982
		 * Whether UI for backups should be displayed.
6983
		 *
6984
		 * @since 6.5.0
6985
		 *
6986
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
6987
		 */
6988
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
6989
	}
6990
6991
	/*
6992
	 * Deprecated manage functions
6993
	 */
6994
	function prepare_manage_jetpack_notice() {
6995
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6996
	}
6997
	function manage_activate_screen() {
6998
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6999
	}
7000
	function admin_jetpack_manage_notice() {
7001
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7002
	}
7003
	function opt_out_jetpack_manage_url() {
7004
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7005
	}
7006
	function opt_in_jetpack_manage_url() {
7007
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7008
	}
7009
	function opt_in_jetpack_manage_notice() {
7010
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7011
	}
7012
	function can_display_jetpack_manage_notice() {
7013
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7014
	}
7015
7016
	/**
7017
	 * Clean leftoveruser meta.
7018
	 *
7019
	 * Delete Jetpack-related user meta when it is no longer needed.
7020
	 *
7021
	 * @since 7.3.0
7022
	 *
7023
	 * @param int $user_id User ID being updated.
7024
	 */
7025
	public static function user_meta_cleanup( $user_id ) {
7026
		$meta_keys = array(
7027
			// AtD removed from Jetpack 7.3
7028
			'AtD_options',
7029
			'AtD_check_when',
7030
			'AtD_guess_lang',
7031
			'AtD_ignored_phrases',
7032
		);
7033
7034
		foreach ( $meta_keys as $meta_key ) {
7035
			if ( get_user_meta( $user_id, $meta_key ) ) {
7036
				delete_user_meta( $user_id, $meta_key );
7037
			}
7038
		}
7039
	}
7040
7041
	/**
7042
	 * Checks if a Jetpack site is both active and not in development.
7043
	 *
7044
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7045
	 *
7046
	 * @return bool True if Jetpack is active and not in development.
7047
	 */
7048
	public static function is_active_and_not_development_mode() {
7049
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7050
			return false;
7051
		}
7052
		return true;
7053
	}
7054
}
7055